ADB not seeing devices on Debian 8.2

Question: After moving from Windows to Debian I've encountered big problem. I can't run any of my apps developed in Android Studio. "Device Chooser" doesn't see any of my devices (LG G2 and LG G4), "adb devices" also gives no results:
adb devices:
nomader@ideapad:~$ adb devices
List of devices attached

But phone is clearly connected:
lsusb:
nomader@ideapad:~$ lsusb
Bus 004 Device 003: ID 04f2:b2f1 Chicony Electronics Co., Ltd
Bus 004 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 004 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 003: ID 09da:9090 A4 Tech Co., Ltd XL-750BK Laser Mouse
Bus 003 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 1004:633e LG Electronics, Inc.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I added rule to /etc/udev/rules.d
51-android.rules:
SUBSYSTEM=="usb", ATTR{idVendor}=="1004", MODE="0666", GROUP="plugdev"

and edited adb_usb.ini:
# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x1004

But none of this worked and I'm still not able to detect my devices.
Any ideas?
edit: on Windows everything was working
Comment: http://ktnr74.blogspot.com/2014/09/the-most-comprehensive-write-up-on-how.html
Comment: forget `adb_usb.ini`. it's no longer needed (since platform-tools v23). but no output from `find -L /sys/bus/usb/devices -maxdepth 2 -path "*/modalias" -printf "%h\t" -exec cat {} \; | grep 'icFFisc42ip01'` mean that `USB Debugging` is not on (or working properly) on your device.
Comment: I've found solution. I was pretty desperate, so I started switching settings on my phones and it turned out that changing USB Connection from MTP to PTP fixes this problem.
Thanks for your help :)
Comment: Almost none of it works for me. I've only found Interface Descriptor in `lsusb -v` that matches one in article, but I already added 0x1004 to adb_usb.ini and `~$ find -L /sys/bus/usb/devices -maxdepth 2 -path "*/modalias" -printf "%h\t" -exec cat {} \; | \
awk -F: '/icFFisc42ip0/ {print $1}' | xargs -i cat {}/idVendor | awk '{print"0x"$1}' ` doesn't give any output. My hardware is working, because on Windows everything is working perfectly.
Comment: Is there possibility that USB Debugging is not working properly on my devices if on Windows everything works? Is there  any setting that I can change to make this work on Debian?
Answer: I've found solution. I was pretty desperate, so I started switching settings on my phones and it turned out that changing USB Connection from MTP to PTP fixes this problem.
Answer: You should
a) restart udev after editing /etc/udev/rules.d/* files
$ sudo service udev restart

b) replug your device after restarting udev - just plug it off and in again.
Also, you must install 32-bit libs if you run 64-bit OS.
Comment: Both Andrey's suggestions are irrelevant. It is not a permissions issue (so `udev` is not going to help). And since `adb devices` printed `List of devices attached` line - you already have all the libraries you need for `adb` to work.
Comment: I'm restarting my computer after every change in rules and it still doesn't work. Which libs do you mean?

ADB not seeing devices on Debian 8.2


$A-B$ and $B-A$ positive semidefinite $\implies$ $A=B$

Question: I am trying to show that $A-B$ and $B-A$ positive semidefinite $\implies A=B$, but I'm having some trouble.
$A-B$ PSD iff $x'(A-B)x \geq 0 \forall x$, and $B-A$ PSD iff $x'(B-A)x \geq 0 \forall x$.
Both of these are true iff $$x'Ax=x'Bx \forall x,$$
which holds iff $$x'(A-B)x=0, \forall x,$$
$$\iff x \perp (A-B)x, \forall x$$
But this holds if, for instance, (A-B) is a 90-degree rotation. It doesn't seem to require $A-B=0$. What am I missing?
Answer: An easier way is using the spectral decomposition for $A - B$ (I am assuming it is symmetric), which gives
$$A - B = Odiag(\lambda_1, \ldots, \lambda_n)O^T,$$
where $O$ is orthogonal matrix and $\lambda_1 \geq \cdots \geq \lambda_n \geq 0$ are eigenvalues of $A - B$ (since it is positive-semidefinite by condition). Hence
$$B - A = Odiag(-\lambda_1, \ldots, -\lambda_n)O^T.$$
That is, $B - A$ is orthogonal similar to a diagonal matrix $diag(-\lambda_1, \ldots, -\lambda_n)$, hence $-\lambda_1, \ldots, -\lambda_n$ are also eigenvalues of $B - A$. By assumption, $B - A$ is positive-semidefinite, therefore,
$$-\lambda_i \geq 0, i = 1, \ldots, n.$$
In this way, we can see that $\lambda_1 = \cdots = \lambda_n = 0$. Thus $A - B = 0$, or, $A = B$.
Answer: The usual definition of a positive semi-definite matrix requires the matrix to be symmetric (or Hermitian in the complex case). This will rule out the possibility that $A-B$ is a rotation matrix.
As for proving this statement, suppose $A$ and $B$ are $n \times n$ symmetric matrices. Let $e_k$ be the $k$-th standard basis vector.
Since $x'(A-B)x = 0$ for all $x$ (as you have already deduced), we have that $e_k'(A-B)e_k = 0$, i.e. $(A-B)_{k,k} = 0$ for all $k$. Hence, the diagonal of $A-B$ is zero.
For sake of contradiction, suppose $(A-B)_{i,j} = \alpha \neq 0$ for some $i,j$ such that $i \neq j$. Since $A$ and $B$ are symmetric, $A-B$ is symmetric. So, $(A-B)_{j,i} = \alpha$ as well.
Now, what can you say about $(e_i+e_j)'(A-B)(e_i+e_j)$? Do you see the contradiction?
Comment: Cool.  $(e_i+e_j)′(A−B)(e_i+e_j) = (A-B)_{ij} + (A-B)_{ji}=0$ and for symmetric $(A-B), (A-B)_{ij} + (A-B)_{ji}=0 \iff (A-B)_{ij} =0$. Thus $x'(A-B)x=0 \implies (A-B)_{ij}=0 \forall i,j$ if $A,B$ symmetric. Right?


beta reduction: correct way to replace bound variables?

Question: say I have the following example of a lambda expression with \x meant to represent lambda x
What would the beta reduction of the following be?
(\x.\x.(x x)) \z.z

My first instinct would have been for this to be
\x.(\z.z \z.z)

But someone I spoke with was of the opinion that the second \x would also be replaced with \z.z
which would mean it is really
\(\z.z).(\z.z \z.z)

Can someone please clarify what the correct approach would be. I can't say I really understand the second approach.
Answer: Actually, (\x.\x.(x x)) \z.z is alpha equivalent to (\x.\y.(y y)) \z.z because variables are always bound to the closest lambda abstraction.
This means (\x.\x.(x x)) \z.z is beta equivalent to \x.(x x).
Substitution is never done on lambda abstractions, the \x. part.
Comment: Rui thank you for the response. I had that feeling, any chance you might have a reference to a website/textbook that might highlight the  "never substitute on lambda abstraction" part? I'd like to share that with them so that we're all on the same page. Thanks!
Comment: Beta reduction is defined in terms of substitution, so [here](http://en.wikipedia.org/wiki/Lambda_calculus#Capture-avoiding_substitutions) and [here, page 8](http://homepage.cs.uiowa.edu/~slonnegr/plf/Book/Chapter5.pdf).


adding multiple records in linked lists

Question: I have basically two queries. First this code is working fine I just want to print the results and second this program enters only one record. I want to save a complete address book of a record like name contact. For that I will have to give separate struct pointer for every field? Please help me out.
<code>#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct node
{
   int data;
   struct node *link;
} *head=NULL;

void inserfirst();

int main()
{
    insertfirst();
    getch();
    return 0;
}

void insertfirst()
{
     int item;
     struct node *ptr;
     scanf("%d",&item);
     if (head==NULL) {
         head=(struct node*)malloc(sizeof(struct node));
         head->data=item;
         head->link=NULL;
     } else {
         ptr=head;
         head=(struct node*)malloc(sizeof(struct node));
         head->data=item;
         head->link=ptr;
     }
}
</code>
Comment: @H2CO3 what's wrong with `sizeof(type)`? And what's wrong with casting? It's more verbose and can be even necessary if C++ compiler is used (which is the case in 99%)
Comment: `head=(struct node*)malloc(sizeof(struct node));` is **plain wrong,** it should be `head = malloc(sizeof(*head));` (i. e. don't cast, use `sizeof(*pointer)` instead of `sizeof(type)` and use whitespace properly).
Comment: @icepack 7. `sizeof(type)` **will** break when you change the type of the pointer (and you'll get more-than-hard-to-track-down segfaults).
Comment: Regarding malloc()-casting in C++, earlier [this week](http://stackoverflow.com/questions/13677566/malloc-a-2d-array-in-c/13677636#13677636) I answered that very issue. I suppose so long as you're not using the features of the C language supported by the standard (VLAs for example) then go ahead and compile with C++. Of course, any self-respecting C++ programmer will use a vector<> in that case, but then that won't compile in C, now will it. Face it. They're different, and I blame the whole "move at your own pace from C to C++" bullshit people bought into hook, line, and sinker (and still do).
Comment: @user1885560 all the better if you're mission is writing **C** code, sir. If you're mission is writing C-code that compiles with a C++ compiler, *they're different missions*. Obviously in your case, I wouldn't worry about. Dance with the one you brought.
Comment: You should indent ALL of your code by 4 spaces so people can see your code better
Comment: @icepack 1. No one is talking about C++, the question is tagged C. 2. Don't try to compile C++ as C, because they're different languages. 3. Don't use a C++ compiler which does not have a C-only mode. 4. The cast is not just more verbose, it explicitly decreases readability (casts are *ugly*). 5. It's redundant, since `void *` (the return value of `malloc()`) is explicitly compatible with any data pointer type. 6. It's dangerous if you forget to `#include `. Then `int` will be assumed as return type, and if `sizeof(int) != sizeof(void *)`, then it causes memory corruption once again.
Comment: @H2CO3 also have no problem with the type cast - makes for legibility. And sizeof(Type) is widely used and sometimes required (what if your pointer is a void*) - certainly not a huge issue.
Comment: @Elemental wrong, wrong, wrong, wrong... You both are in the serious need of reading [this](http://www.kernel.org/doc/Documentation/CodingStyle), [this](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) and [this](http://stackoverflow.com/questions/7545365/why-does-this-code-segfault-on-64-bit-architecture-but-work-fine-on-32-bit).
Comment: @H2CO3 I think I understand the issues: the style guide explicitly says style is a matter of personal preference; the two stack overflow links both have conflicting opinions. Personally ONLY the 'what if you leave stdlib out' argument  seems at all strong and basically *This is why you never compile without warnings about missing prototypes*.
Comment: @Elemental the two SO answers do not have conflicting opinions, they both say basically what I advise as well. All of the 64 vs 32 bit, `sizeof(type)` vs. `sizeof(*ptr)` and "typecasting is redundant" arguments are valid and respected by most decent programmers, but go ahead and write buggy and unreadable code if you wish.
Comment: @H2CO3 First of all, writing **"plain wrong"** about the posted code is plain wrong. The code is correct despite your coding style preferences and disadvantages that such approach may or may not have. Second, C++ compiler is widely used for C code, whether you like it or not. Third, various compilers support various C standards - notable is MSVC with only C90 support. And finally, your links have serious discussions about the issues you raise (both casting and sizeof) - the conclusion  is that there is no absolute answer and it depends on the specific situation.
Comment: @H2CO3 actually, I find it funny when people claim *"bla bla 1 will not work if you change bla bla 2"* - meaning it's acceptable to completely change *bla bla* but it's not ok to use C++ compiler which have stronger typing and can actually prevent bugs at compiler level that pure C compiler won't.
Comment: What is this error and how will it be removed?   "Lvalue required"
Comment: The biggest problem is that i have to use c compiler i am in such a situation where i am not allowed to use any other compiler...
Comment: @WhozCraig There is an item pusblished long ago by MS that I personally find insightful. Among other things it discusses the subtlties and mentions the advantages of using C++ compiler for a C code in an environment that wasn't natively ready for C++: http://msdn.microsoft.com/en-us/library/windows/hardware/gg487420.aspx#EFC
Comment: @icepack I remember when that article came out, and it struck me somewhat odd that there were *no* "advantages" specified besides generic euphemisms and, of course, "stricter type checking", and even that was discussed as disadvantageous for otherwise-legal kernel driver code. The rest of the article dissects all the gotchas where using C++ as a "Super-C" in a driver environment can bite you in the ass. Funny that. For me, if one's goal is to write C++ compilable "C-code", so be it. Just like C-compilable "C++ code", you will be restricted on feature choice either way (the latter more-so).
Comment: @WhozCraig Stricter type checking is a big issue. Not so long ago we moved our kernel code base to C++. The first step was, of course, the compilation. Not surprisingly, lots of **real** errors were discovered in pure C90 code, some are serious and some less.
Comment: @icepack yeah I wish the stds committees would just squeeze that, and *only* that, into the C std for good, without all the other C++ cruft. I love *both* languages, and there are some things I wish I could do in each from the other, but alas, not to be.
Answer: To address your issues:
In general the way would keep multiple bits of information (Name, numbers, address etc) is by including them in the node struct, something like:
<code>struct node
{
   int data;
   char name[50];
   char phone[20];
   struct node *link;
} *head=NULL;
</code>
This is a list of contacts, each node has the contact details, the list contains multiple contacts.
To print such a list out one would iterate through the list and print each node, specifically:

Start with the head
if the current node is null then we're at the end so exit
print of the content of the current node
set the current node to the next node (i.e. current->link)
go back to step 2
Comment: that means i do not need to give a separate struct pointer for every field right? just one *link that will link to the next complete node...
Answer: you can use this also

   typedef struct contact
    {
     int data;
    char name[40];
    char add[90];
    }book;
    stuct node
    {
    book b;
    struct node*link;
    }*head=NULL;

adding multiple records in linked lists


getting alternate column names while reading a line using buffered reader in java?

Question: I am using this code to read a line in csv and get the column names,but the problem is I am getting alternate cloumn names.It is skipping the first column reading the second and then skipping the third and reading the fourth..
<code>BufferedReader br = new BufferedReader(new FileReader(csvFile));
               String line = "";
               StringTokenizer st = null;

               int lineNumber = 0;
               int tokenNumber = 0;

               //read comma separated file line by line
               while ((line = br.readLine()) != null) {
                 lineNumber++;

                 //use comma as token separator
                 st = new StringTokenizer(line, ",");

                 while (st.hasMoreTokens()) {
                   //tokenNumber++;
                   s.add(st.nextToken());
                   //display csv values
                   System.out.print(st.nextToken() + "  ");

                 }
</code>
Comment: As stated in the javadocs for `StringTokenizer`, you really shouldn't be using it in modern (new) code. `String[] array = line.split(",");`
Answer: You are calling st.nextToken() twice in the while loop. Each time, it will grab the next element.
You may want to replace the StringTokenizer with line.split(",") unless you have a particular need to use it (such as performance).


Finding covariance using the expectation values using E(XY)

Question: We choose numbers from {2, 3} by tossing a fair coin; the coin
is tossed twice. Choose 2 if the coin turns up Heads and 3 if the coin is Tails. So
the possible outcomes are {(2, 2),(2, 3),(3, 2),(3, 3)}. Let X be the first number
chosen (so X ∈ {2, 3}) and let Y be the product of the two chosen numbers. Compute the covariance
Cov(X, Y).
So I know the formula for covariance is Cov(X,Y) = E(XY)-E(X)E(Y).
I have worked out E(X) = 2P(X=2) + 3P(X=3) = 2.5
E(Y) = 4P(X=4) + 6P(X=6) + 9(X=9) = 6.25
However I am confused as to how to find E(XY)?
Answer: Well, you do the same analysis: $XY$ can possibly be $8$, $12$, $18$ and $27$, so
\begin{align}
\mathbb{E}(XY) &=8\mathbb{P}(XY=8)+12\mathbb{P}(XY=12)+18\mathbb{P}(XY=18)+27\mathbb{P}(XY=27)\\
&= \frac{8+12+18+27}{4}\\
&= \frac{65}{4}
\end{align}
Comment: Thanks, I understand the formula but, I'm trying to understand where you got (8 + 12 + 18 + 27)/4 from?
Comment: Each event has probability $\frac{1}{4}$.
Comment: Oh that makes sense, that's a lot. However I think you made a slight addition mistake since 8 + 12 + 18 + 27 = 65.
Comment: You are correct.


How to configure channel options in Google.Cloud.PubSub.V1 SubscriberServiceApiClientBuilder

Question: In Google.Cloud.PubSub.V1 version 1.x.x, I was using PublisherServiceApiClient.Create and passing in "Channel" object, which was configured with target, credentials, and ChannelOptions. The ChannelOptions are grpc.max_receive_message_length and then grpc.max_send_message_length.
According to the documentation (https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/api/Google.Cloud.PubSub.V1.SubscriberServiceApiClient.html#Google_Cloud_PubSub_V1_SubscriberServiceApiClient_Create) you have to use SubscriberServiceApiClientBuilder (if you are not going to use default values: https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/api/Google.Cloud.PubSub.V1.SubscriberServiceApiClientBuilder.html).
SubscriberServiceApiClientBuilder allows you set ChannelCredentials, and Endpoint, but I don't see a way to set the ChannelOptions. How do I set the ChannelOptions in SubscriberServiceApiClientBuilder?
Old code for creating SubScriberServiceApiClient:
SubscriberServiceApiClient.Create(channel); // channel is of type Channel
New code for creating SubscriberServiceApiClient:
new SubscriberServiceApiClientBuilder
{
    ChannelCredentials = channelCredentials,
    Endpoint = endPoint,
}.Build()

Answer: As you pointed out, SubscriberServiceApiClient.Create() has stopped accepting grpccore::Channel object. But you can still create a client by creating an underlying SubscriberServiceApiClientImpl object directly.
To elaborate more, SubscriberServiceApiClientImpl takes in a Subscriber.SubscriberClient object, that is derived from the channel variable (a grpccore::Channel object) that you wish to pass in. You can check the old implementation for how the grpcClient is created.
So in sum, your code may look like the following:
// Assuming `settings` (a `SubscriberServiceApiSettings` object) is
//     created (default to null)
// Assuming you're created a `channel` object that is a `grpccore::Channel`
gax::GaxPreconditions.CheckNotNull(channel, nameof(channel));
grpccore::CallInvoker callInvoker = new grpccore::DefaultCallInvoker(channel);
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor;
if (interceptor != null) {
    callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(
        callInvoker, interceptor);
}
Subscriber.SubscriberClient grpcClient = new Subscriber.SubscriberClient(callInvoker);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(
    grpcClient, settings);


Finland goal song at IIHF WM 2019

Question: What's the song name which is played after Finland scores goal in IIHF Ice Hockey World Championship 2019 in Slovakia?
Comment: This seemingly [similar question](https://sports.stackexchange.com/questions/18637/what-is-the-walk-out-song-world-cup-2018) was received well. What's the difference?
Answer: It's called Peto on Irti by VilleGalle
https://www.youtube.com/watch?v=svb8hBO52MY

Finland goal song at IIHF WM 2019


Debugar classes instanciadas no Magento

Question: No PHP existem métodos get_object_vars e get_class que retornam informações sobre a classe, no Magento podemos usar Zend_Debug::dump(), o Mage::log() e até o XDebug do PHP, mas durante o desenvolvimento de módulos no Magento, onde precisamos sobrescrever alguma parte do painel administrativo, para isso temos que procurar pelas classes corretas.
Como fazer para obter a lista de todas as classes instanciadas ao acessar uma página do Magento?
Exemplo: O usuário X acessou Catálogo->Atributo->Gerenciar Atributo, como gerar um Debug com a lista de todas as classes que foram instanciadas quando o usuário acessou a página Gerenciar Atributo?
Answer: Encontrei 2 soluções para o meu problema
1º Existe Mage_Core_Model_Config::getModelInstance
public function getModelInstance($modelClass='', $constructArguments=array())
    {
        $className = $this->getModelClassName($modelClass);
        if (class_exists($className)) {
            Varien_Profiler::start('CORE::create_object_of::'.$className);
            $obj = new $className($constructArguments);
            Varien_Profiler::stop('CORE::create_object_of::'.$className);
            return $obj;
        } else {
            return false;
        }
    }

pode usar esse método para encontrar todas as classes instanciadas. Por ProxiBlue
2º Adicionar

<?php htmlspecialchars( print_r( get_included_files() )); ?>

No final do arquivo.php . Isso imprimir cada arquivo incluído por Magento para um determinado pedido, e desde que os arquivos do Magento são nomeados de forma consistente você pode derivar os nomes de classe. Por Alan Storm

Debugar classes instanciadas no Magento


How to stop the jquery element being added on ajax requests

Question: I've added a toggle for my superfish menu, it works fine but for every ajax load or colorbox trigger the span is created multiple times. How to fix it???
(function ($){
Drupal.behaviors.customjs  = {
attach: function (context, settings) {
$(document).ready(function(){

$("#superfish-1").before("Menu");
$('#superfish-1').toggle();
 });

Answer: The better way would be to use the context of the behaviour along with .once() as mentioned here ( https://www.drupal.org/node/1667874 ), something like below:
(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      // Add context along with .once something like below.
      $("#superfish-1", context).once("CLASS-NAME").before("Menu");
    }
  }
})(jQuery);

Comment: Damn, I had network failure and my answer got sent after yours. Anyway, +1 from me as we basically did the same thing. I'll leave mine in place, I think it is bit more descriptive.
Comment: @Mołot Yeah please keep yours as well.
Comment: Thanks ankit and @Molot choosing this as the right ans and upvoting Molot's
Answer: First, don't use $(document).ready in behavior. It should not be needed to make behavior work when things are ready, and second, usually it will be executed immediately if page was ready in the past - not what you want.
Second thing is to always use context in top level $( selectors. And use once() to be sure.
So your code after changes could look like this:
(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      $("#superfish-1", context).once("customjs-before").before("Menu");
      $("#superfish-1", context).once("customjs-toggle").toggle();
    }
  };
})(jQuery);

Answer: Add jQuery once to your menu wrapper http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors


Prove that $X_0$ is a closed subspace of $X$

Question: I encounter the following exercise in functional analysis:
Let $(X,\|\cdot\|_{X})$ and $(Y,\|\cdot\|_{Y})$ be Banach spaces and $\{T_n\}$ be a family of uniformly bounded linear maps form $X$ to $Y$, i.e. $\|T_n\| \leqslant C$ for some positive constant $C$ for all $n$.
Let $X_0 = \{x \in X \mid \lim_{n \to \infty} T_n(x) \text{ exists}$}. Show that $X_0$ is a closed subspace of $X$.
Here's my approach: Let $y$ be a limit point of $X_0$, then there exists a sequence $\{x_k\}$ in $X_0$ that converges to $y$ in the $\|\cdot\|_X$ norm.
I want to show that $\{T_n(y) = \lim_{k \to \infty} T_n(x_k)\}$ is a Cauchy
sequence in $Y$ so that $y \in X_0$. But I don't know how to go from there.
Answer: Assume $x_j\to x$, with all $x_j\in X_0$. Given $\epsilon$, let $j_0$ be so that $\|x_{j_0}-x\|<\frac{\epsilon}{3C}$. Now find $N$ so that $m, n>N$ implies
$\|T_m x_{j_0}-T_n x_{j_0}\|<\frac{\epsilon}{3}$. Thus
$$
\begin{aligned}
\|T_mx-T_nx\|=&\|T_mx-T_mx_{j_0}+T_mx_{j_0}-T_nx_{j_0}+T_nx_{j_0}-T_nx\|\\
\leq & \|T_mx-T_mx_{j_0}\|+\|T_mx_{j_0}-T_nx_{j_0}\|+\|T_nx_{j_0}-T_nx\|\\
\leq & C\|x-x_{j_0}\|+\|T_mx_{j_0}-T_nx_{j_0}\|+C\|x_{j_0}-x\|\\
\leq & C\frac{\epsilon}{3C}+\frac{\epsilon}{3}+C\frac{\epsilon}{3C}=\epsilon.
\end{aligned}$$


Android API 23 : cannot resolve FragmentActivity

Question: I upgraded appcompat to rev 40 just now. After that, my project is throwing a compile error - it is not able to resolve FragmentActivity.
Build Target : API 23
Min : 16
Please let me know what I might be doing wrong. Appreciate your help.
Comment: @KrishnanVS r u using Eclipse or AStudio?
Comment: @KrishnanVS:  You don't need to import v4. Because when using v7, v4 is automagically included.
Comment: which library you are using v4 or v7
Comment: I am using v7, do I need to use v4 too ? Am not clear about the diff - the "libs" folder had both android-support-v4.jar and android-support-v7-appcompat.jar, I included both in the Build path of the appcompat project and then built my project.
Comment: for fragments you need to use v4
Comment: import android.support.v4.app.Fragment;
Comment: @karthick: op asking for `FragmentActivity` not `Fragment`.
Comment: Sure, is there a version that I should import. Can I import the android-support-v4.jar itself that I found in the appcompat lib ?
Comment: I am using Eclipse
Comment: @KrishnanVS:  isn't that AppCompat rev 40 is for API 25? So, did you using `compile com.android.support:appcompat-v7:25.x.x`? If yes, then you need to change Target SDK, buildTools, and Compile SDK to API 25.
Comment: @KrishnanVS did u try with cleaning the project?
Comment: rev 40 was for API 23, that was why I just did the update. I tried cleaning as well.
Comment: Try this may will help you.Go to "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.
Comment: @sasikumar he is using Eclipse
Answer: You should use AppCompatActivity because it is derived class of FragmentActivity
see the description below
java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity
                   ↳    android.support.v4.app.FragmentActivity
                       ↳    android.support.v7.app.AppCompatActivity

Answer: Thanks all of you, for taking time to help me out. I took the lead from karchick and added an external reference to android-support-v4.jar that was present in the updated AppCompat project/libs and the error got resolved.
Comment: no need to use FragmentActivity , you should use AppCompactActivity which is derived class of FragmentActivity


My notebook goes offline automatically after some time

Question: I have about 3 computers and 1 windows 2003 server in office and 1 network printer (HP LJ 2840).

My network printer is installed on the server.
I an sharing this printer on all clients with windows XP.
All other computers are fine only 1 HP laptop.

When I start that HP laptop the printer works fine but after some time, printer goes offline and I can't print until I restart the laptop.
When that laptop goes to offline mode, I can work on that laptop, I can use shared network drives, I can ping server but it shows offline mode icon in Task bar status area.  If i use <code>\\servername</code> I can see the server's shared items and if i go to printers I can't see any printer...
I try my best to solve this issue, but I can't.
Thanks
Comment: Given it's such a small network have you considered just setting each machine up to print directly rather than via the server?
Answer: Instead of restarting the computer try restarting the Print Spooler service.  Check the event log on the laptop to see if an errors are being logged.


How to display always the last day of the week

Question: I have a JSF table which displays activity of users.

public class Statistics implements Serializable {

    private CartesianChartModel weeksActivity;

    public Statistics() {
        createweeksActivity();

    }

    public CartesianChartModel getweekActivity() {
        return weeksActivity;
    }

    private void createweeksActivity() {
        weeksActivity = new CartesianChartModel();

        ChartSeries boys = new ChartSeries();
        boys.setLabel("Active Accounts");

        boys.set("Monday", 120);
        boys.set("Tuesday", 100);
        boys.set("Wednesday", 44);
        boys.set("Thursday", 150);
        boys.set("Friday", 120);
        boys.set("Saturday", 82);
        boys.set("Sunday", 115);

        ChartSeries girls = new ChartSeries();
        girls.setLabel("Blocked Accounts");

        girls.set("Monday", 52);
        girls.set("Tuesday", 60);
        girls.set("Wednesday", 110);
        girls.set("Thursday", 135);
        girls.set("Friday", 120);
        girls.set("Saturday", 140);
        girls.set("Saturday", 130);
        girls.set("Sunday", 140);

        weeksActivity.addSeries(boys);
        weeksActivity.addSeries(girls);
    }

}

I want to display the current day always last in order. For example:
Now I get this order: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
If for example today is Wednesday I want to get this order when I open the web page:
Thursday, Friday, Saturday, Sunday, Monday, Tuesday, Wednesday

How I can solve this problem?
EDIT:

I updated the code this way:
private void createweeksActivity()
    {

        weeksActivity = new CartesianChartModel();

        ChartSeries activeAccounts = new ChartSeries();
        activeAccounts.setLabel("Active Accounts");

        ChartSeries blockedAccounts = new ChartSeries();
        blockedAccounts.setLabel("Blocked Accounts");

        GregorianCalendar calendar = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat("EEEE");
        for (int i = 0; i < 7; i++)
        {
            calendar.add(Calendar.DATE, 1);
            System.out.println(df.format(calendar.getTime()));
            activeAccounts.set(df.format(calendar.getTime()), getNumberOfLogins(df.format(calendar.getTime())));
            blockedAccounts.set(df.format(calendar.getTime()), getNumberOfLogins(df.format(calendar.getTime())));
        }

        weeksActivity.addSeries(activeAccounts);
        weeksActivity.addSeries(blockedAccounts);
    }

    public int getNumberOfLogins(String day){

        // Get here the number of logins using SQL command
        // Example: SELECT * FROM HISTORY WHERE DAY = day;

        return 100;
    }

I suppose that it will work.
Answer: GregorianCalendar calendar = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("EEEE");
for (int i = 0; i < 7; i++) {
    calendar.add(Calendar.DATE, 1);
    System.out.println(df.format(calendar.getTime()));
}

A GregorianCalendar represents an instant in time, under our gregorian calendar. Its no-arg constructor initializes it to the current time.
A DateFormat is used to format dates. You can transform a (Gregorian)Calendar into a Date using its getTime() method. "EEEE" means the day of the week, in its longest form.
The (Gregorian)Calendar.add() method allows adding a value to any field of the calendar (year, month, date, hour, etc.). Since you want to iterate through the days of the week, I start from tomorrow, and add 1 day at each iteration.
Everything is available in the javadoc.
Comment: Would you please extend the code a little bit. I'm new to Java. I need a little explanation how I can use this code.
Answer: Have your Days of Week as a Map to its DAY OF WEEK number according to Calendar.
Then use Calendar to get the Current Day and use Modular Arithmetic to change the ordering.
Something like:
//This you can do it one time and then use it in your program
Map<Integer, String> daysOfWeek = new HashMap<Integer,String>();
daysOfWeek.put(Calendar.MONDAY, "Monday");
daysOfWeek.put(Calendar.TUESDAY, "Tuesday");
//so on and so forth.

//Now the code that will be running
//You get your current Day  (Which will be the last one you want to see)
int weekday = calendar.get(Calendar.DAY_OF_WEEK);

//Start with next value (modulus 7 since you don't want overflow)
int currDay = (weekday+1) % 7;

//Go over the seven Days
for(int i = 0; i < 7; i++) {
    String currDay = daysOfWeek.get(currDay);  //Get your Day String

    //Here do whatever you need to do to set up the DAY in JSF

    currDay = (currDay+1) % 7;  //Moving currDay to the next Day
 }


Como eu faço um condicional usando apenas usando o MÊS da data e a partir dela inserir uma fórmula em uma certa célula?

Question: Estou otimizando uma planilha, porém não está dando certo essa fórmula =SE($A2="/01/";$S2="=MÊS($A2)";"errado"). Eu gostaria que a fórmula fizesse o seguinte, caso na célula A2 conter o mês de janeiro (independente do dia e ano) insira na célula S2 a fórmula =MÊS(A2), caso de errado insira ERRADO, porém na célula A2 da minha planilha contém a data 12/01/2018, porém ele esta retornando na célula S2 o valor "ERRADO".
Answer: A sua sintaxe da fórmula =SE() está errada.
Insira a seguinte fórmula em S2:
=SE($A2="";"";SE(MÊS($A2)=1;TEXTO(MÊS($A2);"mmmm");"errado"))
A função =MÊS() retorna o mês de uma data em formato numérico, então é necessário converter para o mês em texto com a função =TEXTO().
E quando a célula está vazia, o Excel entende que é janeiro, então é necessário adicionar uma condicional para verificar se a célula A2 está vazia.


How to get the "real-time" updates from an android mobile phone's clock?

Question: I am creating an alarm clock application and I would like to have a small text-based representation of the actual time in "hh:MM:ss am/pm" format that would be in sync with the actual time of the mobile phone.
I tried searching around but nothing seemed to help me. Any thoughts?
Answer: System.currentTimeinMillis() will give you the current real time accurately.
Then use a handler to trigger an update to your UI every second.
Answer: As of Android 4.2 (v17), you can use TextClock to provide a formatted, always up to date text representation of the current time. For previous versions, you would need to create your own widget that controls updating the time (the TextClock source may prove helpful).


Formula for the ratio $\frac{\Gamma\left(n + \frac{1}{2}\right)}{\Gamma(n + 1)}$ of two values of the Gamma function

Question:
Show that $$\frac{\Gamma\left(n + \frac{1}{2}\right)}{\Gamma(n + 1)} = \frac{1 \cdot 3 \cdot \cdots (2 n - 3) (2 n - 1)}{2 \cdot 4 \cdot \cdots (2 n - 2) \cdot 2n} .$$

I have proved that $$\Gamma\left(n + \frac{1}{2}\right) = \frac{1 \cdot 3 \cdot \cdots (2 n - 3) (2 n - 1) \sqrt{\pi}}{2^n} \qquad \textrm{and} \qquad\Gamma(n+1) = n! ,$$
but when I divide, I am not able to proceed. Could you please help me?
Comment: I've taken the liberty of formatting the post using MathJax. Please make sure it preserves the intended meaning. In particular, (1) the identity seems to be missing a factor of $\sqrt\pi$, and (2) the last equation in the original post was nonsensical; you might like to reinstate a corrected version.
Comment: The statement is false, as @Travis points out. Check it for $n=1$: $$\frac{\Gamma(3/2)}{\Gamma(2)} = \frac{\sqrt{\pi}}{2} \neq \frac{1}{2}$$ Missing a $\sqrt{\pi}$ somewhere?
Comment: (Once you put that $\sqrt{\pi}$ back, what you have proven gives the result. Simply note that $$2^n n! = 2^n \prod_{k=1}^n k = \prod_{k=1}^n (2k) = 2\cdot 4\cdot 6\cdots (2n-2)\cdot 2n$$ to conclude)
Comment: Please see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: $\Gamma(n+1/2)/\Gamma(n)$ really **is** a rational multiple of $\sqrt\pi$ for $n\in\Bbb N$.
Comment: I did downvote. please use true format for your post to make it readable!
Answer: You may

Define $f(n)$ as $\frac{\Gamma(n+1/2)}{\Gamma(n+1)}$ and $g(n)$ as $\frac{(2n-1)!!}{(2n)!!}$
Compute $\frac{f(n+1)}{f(n)}$ (via $\Gamma(z+1)=z\,\Gamma(z)$) and $\frac{g(n+1)}{g(n)}$, then check they are equal
Compare $f(1)$ with $g(1)$ to derive that $f(n)$ is a constant multiple of $g(n)$ for any $n\in\mathbb{N}^+$.


A doubt in Probability essentials by Protter

Question:
Why is the first inequality valid(In part (v))? I mean I know that we can show that if $X \in L^2 \implies X \in L^1 $ by using Holder's Inequality.
This inequality does not make any sense to me howsoever. I would be grateful if someone could explain me why!
Thanks
Comment: What is the definition of $p_{\omega}$? Is $\Omega$ a countable space here?
Comment: $p_{\omega}=P(\{\omega\}), \omega \in \Omega$
Comment: the probability is defined on a countable space, where $p_{\omega}$ is the probability of each atom
Comment: X is an indicator function so no absolute values are necessary, yes? It's 0 or 1.
Answer: It seems, at least to me, that taking the absolute values off there after the first inequality is not necessary, or maybe not even desirable. Note that $\Omega=\{\omega:|X(\omega)|<1\}\cup\{\omega:|X(\omega)|\geq 1\}$ and these sets are disjoint, so the sum is only divided to two different parts there. In more detail:

In the first inequality he divides the sum over those two disjoint sets. You can keep absolute values here on both sums on the right and we have an equality instead of an inequality.
Then he uses the estimate on $|X(\omega)|<1$ in the first sum of the second inequality by replacing $|X(\omega)|p_{\omega}$ with $p_{\omega}$, and in the second sum as $|X(\omega)|\geq 1$ then $|X(\omega)|\leq |X(\omega)|^{2}$.
He omitted this step but in the second inequality he finally replaces the sum over a subset of $\Omega$ by sum over the whole $\Omega$ in both sums.
Comment: @jdods: $X$ is an indicator function in part $(v)$ and this seems to be a discontinuation of it, and rather a general statement. In either case it makes no difference, if one leaves the absolute values the argument goes through with same steps.
Comment: But then why use an inequality, it should be an equality with the absolute value of $|X(\omega)|$?
Comment: @user3503589: There is probably a mistake in the print. What is certain is, that once you leave the absolute values you have an equality, and he is, essentially, arguing that if you drop the absolute values the estimate grows. Which seems to be false. But you can keep the absolute values and the argument goes through.
Comment: Okay and the second inequality is clear . Thank you Thomas for the swift reply
Comment: Isn't it important that X is an indicator function?
Comment: @jdods Those two are not related I guess
Comment: @user3503589: You're welcome.
Comment: Ok op seemed to think the inequality was part of part v. Hard to tell without more context.
Comment: What if X takes negative values? Nvm, I see. Must be a typo.


Atualizar o restante de uma tabela a partir dos dados contidos em uma linha

Question: A figura abaixo explica bem o que quero tentar fazer (e o que tentei fazer mas não deu certo):

Ou seja, preciso atualizar algumas linhas de uma tabela com os mesmos dados contidos em uma linha (especificamente, as colunas bankId, proj_day e liq_day, em vermelho na figura acima). Reparem que a coluna id é igual à coluna entryID das demais linhas que precisam ser preenchidas (em verde na figura acima). A query que montei não deu certo e há centenas de dados como esse que precisam ser atualizados dessa forma.
Alguém saberia me dar uma luz? Obrigado!
Comment: A imagem é uma boa ilustração, mas inclua o código do seu sql em formato texto
Answer: Achei curioso não ter funcionado, apesar de na querie  estar declarado com dois bancos distintos, na sua pergunta não deixou claro se precisa fazer isso relacionando duas tabelas em bancos distintos ou se poderia montar com um auto relacionamento dentro da mesma tabela em apenas uma base de dados. Então peguei o seu exemplo e montei uma tabela de teste como abaixo:

Deixei com o valor default null os campos que deveriam ser atualizados em seguida construi a querie:
<code> UPDATE flux AS A INNER JOIN flux AS B ON A.entryId = B.id
 SET
     A.proj_day = B.proj_day,
     A.liq_day = B.liq_day,
     A.bankId = B.bankId
 WHERE A.userid = 307 AND A.entryID > 0
</code>
Montei um auto-relacionamento seguindo a sua querie, a diferença é que a querie acima relaciona ela com ela mesmo (auto-relacionamento) pelo campo entryID e id.
Em seguida rodei a querie e funciona perfeito como imagem abaixo:

O que eu acho que está errando é que está utilizando dois bancos de dados distintos, possivelmente criou uma nova base para não afetar os dados que estão sobre produção e para ter um ambiente de testes. Como não especificou o erro, em sua pergunta, ficou difícil de te ajudar mais. Utilizando o auto-relacionamento acima funcionaria perfeito!
Comment: Você está certo! Na verdade a query estava correta e não precisava eu ter duplicado a mesma base de dados para fazer o inner join (de fato, esqueci de mencionar isso na pergunta). Além do mais, eu estava com a visão do banco de dados que não recebe a atualização. Que bagunça a minha... Muito obrigado pelo esclarecimento!


Remote administration for Mac OS X?

Question: I've inherited a Jenkins cluster of six Macs, all of which sit in a server room and are accessible on the internal network only, but have a shared admin user and VNC password for Mac OS X (To clarify: Jenkins software access controls are sorted, I'm not asking about that).
I'm not a devops or a network admin; I'm working under a few company policy constraints and I'm only filling in the role "temporarily" (read: part time, for maybe up to a year). But I would like to clean this up with the limited time I have available. Because my time and experience, in this area is limited, I delegate some admin tasks to 3 other people as needed. I want a solution that will stay between those people, and to not share a single password between them all, because users sharing an account/login is against my company policy (despite it happening now).
It would be great to have network user logins, but given that this is not set up, I am thinking of creating local accounts for each admin with VNC access (through standard Mac OS X Screen Sharing). However, I'm worried about 4 GUI sessions being run in a machine that is meant to be crunching away for us. Will this cause problems or session time outs or the like?
What are my options here, and what would be a common approach when you need 6 admins to have VNC access, but individual passwords/accounts?
Answer: Open Directory (Apple's LDAP implementation) is probably what you're looking for.
If you don't want to be bothered setting that up, yes, local accounts for each admin on each server would work... but that would be 24 accounts to set up, so it seems like setting up LDAP would be quicker and easier.
If you're married to VNC, many implementations allow LDAP-based authentication, though personally, my feeling would be that if you need the GUI to administer a server, you have no business administering a server, so here's SSH.
As to the CPU load with VNC, it shouldn't be high enough to make a significant difference (usually a few % at most), though I'd still prefer offering SSH access only, unless I got a really compelling reason for why the admins need a GUI.  In the case that a GUI is required, it's probably worth looking into RDP as an option as well.

Remote administration for Mac OS X?


fmt:formatNumber throws exception if number has length >= 20 digit?

Question: I have a currency field which has length > 20 digit
E.g : 99999999999999999999
and when i used:
<fmt:formatNumber
     value="${crudShipmentForm.invoiceVat}"
     pattern="###,###,###,###,##0.000"  />

I received NumberFormatException ?
How can I format this field to currency using fmt:formatNumber ?
Answer: You've exceeded the maximum value of long which is 9223372036854775807.
This indicates that you're using String to hold the number instead of BigDecimal or BigInteger. It's not only technically the wrong type, but EL will also coerce it to long. Fix it accordingly.
private BigDecimal invoiceVat; // And fix getter/setter as well.

or if you really cannot change the type for some odd reason, do it in the getter
public BigDecimal getInvoiceVat() {
    return new BigDecimal(invoiceVat);
}

Answer: You can not use NumberFormat for numbers bigger than Long.MAX_VALUE. You should use DecimalFormat instead of NumberFormat class.
Comment: We're talking about JSP, not Java, and I don't know of a JSP DecimalFormat tag, at least not in JSTL
Answer: Your number is too large.
Here's the relevant code from FormatNumberSupport:
if (input instanceof String) {
    try {
    if (((String) input).indexOf('.') != -1) {
                // String value is interpreted as a double
        input = Double.valueOf((String) input);
    } else {
                // String value is interpreted as a long
        input = Long.valueOf((String) input);
    }
    } catch (NumberFormatException nfe) {
    throw new JspException(
                Resources.getMessage("FORMAT_NUMBER_PARSE_ERROR", input),
        nfe);
    }
}

Your number is way beyond the scope of long
Answer: I presume you want to format the integer digits in thousands, in which case using the pattern="###,##0.000" should do the trick.


How do I access a child element in a TemplateRef variable?

Question: I have a component that includes a modal. The modal is wrapped in a <ng-template> tag.
<ng-template #modalm let-modal>
...
   <button type="button" (click)="onSubmit()" class="btn btn-primary">OK</button>
...
</ng-template>

This allows me to open and close the modal from my component.ts file.
constructor(private modalService: NgbModal,
    private activeModal: NgbActiveModal)
...
public openModal(modalm: TemplateRef<any>){
    this.activeModal = this.modalService.open(modalm);
    const btn = modalm.elementRef.nativeElement.querySelector('.btn-primary');
  }

I would like to access the button element and set a property on it. I am following the accepted answer in How do I find Element inside TemplateRef, calling querySelector off of modalm.elementRef.nativeElement. This gives me an error:
TypeError: modalm.elementRef.nativeElement.querySelector is not a function

Why am I not able to call querySelector in this case?
I understand that I have to use the type TemplateRef due to the modal being wrapped in ng-template. What is the correct syntax for accessing an element in the modal?
Comment: You should avoid rely on `.querySelector`. Why don't you try to pass the needed option through `NgbModalRef#componentInstance` instead?
Comment: @developer033 I could create a separate component for the modal. Is this required or can I access the html element from the component.ts file of that component?
Answer: This video from Max NgWizard pointed me in the right direction. For a TemplateRef instance there isn't a way that I could find that allows ts access to the DOM such that a button property can be set. As the comments indicate, setting element properties in a ts file is also not recommended practice. It is better to put a directive like ngClass in the html markup and look for a flag in the ts file. A class in the component css file can be created for this purpose.
First I create a class ".myClass" with the style properties I need in the component css file. Then I can put a conditional directive on my button to add this class, like
<button type="button" (click)="onSubmit()" class="btn btn-primary" [class.myClass]="loadComplete">OK</button>

The boolean loadComplete controls the application of the css class from within the ts file.
The css class needs the !important statement added to override Bootstrap style definitions in my case.
.myClass {
    outline: none;
    border: none !important;
    -webkit-box-shadow: none !important;
    -moz-box-shadow: none !important;
    box-shadow: none !important;
    color: red !important;
  }


Angular AUTH Guard not working when waiting for API response

Question: I am using AUTH Guard in my angular application. It is working properly. But when I am waiting for API response, The referenced page does not load. My API is working properly. Is there any timeout issue in AUTH guard or some other problem? Please help.
in my memberDetails-routing.module:
 const routes: Routes = [
        {
            path: '', component: MemberLayoutComponent,
            children: [
                { path: 'members', component: MemberListComponent , data: { roles: ["SuperAdmin"] }, canActivate:UserAuthGuard] }]
        }];

in my member-auth.guard.ts:
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

   return true; // Here it is working properly and members page is loaded

   this.apiService.getMemberSettings().subscribe((response: any) => {
       return true; // Here API is returning response but members page is not loaded

   }
}

Answer: canActivate will not wait for subscribe response. just return
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.apiService.getMemberSettings();
   }
}

in canActivate you should return Observable/Boolean/Promise
Docs: https://angular.io/api/router/CanActivate


Erro ao instalar Magento no Windows 10

Question: Para sempre nos 50%. Alguém da uma luz??
Module 'Magento_Directory':
Installing data...
[ERROR] PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'AD' for key 'PRIMARY' in...
Answer: A resposta está na própria mensagem de erro:

Integrity constraint violation: 1062 Duplicate entry 'AD' for key 'PRIMARY' in...

Você tem uma tabela que possui um campo com restrição de unicidade ("unique key"), e o instalador tenta inserir na tabela um registro com um valor já existente.
Reveja seu instalador, ou remova a entrada que possui o valor repetido, e tente instalar novamente.
Comment: Cara.. eu tava fazendo coisa errada aqui.. já tinha apagado o banco, mas o banco errado. Instalei duas versões de mysql, por isso não tava dando certo... mas valeu!

Erro ao instalar Magento no Windows 10


how to use mock in webdriverIO to send response as string

Question: I have a POST API that returns the response as a string.
when I tried mocking as browser.mock('**/validate').respond('SUCCESS', { statusCode: 200 });
It's not getting mocked instead original API is hit
Can someone help me in this??.
Answer: Have you tried using WireMock Service?
More info: https://webdriver.io/docs/wdio-wiremock-service/


Is every definite integral unique up to change of variable?

Question: Given a definite integral $$I=\int_a^b f(x)\text{d}x$$ for some function $f$, we can make any number of substitutions $x=u(x)$ which produce symbolically new integrals, all of which evaluate to the same value.
My main question is this: is it possible to have two definite integrals both of which give the same value yet each of which can not be transformed (i.e. made to look the same symbolically) into the other by substitution?
I get the impression the answer to my question is YES, but I'm not sure. Is there any information or theory out there that deals with this? How can we know when the transformation can not be done (if indeed it cannot be done)?
Comment: Ok here's one that definitely provides a counterexample. Take $\rho$ to be a smooth function that vanishes in some interval $[0,a)$, with $0< a< 1$, and such that $\int_{0}^1\rho(x)\,dx = 1$. Now assume that we can find a substitution $u(x)$ such that $\rho(u(x)) \,du(x) = dx$ and $u(0) = 0$, $u(1) = 1$. This means that $\rho(u(x))u'(x)$ is identically $1$. But $\rho(u(x))$ must vanish in a neighborhood of $0$, so $\rho(u(x))u'(x)$ must vanish there too; this is a contradiction.
Comment: Given any two definite integrals, you can multiply by constants to produce integrals that are equal.
Comment: What are the rules of the game here? That is, what types of algebraic manipulations do you want to consider?
Comment: @orlandpm I'm just thinking of any algebraic substitution for the variable of integration.
Comment: @DavidMitra +1, although I wanted to consider "non-trivial" substitutions which exclude multiplication by constants.
Comment: That's not what I meant to suggest. If it were true that equal integrals can be transformed into each other via substitution, then any two integrals could be transformed into each other, after multiplying one of them by an appropriate constant.
Answer: The two definite integrals
$$\int_0^\infty \sin(x^2)dx=\frac{\sqrt{2\pi}}{4}$$
and $$\int_0^\infty \cos(x^2)dx=\frac{\sqrt{2\pi}}{4}$$
are equal, but I know of no substitution which shows they are.
Comment: I don't see immediately why there shouldn't exist such a substitution. Do you have a proof?
Comment: I don't have a proof. I did try to show these were equal using not only substitutions, but anything I could think of to work on the difference of the two integrals, without using contour integration. Nothing I tried like this showed they were equal.
Answer: Let's start with the good-old unit semi-circle:
$$I_1=\int_{-1}^{1} \sqrt{1 - x^2}\text{d}x = \frac{\pi}{2}$$
Now let's add a fancy triangle:
$$I_2=\int_{0}^{1} \pi{x}\text{d}x = \frac{\pi}{2}$$
And, finally, a constant for good measure:
$$I_3=\int_{0}^{1} \frac{\pi}{2}\text{d}x = \frac{\pi}{2}$$
Hey... what did you expect? It's 1:00am.
Comment: We can convert $I_2$ to $I_3$ by the substitution $x = u^{1/2}$ in $I_2$. I don't think $I_1$ can be converted to $I_3$, but (unless I'm being dumb) this still requires proof.
Comment: You're, of course, absolutely right. I think what I meant to say was that you cannot convert $I_1$ to either $I_2$ or $I_3$ and it just came out wrong. As I said, 1:00am. That's my excuse and I'm sticking to it!
Answer: Note that, $$\int_0^{\pi /2}\cos x dx=1=\int_0^{\pi/2}(2/\pi)dx$$ Now for any substitution $x=u(x)$ we have $$\int_0^{\pi /2}\cos x dx=\int_0^{\pi/2}\cos (u(x))u^\prime(x)dx$$ So we should have, $2/\pi=\cos (u(x))u^\prime (x)$ which can not be true, because the LHS is constant but the RHS is not.
Comment: This doesn't completely satisfy me. Why is it clear that we can't solve $u' = 2/(\pi \cos{u})$ on $(0,\pi/2)$, subject to $u(0) = 0$ and $u(\pi/2) = \pi /2$? Obviously we'd have to let $u'$ be infinite at $1$, but that might not be out of bounds.
Comment: On second thought, we can solve $u' = 2/(\pi \cos{u})$ pretty easily. Take $u = \arcsin(2x/\pi)$. Then $u(0) = 0$ and $u(\pi/2) = \pi/2$, and also, since $\sin\circ u(x) = 2x/\pi$, the chain rule shows that $u' = 2/(\pi \cos{u})$.


Como achar o menor valor de uma matriz em lua?

Question: Eu fiz esse código que faz uma Matriz (Pelo menos eu acho que está fazendo) e depois escreve todos os valores nela. obs: Os valores são aleatórios.
Preciso encontrar o menor valor da matriz, mas a lógica que usei sempre me dá um resultado previsível.
Exemplo: Digamos que o range do invertalo é dado por x e y. Sendo x o menor valor que pode ser assumido e y o maior.(No código x=0 e y=2500).No código, o valor da variavel menor está sempre dando x + 2, ou seja, no meu código a variavel menor está sempre resultando no valor 2. Se eu definir o menor valor do range como 5, por exemplo, no final o valor da variável menor será 7.(x=5, x+2 = 7)
<code>matriz={}
for l=1,20 do
    matriz[l]={}
    for c=1,40 do
        matriz[l][c] = math.random(0,2500)
    end
end
menor = matriz[1][1]--Inicia na menor posição possivel
for i=1,20 do
    for j=1,40 do
        print("O valor na Linha:"..i.." Coluna:"..j.." é "..matriz[i][j])
        if matriz[i][j]<menor then-- essa parte deveria encontrar o meno valor
            menor = matriz[i][j]
        end--Final
    end
end
print("O menor valor encontrado é:"..menor)
</code>
Esse é o código que fiz, como estou começando, não estou entendendo onde está o erro dele.
Comment: ao bater o olho no código notei essa linha `menor = matriz[1][1]`, inicie sua variável `menor` com um número infinito ou que seja maior do que o range dos número randômicos inseridos
Comment: Eu iniciei a variável menor com o valor acima do range dos números randômicos e o problema persistiu.
Comment: `Se o intervalo dos números sorteados é 0 e 5, no final a variável Menor irá conter o valor 0 + 2, ou seja 2.` ??? não entendi ....
Comment: Eu dei uma melhorada no exemplo. Curto e grosso: O valor da variável menor é sempre o valor minimo do range mais 2.
Comment: humm isso é um problema do lua em algumas plataformas, as vezes ele gera sempre as mesmas sequencia, antes do `math.random` insira `math.randomseed(os.time())`
Comment: Agora que notei que ele realmente está gerando os mesmo valores sempre. No caso o problema está na plataforma, correto?(Minha preocupação é saber se a lógica está errada)
obs: Estou usando o Scite pra compilar.
Eu não entendi a parte de inserir o randomseed antes, poderia ser um pouco mais específico?
Comment: a lógica esta correta, não esqueça de sempre iniciar sua variável menor  conforme indicado no meu primeiro comentário ...
Answer: Como sugerido pelo @ederwander, faltou colocar um comando para preparar a geração de números pseudo-aleatórios. Fora isso sua lógica está correta.
<code>#!/bin/lua

math.randomseed(os.time()) -- faltava isso

matriz = {}

for l=1,20 do
    matriz[l] = {}
    for c = 1,40 do
        matriz[l][c] = math.random(0,2500)
    end
end

menor = matriz[1][1] -- Inicia na menor posição possivel

for i = 1,20 do
    for j = 1,40 do
        print("O valor na Linha:"..i.." Coluna:"..j.." é "..matriz[i][j])
        if matriz[i][j] < menor then -- essa parte deveria encontrar o meno valor
           menor = matriz[i][j]
        end -- Final
    end
end

print("O menor valor encontrado é:" .. menor)
</code>


Exclude destination files/directories form robocopy?

Question: I have a deploy process that is currently using this robocopy command:
robocopy [source] [destination] /MIR /XF [file pattern] /XD [directory pattern]
The [destination] may have additional files or directories added to it outside this process that the [source] does not. The /MIR flag is present because if I add files or directories to [source] I want them to appear in the [destination]. Also, if I remove a file/directory from [source] that exists in [destination] I want to remove that from [destination].  However, this will also remove any of the new files/directories that may have been added to [destination].
The /XF and /XD flags appear to only restrict the source files/directories. Is there a corresponding way to exclude destination files from the copy? Something to indicate "When doing \MIR don't delete directories starting with the string 'new'," for example.
Answer: Should have run more tests before asking. It appears that amending the command to be:
robocopy [source] [destination] /MIR /XF [file pattern] /XD [source directory pattern] "new*"
Does, in fact, ignore directories in the [destination] that have "new" as the start of their name.


Bind to error event of a model created by collection.create()?

Question: I have a collection of Comments and a view which is used to create new comments. Each comment has some client side validation going on:
class Designer.Models.Comment extends Backbone.Model

  validate: (attrs) ->
    errors = []

    # require presence of the body attribte
    if _.isEmpty attrs.body
      errors.push {"body":["can't be blank"]}

    unless _.isEmpty errors
      errors

The Comments collection is super simple:
class Designer.Collections.Comments extends Backbone.Collection
  model: Designer.Models.Comment

I create comments in the NewComment view. This view has access to the comments collection and uses it to create new comments. However, validations fails in the Comment model don't seem to bubble up through the collection. Is there a batter way to do this?
class Designer.Views.NewComment extends Backbone.View
  events:
    'submit .new_comment' : 'handleSubmit'

  initialize: ->
    # this is where the problem is. I'm trying to bind to error events
    # in the model created by the collection
    @collection.bind 'error', @handleError

  handleSubmit: (e) ->
    e.preventDefault()
    $newComment = this.$('#comment_body')

    # this does fail (doesn't hit the server) if I try to create a comment with a blank 'body'
    if @collection.create { body: $newComment.val() }
      $newComment.val ''
    this

  # this never gets called
  handleError: (model, errors) =>
    console.log "Error registered", args

Answer: The problem is that the collection event that aggregates all of the model events hasn't been hooked up yet.  That hookup happens in the _add() function.  Since the validation fails before the model gets added, you don't get the event.
The only indication of failure happens when create returns false but it looks like you've figured that out already.
If you need the validation errors, you will need to come up with a way to get the errors to you.
One way would be to fire off an EventAggregator message inside the validator.  The other would be to circumvent or re-define the Collection.create function to hook the error event on the model.
Something like this?
model = new Designer.Models.Comment()
model.bind "error", @handleError
if model.set body: $newComment.val()
    model.save success: -> @collection.add(model)


show $ x \to (x,f(x))$ is an embedding

Question: Let $f:\mathbb{R}^n \to \mathbb{R}^m$ be ca continuous function and $(\mathbb{R}^n,\mathcal{O}_{\mathbb{R}^n}) $ the real numbers equipped with the euclidian topology.  Why the map $F:\mathbb{R}^n \to \mathbb{R}^{m+n}$ with $ x \to (x,f(x))$ is an embedding?
Of course $F$ is naturally injective and F is also continuous. But it's not clear to me why the map $F: (\mathbb{R}^n,\mathcal{O}_{\mathbb{R}^n}) \to (F(\mathbb{R}^n),\mathcal{O}_{\mathbb{R}^{m+n} | \mathbb{R}^n})$ is open? Where $\mathcal{O}_{\mathbb{R}^{m+n} | \mathbb{R}^n}$ is the subspace topology from $\mathbb{R}^n$ in $\mathbb{R}^{m+n}$.  Can someone give me a little hint?
Answer: It is easier to show that it is closed.
Indeed, let $A$ be closed in $\mathbb{R}^n$. We will show that $F(A)$ is closed. Pick any convergent sequence $(X_n)$ in $F(A)$. Obviously $X_n=(x_n, f(x_n))$ for some sequence $(x_n)$ in $A$. Since $X_n$ is convergent, then so is $(x_n)$ because projection to the first coordinate is continous. Since $A$ is closed then $(x_n)$ converges to $x\in A$ and since $f$ is continous then $f(x_n)$ converges to $f(x)\in f(A)$. Therefore $(x_n, f(x_n))$ converges to $(x, f(x))\in F(A)$ so $F(A)$ is closed.
Thus $F$ is both closed and bijective on image. Therefore it's an embedding.

show $ x \to (x,f(x))$ is an embedding


Is this an expected behavior of an ARIMA(0,0,4,1,1,1)

Question: I have data of daily sales and want to make a forecast in SPSS modeler, however I'm getting a result that I can't explain. The plot is inserted below. The fit is the red line and the blue is the historical actual sales. So the forecast starts where the red line ends.
Looking at information regarding the fitted model, we observe that the model is an $\text{ARIMA}(0,0,4)$ which is equivalent to $\text{MA}(4)$, thus our model in a mathematical form is given by the stochastic process
\begin{equation}
 X_t = \mathbb{E}[X_t] + \epsilon_t+\sum_{i=1}^{4}\theta_i\epsilon_{t-i} = \mathbb{E}[X_t]+\epsilon_t + \theta_{1}\epsilon_{t-1}+\theta_{2}\epsilon_{t-2}+\theta_{3}\epsilon_{t-3}+\theta_{4}\epsilon_{t-4}
\end{equation}
where $\epsilon_t,...,\epsilon_{t-4}$ are white noise error terms and $\theta_1,...,\theta_4$ are the parameters to be tuned.
Question: Is there an explanation for the horrible forecast using the equation above or does it possibly depend on something else?
NOTE: I do understand that fitting an ARMA model to seasonal data might not be ideal and that this types of models are not optimal for long term forecasting (I do use neural prophet instead that works very good) but I'm trying to understand how SPSS modeller works and if I've made a mistake in setting the parameters in SPSS or if the below is actually a reasonable result to expect given the mathematics.

EIDT: Following the answer of Richard Hardy, I removed the seasonal differencing. Now the result is simply constant with not only constant mean but also with zero variance:
Comment: Hi Richard, my sincere apologies I really thought I had already accepted it, but I apparently only upvoted it. Your answer was perfect and thank you very much!
Comment: No problem at all!
Answer: I think it is as expected. This is a result of seasonal differencing. The effects of the MA, SAR and SMA components die out over time, and the forecast converges to one where each season has its own constant forecast. Asymptotically (in terms of a growing forecast horizon), it is as if your time series consists of $m$ independent random walks where $m$ is the number of seasons. The optimal forecast for each of them is the last observed value. These constants alternate as the seasons do.
I would consider a model without seasonal differencing instead. If you want to maintain some seasonal variation in the forecast, consider regression with ARMA errors where the regressors are seasonal dummies or Fourier terms. That would give you something similar to your original forecast but smoother (in case of Fourier terms) and on a different level. Perhaps relevant: Rob J. Hyndman "Forecasting with long seasonal periods" (2010).
Comment: Thank you for the answer. I removed the differencing and the result is now an ARIMA(0,1,8). The forecast is just constant. Please check my edit.
Comment: @Parseval, yes, that is what you expect from ARIMA(0,1,8). The forecast becomes constant after the first 8 periods. If you want to maintain some seasonal variation in the forecast, consider regression with ARMA errors where the regressors are seasonal dummies or Fourier terms. That would give you something similar to your original forecast but smoother (in case of Fourier terms) and on a different level. How many seasons are there? Perhaps relevant: https://robjhyndman.com/hyndsight/longseasonality/
Comment: Why do the forecasts become constant after 8 periods? I can't understand why by looking at the ARIMA equation. I'm simply adding 8 terms that are multiplied with noise. That Fourier solution was neat! I assume that's not possible to implement in SPSS modeler then but needs to be done manually in R/Python. Thanks!
Comment: @Parseval, check out some textbook material on forecasts from MA(q) models. You will see that the first q forecasts (1 step ahead, 2 steps ahead, ..., q steps ahead) vary but after that the forecasts stay constant. I have no experience with SPSS for time series forecasting, but I do no think SPSS offers much in that regard. It is mostly suited for other types of data and analyses.


Combinatorics problem that deals with trigonometric functions

Question:
If $m$ and $p$ are positive integers and $m \geq p$, then show that
  $${m \choose 0}+{m \choose p}+{m \choose 2p}+{m \choose 3p}+\cdots$$
  has value $${2^m \over p}\left(1+\sum_{k=1}^{\left \lfloor {p-1 \over 2} \right \rfloor}{{\left( \cos{k\pi \over p}\right)}^m \cos{mk\pi \over p}}\right)$$

I have no idea how to approach this problem. I cannot find a way to express combinatorial arguments using trigonometric functions. It'd be great if someone can give me any hints.
Comment: I would try looking at something like $$\sum_{i=0}^{p-1}(1+\zeta^i)^m$$ where $\zeta=e^{2\pi i/p}$.
Comment: You can use `\left` and `\right` with `\lfloor` and `\rfloor` to make them adapt to their content.
Comment: @joriki Thanks. Corrected that.
Answer: With $\zeta=e^{2\pi\mathrm i/p}$ as Gerry suggested,
\begin{align}
\sum_{l=0}^{\left\lfloor\frac mp\right\rfloor}\binom m{lp}
&=\sum_{j=0}^m\binom mj\frac1p\sum_{k=0}^{p-1}\zeta^{jk}\\
&=\frac1p\sum_{k=0}^{p-1}\sum_{j=0}^m\binom mj\zeta^{jk}\\
&=\frac1p\sum_{k=0}^{p-1}\left(1+\xi^k\right)^m\\
&=\frac{2^m}p\sum_{k=0}^{p-1}\left(\cos\frac{k\pi}p\right)^m\mathrm e^{mk\pi\mathrm i/p}\\
&=\frac{2^m}p\left(1+2\sum_{k=1}^{\left\lfloor\frac{p-1}2\right\rfloor}\left(\cos\frac{k\pi}p\right)^m\cos\frac{mk\pi}p\right)\;,
\end{align}
so I think you were missing a factor of $2$ before the sum.
Comment: @SayantanSantra: Sorry, yes -- all those upper limits were supposed to be $p-1$. Fixed. Does that resolve your question about the first line?
Comment: @SayantanSantra: The $1$ is the $k=0$ term. It's the only one that doesn't form a pair. Note that if $p$ is even, the $k=\frac p2$ term also isn't paired, but in this case $\cos\frac{k\pi}m=\cos\frac\pi2=0$.
Comment: I cannot understand the very first line.
Comment: I think the upper limit of the second sum on the first line should be $p-1$.
Comment: Yeah. Now it's clear. Thanks for this briliant answer.
Comment: Yeah. Got that.
Comment: Just FYI, [it's probably not an old contest](http://stackoverflow.com/questions/36808913/shortest-path-in-a-weighted-graph-with-coloured-edges). But I didn't find a source.


Why do German football clubs have a number in their name?

Question: I am not referring the year of creation, which it seems German are very proud of (FC Schalke 04, Hannover 96).
Why do some 1.Bundesliga or 2.Bundesliga teams have the number one and a dot: 1.
Here are a few notable examples: 1. FSV Mainz 05, 1. FC Nürnberg, 1. FC Köln, 1. FC Union Berlin...
Answer: According to this article on the the Bundesliga's website:

Germans are traditionally sticklers for accuracy and they're no different when it comes to football. As a general rule of thumb, if you see a '1.' in front of your team's name that's because they want you to know they were the first such club to be founded in their city. Similarly, any other numbers that feature (usually at the end) demonstrate the club's pride in their historical roots by flaunting the year they came into existence.


Are there common situations that cause a "401 Error" being displayed without a login dialog being displayed first?

Question: Perhaps this is a somewhat broad question, but I am currently relying on shots in the dark ...
We sometimes provide access to some web URLs (running Apache 2.4) protected by basic password protection.
I have never seen it myself, but every now and then I hear from external users that they are immediately seeing a 401 Unauthorized error. While it is true that the server reply is by design a 401 error code, it is also accompanied by a www-authenticate header, and this should trigger a login dialog at the user's end (where they should enter the credentials we gave them). In the cases in question, it is reported that no login dialog appeared. Unfortunately, I never have direct contact with the affected external users that would allow me a deeper analysis.

Does there exist a somewhat common browser that does not understand the www-authenticate machanism?
CanIUse surprisingly
suggests that Sfari and Opera are problematic - however I just made a
successfull test with one of them.
Do there exist other common obstacles, e.g., firewall policies that rigorously strip the needed http headers?
Any other ideas what could be going wrong in these cases, or what I could test?

EDIT: Regarding things that were suggested for consideration:

The URLs in question are https: (may I say - of course?)
The problems occur with first-time users, i.e., they never get "in" in the first place. (Nevertheless, my understanding would be that a cached wrong password is supposed to trigger the dialog for the user to try again). This also seems to rule out password manager problems
I doubt that the affected users have settings in place that make them automatically try their windows credentials or other automatic logins with (to them) foreign internet hosts.
Comment: Chromium will purposefully not support *basic auth* popups if the header is loaded on a sub-resource that does not match origin. You can tell whether someone is accessing your site embedded somewhere by logging *refer(r)er* and *fetch metadata request headers*.
Comment: The specifics are fixed, but the general bug class of related issues I found long ago might still apply: bad client UI was always triggered with **unusual entry points**, e.g.: the first 401 response being received by the built-in PDF viewer, the target of an POST form (re-submitted from an old browser tab), a non-canonicalized `https://email@example.com/fileslash/` URL being the result of my link being modified by the recipients MUA. You might make some progress by a) looking at what were the first two requests per IP and b) special-casing empty passwords.
Comment: Does your `realm=` value contain any funny characters, comma being one? Ideally, keep it simple, because parsing *almost* like the RFC ABNF is a common source of bugs ;)
Answer: A few things to try or consider:

Are you serving these pages securely? There is a GPO and Google Workspace setting that only allows basic auth using HTTPS - GPO, Chrome Policy

Do the credentials to the URLs change reasonably frequently? It could be possible the user hasn't closed/restarted their browser since their last successful login and subsequently the credential change causing the httpauth cache to be incorrect and cause the issue.

There are some auth settings in the Windows Internet Options dialog that apply to Chrome and IE that could cause an attempted automatic login.

Are there any password managers that can autofil the login dialog?

Just did a few quick tests with some online proxies and a HTTP basic auth prompt with mixed results. Some refused to load the page, some presented their own login prompt and some used the built in browser prompt. It suggests that a misconfigured proxy could cause no login prompt to appear.
Comment: All good suggestions. In my case, I believe tha tthe proxy idea is the most promising for me to have a look into.


Wix project template doesn't appear in VS2012 after installing it

Question: I have installed WiX 3.7 to create installer in VS 2012. But WiX project template is not coming in VS2012 Prof edition.
I have tried some resolution available in web, but no result.
How can I solve this?
Comment: The WiX project template (actually, a number of templates for MSI, MSM, custom action, etc.) are brought to VS by the WiX Toolset itself. If that's not the case for 3.7 version, you should file an issue: http://sourceforge.net/p/wix/bugs/
Answer: I am not sure what are you refering in Wix Project template but there are template for EXE file and MSI file. and others.
here is my VS2012 + wix 3.7 photo. it's works great by the way.
Comment: These do not appear to me either
Comment: the templates do not appear after performing installation. Tried installing and uninstalling many time
Comment: you need to install wix 3.7 http://wixtoolset.org/ the plugin for visual studio 2012 comes with the installtion
Comment: I did, there is a problem preventing some users to get Wix 3.7 installed correctly :(
Comment: what do u mean a problem?
Comment: oh well i guess you tried to restart the computer after that. so yes the wix forums are your help


Two columns on frontpage with a CCK form and a node list

Question: I want to show a simple frontpage that contains a content creation form (cck) on the left side and a list of nodes on the right side. With a head and a footer, the page looks like this:

I have looked into doing this with the Panel module, but it seems like overkill and I don't think it plays well with the grid layout I use.
I have also looked on doing this with the Views module and the Context module, but I don't really understand how I can execute the code for rendering the content creation form with this approach.
A third solution is to override the template for the page-front and hard code the rendering there, but a drawback would be that I then need to maintain multiple page templates.
So what is a good solution for this do you think? I would like to involve as little complexity as possible and my head is already spinning with all these modules for such an apparently simple problem.
Appreciate guidance from someone who is fluent with View, Context, CCK and Panels.
Answer: Administering panels has a huge overhead, however, since panels are highly cached there is actually a performance boost to use them over plain blocks. It's discussed in this article, Assembling Pages with Drupal.
If this is some type of survey or questionaire you can make the node edit form the front page by using using the site configuration feature assigning the font page path. With Views you then can create two blocks that you use to show on the right column in either the block administration page or the panels administration page. However, for surveys the standard is to use the Webform module.
Answer: You could create two block regions in page-front, and add the form and the list of nodes as blocks.


Problems executing project using jbehave in eclipse

Question: I am completely new to jbehave and even automated testing.
I read a tutorial online and tried following the steps.
I am trying to run this application in eclipse IDE.
I made a Math.story file which contains the tests:
Scenario: 2 squared
Given a variable x with value 2
When I multiply x by 2
Then x should equal 4

In a .java file called ExampleSteps.java, the steps are written:
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.steps.Steps;

public class ExampleSteps extends Steps {
    int x;

    @Given("a variable x with value $value")
    public void givenXValue(@Named("value") int value) {
        x = value;
    }

    @When("I multiply x by $value")
    public void whenImultiplyXBy(@Named("value") int value) {
        x = x * value;
    }

    @Then("x should equal $value")
    public void thenXshouldBe(@Named("value") int value) {
        if (value != x)
            throw new RuntimeException("x is " + x + ", but should be " + value);
    }
}

I created another class SimpleJbehave which has the main method:
import java.util.Arrays;
import java.util.List;
import org.jbehave.core.embedder.Embedder;

public class SimpleJBehave {

    private static Embedder embedder = new Embedder();
    private static List<String> storyPaths = Arrays
            .asList("Math.story");

    public static void main(String[] args) {
        embedder.candidateSteps().add(new ExampleSteps());
        embedder.runStoriesAsPaths(storyPaths);

    }
}

When I run this code, I get the following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/Transformer
    at org.jbehave.core.configuration.Configuration.<init>(Configuration.java:112)
    at org.jbehave.core.configuration.MostUsefulConfiguration.<init>(MostUsefulConfiguration.java:49)
    at org.jbehave.core.embedder.Embedder.<init>(Embedder.java:30)
    at org.jbehave.core.embedder.Embedder.<init>(Embedder.java:37)
    at SimpleJBehave.<clinit>(SimpleJBehave.java:8)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.Transformer
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 5 more

As I am a novice, I have not been able to understand what exactly the problem is.
It will be really nice if someone could tell me what I should do to get this code working.
Is my approach wrong?
Thank you very much in advance.
Answer: It looks like you don't have org.apache.commons.collections.Transformer on your classpath.  It looks like this class is available in the apache-commons-transformer library here: http://commons.apache.org/collections/api-release/org/apache/commons/collections/Transformer.html
Download the jar and add it to your classpath.  It might work.
Comment: I added apache-collections-commons-collections-3.1.jar, freemarker-2.3.6.jar, jbehave-core-3.0.2.jar, org.apache.commons.io.jar and org.apache.commons.lang.jar to the path.

But now, I get Failed to generate stories view in outputDirectory.
It is caused by org.jbehave.core.reporters.FreemarkerViewGenerator$ViewGenerationFailedForTemplate.

I am not sure how to deal with this? Is something wrong with the .story file that I created? Because it says, "no step is matching".

I am really new to this and have no idea at all about what I should be doing.

Thank you.
Comment: @Sathya: Did you find any solution to this problem, I am facing the same issue and I just started working on Jbehave, please let me know if there is a fix for this.

Thanks in advance!!


Why are cumulative residuals from regression on stock and index returns mean reverting

Question: In the paper

M. Avellaneda and J. H. Lee, Statistical arbitrage in the U.S. equities market, July 2008,

in the Appendix on page 44, I have some questions.
First he runs the regression of stock-return ($R_n^S$) with index/ETF-return ($R_n^I$).
$R_n^S = \beta_0 + \beta R_n^I + \epsilon_n, ~~~~~n=1,2,...,60$
Then he defines an auxiliary process $X_n$ as sum of the residuals from regression of $R_n$, and estimates it to be a mean reverting process.
$X_n = \sum_{j=1}^{n} \epsilon_j ~~~~~n=1,2,...,60$
I have two related questions?
What is the significance of taking cumulative sum of residuals as opposed to taking just residuals as a mean reverting process? I have a basic intuition but lack a good understanding.
Second, he says that the regression on stock-returns "forces" the residuals to have mean zero. Why is this? How does this imply that the sum of all residuals, $X_{60}=0$?
Comment: @user862, The sum of residuals equal to zero is a standard feature of regression with intercept. Differentiate sum of squares with respect to intercept to see why.
Answer: The significance of modeling the cumulative sum of residuals is to better approximate the Ornstein-Uhlembeck process of equation $(12)$ with discrete real-life data.
This process $X_i(t)$ represents the idiosyncratic above- or below- market fluctuations of the particular stock. More specifically, it is the difference between the stock's return and that of its industry sector (ETF). The expected value of the infinitesimal increment $dX_i(t)$ of the $X_i(t)$ process is based on the previous value of the process:
$$
E[dX_i(t)|X_i(s),s{\le}t] = {\kappa}_i(m_i-X_i(t))dt
$$
Note the $X_i(t)$ on the right-hand side, suggesting a cumulative process.
The authors approximate a stock's $X_i(t)$ process with actual market data by first regressing the stock on its industry ETF (top of p.45), and then summing the residuals up to a certain point in time. This represents the cumulative above- or below- market return of the stock before the end of the regression time window.


Is there a way to make an image of a single volume at a point in time?

Question: I have a Windows Server 2008 R2 box that I need to be able to re-image at any given point. With VMWare, is it possibly to create a snapshot or image of only a specific drive at a point in time?
Also, would this cause any performance overhead for the image to be maintained?
Comment: If this is a production machine, running off a snapshot is bad practice, just FYI.
Answer: Assuming you are using Vmware ESXi, you should just be able to right click on the instance, and create a snapshot.  It will take up the obvious disk space, and while the image is being created CPU/Disk/Memory usage.


Markov Property as given in Norris' book on Markov chains vs standard formulation

Question: In the book, Markov Chains, the following theorem is mentioned:
Let $(X_n),n≥0$ be Markov$(λ,P)$. Then, conditional on $X_m=i,(X_{m+n})_{n≥0}$ is Markov$(\delta_i,P)$ and is independent of the random variables $X_0,\dots,X_m$.
This is proved by showing that for any event A determined by $X_0,\dots ,X_m$ we have:
$P({X_m=i_m,...,X_{m+n}=i_{m+n}}\cap A|X_m=i)=\delta_{ii_m}*p_{i_m,i_{m+1}}...p_{i_{m+n−1},i_{m+n}}*P(A|X_m=i)$
I am wondering how this definition is related to the standard Markov property statement that $P(X_{n+1} | X_n, ..., X_0)=P(X_{n+1} | X_n)$ ?
Comment: Both are equivalent to memorylessness
Comment: Are they equivalent between each other?
Comment: It's a transitive thing so yes. I only understand it that handwavey way
Answer: This is based on the following equivalence:

Consider three random variables or families of random variables $U$, $V$, and $W$, then $P(U\mid V,W)=P(U\mid V)$ if and only if $(U,W)$ is independent conditionally on $V$.

To see why in the discrete case (the general case being similar), note that the first condition reads $$P(U=u\mid V=v,W=w)=P(U=u\mid V=v),$$ for every $(u,v,w)$, that is, $$P(U=u,V=v,W=w)P(V=v)=P(U=u,V=v)P(V=v,W=w),$$ or, still equivalently, $$P(U=u,W=w\mid V=v)=P(U=u\mid V=v)P(W=w\mid V=v),$$ which is the second condition.
In the context of the question, use $U=(X_n)_{n\geqslant m}$, $V=X_m$ and $W=(X_n)_{n\leqslant m}$.


AD: Unable to perform remote desktop logon

Question: For my users in Active Directory, I did setup a GPO in order to allow the remote desktop connections.
For a specific user in particular, I did also manually setup the group membership for Remote Desktop Users:

However, I still get an error while performing a remote logon, saying that the user is not allowed to login in remotely.
Do you have any clue about it?
Please just consider that Admins can correctly perform this operation, and the target machine is a generic windows server machine (no specific role yet installed, just joined to the domain).
Answer:
For my users in Active Directory, I did setup a GPO in order to allow
  the remote desktop connections.

What specifically did you configure in the GPO?

For a specific user in particular, I did also manually setup the group
  membership for Remote Desktop Users.

Did you add this user to the domain Remote Desktop Users group in Active Directory Users and Computers or did you add them to the local Remote Desktop Users on the server itself? You need to add them to the local Remote Desktop Users group on the server itself.
Comment: The GPO setting is correct but the user must also be a member of the local Remote Desktop Users group on the server itself. Add the user to the local Remote Desktop Users group.
Comment: Sure. You could use Group Policy Preferences to populate the local Remote Desktop Users group on the servers.
Comment: Yes, he could add the domain group to the local group. The point is that the user needs to be a member of the local group, either directly or as a member of another group which is a member of the local group. RDP access requires two things: User Rights and Permissions. User rights can be granted locally or via domain based GPO. Permissions can only be granted locally by making the user a member of the local group.
Comment: I added the user to the Remote Desktop User group directly in Active Directory Users and Computers. About the GPO, I did follow this guide: https://thesysadminchannel.com/how-to-enable-remote-desktop-via-group-policy-gpo/
Comment: Is there no programmatic way to do it? I am looking for is a mean to automatically grant this privilege to all users in a given OU for all computers belonging to a particular group.
Comment: Couldn't he just add the AD group to the local group? Or alternatively grant the AD group the same user rights that the local group has?


Inserir múltiplos valores com WEB API

Question: E ai meus queridos como estão? tranquilos? Vou resumir meu projeto para auxiliar no entendimento: estou criando um CRUD para me auxiliar em algumas tarefas da empresa. Tenho 3 areas as quais utilizo (System, Database e SystemDatabase). Na area System eu cadastro os sistemas aos quais eu utilizo na empresa, já na Database eu cadastro todos os bancos de dados aos quais meus sistemas podem utilizar e no SystemDatabase ficam armazenados os sistemas juntamente dos seus bancos de dados ativos. Estou utilizando Angular no frontend e WebAPI com ASP.NET e EF CORE no backend.
No meu formulário eu informo qual vai ser o sistema que irei dizer os bancos que estarão ativos pra ele, como um sistema pode se comunicar com vários bancos de dados, eu optei por utilizar um "multiple select" para listar todos os bancos que posso adicionar, veja abaixo:

O problema é que eu não sei ao certo como inserir esses dados na tabela, e do jeito que eu fiz não estou tendo o retorno desejado, pesquisei bastante a respeito porém não existe muito conteúdo abordando este assunto pela internet. Já li documentação da linguagem, documentação do framework, pedi ajuda pra um colega, pesquisei até em site indiano e não consegui encontrar muita coisa.
A minha lógica foi a seguinte: pensei em criar um array pra armazenar o Id de cada banco selecionado e ao salvar (executar o POST) ele rodar um for que fará uma verificação através de um índice e caso exista dados no array, ir adicionando no banco um por um

Pra fazer isso, fui no meu Model e criei uma propriedade que é um array de inteiro chamada de IdDatabases:
using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace ITControl.Models
{
    public partial class SystemDatabase
    {
        public int IdSystemDatabase { get; set; }
        public int IdSystem { get; set; }
        public int IdDatabase { get; set; }
        [NotMapped]
        public int[] IdDatabases { get; set; } // <============ AQUI
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string UserInserted { get; set; }
        public string UserUpdated { get; set; }

        public virtual System System { get; set; }
        public virtual DataBase DataBase { get; set; }
    }
}

E passei essa lógica pra dentro do meu controller no [HttpPost]
        [HttpPost]
        public async Task<ActionResult<SystemDatabase>> PostSystemDatabase(SystemDatabase systemDatabase)
        {
            systemDatabase.CreatedAt = DateTime.Now;
            systemDatabase.UserInserted = (HttpContext.User.Identity as ClaimsIdentity).Name;

            for (int i = 0; i < systemDatabase.IdDatabases.Count(); i++)
            {
                systemDatabase.IdDatabase = systemDatabase.IdDatabases[i];
                _context.SystemDatabase.Add(systemDatabase);
            }

            await _context.SaveChangesAsync();

            return CreatedAtAction("GetSystemDatabase", new { id = systemDatabase.IdSystemDatabase }, systemDatabase);

        }

O resultado que eu esperava, era que ele adicionasse um por um ele me retornasse algo mais ou menos nessa pegada no banco:

Mas na realidade ele não adiciona um por um, ele está jogando apenas o ultimo Id no banco:

Fui nas ferramentas de desenvolvedor do navegador, olhei a resposta que ele estava me dando no network quando fazia o Post e ele me retornou o seguinte preview:
{IdSystemDatabase: 40, IdSystem: 3, IdDatabase: 13, IdDatabases: [1, 13],…}
CreatedAt: "2020-08-25T08:54:13.5748194-03:00"
DataBase: null
IdDatabase: 13
IdDatabases: [1, 13]
0: 1
1: 13
IdSystem: 3
IdSystemDatabase: 40
System: null
UpdatedAt: null
UserInserted: "OliveiraRBru"
UserUpdated: null

Ele está recebendo os Id's no IdDatabases porém não está registrando um por um, o que eu posso estar fazendo de errado?? To realmente perdido, acredito muito que o erro esteja dentro do meu For
Comment: cara pelo tamanho da sua pergunta ela parece ser especificac do seu sistema, tenta fazer uma pergunta mais concisa e especifca de um problema
Answer: Analisando mais a fundo e consultando alguns outros colegas, consegui resolver o erro. Eu iria desfazer a pergunta, mas como vi que não existe muita coisa na internet falando a respeito disso, irei compartilhar com vocês e deixar minha contribuição á comunidade ;D
A solução a qual encontrei foi a seguinte, removi o IdSystemDatabase do meu model e do meu context, já que minha tabela no banco só seria usada para armazenar o ID do sistema e do banco de dados, logo ele se tornaria inútil e também iria ficar trazendo alguns erros, então já tratei de remove-lo.
Meu model ficou da seguinte forma:
using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace ITControl.Models
{
    public partial class SystemDatabase
    {
        public int IdSystem { get; set; }
        public int IdDatabase { get; set; }
        [NotMapped]
        public int[] IdDatabases { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string UserInserted { get; set; }
        public string UserUpdated { get; set; }

        public virtual System System { get; set; }
        public virtual DataBase DataBase { get; set; }
    }
}

Após remover o IdSystemDatabase do meu context, foi necessário passar o IdSystem e IdDatabase como chave
Coloquei o seguinte no context:
entity.HasKey(d => new { d.IdDatabase, d.IdSystem });

Passados o IdSystem e o IdDatabase como chaves no context, eu alterei algumas coisas no meu for. Primeiro eu utilizei um if para verificar se não haveriam dados repetidos ou nulos, e dentro do if passei a condição que estava anteriormente direto no for. Verificando com um breakpoint anteriormente, eu tinha percebido que estava cometendo um erro, eu não estava pedindo para salvar a inserção após verificar, ele recebia o id dentro do índice, recebia o comando pra adicionar porém não recebia nada falando pra ele salvar essa inserção e por conta disso ele adicionava no banco apenas o ultimo id passado pelo índice já que era o ultimo armazenado no IdDatabase, somente depois que ele saia do for que iria salvar, este era o erro. Logo pra corrigir isso eu passei o await _context.SaveChangesAsync(); pra dentro da condição do for ficando tudo da seguinte forma:
        [HttpPost]
        public async Task<ActionResult<SystemDatabase>> PostSystemDatabase(SystemDatabase systemDatabase)
        {
            systemDatabase.CreatedAt = DateTime.Now;
            systemDatabase.UserInserted = (HttpContext.User.Identity as ClaimsIdentity).Name;

            for (int i = 0; i < systemDatabase.IdDatabases.Count(); i++)
            {
                if (_context.SystemDatabase.Where(w => w.IdSystem == systemDatabase.IdSystem
                                                 && w.IdDatabase == systemDatabase.IdDatabases[i]).FirstOrDefault() == null)
                {
                    systemDatabase.IdDatabase = systemDatabase.IdDatabases[i];
                    _context.SystemDatabase.Add(systemDatabase);
                    await _context.SaveChangesAsync();
                }
            }

            return CreatedAtAction("GetSystemDatabase", systemDatabase);

        }

E pronto, consegui obter o resultado desejado no banco, vejam só:

E tratando os ID's pra apresentar os seus respectivos nomes no CRUD, este foi meu resultado final:

(Censurei pois são sistemas da empresa)

Inserir múltiplos valores com WEB API


curvature of objects on a 2-d digital image

Question: For a 2-d digital grey-scale image, I assume that any object, such as lines, edges, contours, is just 2-d stuff, isn't it? Or since each pixel of any object has a grey-scale value, which makes them 3-d?
I just read an article, which tells that for a point in the image, it has 2 principal curvature, which confuses me, because if any object on the image is just 2-d, how could it 2 principal curvatures, right?
Furthermore, what's the relationship between principal curvatures and Hessian matrix?
Answer: You seem to be right that the $D$ in that article is just 2D image data; i.e. a real function on some 2-dimensional domain. When they talk about the curvature, they're considering the curvature of the graph of the function $D$; i.e. the surface in $\mathbb{R}^3$ given by $G(x,y) = (x,y,D(x,y))$.
For such a surface, the second fundamental form is proportional to the Hessian of $D$, and thus the principal curvatures are proportional to the eigenvalues of the Hessian. Here's a sketch of this calculation using subscript notation for all derivatives.
By definition, the second fundamental form is $$A_{ij} = G_{ij} \cdot \nu$$ where $\nu$ is the upwards unit normal vector $$\nu = \frac{G_x \times G_y}{\Vert G_x \times G_y \Vert} = \frac{1}{\sqrt{1 + D_x^2 + D_y^2}} (- D_x, - D_y, 1).$$
Differentiating $G$ gives $$G_{ij} = (0,0,D_{ij}).$$ Taking the dot product with the unit normal then gives $$A_{ij} = \frac{1}{\sqrt{1 + D_x^2 + D_y^2}}D_{ij}.$$ Notice that the matrix $D_{ij}$ is exactly the Hessian of $D$.
(Note that the sign can vary for two reasons - the choice of orientation of normal vector and the sign convention used in the definition of $A$.)
Comment: Yeah, that's the problem, I don't understand why the Hessian's eigenvalues are the principal curvatures.
Comment: @loganecolss: Actually my claim is flawed - this is only true at critical points of $D$. I'll expand my post with some details.
Comment: Thanks, but I don't get it that why the second fundamental form is $A_{ij}=\nabla_jG\cdot\nabla_iv$? And by $A_{ij}$, do you mean there are more than one second fundamental form, which depends on the choice of $x,y$ coordinates?
Comment: @loganecolss: $A_{ij}$ is the $(i,j)$th entry of the matrix $A$. What is your definition of the second fundamental form?
Comment: Well, I only know the definition of second fundamental form from http://en.wikipedia.org/wiki/Second_fundamental_form
Comment: @loganecolss: rewrote it starting from wikipedia's definition
Comment: Thank you so much, so $A_{ij}$'s value is determined by both $D_{ij}$ and the first-order derivatives $u_x,u_y$, right? When $u_x = u_y = 0$, I can understand $Hessian$ determines the local curvatures, otherwise, $u_x,u_y$ still have some affect on $A_{ij}$, although the ratio of the two eigenvalues doesn't change
Comment: @loganecolss: correct. For some reason I used both $D$ and $u$ to mean the same thing, I'll correct that.
Comment: So, if $D_x,D_y \ne 0$, we cannot just use Hessian matrix without $D_x,D_y$ to estimate the local curvature, can we?
Comment: @loganecolss: that's right. All the Hessian can give you by itself is the ratio and directions of the principal curvatures.
Comment: Thank you so much for your patience, you're so kind ;-)