Set encoding for Apache POI excel workbook

Question: I'm using the Apache POI library to create, and fill an excel sheet in C# .NET.
The problem I'm faced with however, is that the data I populate my workbook with, contains some special characters (e.g. é, á, í, etc). I have been told that I need to create the worksheet with UTF-8 encoding in order for our partners to be able to auto ingest these excel files.
Does anyone who has experience using the POI library know how to set this value?
Answer: Apache POI is normally used from Java, so I don't know if the fact that you're using C# is affecting things or not...
If you were using POI in pure Java, then you simply create a Java String with your characters in it as normal. Next, pass that String to POI when setting the cell contents. POI will either store the text as ASCII or Unicode depending on the contents, and you don't need to do anything. (The encoding is all handled for you)
I'd suggest you ensure that you're creating the string properly with the international characters in it, then try passing that string to POI and see what happens. Hopefully C# will behave the same as Java and you'll be fine!
(If not, you might need to look into your C# / Java bridge, since as long as the right Unicode strings turn up in Java then POI should be correctly handling all the encoding stuff for you)


NetLogo: Is there any way to change patch colour under turtles which dies?

Question: I wrote a simulation which contain ants and spiders. spider will kill ants and not things will happens however spider will take some of ant venom and reduces health. At some certain point spider will die after there energy is equal 0 . I want spider to die and change patch colours under death spider from black to brown
I have tried this code but it didn't work .spider just disappear (die) but pcolor is not change
to spider-death
  if energy  <= 0 [ask antiagents-here [die if pcolor = black [set pcolor brown]]]
end

please help
Answer: After an agent dies, it no longer exists, and therefore can no longer take any actions.
So for example:
ask turtles [
  die
  print "hello!"
]

Nothing will ever be printed, because the turtle dies before it can print anything.
So in your code, you just need to change this part:
die if pcolor = black [set pcolor brown]

to:
if pcolor = black [set pcolor brown] die

Comment: It is still not working however spider just die without changing patch color under it

to spider-death  ;; turtle procedure

  if energy  <= 0 [ask antiagents-here [if pcolor = black [set pcolor brown] die]]
Comment: There is nothing else incorrect in the code you posted, so whatever the problem is, it must have to do with the broader context. Try adding some print statements to check your understanding of what's going on.
Comment: I am quite new to this program is it possible that can you please show me how to do it
Comment: Well so for example if you change it to `if pcolor = black [ set pcolor brown show "hello!" ] die` but it never prints "hello!", you know that part of the code isn't even running.
Comment: I try it still no hello show up  , Really have no idea now ?
Comment: I have answered your present question. Ask a new question, include more code and more information about what you tried and what you found.


Active navigation on scroll error - Vanilla JS

Question: I'm trying to make an active state nav menu were the anchor links are highlighted once they're scrolled to each section. I just tested my site and received the following errors:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': The provided selector is empty.
NodeList.forEach ()
The errors are for this code:
navLinks.forEach(link => {
    let section = document.querySelector(link.hash);

I've never seen these before and I'm confused as to what I should do. Thank you!
--HTML--

Store

Home

Products

Featured

Best Sellers

Contact

Products

Featured

Best Sellers

Contact

--JS--
//Change navigation style on scroll
window.addEventListener('scroll', event => {
    let scrollLink = document.querySelector('a.nav-link');

    (window.scrollY >= 45) ? scrollLink.classList.add('scroll') : scrollLink.classList.remove('scroll');
});

//Active navigation on scroll
window.addEventListener('scroll', event => {
  let navLinks = document.querySelectorAll('a');
  let fromTop = window.scrollY;

  navLinks.forEach(link => {
    let section = document.querySelector(link.hash);

    if (
      section.offsetTop <= fromTop &&
      section.offsetTop + section.offsetHeight > fromTop
    ) {
      link.classList.add('active');
    } else {
      link.classList.remove('active');
    }
  });
});

--CSS--
a {
    color: inherit;
    text-decoration: none;
}

a:hover,
a:focus {
    color: #fa448c;
    text-decoration: underline;
}

a.active {
    padding: 8px 15px;
    display: block;
    text-transform: capitalize;
    background-color: #fa448c;
    color: #fff;
}

li {
    list-style-type: none;
}

Comment: Hello. Make a minimal reproducible example with your problem spot in the code, pls.
Comment: Hi, I added my code, thank you!
Answer: This code means that the number of sections must correspond to the number of tags a.
I corrected your code a bit, and also commented out the first and last a tag. See how it works. But there is no need to stop there. It is necessary to exclude the first and last tag when accessing, using method querySelectorAll(".nav-list a").

let mainNavLinks = document.querySelectorAll(".nav-list a");

window.addEventListener("scroll", event => {
  let fromTop = window.scrollY;

  mainNavLinks.forEach(link => {
    let section = document.querySelector(link.hash);

    if (
      section.offsetTop <= fromTop &&
      section.offsetTop + section.offsetHeight > fromTop
    ) {
      link.classList.add("active");
    } else {
      link.classList.remove("active");
    }
  });
});
.menu {
    position: sticky;
    top: 0;
    background-color: white;
}

a {
    color: inherit;
    text-decoration: none;
}

a:hover,
a:focus {
    color: #fa448c;
    text-decoration: underline;
}

.active {
    padding: 8px 15px;
    display: block;
    text-transform: capitalize;
    background-color: #fa448c;
    color: #fff;
}

li {
    list-style-type: none;
}

#products {
  background-color: red;
  height: 500px;
}

#featured {
  background-color: green;
  height: 500px;
}

#best-sellers {
  background-color: yellow;
  height: 500px;
}

#contact {
  background-color: grey;
  height: 500px;
}
--HTML--

Store

Products

Featured

Best Sellers

Contact

"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"

Comment: Thank you! I just entered the code & received the same errors. Uncaught DOMException: Failed to execute 'querySelector' on 'Document': The provided selector is empty.

NodeList.forEach ()  I added my section code in my question, my apologies for not adding it prior.


All k-term sums of the first n natural numbers

Question: is there a formula that generates k-term sums of the first  $n$ natural numbers? The numbers are not allowed to repeat. For example, for $n=10$ and $k=4$, some possible sums would be $1+2+3+4, 2+6+7+8, 5+4+8+9$, etc. Some impossible sums would be $1+2+5+8+9, 4+6, 2+2+2+2, 6+2+3+2$, etc. Pardon the lack of formatting, I am writing from my phone in the car.
Comment: Don't write from your phone in the car. That's dangerous to you and others.
Comment: It is not clear to me what exactly you are after.  Are you looking for the *number* of possible summations?  Do you treat $1+4$ differently than $2+3$ because the addends are different or do you treat them as the same since their total is the same?  Or... are you looking for a way to generate the *list* of possible summations (*or results of summations*)?
Comment: In general, the sum $\sum _{k=n+1}^{m}k$ equals $\frac{m(m+1)-n(n+1)}{2}$. You may write down each of your sum as combinations of sums of this type (that is, of sums of a certain number of consecutive integers).
Comment: One way to interpret your Question is whether there is an expression which yields all values (and only those values) that are sums of $k$ summands drawn (without replacement) from the set $\{1,\ldots,n\}$.  However without seeing what use would be made, I'm doubtful that I've understood your request clearly enough to give a useful response.
Answer: They are, in fact, all positive integers between the minimum possible sum
$$\frac{(k)(k+1)}{2}=1+2+3+...+k$$
and the maximum possible sum
$$kn-\frac{k(k-1)}{2}=(n-k+1)+(n-k+2)+...+n.$$
Can you show, by perturbing previous sums, why all of these sums can be reached?


How do i compare a date and a text coming from a text file with a date and text in SQL server and do the further transformation as needed?

Question: I need to develop a SSIS package and the need is to check two things before the data gets inserted.
There would be a text file where there would be a date and a text (anydate,text) and there is a table in sql server which will have the same pair of data(only one row where i might update it every time and i will insert data there for the first load so that it can be compared from the date and text coming from text file).
My question is, how can i compare the data coming from the text and the data coming from the sql server and do my transformation on the basis of true or false(if date matches do something and if it doesn't match update the present date in sql with this new date and do something else)
Comment: Use a lookup transformation? Not really clear what you're *really* asking here.
Comment: Can you put some code as example to show us what you've tried first?
Comment: i want to compare a date which is previously present in a sql server table to the date which i will be pulling from a text file
Comment: @Larnu i think he is looking to perform an upsert operation
Answer:
My question is, how can i compare the data coming from the text and the data coming from the sql server and do my transformation on the basis of true or false(if date matches do something and if it doesn't match update the present date in sql with this new date and do something else)

You are looking to perform an Upsert operation. To do that you need first a lookup transformation to check if the row exists; if lookup matched (row exists) use an OLEDB command to update the row else use an OLE DB destination to achieve that. You can refer to the following link for a step-by-step guide:

SSIS: Perform upsert (Update/Insert) using SSIS Package

Note that lookup transformation is case sensitive

Another method is to use Merge Join and conditional split:

SSIS insert and update rows in a table based on the contents of a Excel file


UIWebView still active after pressing back button

Question: I'm using a Navigationcontroller which pushes a new Viewcontroller containing a Webview every time a link is clicked. One of the URLs has a javascript function, which calls another function every 60 seconds. It works fine, but when I hit the back button once after being on that web view (containing the javascript), the webview stays active and keeps doing the javascript calls, while going back to the previous webview flawlessly. I can see it doing things through NSLog. Why is that and how can I avoid this?
EDIT:
I have declared my subclass of UIWebView in my Viewcontroller like this:
@property (strong, nonatomic) AFXTWebView *wv;

and this is how I instantiate it (in ViewDidLoad):
    [self setWv:[[AFXTWebView alloc] initWithVC:self andURLString:[self.pageConfig objectForKey:xAFXTPageLink]]];

    [self.view addSubview:self.wv];

    [self.wv loadWebView];

I have also tried setting the webView to nil in viewWillDisappear:
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.wv = nil;
}

Answer: You have to use the viewWillAppear & viewWillDisappear methods
-(void)viewWillAppear:(BOOL)animated
{
_webView=[[UIWebView alloc]init];
......//do your stuff
}

-(void)viewWillDisappear:(BOOL)animated
{
[_webView removeFromSuperView];
_webView=nil;
}

Comment: Does your AFXTWebView perform anything on queue/NSOperation/blocks?
Comment: No, I'm not doing anything like that :-(. the removeFromSuperView also didn't work, except showing a blank page when navigating back.
Comment: still i dint get any idea what is going on that AFXTWebview Class
Comment: It's just a subclass of UIWebView, nothing special.
Answer: In your viewWillDisappear load a blank page into the web view.
Answer: This sounds like your web view and view controller are not being released, i.e. you have a leak. You should check your code for any unreleased retained/strong references to your view controller or web view.
Comment: Yes, that's what I think is the problem. But I just can't figure it out :-(. I have updated my answer so you can see how I'm instantiating the Webview. Any thoughts on that? Thanks
Comment: Is the AFXTWebView class storing a strong reference to the view controller?
Comment: Yes, I made it a strong reference
Comment: That sounds like your problem then. If both objects have a strong reference to each other (view controller <-> web view), neither will ever be released. Make your web view's reference to the view controller weak, and see if that fixes the problem.
Comment: I tried this, but then my webview always just stayed white without showing any content
Answer: -(void)viewDidDisappear:(BOOL)animated
{
  [super viewDidDisappear:animated];
  [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
}


gcc memory allocation issue - buffer overflow attack

Question: Does gcc do memory allocation intelligently to prevent buffer overflow attack?
int function(char *str) {
    int a = 0;                 // See the
    char b[16] = "abcd";       // changes here

    if(!strcmp(b, str))
        a = 1;

    return a;
}

and
int function(char *str) {
    char b[16] = "abcd";       // See the
    int a = 0;                 // changes here

    if(!strcmp(b, str))
        a = 1;

    return a;
}

When I debug it with gdb, it always allocate memory first to integer variables and then character array; no matter what is the order of variable declaration.
i.e. In above both cases, compiler allocates memory first to a and then to b.
(higher address)
  Memory
|        |
|        |
+--------+
|        |
|        |
|        |
|        |
+--------+ <----- b (16 bytes)
|        |
+--------+ <----- a (4 bytes)
|        |
(lower address)

So, even if we supply more than 16 character in str, it can not affect value of a.
Can anybody help me out here?
Thank you.
Comment: _The Standard_ allows such reordering for any purposes, the compiler wants to accomplish. Most common - optimization. It's still "intelligence", but not for preventing "the buffer overflow attack". And it's still an _undefined behavior_ (the buffer overflow)
Answer: Yes, if run with the -fstack-protector flag.
When run with the flag, GCC adds stack canaries, sorts array variables to the highest part of the stack frame to make it more difficult to overflow them and corrupt other variables, and makes copies of the function arguments to be stored with the other locals.
See the Wikipedia page on Buffer overflow protection and the ProPolice homepage for more information
Comment: You are right. GCC enable it by default. If we compile with `-fno-stack-protector`, it allocate memory sequentially in order of declaration rather than _array variables to the highest part of the stack frame_. Thank you
Comment: @Ravi: Some distributions enable it by default. Try compiling with `-fno-stack-protector` and see if it makes a difference.
Comment: @MM.: Added. Was mostly left out for brevity.
Answer: Even if GCC has such a feature to protect against buffer overflows, there are many other considerations here that may cause a fixed variable declaration order. Where the declaration is made is not really important, the compiler will take allocation decisions based on when and how the variable is used in runtime.
Most importantly, the compiler will hopefully allocate variables in the stack frame with the best possible alignment in mind. This could be made in entirely different ways depending on CPU and optimizing setting. Optimize for speed may give a completely different allocation, compared to optimize for memory consumption. And most likely, it will put some variables in CPU registers, removing the whole RAM allocation need.
So to answer your question: GCC allocates variables in various ways, depending on compiler port. How it does so, is not something the programmer needs to overly concern themselves about. There may be options to rearrange the stack to protect against buffer overflow attacks, but that only makes sense in some types of applications. There might not even be any input to a particular system, for all we know. So it doesn't make sense for a compiler to have this security feature enabled by default.
Answer:
Does gcc do memory allocation intelligently to prevent buffer overflow attack?

No, it doesn't. You cannot prevent an attack or a buffer overflow without bounds checking, which isn't always possible. You can only sometimes detect an overflow after the fact.
At best the compiler can include extra information (a so called canary value) near the return address on the stack and before returning from the function check that it's intact and not overwritten as a result of a buffer overflow.
Comment: This is wrong, GCC can and does reorder variables to prevent the effects of buffer overflow
Comment: @Hasturkun You cannot prevent an overflow without bounds checking. You can only sometimes detect one.
Comment: That's true. But you can mitigate them, as done by ProPolice, etc.
Comment: @Hasturkun Prevention != mitigation.


Get rid of unassigned shard

Question: I've an ELK stack with two ElasticSearch nodes running and the cluster state turned red due to some unassigned shards which I can't get rid of. Looking up the unassigned shard, resp. the incomplete index with:
# curl -s elastic01.local:9200/_cat/shards | grep "logstash-2014.09.29"

Shows:
logstash-2014.09.29 4 p STARTED       745489  481.3mb 10.165.98.107 Crimson and the Raven
logstash-2014.09.29 4 r STARTED       745489  481.3mb 10.165.98.106 Glenn Talbot
logstash-2014.09.29 0 p STARTED       781110  502.3mb 10.165.98.107 Crimson and the Raven
logstash-2014.09.29 0 r STARTED       781110  502.3mb 10.165.98.106 Glenn Talbot
logstash-2014.09.29 3 p INITIALIZING                  10.165.98.107 Crimson and the Raven
logstash-2014.09.29 3 r UNASSIGNED
logstash-2014.09.29 1 p STARTED       762991  490.1mb 10.165.98.107 Crimson and the Raven
logstash-2014.09.29 1 r STARTED       762991  490.1mb 10.165.98.106 Glenn Talbot
logstash-2014.09.29 2 p STARTED       761811  491.3mb 10.165.98.107 Crimson and the Raven
logstash-2014.09.29 2 r STARTED       761811  491.3mb 10.165.98.106 Glenn Talbot

My attempt to assign the shard to the other node fails:
curl XPOST -s 'http://elastic01.local:9200/_cluster/reroute?pretty=true' -d '{
    "commands" : [ {
            "allocate" : {
              "index" : "logstash-2014.09.29",
              "shard" : 3 ,
              "node" : "Glenn Talbot",
              "allow_primary" : 1
            }
        }
    ]
}'

With:
NO(primary shard is not yet active)]

I can't really seem to find an API to push the shard states any further. How could I proceed here?
Just for a complete picture, that what the system health looks like:
{
  "cluster_name" : "logstash_es",
  "status" : "red",
  "timed_out" : false,
  "number_of_nodes" : 2,
  "number_of_data_nodes" : 2,
  "active_primary_shards" : 114,
  "active_shards" : 228,
  "relocating_shards" : 0,
  "initializing_shards" : 1,
  "unassigned_shards" : 1
}

Thank you for your time and help
Comment: Did you ever find a solution to this?
Comment: Deleting the shards and loosing the data was the only way to solve it, back then
Answer: I actually ran into this situation with ElasticSearch 1.5 just the other day. After initially getting the same error, I simply repeated the /_cluster/reroute request the next day for lack of other ideas, and it worked, and it put the cluster back into a green state immediately.

Get rid of unassigned shard


Why doesn't gcc support naked functions?

Question: I use naked functions to patch parts of a program while it's running. I can easily do this in VC++ in Windows. I'm trying to do this in Linux and it seems gcc doesn't support naked functions. Compiling code with naked functions gives me this: warning: 'naked' attribute directive ignored. Compiled under CentOS 5.5 i386.
Comment: This seems to be a particular feature of VC: http://msdn.microsoft.com/en-us/library/21d5kd3a(v=vs.80).aspx
Answer: The naked attribute is only supported by GCC on certain platforms (ARM, AVR, MCORE, RX and SPU) according to the docs:

naked:
  Use this attribute on the ARM, AVR, MCORE, RX and SPU ports to
  indicate that the specified function does not need prologue/epilogue
  sequences generated by the compiler. It is up to the programmer to
  provide these sequences. The only statements that can be safely
  included in naked functions are asm statements that do not have
  operands. All other statements, including declarations of local
  variables, if statements, and so forth, should be avoided. Naked
  functions should be used to implement the body of an assembly
  function, while allowing the compiler to construct the requisite
  function declaration for the assembler.

I'm not sure why.
Comment: @Seth: the instructions used in the assembler code can have operands, but an "asm statement" doesn't mean the assembler instruction, it's the whole `asm ("some insns" : outputblah : inputblah : clobberblah);`. The "blahs" are the operands of the asm statement, and that's what you can't use if you don't have the compiler-generated prologue. You can write assembler, but you can't hook it up to C variables.
Comment: Why do you need to only use asm statements that don't have operands? Don't nearly all commands have operands (even things like `jmp` take an operand)?
Answer: === Update ===
As of 2023 they do work:
__attribute__((naked))
void my_write(int fd, char const* str, int size) {
    asm
    (
    "       pusha                              \n\t"
    "       movl   $4, %eax                    \n\t"
    "       movl   36(%esp), %ebx              \n\t"
    "       movl   40(%esp), %ecx              \n\t"
    "       movl   44(%esp), %edx              \n\t"
    "       int    $0x80                       \n\t"
    "       popa                               \n\t"
    "       ret                                \n\t"
    );
}

void _start() {
    my_write(1, "hi\n", 3);
    my_write(1, "bye\n", 4);
}

compiled with gcc -m32 -nostdlib my_write.c using gcc version 10.2.1 20210110 (Debian 10.2.1-6)
=== Old answer ===
On x86 you can workaround by using asm at global scope instead:
void my_write(int fd, const void *buf, int count);

asm
(
".global my_write                          \n\t"
"my_write:                                 \n\t"
"       pusha                              \n\t"
"       movl   $4, %eax                    \n\t"
"       movl   36(%esp), %ebx              \n\t"
"       movl   40(%esp), %ecx              \n\t"
"       movl   44(%esp), %edx              \n\t"
"       int    $0x80                       \n\t"
"       popa                               \n\t"
"       ret                                \n\t"
);

void _start()
{
    my_write(1, "hi\n", 3);
    my_write(1, "bye\n", 4);
}

Also naked is listed among x86 function attributes, so I suppose it works for newer gcc.
Answer: GCC only supports naked functions on ARM and other embedded platforms. http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Also, what you're doing is inherently unsafe, as you cannot guarantee that the code you're patching isn't executing if the program is running.
Answer: That's an ugly solution. Link against a .asm file for your target architecture.


What is the correct way for correlation and auto correlation plot?

Question: I am trying to plot the auto and cross correlation of the bitstream that is obtained from a nonlinear dynamical system.
The graph is the Auto and cross-correlation for the bitstream obtained from the same nonlinear dyanamical system.

I am not sure how to interpret the graph. Whether the program is incorrect or not. I wanted to obtain the plot of lags vs ACF but what I got is   different than the actual plot given in a book. Please help.
A = .5;  B = 1.99;  phin = .5;  xphi(1) = A - (B*phin);

for it = 2:1:5000
 xphi(it) = A - (B*abs(xphi(it-1)));
end
phi = 2*(xphi>=0.5)-1;
A = .51;  B = 1.90;  phin = .5;  xphit(1) = A - (B*phin);

for it = 2:1:5000
 xphit(it) = A - (B*abs(xphit(it-1)));
end
phit = 2*(xphit>=0.5)-1;

CST = xcorr(phit,phi);
AST = xcorr(phi,phi);

Time = 0;
for nn = 2:1:length(CST)
Time(nn) = Time(nn-1) + 1;
end

plot(Time,AST,'r',Time,CST,'g');       title('\bf AUTO & CROSS correlation');
xlabel('\bf Time');    ylabel('\bf Auto & Cross correlation'); legend('red-AC','green-CC');

The plot should resemble

where the figure on top is the cross-correlation and the bottom is the auto-correlation
Comment: I am not sure what  graph have you plotted. Are you using R ?
How can ACF values be outside -1 and 1
Comment: @NG_21: I have used Matlab and included the code that is used to generate the plot
Answer: tl;dr: Your time axis is wrong and the correlation values could be rescaled.
Time Axis
The cross-correlation of two continuous signals $F$ and $G$ is
$$(F \star G)(\tau) = \int_{-\infty}^{\infty} F^*(t)G(t+\tau)dt$$
In other words, it is the dot product between $F$ (or its complex conjugate $F^*$ for complex-valued signals) and a version of $G$ that has been shifted forwards and backwards. (It's very much like convolution, except that for convolution, one of them is also reversed: $t+\tau$ becomes $t-\tau$ for convolution).
This implies that your cross-correlation plot has zero at its center, rather than on one edge. You constructed the time axis yourself, so you could change the code to put 0 at the center, -1 and +1 on either side, etc. Matlab also does this for you as the second argument from xcorr (docs):
[CST, lags] = xcorr(phit, phi);
plot(lags, CST); title('Cross-correlation');
[AST, langs] = xcorr(phi, phi);
plot(lags, AST); title('Autocorrelation');

Rescaling
The formula above assumes that your signals are infinite, but your actual data probably is not. As you "push" one array past the other, they become different lengths and you can no longer compare them. One approach is to shift one array circularly (i.e., G(1) becomes G(2), G(2) becomes G(3), ...., G(N-1) becomes G(N), and G(N) becomes G(1)).
Matlab doesn't do that. Instead, it pads them with zeros (it actually does the computation in the frequency domain, and the fft call does the padding). If your signal has a non-zero mean, it becomes a strangely-shaped little "step" in the midst of zeros. The convolution or cross-correlation of the two steps produces that weird triangular shape. There are a few ways of dealing with it:

Standardizing your signal so it has zero mean and unit variance helps
You can also get an unbiased estimate of the cross-correlation by rescaling $R(\tau)$ by $\frac{1}{N-|\tau|}$. Matlab does this if you add a third option to the function call xcorr(F,G,'unbiased') (there are a few other normalization options too).

Incidentally, you might want to play around with a less pathological pair of "signals" for practice so you can see by eye what the result should be.
Comment: Thank you for your reply. I am getting the same triangle ACF plot using the code that you have given. I still cannot understand what the plot means, whether the bit stream data is correlated or not. Could you please elaborate on these points (a) what can we infer about independence by looking at the spike in the ACF plot (b) What does the plot for ACF using the bit stream indicates about independence (c) How can I get normalized ACF on the Y Axis?


Align the checkbox to left of the label

Question: I have a checkbox with ripple effects. The below code displays the label text first and then the checkbox
I wanted to display the checkbox first and then the label text. The entire div expands and shrinks sometimes,

<input id="onoff" type="checkbox" style="display:table-column"/>
Turn on/off

Answer: you can do so by using following code
#onoff+label {
    margin-left: 30px;
    position: relative;
}

#onoff+label::after {
    left: -10px;
    right: auto;
}

#onoff+label::before {
    left: 0;
    right: auto;
}

<input id="onoff" type="checkbox" style="display:table-column"/>
Turn on/off

Align the checkbox to left of the label


Building a jquery/javascript HIIT with autoplay video or image slider "playlist" using and php/mysql

Question: I am trying to create a countdown timer with videos. The timer needs to load data such as time for countdown, time for breaks, and number of sets the timers needs to run, video(or images in case of no video) from a MySQL table.
The timer starts counting down but needs also to start auto-playing video of image slider. When time ends starts counting down for the time break. This process continues till number of sets reached. Then it is needed to either click to go to the next countdown or after a short countdown break to load the next in queue.
I can load the data from MySQL with php and create a while loop to pass the variables need in the jQuery/JavaScript script. But i am not sure if this is the right way.
This is my approach with a bug related on clicking start/stop/reset buttons which leads to an increase of speed during countdown, and in some unwanted results regarding counting down.
A fix on that bug would be appreciated.
My code:

var startTime = 10;
var restTime = 5;
var currentTime = 0;
var myTimer;
var myTimerSpeed = 1000; // 1 sec
var currentSet = 0;
var currentPause = 0;
var totalSets = 5;

resetTimer();
restTimer();

$('#pause').hide();
$('#next_exe').hide();
$('#player').show();

$('input[value="start"]').click(startTimer);
$('input[value="stop"]').click(stopTimer);
$('input[value="reset"]').click(resetTimer);

$('#currentset').html(currentSet);
$('#totalset').html(totalSets);
$('#currentpause').html(currentPause);
$('#totalpause').html(totalSets);

function resetTimer() {
  stopTimer();
  currentTime = startTime;
  $('#timer').html(currentTime);
}

function startTimer() {
  currentSet++;
  if (currentTime <= 0) {
    //resetTimer();
    startTimer();
  } else {
    myTimer = setInterval(timerTick, myTimerSpeed);
  }
  $('#currentset').html(currentSet);
}

function restTimer() {
  stopTimer();
  currentTime = restTime;
  $('#timer').html(currentTime);
}

function breakTimer() {
  currentPause++;
  if (currentTime <= 0) {
    restTimer();
    breakTimer();
  } else {
    myTimer = setInterval(timerTick, myTimerSpeed);
  }
  $('#currentpause').html(currentPause);
}

function timerTick() {
  currentTime--;
  if (currentTime == 0 && currentSet == totalSets) {
    if (currentPause < totalSets && currentPause < currentSet) {
      restTimer();
      breakTimer();
      $('#pause').show();
      $('#player').hide();
      $('#next_exe').hide();
    } else {
      stopTimer();
      //$('#myTimer').hide();
      $('#next_exe').show();
      $('#pause').hide();
      $('#player').hide();
    }

  } else if (currentTime == 0 && currentSet < totalSets) {
    if (currentPause < totalSets && currentPause < currentSet) {
      restTimer();
      breakTimer();
      $('#pause').show();
      $('#player').hide();
    } else {
      resetTimer();
      startTimer();
      $('#pause').hide();
      $('#player').show();
    }
  }

  $('#timer').html(currentTime);
  $('#currentset').html(currentSet);
  $('#currentpause').html(currentPause);
}

function stopTimer() {
  clearInterval(myTimer);

}

  I want to create 2 countdowns, which can loop everytime countdown ends and a set is completed.

    PAUSE

    Next Exercise

  <input type="button" value="stop">
  <input type="button" value="start">
  <input type="button" value="reset">

  Number of Sets completed:  /

 Number of Breaks completed:  /

Also available on JSfiddle
Suggestion of a friend:

$('#pause').hide();
$('#player').hide();
$('#next_exe').hide();

function Timer(speed, duration, onTick, onComplete) {

  var speed = speed;
  var interval = null;
  var current = duration;
  var onTick = (typeof onTick == 'function') ? onTick : function() {}
  var onComplete = (typeof onComplete == 'function') ? onComplete : function() {}

  function decrement() {
    onTick(current);
    if (current > 0) {
      current -= 1;
    } else {
      stop();
      onComplete();
    }
  }

  function start() {
    if (!interval) {
      interval = window.setInterval(decrement, speed);
    }
  }

  function stop() {
    if (interval) {
      interval = window.clearInterval(interval);
    }
  }

  function reset() {
    current = duration;
    onTick(current);
  }

  return {
    start: start,
    stop: stop,
    reset: reset
  };
}

function RoundCounter() {
  var currentSet = 0;
  var totalSets = 2;
  var currentPause = 0;
  var totalPause = 2;
  var currentTimer = null;
  var mode = null;

  function initialize() {
    mode = "set";
    currentTimer = Timer(1000, 10, timerTick, completeSet);
    setupUI();
    bindUIEvents();
  }

  function setupUI() {
    $('#totalset').html(totalSets);
    $('#totalpause').html(totalPause);
    $('#currentset').html(currentSet);
    $('#currentpause').html(currentPause);
  }

  function bindUIEvents() {
    $('input[value="start"]').click(function() {
      runTimer(currentTimer);
      $('#pause').hide();
      $('#player').show();
      $('#next_exe').hide();
    });

    $('input[value="stop"]').click(function() {
      stopTimer(currentTimer);
    });

    $('input[value="reset"]').click(function() {
      resetTimer(currentTimer);
    });

    $('#sets')
      .on("timerset.complete", function() {
        updateUI();
      })
      .on("timerpause.complete", function() {
        updateUI();
      });
  }

  function updateUI() {
    $('#currentset').html(currentSet);
    $('#currentpause').html(currentPause);

    if (currentPause == totalPause &&
      currentSet == totalSets) {
      endRound();
      return;
    }

    if (mode == "set") {
      $('#pause').hide();
      $('#player').show();
      $('#next_exe').hide();
      if (currentPause < totalPause) {
        currentTimer = Timer(1000, 5, timerTick, completePause);
        runTimer(currentTimer);
      }
      mode = "pause";
    } else if (mode == "pause") {
      $('#pause').show();
      $('#player').hide();
      $('#next_exe').hide();
      if (currentSet < totalSets) {
        currentTimer = Timer(1000, 10, timerTick, completeSet);
        runTimer(currentTimer);
      }
      mode = "set";
    }
  }

  function startNextTimer() {
    if (mode == "set") {}
  }

  function timerTick(currentTime) {
    $('#timer').html(currentTime);
  }

  function runTimer(timer) {
    timer.start();
  }

  function stopTimer(timer) {
    timer.stop();
  }

  function resetTimer(timer) {
    timer.reset();
  }

  function completeSet() {
    currentSet += 1;
    $("#sets").trigger("timerset.complete");

    $('#pause').show();
    $('#player').hide();
    $('#next_exe').hide();
  }

  function completePause() {
    currentPause += 1;
    $("#sets").trigger("timerpause.complete");

    $('#pause').hide();
    $('#player').show();
    $('#next_exe').hide();
  }

  function endRound() {
    $('#myTimer').hide();
    $('#sets')
      .off('timerset.complete')
      .off('timerpause.complete');
  }

  return {
    initialize: initialize
  };
}

// on document ready, initialize everything
$(function() {
  RoundCounter().initialize();
});

  I want to create 2 countdowns, which can alter everytime countdown ends and a set is completed.

     VIDEO or Image Slider

    PAUSE

    go to next exercise

  <input type="button" value="stop">
  <input type="button" value="start">
  <input type="button" value="reset">

  Number of Sets completed:  /

 Number of Breaks completed:  /

This is also available on JSfiddle
Comment: At first glance and with the little info available, this looks like you're not properly calling `clearInterval()` on your timers when you click the stop button, or are duplicating said interval on your start or reset buttons
Comment: Your friend's code seems to work fine, are you experiencing issues with it too? Or is your question mainly about understanding why yours bugs?
Comment: @Pepper, i want to choose the right approach. I know that i only have a bug, and thank you for pointing to that direction. I had firstly started working with my code, and till know i didn't adopt friend's solution. If you run the jsfiddle you will see that although i do have a bug, i have made a more "complete" solution of what i want to achieve. What i am missing is how to apply the repeat of all those actions when first video loop ends and is time to load the next one!
Answer: Your timer issue comes from these lines of code:
myTimer = setInterval(timerTick, myTimerSpeed);

An interval is not really a variable, when you call setInterval you are creating an interval and getting in return a reference to that interval.
So if the code above is called twice, you'll have 2 intervals running but only a reference to the 2nd one, which means it will run forever and you no longer have the value needed to stop the first one.
What your friend did is to ensure there was no running interval referenced by his variable before starting a new one.
You can achieve the same result by replacing the lines above with:
if(myTimer) clearInterval(myTimer);
myTimer = setInterval(timerTick, myTimerSpeed);

And adding an initial value to your timer with var myTimer = false;. That should fix your timer issues
To fix transitions, I basically removed their logic from the timers start/stop functions. All transitions are now handled by timerTick().
I added a isBreak variable to remember if we're currently in a break or set, which is then used to determine what step is next and what timer initial value to fetch.
I included two reset functions in the code (resetAll() & resetCurrent()), since I didn't know if you wanted to reset everything or only the current timer.
It should now work as follow: set -> break (5x) and on the last break, instead of PAUSE it displays Next Exercise (to which you can add a click listener calling loadNext() if you want the user to be able to start it manually).
In loadNext() you can load the images for the next exercise, and if you uncomment startTimer() it will start right away.
Result: Fiddle
Does that work as you wanted it to?
Comment: (Tip: If the edited version supercedes the original fiddle, then you can remove the original and the commentary about it not working. If you believe the OP is following along, you can add a comment about looking at the [revision history](https://stackoverflow.com/posts/57459370/revisions), but otherwise answers are better in a pristine condition, for the benefit of readers who have not seen it yet. You can keep it to multiple updates though if you want all of your future readers to see the progress, if there is genuine value in that.)
Comment: Thanks for the tip, I didn't know about revision history either!
Comment: Marvellous, good changes, +1. You've already removed it, but I am a bit wary of promises for future updates in posts, since they are often left in for years. But it is fine if you genuinely do plan to come back and edit.
Comment: @Pepper with a small in the provided fiddle i believe it will work. The only thing ledt is the right way to implement loadNext(), i am thinking with ajax call but i will figure it out. Thanx a lot.
Comment: I have to admit that i am stuck.  I can't find the right way to use loadNext as @Pepper provided. The thing is that i want to have either multiple divs with data attributes add apply some kind of loop either use an ajax call update all the data of the current div and allow instantly to execute startTimer().
See related [https://jsfiddle.net/kpmdevgr/4h5wytkb]
Comment: I can try to help, but I'd like some precisions on what you're trying to achieve: Are you playing videos or 1 image per exercise? If it's videos, do you have the source file, or do you want to play them from a link (youtube, etc), and finally, if your workout has 3 exercises (E1, E2, E3) and 5 reps, do you want to do 5x E1, 5xE2, 5xE3 or 5x E1->E2->E3? (Also, your jsfiddle doesn't seem to exist)
Comment: Sorry for the delay. Well the videos will come from youtube. As for the part with the timings both cases can apply. That's why i do have the data-attributes on the div#player.
Now imagine either many div#player on the same page or either with the use of ajax to call the next video.
And yes i saw the issue with the link so here is the right one [link]https://jsfiddle.net/kpmdevgr/4h5wytkb
Comment: I made some [changes](https://jsfiddle.net/fhw2dL80/) but it can still be improved. It's using a single player and dynamically loading the videos between exercises, it will probably be better with 1 player per exercise, but I don't have time right now^^ (I also added timestamps in case you don't want to start at 0 in the videos)


Selenium - Falta de permissão para Download

Question: Criei um script em Python usando o Selenium para acessar um site e fazer o download de alguns arquivos, porém, o navegador bloqueia o download e informa a seguinte mensagem: "Não foi possível baixar - Não há permissões". Obs: Não possuo conta de adm no computador que executo, mas o bloqueio só acontece quando utilizo o Selenium. Se eu abrir o navegador manualmente os downloads são feitos normalmente.
Há alguma opção de ajuste no código para tratar esse bloqueio de downloads (por exemplo, alguma opção no "Options")?
Segue abaixo  uma parte do código como exemplo, mas o erro de permissão acontece em qualquer página/site.

def baixa_relacao():
    options = EdgeOptions()
    options.use_chromium = True
    driver = Edge(options=options)
    actionChains = ActionChains(driver)

    driver.get('confidencial')

    driver.find_element_by_xpath('//*[@id="gsft_nav"]/div/magellan-favorites-list/ul/li[1]/div/div[1]/a/div[2]/span').click()

    driver.switch_to.frame('gsft_main')
    driver.find_element_by_link_text('Enviar Segurado...').click()

    botao = driver.find_element_by_xpath('//*[@id="hdr_sc_req_item"]/th[5]/span/a')
    actionChains.context_click(botao).perform()

    driver.find_element_by_xpath('//*[@id="context_list_headersc_req_item"]/div[13]').click()

    driver.find_element_by_xpath('//*[@id="d1ad2f010a0a0b3e005c8b7fbd7c4e28_sc_req_item"]/div[2]').click()

    driver.find_element_by_id('download_button').click()

Comment: Você já fez essa pergunta [aqui](https://pt.stackoverflow.com/questions/521708/edge-download-com-selenium) não tem como o responder sem saber  a qual página que esse código é destinado.
Comment: Independente da página, ele bloqueia o download. Ou seja, se o script entrar no google e tentar baixar algo, vai dar o mesmo problema de permissão. Eu já tentei em diversas páginas. O código acima foi só uma das páginas de exemplo.
Comment: Mas como assim independente de página, o xpath é bem específico ele só pode ser aplicado aa arvore cujo qual foi projetado.
Comment: O código que coloquei acima é só uma parte do script que acessa determinado site e faz o download de um arquivo. O script acessa outras páginas na internet também para fazer download de outros arquivos. Independente do site ou do navegador que eu usar eu não consigo fazer nenhum download de arquivo e eu recebo a mensagem de "Não há permissões". Eu já tentei inclusive mudar a pasta onde os downloads são salvos, mas também sem sucesso.
Answer: Utilize um User-Agent, por exemplo:
header = {'User-Agent': "Coloque seu User-Agent aqui"}

Depois insira no parâmetro no driver.get, assim:
driver.get('confidencial', headers=header)

Obs.: para conseguir seu User-Agent basta pesquisar algum site pelo termo "My User-Agent".


error while starting xampp on fedora17

Question: I currently installed xampp on my fedora (64 bit) system. i edited out the following code to make it 64 bit compatible.
<code># XAMPP is currently 32 bit only
#case `uname -m` in
#    *_64)
#    if /opt/lampp/bin/php -v > /dev/null 2>&1
#        then
#            :
#    else
#        $de && echo "XAMPP gibt es zur Zeit nur als 32-Bit Applikation. Bitte verwende eine 32-Bit Ko$
#        $de || echo "XAMPP is currently only availably as 32 bit application. Please use a 32 bit com$
#        exit
#    fi
#    ;;
#esac
</code>
but i am getting the following error
<code>[root@localhost ~]# /opt/lampp/lampp start

Starting XAMPP for Linux 1.8.1...

/opt/lampp/share/lampp/phpstatus: /opt/lampp/bin/php: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

XAMPP: Starting Apache with SSL ...
/opt/lampp/bin/apachectl: /opt/lampp/bin/httpd: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

XAMPP: Error 126! Couldn't start Apache!
XAMPP: Starting diagnose...
XAMPP: Sorry, I've no idea what's going wrong.
XAMPP: Please contact our forum http://www.apachefriends.org/f/

XAMPP: Starting MySQL...
/opt/lampp/bin/mysql.server: /opt/lampp/bin/my_print_defaults: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
XAMPP: Couldn't start MySQL!

XAMPP: Starting ProFTPD...
XAMPP: /opt/lampp/lampp: /opt/lampp/sbin/proftpd: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
XAMPP: Error 126! Couln't start ProFTPD!

XAMPP for Linux started.
</code>
Comment: Can you see the similarities between this and your editing of the 64bit check?   I was driving a car when the warning light lit up, warning me the car was out of fuel. It would not work anymore. So I smashed the warning light and it still not not working.
Answer: Why on earth would you think that disabling the 64 bit check would magically make it work? This has no chance of ever working.
Moreover, you should never use lampp on fedora or any other distro that provides the relevant packages (read: all of them). Get rid of it and simply install the apache, mysql and php packages from the fedora repos.
Comment: +1: 100% approve this, then also if you plan to install some administrative panel for managing your server from the web (ex. `webmin`, `plesk`, etc) customized system configuration of *AMPP not be compatible with these panels, and configuration not be easily exportable to other machines and should always have a support dedicated to *AMPP.

error while starting xampp on fedora17


Best accuracy of ice-hockey prediction achieved

Question: What is the best accuracy of predicting ice-hockey game winner ever achieved? I have found many sites where some mathematical models can predict winner of NHL game with accuracy from 55% to 60%. Is this the best accuracy we can get?
When can we say a model has a good accuracy? These models with 60% accuracy are really complicated and take to account so many stats and still I think that if I randomly choose a winner with a little knowledge about past games, I will have a better accuracy than 60%.
Comment: "I think that if I randomly choose a winner with a little knowledge about past games, I will have a better accuracy than 60%." If you can actually do this, you should be able to make a lot of money on the sports betting markets. Come back in a year and tell us your profit.
Comment: Survivor bias is a fallacy. One person making money over a series of random bets does not outweigh the many hundreds who lost, bringing the real expected value down to basically the theoretical, around 90% depending on the vig. If all bets are even money, EV is still 0. Especially with the number of games in a season, it is exceptional luck to get much past the low 50s, much less above 60%.
Comment: Actually I made a few hundreds from a few tens o bets with 1 euro bet :D
And when you take to account that absolutely random tip has a chance of 50% being correct.
Comment: Of course, but I wasn't asking because of betting initially. I am just curious how well can be an ice-hockey game predicted, only the winner. We have so much data from the matches and still it is totally unpredictable. 50% accuracy is just no accuracy at all, and these few percent up to 60 is really not amazing, in practical world.
Comment: You seem to have a very different idea of what it means to be practical, and what counts as amazing in that respect.
Comment: Why? 50% accuracy doesn't tell nothing. A few percent up sure isn't amazing. Neither manager, coaches, betters, or anybody else can use it practically.
Comment: Bettors use predicted or simulated wins all the time. Some are better than others. Managers and coaches tend to focus on action that gives them a better chance of winning, of course they don't use predictions to decide whether they should bother playing well or not.
Comment: More importantly, if I was able to predict the outcome of hockey games with greater than 65% accuracy, I'd never in a million years tell you (or anyone), or more importantly divulge my method to you (or anyone). It would simply be worth too much to someone.
Answer: The better team doesn't always win
The best teams in hockey in the 2020-1 season were the Colorado Avalanche and the Vegas Golden Knights, with 82 points.  They won 69.6% and 71.4% of their games respectively.  So even if you knew a priori that they were the best teams and picked them to win, you would only get about 70%.
The worst team was the Buffalo Sabres, with 37 points.  They lost 73.2% of their games.
Not every team wins or loses 70% of its games
Those examples are the most extreme.  But many games do not include any of the Avalanche, Knights, or Sabres.  What happens when the New York Rangers face the Montreal Canadiens?  Who's the better team?  In games like that, your chances of being wrong are much higher.
Not every opponent is average
The Avalanche and the Golden Knights are in the same division.  Some of the time, they play each other. Again, your chances of being wrong are much higher.
Look at the playoffs for more examples.  In eight first round matches, five undercards won, including two of the number one seeds losing to the number four seeds, despite home rink advantage.  In the four second round matches, the lower seed won every one.  Including the Montreal Canadiens, who had a losing record in the regular season but went to the finals.  Overall, the better seed only won five of fifteen matches.  Of course, the year before, the better seed won a majority of the matches.
Most decisive
It's as useful to us for a team to be at the bottom of the rankings as at the top.  Either way, it tells us how that team is likely to do in games.  So rather than think of the Sabres as winning only 26.8% of their games, think of it as their opponent wins 73.2%.  If we think of every team like that, the Sabres were the most decisive team.  If we guessed that they'd lose, we'd be right 73.2% of the time.  The worst team would be a team that won and lost equal numbers of games.  Such a team would only be 50% decisive.
Give every team a decision score.  They will all be between 50% and 73.2% (in the 2020-1 season).  If you average those numbers together, you get that the average team is around 60% or so decisive.  Hey, that's about the same as the predictions!
So what is this telling you?  The fundamental problem with consistently guessing the winner with more than 60% accuracy is that games are only 60% accurate at determining who is the better team.  If we had a perfect system that could tell who was the better team, it would still only be 60% accurate at predicting games.  Because on average the games themselves are only 60% accurate.  This should not be terribly surprising.  It is after all, the reason why playoff matches are seven games and not just single games.
More rigor
It would be better for this analysis to look at head-to-head matchups rather than overall records.  But I could easily find the overall records (thanks Wikipedia) and could not as easily find the head-to-head results.  Also, I doubt that there would be enough data for a truly rigorous examination.  Note that 31 teams played 56 games each.  That's less than 2 games per matchup.  Even in a full 82 game season, that's less than 3 games per matchup average with 2 (other conference) to 4 (same division, maybe) being the actual numbers.
Neither 2 nor 4 is a large enough sample.  Really, 82 is rather on the small side.  Statistics usually work with hundreds if not thousands.  But that to helps explain the problem.  There isn't enough data to make really accurate predictions.
Survivorship bias
One of the problems with your initial analysis is that I strongly suspect that you are looking mostly at the easy matchups.  The Avalanche or the Golden Knights will usually beat the Sabres (at least as the teams were in 2020-1).  But other teams are going to be far more evenly matched.  For example, in the playoffs, they were 4-2 (so the better team only won 67% of the time--assuming the Golden Knights were the better team; perhaps the better team only won 33% of the time).
If you get to pick which matchups, you can do better than 60%.  But if you have to pick every game, then you have to pick a lot of games where either team could win.  And naturally the matchups that you measure are those where you came to a decision.  If you couldn't choose between two evenly matched teams, you don't score yourself with a miss.  You just figure that you didn't have time.  But those hard matchups should pull down your percentage.
This is why the comments keep telling you to try it.  Because if you actually tried to pick all the games this season, it is very unlikely that you would do much better than 60% overall.  You might well do better than that for some teams though.
Practical use
It's not clear to me that even a perfect predictor would have a practical use.  What does it change for managers and coaches?  Anything short of perfect, they still have to play the games.  Perhaps it might help them plan a bit as to when to rest players (if you're going to lose, might as well lose with your second team on the ice).  But even then, what if that would have been the game where you would have beat the odds?
For bettors, to have a bet, you need two sides.  So the weighted win percentage in betting is always 50%.  It may feel like you're betting against the bookie, but that usually isn't true.  Bookies don't normally pick a side.  Instead, they lay off their bets with other bookies such that, they come out a little ahead regardless of what happens.  If there was a service that provided perfect predictions, then everyone would use it and you could never place a bet.  There would be no one to bet the other side.
With our current imperfect system, what happens is that they use odds and/or the spread to balance things.  But the average return is such that if you bet both sides, you will lose money.  Because the winnings are less than the cost of placing the bet both ways so that the bookie has a profit margin.
That's not to say that you can't win individual bets.  Or even beat the odds on average.  But everyone can't do that all of the time.  Someone has to take the losing side.  People who tend to beat the odds are the ones who pick games where bettors are likely to be irrational.  For example, where people are betting on their home team, even when it's not that good.  That can skew the odds.
Comment: Thanks for your answer! So the problem is that NHL teams are really balanced in strength. Maybe current models used for predictions should instead of analysing each team and player individually (in context of other teams and players) try to analyse and train on types of teams and players, that would mean a lot of more data could be used for predicting a single match. So two similarly playing players would be processed as one.
Comment: "So the problem is that NHL teams are really balanced in strength" - _citation needed_


How to transfer object server-to-server in a GWT project?

Question: i'm doing a GWT project for school and i need your help.
I must do a web app, for a car rent agency. Each agency has a database and i need to start two (or more) istances of the same web app: one for each agency.
this picture rappresent perfectly what i'm tryin to explain:
https://drive.google.com/file/d/0ByvS4LX9oVXnd1NtWGFiVXR3ZnM/edit?usp=sharing
So i must transfer object (for example a car) from a database to another database, similar to what I just do "locally" with GWT RPC, but from server to server. How can i do this?
I just done the "local" part of this project, so i can add employeers, clients, cars and start/stop a rent. If can help, I used Hibernate and HSQLDB as database.
I know about syncproxy, but i noticed a small documentation on the web, there are an alternatives?
Thank you!
Answer: I wouldnt recommend a GWT based solution for this. What you need is a replication between your  local and remote database. I dont know the capabilities of the hsqldb, but you also can serialize your objects between the java backends.


SetValidUntilExpires alternative

Question: What is the alternative for context.Response.SetValidUntilExpires(true) in asp.net core?
I checked the headers in an asp.net app, and could not find any changes on setting the flag as true or false.
context.Response.Cache.SetExpires(DateTime.Now.AddDays(7));
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.SetCacheability(HttpCacheability.Public);

Answer: Whenever you want to cache something, do not trust the client. The client can easily ignore it and ask your API again and again.
A better approach would be to use server side caching techniques.
However, it is possible to use the ResponseCacheAttribute to solve your issue. Here is an example.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        [ResponseCache(Duration = 123, VaryByHeader = "User-Agent")]
        public IEnumerable<string> Get()
        {
            return new string[] {"value1", "value2"};
        }

    }
}

In case you are serving static files. Caching is achieved by configuring it in the Startup.cs File of your project.
Here is an example:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

using Microsoft.Net.Http.Headers; // required

namespace WebApplication1
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var durationInSeconds = (int) TimeSpan.FromDays(1).TotalSeconds;
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    context.Context.Response.Headers[HeaderNames.CacheControl] =
                        $"public,max-age={durationInSeconds}";
                }
            });

            app.UseMvc();
        }
    }
}

Comment: Hi, Thanks. But, I'm dealing with static files. Hence, I have the caching logic as part of a Middleware and not in a controller.
Comment: okay, i updated my answer. hope it helps. could you update your question too and mention the static files =)

SetValidUntilExpires alternative


Unable to run phonegap iOS app

Question: I am unable to 'run' phonegap ios hello world app. Same approach on windows machine with android SDK worked. I've been googling this for a while but didn't found anything helpful. Any thoughts what may error I am getting mean?
Configuration:

phonegap -v: 3.4.0-0.19.7
cordova -v: 3.4.0-0.1.3
Mac OS X: 10.7.5 (unupgradable - Intel GMA X3100)
Xcode: 4.6.3

approach:
~: phonegap create hello
~: cd hello
~: phonegap run ios
...
** BUILD SUCCEEDED **

2014-03-16 18:24:17.091 ios-sim[6863:707] stderrPath: /Users/username/git/hello/platforms/ios/cordova/console.log
2014-03-16 18:24:17.096 ios-sim[6863:707] stdoutPath: /Users/username/git/hello/platforms/ios/cordova/console.log
2014-03-16 18:24:17.110 ios-sim[6863:707] Error loading /Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/DVTFoundation:  dlopen(/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/DVTFoundation, 265): no suitable image found.  Did find:
    /Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/DVTFoundation: GC capability mismatch
Unable to dvtFoundationBundle. Error:
   [error] /Users/username/git/hello/platforms/ios/cordova/run: Command failed with exit code 1

Answer: I solved that issue by downgrading to ios-sim 1.8.2
npm uninstall -g ios-sim
brew uninstall ios-sim
npm install -g ios-sim@~1.8

Comment: I wrote that I needed to downgrade to 1.8. Your version [1.9] was the problem. See `npm install -g ios-sim@~1.8`.
Comment: no i have [ios-sim --version 1.9.0] and i have the same error
Answer: I got the same issue. I had installed ios-sim using npm. Try uninstalling ios-sim and install it using brew.
npm uninstall -g ios-sim

brew install ios-sim

Comment: ios-sim from brew give the latest version, only. So it doesn't help.
Answer: I solved this by (1)brew uninstalling the 1.9 version and then
                 (2) brew install the 1.8 version
This link explains the version change in brew: https://coderwall.com/p/lqphzg
Comment: Add more explanation to your answer. Because link only answers will expire if the link is expired.
Answer: I solved the issue by upgrading Xcode from 4.x.x to the latest (5.1.1). Then I reinstalled ios-sim using MacPorts. Then "phonegap run ios" succeeded.
Answer: This is a strange issue.
In my case, I solved this by running the project in Xcode on a simulator (found at platforms/ios/*.xcodeproj). When I went back to phonegap the problem was resolved.

Unable to run phonegap iOS app


Java Program file.exists failure post Oracle upgrade to 18.104.22.168

Question: We have a backend Java application responsible to schedule batch-jobs. It connects to the Oracle database, obtains the list of applicable jobs for the current run and executes them. The job type could vary from calling a Stored Proc, to moving a file etc.
We are testing upgrade of Oracle from 184.108.40.206 to 188.8.131.52. Surprisingly, all the Move jobs are failing (indicating file doesn't exist) post this upgrade. This is the issue I am facing.
Unfortunately, this Java application is a packaged product and I don't yet have access to the complete source code. I decompiled the class files. Before the move occurs, the Java program checks for the existence of the files using "if(!sourceFile.exists())"
This attempt fails, leading to reattempts by the job and finally fails. We have already verified the file and folder permissions etc. I also downloaded the latest ojdbc5.jar for 220.127.116.11 from Oracle's website. But no luck. This environment is on a Linux-Solaris server.
My question: Do you think there is any version dependency on Java or anything else because of the Oracle upgrade?
Please let me know if you have any suggestions.
Answer: The list of new features for 126.96.36.199 says in 2.1.8:

Oracle ACFS security feature provides the ability to create realms to specify security policies for users or groups for accessing file system objects. The Oracle ACFS security feature provides finer-grained access control on top of the access control provided by the operating system.

So I suspect the permission to access the file system is missing on the java level.

Java Program file.exists failure post Oracle upgrade to 11.2.0.3


How to interpret the transformation guide for fitting linear regression?

Question: These two figures give the plot of x vs y, and how to transform either or both x or y variables to fit a linear regression. How to interpret the following transformation schemes? Especially, how to interpret the last column "Linear Form"  and "Linearizable Function" given the transformation? note: Figure a and b are the first two graphs. c and d are the second two below a and b and so on.
Answer: Regression via OLS can only be applied if the model equation is linear in the parameters. This means that all parameters $\beta_i$ that are to be estimated need to be either added, subtracted or multiplied to the regressors $X_i$. They cannot be a power or be in a logarithm for example (any non-linear operation). This is so because non-linear parameters cannot be written in matrix form and hence cannot be minimized algebraically yielding a unique solution via minimizing a squared loss (numerical optimizations are possible). The restriction does not hold for the regressors themselves, hence "linear regression" does not mean you can't have for example $X^2$, but that you can't have for example $2^\beta$.
In your table, the "linearizable functions" are functions non-linear in the parameters (note how the $y$s are not linear in the $\beta$s). However, by transforming $y$ using the function in the column "transformation", the function can be made linear in the parameters and thus estimate-able via OLS. The form shown in the last column "linear form" is the form you can do OLS with.

Take for example the first row:

$y = \beta_0 x^{\beta_1}$. Here $\beta_0$ is linear, $\beta_1$ is in the exponent.

Take the log of 1. to get $\log(y)=\log(\beta_0)+\beta_1\log(x)$. Here, $\beta_1$ has been linearized, so no more problems there. However, $\beta_0$ is inside the $\log$ which is not linear. However, when we do the LS regression, we will get $\log(\beta_0)$ as an estimate which we can then simply exponentiate to get $\beta_0$. Since no regressor $x$ is attached to (e.g. multiplied by) $\beta_0$, this is no problem.

Define $\log(y)=y'$ and $log(x)=x'$. Now to do OLS, simply use $\log(y)$ as a response and $\log(x)$ as a regressor (instead of the original $y$ and $x$).


Python smtplib email doesn't send to External Addresses

Question: I'm able to automate some emails internally using mime and smtplib, but for some reason, these emails fail to send to external addresses (outside of company's domain)
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import Encoders
import smtplib

SERVER = 'mailrelay'
FROM = 'firstname.lastname@example.com'
TO = ['firstname.lastname@example.com','email@example.com']

body = 'This is a test'

msg = MIMEMultipart()
msg["To"] = ','.join(TO)
msg["From"] = FROM
msg["Subject"] = 'Automated Test Email'

msgText = MIMEText(body, 'html')
msg.attach(msgText)

message = msg.as_string()

server = smtplib.SMTP(SERVER)
server.sendmail(FROM,TO,message)
server.quit()

Produces this error:
SMTPRecipientsRefused: {'email@example.com': (550, '5.7.1 Unable to relay')}

Admin insists that relaying is enabled, and told me that sending emails to external domains using Powershell works, so it can't be a relay issue.
So now I'm stuck. If it's not the problem python is telling me it is, is my admin wrong or is something else going on?
Any ideas?
Answer: Looks like I just needed to authenticate in this case:
server.ehlo()
server.starttls()
server.ehlo
server.login('user', 'pass')


How to create a chart about a date range if some dates in this range are missing?

Question: I use charts module Charts and I want to create a view that shows the stats from a date range.
I have an exposed filter and this filter has a between range. I want to show all dates from values of exposed filter.
I provided the values 7/10/2015 and 15/10/2015 as my date range and always show the dates if no stats exist for specific days in this range.
For example:
7/10/2015, 8/10/2015, 9/10/2015, 10/10/2015, 11/10/2015, etc. up to 15/10/2015,
Attached an image to understand what I want (how the chart should look like).

How can I do this, with filter, arguments or handlers, please give me a example.
For this moment the module "views between date filter" is not working as I want: it only shows all dates for which some data exist. But always need show the dates that no have results.
Answer: I'm assuming you're using the Charts module and that your problem is similar to what is detailed in Comment nr 12 of Issue nr 2052429. Here is part of what that comment includes:

... It's not an issue Google Charts could actually fix, as there is no "labels" sent to Google Charts for the chart addons for it to recognise gaps in the data ...

So at a minimum I recommend you to try the most recent DEV version, and apply the patch attached to that comment, to check if that helps in your case. If it doesn't, know that it is a prereq for sure (without that patch you won't be able to get it to work).
If applying the patch is not sufficient, then I'd recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.
Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.
Comment: sorry my english is no good, y try the latest version of charts module and i tell you
Comment: thank you for the update. Make sure to use the latest "dev" version of the charts module. It is really stable, and fixes multiple issues that exist in the RC1 version (and probably soon to be released as a next official release. Let me know how it goes (via an extra comment here), ok? Ps: please EDIT your question to add the CHARTS module link somewhere in your question (as I suggested before).
Comment: i use the lastest version dev of charts module, but continue without make the functionality that i want, any idea to make the stats that i want, always show the date range, first i dont know how to show fields, provide to filter views, always show the range, but first i need to create the field that show this range but i dont know how, thanks again
Comment: Hm, that sounds like you have "a few" (1 or more?) other questions you need to get sorted out (before you have a chance to succeed with the chart you asked about in this question). Attempt to get you going: please look at my answers to the questions at http://drupal.stackexchange.com/search?q=user%3A39516+[charts]+date ... If needed feel free to add a comment to any of my answers there (related to the specific question/answer). Otherwise create 1 (or more) new specific questions, to find the answer(s) step by step. OK?


Escaping single and double quotes in Regex inside vee validate

Question: I cannot get my head around how to escape single and double quotes in this case:
v-validate="{ min:3, max:200, url:true, regex: /^(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))$/}"

Comment: I would just move that object definition into your script and out of the template.
Comment: Do you have some sample strings to test?
Answer: regex.html
<input v-validate="{ regex: regex }" />

regex.vue
...
data: {
    regex: /^(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))$/
}
...


Drop down menu without any module

Question: Hello is it possible to create drop down menu without using any plugins at all?
In general the structure of menu is as follows for drop down.

Top1

drop1

drop2

I have create new menu and placed menu parents and children accordingly. Now I need to know if it is possible to show the menu in structure as above without using third-party modules.
Comment: askkirati Where did you paste the code.
Comment: Allergy about plug-ins? :) Do you want to do it without using Superfish or NiceMenu.
Comment: yes @ShoaibNawaz
Comment: I tried to use menu tree but it is only showing top level menus
Comment: Then this question re related about JS/JQuery.
Comment: was unable to answer own question. but follwing worked.

Above code worked. Plus had to make show as expanded in menu management.
Comment: What is the Drupal version you are using?
Answer: You can do it with pure CSS, here is a tutorial: http://csswizardry.com/2011/02/creating-a-pure-css-dropdown-menu/ You can find several more if you google for CSS dropdown menu.
You will need to set up your menu, clicking on the "expanded" checkbox for any submenus you want to render.
Answer: You have two options:

As "Shoaib Nawaz" said in the comments, you can use Javascript (jQuery) to convert the list into a dropdown.
I don't know why you don't want to use any plugins (I suppose you mean "module")?
But if it's fine for you to create your own module, there is another solution:

Create a module
Overwrite the function theme_menu_tree to convert the "ul" into "select"
Overwrite the function theme_menu_link to convert the "li" into "option"
Bonus: If you don't want to overwrite every menus, you can overwrite only a specific menu using [MODULE]_menu_link__[MENU NAME].

Drop down menu without any module


Multi-site, shared users, paid access

Question: I'm working on a project that involves multi-sites in Drupal 8. The client specifically wants  to have shared user accounts across all 4-5 sites. As of now the sites share a codebase but not a shared database. After researching I came across the CAS module. Can CAS allow for multiple logins? When one account is made can other accounts be generated in the other 3-4 Drupal sites? Is there a better way to do this in Drupal 8? Also, the client eventually wants to have paid account registries. For example, a user would pay on one site and get access to all 4-5 sites. IS there any guidance for accomplishing this? If not with CAS what other modules / resources would I need to make this doable in Drupal 8?
So far I've seen sites that offer advice on this but largely with Drupal 7 with out a clear path for doing this in Drupal 8. CAS seemed the most stable option but not sure if it will work. There was also the option of sharing users through shared tables, though this was discouraged in the forums I read. What is the best / proper way to do this in Drupal 8? Or should I go back to Drupal 7?
Comment: Take this with a grain of salt but this sounds like CAS/SAML. CAS has plenty of readme and docs last i looked at it
Comment: It does, however, I haven't seen docs on what I'm looking for.
Answer: CAS module is a nice option, and it is quiet stable in D8 (using it in production site since more than a year). Morerover, SSO looks more confortable for users that don't have to reconnect when they jump from one site to another.
You should know that each D8 site will have its own user table created by the CAS/Externalauth modules'stuff.
If you plan to grant different access permissions based on something (many payments methods), imho, you should store these infos somewhere regardless to drupal (more precisly : anywhere your CAS server can retrieve, i have not tryed cas_server). Those could be retrieved in attributes sent during connection according to CAS protocol (CAS parameters).
Note : Given the fact each of you websites store its user table, and do not necessarily know the existence of an user "x" until its first connection to this site, you just have to pay attention on duplicates. Easiest way is probably to use email as UID but you undestand the idea.
Comment: Do you know of any documentation I can read regarding how to accomplish what I'm looking to do in CAS? On each site we were planning to give users the same permissions. Basically, with the project I'm doing the sites are actually duplicates but with different branding. The person I'm doing it for wants 3 basic payment levels / users and wants them to be able to use one login to access all sites. The setup and documentation to set this up was really confusing. Would you be able to point me in the right direction (I'm new to using this particular module)?
Comment: First, install a CAS authentication server (you can try `cas_server` module, but whatever is nice too), this server has to return some info in CAS parameters (uid, mail, paid access etc.). Pay attention to the version of cas server you are installing (1, 2 or 3, this changes the protocol)
Second, install `cas` module, and set parameters in drupal admin.
Third, you can develop youre own module and listen to the event `CasHelper::EVENT_PRE_LOGIN` and `CasHelper::EVENT_PRE_REGISTER` to compute user parameters before login and registration.

Multi-site, shared users, paid access


Azure files with Network File System

Question: I have to run Moodle production servers in Azure. Need to keep userdata (moodledata folder) in a common location like NFS for better management and scalability. I tried Azure Files-SMB service (premium-SSD). The problem is Moodle website become too slow to operate after I moved 'moodledata' folder to Azure Files.
As Azure SMB protocol is visibly terrible in performance for this application. I need to give a try in NFS. I found somewhere that NFS protocol performs better than SMB in handling files small in size down to KB. Moodle user folder is having thousands of such small files including user session related ones.
I am not familiar with Azure services, looking for an Azure alternative of AWS EFS. I am looking for a step by step guide on how to enable NFS4 in Azure storage account.
Last time I tried, it was asking for something like "Sign Up for NFS on subscription basis". Submitted one survey as part of the "Sign Up", later no idea what happened. Still during Storage Account creation time it shows NFS feature in disabled state. Please help.
If protocol is not really the performance bottleneck here then what else could be?
OS- CentOS-8
DB- Postgresql-10
Comment: I have the same issue, did you find a workaround?
Comment: @OmarJG right now I have an open support ticket with Microsoft Azure. They are analysing the data provided from my test bed. Most probably they may suggest me to go with some cache tweaking I guess.
My Plan-B is to go with Redis or Memcache for Moodle-data directory.
Will update here.
Answer: High latency is killing your performance. SMB isn't designed to work over WAN, NFS isn't different. Try using SMB cache with your SMB File Share.
https://docs.microsoft.com/en-us/azure/storage/files/storage-sync-files-deployment-guide?tabs=azure-portal

Azure files with Network File System


When was the deceptive cadence introduced?

Question: Bach used the Deceptive Cadence as early as his Passacaglia and Fugue in C minor, BWV 582, which dates to the early 18th century. Are there earlier uses? A definitive answer may be impossible, but I am interested in how far back its usage can be traced.
Comment: Ninja cadence is by far the best possible term. Ever.
Comment: I wasn't familiar with the term 'deceptive cadence' only 'interrupted cadence'. Now I see wikipedia also calls them 'ninja cadences' I know what I'm going to use from now on :-)
Comment: You will enjoy a new issue of _Bach Adventures In Chromatic Land_ in next week's "The Baroque Fugue of the Ninja Composer"
Answer: The earliest two references I can find of what are now known as deceptive cadences originate with Josquin des Prez's Missa Una musque de Buscaya (listed without a date on Wikipedia, which only fleetingly mentions it under a different spelling, suggesting that his authorship is doubtful) and Francesco Spinacino's arrangement of Fortuna dun gran tempo.  I was not able to find particular dates for either of these works, but based on the known dates of their authors, this places deceptive cadences at least as far back as the early 1520s, if not as far back as the late 15th century.
The article I found these in itself unfortunately requires access to JSTOR, but below are the two relevant parts of the article.
Page 16:

Josquin based this mass on the popular tune Une mousse de Biscaye. The several phrases of this Hypo-Lydian melody cadence on g, f, g, b-flat, g, f, b-flat. Within the mass however, the bassus frequently adds a third or a fifth beneath these cadence tones--recognizable in the tenor at the several closings within the different parts of the mass--creating (in modern terminology) a 'deceptive cadence'. To the cadence tone f in the tenor the bassus always adds another tone--d or B-flat--disturbing the listener's unambiguous rientation  towards a final cadence in the fa-mode

Page 30:

Within the two periods bordered by the three Lydian cadences just mentioned (mm. 10-17 and 17-25), the avoidance by Spinacino of the b-natural leading tone weakens the temporary orientation  towards C in favour of the following cadences (mm. 144-15', 22242 3 ) which, in turn, are disturbed by means of a 'deceptive  cadence', the result of the contra's  introduction  of the second and third melody segment.


F string prefix in python giving a syntax error

Question: I have a variable called method, it's value is POST but when I try to run print(f"{method} method is used.") it keeps giving a syntax error at the last double quote and I can't find the reason on why it does this. I am using python 3.5.2.
Comment: This line is fine. The syntax error is most likely caused by a previous line, but Python is only detecting it on this line. Can you post the full code?
Answer: F-strings were a new feature introduced in Python 3.6, so of course they're not going to work in 3.5.2.


How could I duplicate special symbols like ^ ,_?

Question: If input = 3
Then output,
^___^
the symbol ^ must be at front and at the last.
underscore _ number is the input value
Comment: Show us what you tried.
Answer: Try <code>'^' + input_val * '_' + '^'</code>, this should do the job.
Try not to use "input" as a variable since it also is the name of the built-in function to get user inputs, it could prevent future errors.
Comment: Shadowing [builtin functions in Python](https://docs.python.org/3/library/functions.html) is a bad idea.
Comment: Could you be more explicit? What's wrong about using built-in overloaded operators + and *?
Comment: Using `input` as a variable name. We should correct mistakes made by the OP.


Why is it necessary to set a netmask of 255.255.255.255 for "alias" addresses in FreeBSD?

Question: From FreeBSD handbook on the topic of virtual hosts:

For a given interface, there must be
  one address which correctly represents
  the network's netmask. Any other
  addresses which fall within this
  network must have a netmask of all 1s
  (expressed as either 255.255.255.255
  or 0xffffffff).

Can anybody explain why this is the case?
Answer: This page contains a good explanation imho:

Since aliases are, in a sense,
  duplicate tags, the system needs to
  know whether the subnet represented by
  the tag is new, and this is indicated
  by the netmask. With a "normal"
  netmask, the system is told this is a
  new subnet, and it can then set up
  internal tables correctly. If the
  subnet is not new, the tables will get
  set up incorrectly if the netmask is
  "normal".
With a netmask of 255.255.255.255, the
  system knows this is a duplicate of an
  existing subnet, and therefore will
  assign the address as if it were
  assigned to the loopback interface,
  with the "point-to-point" mask.
Assigning a netmask of 255.255.255.0
  will, in most cases, appear to work.
  However, the internal tables will not
  be set up correctly, and if the alias
  is removed, problems may ensue. This
  can be overcome by adding appropriate
  host routes when the alias is added,
  and removing the routes when the alias
  is removed. However, the system works
  correctly with the "point-to-point"
  netmask, and maintenance is easier.
Comment: However a "point-to-point" address is a /31 or a /30. A /32 describes a single host.
Comment: @adamo: [In practice point-to-point links are typically implemented using /30 networks, or occasionally by /32 and point-to-point explicit host routes](http://en.wikipedia.org/wiki/IPv4_subnetting_reference)
Answer: In fact you can set the netmask you think is useful.
But, if you change the netmask from /32 you will also need to set a route. If you follow the recommendation you can omit setting a route.
Answer: Well the FreeBSD manpage on ifconfig is not very helpful:

If the address is on the same subnet
  as the first network address for this
  interface, a non-conflicting netmask
  must be given.  Usually 0xffffffff is
  most appropriate.

But what the above means is that a /32 mask makes this a specific network (The simplest network, a single host, is described by a /32 mask). Having the same netmask as the physical interface does not do any harm, as they are two interfaces on the same network.
Now imagine the alias having a mask that describes a superset network than that of the physical interface, e.g. the physical being 192.168.0.1/25 and the alias 192.168.0.2/24. Is 192.168.0.200 on the network and what does this mean for your alias interface?

Why is it necessary to set a netmask of 255.255.255.255 for “alias” addresses in FreeBSD?


How to check $B$ is linear in the proof of Theorem 6.8 in Linear Algebra Done Wrong

Question: I am trying to follow the proof of Theorem 6.8 in Linear Algebra Done
Wrong

Let $A : X → Y$ be a linear transformation. Then $A$ is invertible if
  and only if for any right side $b ∈ Y$ the equation $$Ax = b$$ has a
  unique solution $x ∈ X$.

I cannot understand the following part
$B$ is defined as $B:Y \mapsto X$ where $B(y)$ is the unique solution $x \in X$.

I don't know how to jump from $A(\alpha x_1 + \beta x_2) = \alpha Ax_1 + \beta Ax_2 = \alpha y_1 + \beta y_2$ s to $B(\alpha y_1 + \beta y_2) = \alpha B(y_1) + \beta B(y_2)$.
Thank you in advance!
Comment: How is $B$ defined?
Answer: $A$ is the matrix which represents the linear transformation then
$$A(\alpha x_1 + \beta x_2) = \alpha Ax_1 + \beta Ax_2 = \alpha y_1 + \beta y_2 \iff B(\alpha y_1 + \beta y_2) = \alpha B(y_1) + \beta B(y_2)$$
Refer also to the related

Proving any linear transformation can be represented as a matrix
Comment: @JOHN We are using that $$Ax=y \iff B(x)=y$$ then $$A(\alpha x_1 + \beta x_2) = \alpha y_1 + \beta y_2 \iff B(\alpha y_1 + \beta y_2) = \alpha B(y_1) + \beta B(y_2)$$
Comment: Yes. I know that a matrix is a linear transformation. And I can also follow the left side of the equation. But the right side, I am not OK.


Prevent ListView from cutting off first letter of ListViewItem when selected in WinRT

Question: In a Xaml/C# WinRT application, whenever a ListViewItem is selected, the first letter on the left gets chopped off.  How can I prevent this?
<ListView>
    <ListViewItem Content="Hello World"/>
</ListView>

Unselected and Full:

Selected and Truncated:
Answer: You can apply a margin to an item within the ListViewItem itself like below, which will stop the cut off.  Alternatively you could use a ContentTemplate as the second example.
Example 1:
<ListView>
    <ListViewItem>
        <TextBlock Text="Hello World" Margin="5,0,0,0"/>
    </ListViewItem>
</ListView>

Example 2:
<ListView>
    <ListViewItem Content="Hello World!">
        <ListViewItem.ContentTemplate>

            <DataTemplate>
                <TextBlock Text="{Binding}" Margin="5,0,0,0"/>
            </DataTemplate>

        </ListViewItem.ContentTemplate>
    </ListViewItem>
</ListView>

Comment: Thanks, it's odd that this wouldn't do something like this out of the box
Comment: Yeah you would expect it to indent on selection automatically.  Hope it helped.
Comment: It does.  I'm actually adding the items programmatically so now I'm looking into using the `ContentTemplate` as a resource and applying it to all child items in the `ListView`
Comment: That is how I use it in my projects, gives you a nice amount of control too.
Answer: As a follow up to Brandon Scott's answer, if you would rather not apply this inline, you can set this behavior as a style and then apply that style to individual list items like so
<Application.Resources>
    <ResourceDictionary>

    </ResourceDictionary>
</Application.Resources>

Then, apply the style to your list view items
<ListView>
    <ListViewItem Content="Hello World" Style="{StaticResource ListViewItemMagin}"/>
</ListView>

If you want to enable this by default, you can omit the x:Key property on the style and it will automatically apply to any element matching the TargetType; like so:


The $n$th-derivative of $q(x) = x^4 - 8x^3 - 4x^2 + 3x - 2$, where $n \le 4$

Question: Some factors will be $\frac{4!}{(4-n)!}\cdot a_nx^n, \frac{3}{(3-n)!} \cdot a_{n-1}x^{n-1}, \ldots, \frac{1!}{(1-n)!} \cdot a_0x^0$, but the lowest degree one will always become zero in the next derivative and I don't know how to express that in a formula. I know $f^{(4)}(x)=4!\cdot a_nx^0$ and all the following derivatives are $0$ since $f^{(4)}(x)$ is a constant but how do I get rid of the lower degree terms in $n$th-derivative notation?
Answer: I think it can be done if we do not use the factorial notation.
Let's consider the simplest case $y = x^k$. By writing out the first few derivatives, we easily see that $$y^{(n)} = k(k-1)\cdots(k-n+1) x^{k-n} = \bigg(\prod_{i=1}^n(k+1-i)\bigg)x^{k-n}.$$
There is no problem when the number of times we take the derivative is less than or equal to the degree $k$, that is, no problem when $n \leq k$. But there is also no problem if $n > k$ because somewhere in the product $\prod_{i=1}^n(k+1-i)$, there will be a $0$ term, so that $y^{(n)} = 0$.
So applying the above to the function $q(x)$ in the title, we have
$$
q^{(n)}(x) = \bigg(\prod_{i=1}^n(5-i)\bigg) x^{4-n} - 8\bigg(\prod_{i=1}^n(4-i)\bigg) x^{3-n} -4 \bigg(\prod_{i=1}^n(3-i)\bigg) x^{2-n} + 3 \bigg(\prod_{i=1}^n(2-i)\bigg) x^{1-n} -2 \bigg(\prod_{i=1}^n(1-i)\bigg)
$$
for any $n \geq 1$.


Convert year from unicode format to python's datetime format

Question: I have only year parameter as input in the following manner:
<code>2014,2015,2016
</code>
I want to convert each element from my list into python's datetime format. Is it possible to do this kind of things if the only given parameter is the year ?
Answer: Just set month and day manually to 1
<code> from datetime import date
 YearLst = [2014,2015,2016]
 map(lambda t: date(t, 1, 1),YearLst)
</code>


Webform - How to filter submissions by user?

Question: I need to make a view that displays to the current user her own submissions.
Option 1: For a specific node and then I can display also the data.
Option 2: For any node and then I can just use the metadata of the submission.
Could not find how to do it... Thanks!
Answer: You can create the view to display the webform submissions. You need to give the webform node id to fetch particular submissions.
I have added the exported view. This is just displaying the submitter name as per my webform. So this is just skeletal view. You can add fields as per your requirement. You will have to change your webform node id and manipulate as per your requirement.
<code>$view = new view();
$view->name = 'webform_submission';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'webform_submissions';
$view->human_name = 'Webform Submission';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Webform submissions: Serial number */
$handler->display->display_options['fields']['serial']['id'] = 'serial';
$handler->display->display_options['fields']['serial']['table'] = 'webform_submissions';
$handler->display->display_options['fields']['serial']['field'] = 'serial';
/* Field: Webform submission data: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'webform_submissions';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['webform_nid'] = '1';
$handler->display->display_options['fields']['value']['webform_cid'] = '1';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'user/webform_submissions';
</code>
Answer: You can accomplished this task by downloading this module https://www.drupal.org/project/webform_views
After that, you can get all the elements from your webforms in the VIEWS. Works for me.


Expected Value of the sum of random variables

Question: If i have two random variables X and Y, then $E[X+Y]=E[X]+E[Y]$ . However, do X and Y have to be independent ?
Do you know where i can find a proof of this principle ?
Comment: It is based on the fact that $\int (f+g)d\mu=\int fd\mu+\int gd\mu$. Expectations are integrals on the underlying probability space.
Answer: No, they don't. This is called linearity of expectation and holds for all r.v's $X$ and $Y$ - in fact, it holds for a general sum of $n$ random variables regardless of any correlation.
If you google "linearity of expectation" there are lots of articles that have proofs in them