Angular DataTable Responsive Extension not working for server side dataTable

Question: https://l-lin.github.io/angular-datatables/#/welcome i used this angular datatable extension for, but the responsive is not working for server side datatable.
this my data table configuration
 this.dtOptions = {
      pagingType: "full_numbers",
      columnDefs: [{ orderable: false, targets: 0 }],
      pageLength: 10,
      serverSide: true,
      order:[[1,'asc']],
      processing:true,
      responsive: true,
      searchDelay:500,
      language:{
        processing:"
Loading
"
      },
      ajax: (dataTablesParameters: any, callback) => {
        dataTablesParameters.order[0].column = this.getColumnName(
          dataTablesParameters.order[0].column
        );

        that.http
          .post<DataTablesResponse>(
            this.globals.url + "productservice/getallproducts",
            Object.assign(dataTablesParameters, this.data),
            {
              headers: this.header,
            }
          )
          .subscribe((resp: any) => {
            //console.log("Response",resp);
            //console.log("Date",resp.data);

            that.products = resp.data;

            //to load image
            for(let product of that.products){
              if(product.image_url != null){
                product.image_url = this.globals.url+product.image_url;
              }
            }

            timeout(10),
              callback({
                recordsTotal: resp.recordsTotal,
                recordsFiltered: resp.recordsFiltered,
                data: [],
              });
          });
      },

      columns: [
        // { data: "image_key",title:"" ,responsivePriority: 1},
        // { data: "name",title:"Product name",responsivePriority: 2},
        // { data: "description",title:"Description",responsivePriority: 3 },
        // { data: "price",title:"Price" ,responsivePriority: 4},
        // { data: "hsn_sac_code",title:"HSN code",responsivePriority: 5 },
        { data: "image_key"},
        { data: "name"},
        { data: "description" },
        { data: "price"},
        { data: "hsn_sac_code"}
      ]
    };

my version for angular datatable
"angular-datatables": "^10.0.0",
"datatables.net": "^1.10.22",
"datatables.net-dt": "^1.10.23",
"datatables.net-responsive": "^2.2.7",
"datatables.net-responsive-dt": "^2.2.7",

i am trying to implement https://l-lin.github.io/angular-datatables/#/extensions/responsive
but its not working. have anyone done this previously i couldnt find any question for this issue.
Answer: It is very simple, you need to set callback data
   // that.products = resp.data; // remove this line

  callback({
                recordsTotal: resp.recordsTotal,
                recordsFiltered: resp.recordsFiltered,
                data: resp.data,   // insteal of []
                });

Comment: i tried this way it worked but the problem is that i have click function on my table. In the above way i need to remove tbody for the table. anyways thanks mate @Sarvin Khan Tabatabaie


Use or don't use virtualization for Linux Webserver?

Question: I maintain the servers for a big webproject (java + postgres + some tools around) which is currently hosted on three machines:

Machine: Mailserver (postfix), Ad-Server (lighttpd + php + openx)
Machine: Tomcat + Servlet
Machine: PostgreSQL-Server, static content (via lighttpd)

All machines run Debian Stable and are connected via a VPN (openvpn). As the hardware is very old (AMD Athlon 3000+ and 2GB RAM on each) its time for a change.
These servers should now be replaced by one big machine (16GB Ram, big Intel CPU's supporting VT, 5 IP's).
The question now is: Should I still seperate the differents tasks using Virtual Machines or should I simply put everything on the machine as usual. Where are the pros and cons?
I thought of the following:
Pro Virtualization:

Security: As the vm's are seperated you cant take the whole machine (hopefully)

Con Virtualization:

Performance: There is a performance loss
Work: Every maintaince-work has to be done several times for every vm
Communication: Communcation of the different vm (Servlet do Database) gets more complicated.
Hard Memory Limits: I have to assign static resources (like Memory) to each machine. This can be a con if say my db-server needs more ram for 30 seconds (than it got assigned) and there would be more ram available on other machines. With no virtualization this wouldn't be a problem.

Thanks for any hints.
Comment: Could you indicate what virtualization method you were considering? That impacts answers that address both performance and security points.
Comment: I considered no method, I wanted to make this decission independent of a software choice and then select the best software afterwards.
Answer: Virtualization is nice, as many people mentioned, for the fact that you can easily make/restore a snapshot.
I'd like to address some things. Someone mentioned the need to maintain multiple machines versus one. It is possible to reduce a lot of that maintenance by net booting the vm's, and mounting the partitions of all software from a central point. This way, software updates/installs automatically migrate to the other machines, eliminating most of the additional maintenance time.
There's also a 3rd option: FreeBSD jails. - These let you create separate environments without the overhead of virtualization. - Separation is much higher than common GNU/Linux chroot ( everything, even the network layer, is separated at the kernel level) - each jail can have it's own IP, and these are actually NOT virtualized, rather just isolated environments in the kernel+filesystem.
http://en.wikipedia.org/wiki/FreeBSD_jail
I wouldn't dismiss the security gain as a pro. It is true that it is possible to break out of virtual machines under certain conditions (bugs in vm software - though these get patched; keep up with updates, as with anything else) - Security is about layers, not one layer is failsafe. While simplicity tends to benefit security, there are some things that just give you too much benefit, and as I mentioned, things can be simplified by mounting the base system from a central location (could even be a read-only mount) -
Here's a real-world example:
Say a php application has a mysql injection vulnerability in it, an attacker could exploit this to write files to your server. (eg: via the INTO OUTFILE sql syntax) - A common approach is to write a php file containing more exploit code, further breaching the server; after all a php script is almost equivalent to a shell account running as the user executing it (the user executing the apache process) - From there an attacker is only a local exploit away from full root access.
If mysql is in an isolated environment, say a virtual machine, a bsd jail, or a chroot environment, the attacker would be able to write his php code to a file, but he'd never be able to execute the file by visiting a url, since the mysql service would not have access to any files hosted by apache.
Comment: Thanks for the BSD-Jail-Hint, but I got no BSD experience at all, so thats not an option.
Comment: openVZ seems equivalent to BSD Jails on linux
Answer: I would prefer the virtualization because,
a.) You can do server backups on a very easy way
b.) You can create a second instance of a running server to test something without touching the production server
c.) You can perfectly handle the resources to give one server more priority then the others.
cheers
plucked
Answer: virtualization is the way.
this way, you can easily backup/restore or even move your vm from one server to another with minimal downtime.
with good hardware, software and good setup, the performance loss is minimal. just use ssh for all communication and use separated local IPs that's inaccessible from internet. simple and secure.
in the long run, you will find the maintenance is actually easier. openvz even let you easily take snapshot of any running vm.
and it scale! it's much easier to add more vm than to add more hardware.
also, any one vm crash/down will not affect other vm.
Answer: Performance loss - Yes, technically there is one. Is it something you or your users will notice? Unless it's some crazy high-end workload, or you horribly over-provision VM's* (or are trying to squeeze 5 VM's with a "normal" RAM allocation onto an old, existing server, I seriously doubt it. Remember to actually check your RAM usage - if you're splitting everything up, you don't need, say, 512megs for an NTP server that defaults to runlevel 3. (Splitting off JUST an NTP server is excessive, it was merely an example.)
Work - This is true. If it's only going from, say, one to three servers, probably not that big a deal - do your change, copy/paste your commands from one terminal session to the other. Past that though, you want some kind of management tool, I'm currently looking at Puppet.
*Memory Limits - Depends on the virt. solution you use. Some environments, like ESX/vSphere allow you to allocate more RAM to VM's than physically is available. If you pay for the feature, ESX let's you set up resource pools, and will automatically adjust resources as needed, with the ability to set priorities. Like everything, you have to know how it works and the tradeoffs in a particular environment.
Answer: That security part is pretty relative, as you will have to secure three environments instead of just one, and separation alone isn't exactly going to offer much security.
You are correct that there is a performance loss, not to mention the fact that any bug in your virtualization software may crash the entire machine.


How to get content-type from an iframe?

Question: Is there a way to get the content-type of an iframe's content inside the load event handler function attached to it?
Answer: i assume this should do the work using jquery
<code>$('iframe').contents().contentType
</code>
in the load event this should point to the iframe dom so
<code>$(this).contentType
</code>
should work
Comment: Both ways returns me 'undefined'. But I know where you are going, you are getting the contentType property from the document DOM element. Why the content() method doesn't return the document DOM element? I have found an alternative way of getting the document element using raw javascript, but I would like to do it using jQuery.

How to get content-type from an iframe?


Solution to this limit

Question: Can anyone tell me how to calculate this limit. It is a puzzle so I think there must be some trick.
$lim_{x \to \dfrac{\pi}{20}} \left( {(\sec x)}^{\cos x} + {(\csc x)}^{\sin x} \right)$
Comment: I suspect that it is $\pi/2$, which makes it a bit more interesting.
Answer: Notice, both the limits exist separately so we can break the given limit as follows $$\lim_{x\to \frac{\pi}{20}}\left(\sec^{\cos x}(x)+\csc^{\sin x}(x)\right)$$
$$=\lim_{x\to \frac{\pi}{20}}\left(\sec x\right)^{\cos x}+\lim_{x\to \frac{\pi}{20}}\left(\csc x\right)^{\sin x}$$
$$=\left(\sec \frac{\pi}{20}\right)^{\cos \frac{\pi}{20}}+\left(\csc \frac{\pi}{20}\right)^{\sin \frac{\pi}{20}}$$
Answer: $\sin$ and $\cos$ are analytic, so they're continuous everywhere, and in particular,
$$
\lim_{x \to \frac{\pi}{20}} \sin x = \sin \frac{\pi}{20}
$$
and
$$
\lim_{x \to \frac{\pi}{20}} \cos x = \cos \frac{\pi}{20}
$$
Since $\sin \frac{\pi}{20} \neq 0$ and $\cos \frac{\pi}{20} \neq 0$, the same applies to $\sec$ and $\csc$, so you can just evaluate this limit by substitution: replace all the $x$ with $\frac{\pi}{20}$ and you're done.
Answer: $$\lim_{x \to \frac{\pi}{20}} \left( {(\sec(x))}^{\cos(x)} + {(\csc(x))}^{\sin(x)} \right)=$$
$$\lim_{x \to \frac{\pi}{20}} \sec^{\cos(x)}(x)+\lim_{x \to \frac{\pi}{20}} \csc^{\sin(x)}(x)=$$
$$\sec^{\cos\left(\frac{\pi}{20}\right)}\left(\frac{\pi}{20}\right)+\csc^{\sin\left(\frac{\pi}{20}\right)}\left(\frac{\pi}{20}\right)\approx 2.34901$$

Solution to this limit


Why is half-duplex mode supported for 10BASE-T and 100BASE-TX networks?

Question: I'm currently learning about Ethernet standards, auto negotiation and duplex mismatch. That made me wondering why half-duplex operations is allowed in 10BASE-T and 100BASE-TX networks. Wouldn't it have been easier to enforce full-duplex operation in the IEEE standard?
Answer: Stop it, you're making me feel old. ;)
Ethernet was originally designed to connect to shared media.  There used to be devices called "hubs."  Outwardly, hubs look almost the same as switches do today, but the way that they forward frames is fundamentally different.
Nearly every Ethernet switch will build a database that maps MAC addresses to RJ-45 ports.  It builds that database by learning what is connected to its port.  It deduces what is connected from the source MAC addresses observed on the connected wires.  When a switch receives a frame on a port, it does a lookup in this database to find where it should send the frame.  If there is no database entry, it "floods" the frame - sends it to all ports in an attempt to elicit a response.  The key to remember here is that switches try to send traffic only where it needs to go.
Hubs don't bother with any of that.  It simply sends every frame, every bit received on a port, to all other ports as soon as it is received.  The implication here is that two stations cannot send frames to the network at exactly the same time.  If they did, they would garble each other's frames.  There is an in-built mechanism in Ethernet to deal with this situation called collision detection.  (You may have seen the term CSMA/CD - this is the CD part of that term.)
To answer your question, duplex becomes an issue when connecting to hubs.  Hubs cannot speak to stations in full duplex because, in full duplex operation, there is no way for a station to apply collision detection.  The full-duplex station expects traffic to flow in and out concurrently, and the station assumes that it should not stop transmitting when it receives a frame.  In short, half-duplex operation enables collision detection; full duplex operation disables it.
An Ethernet hub provides 10 or 100 Mbits of shared bandwidth for all connected stations. In other words, the sum total bandwidth usage of all stations on a hub cannot exceed that 10 or 100 Mbits.  Switching technology is clearly far superior when you consider that the total bandwidth usage on any one switch port cannot exceed 10 or 100 Mbits.
Gigabit Ethernet was developed after switches became ubiquitous and half-duplex operation was no longer needed.
If you're interested, Ethernet 10Base-2 is another example of shared media.  Token Ring is yet another example, with a different way of solving the collision detection problem.
HTH!
Comment: How can these "hub" things you're referring to make you feel old?  *Real* Ethernet runs on thick co-ax with vampire taps, transceivers, and AUI cables.
Comment: +1 - I love the smell of melting shared-collision-domain Ethernet in the morning.  >smile<
Comment: I still have a tap coring tool gathering dust on a shelf somewhere.
Comment: @Iain DEMPRs, DECserver 200s and 300s, DELNIs...
Comment: @ward I'll see your nostalgia and raise you DECNet, LAT, VT220, VXT2000
Comment: @B Knight thank you so much for your detailed answer :)..


Iterating over standard in blocks until EOF is read

Question: I have two scripts which are connected by Unix pipe.  The first script writes strings to standard out, and these are consumed by the second script.
Consider the following
# producer.py
import sys
import time
for x in range(10):
    sys.stdout.write("thing number %d\n"%x)
    sys.stdout.flush()
    time.sleep(1)

and
# consumer.py
import sys
for line in sys.stdin:
    print line

Now, when I run: python producer.py | python consumer.py, I expect to see a new line of output each second.  Instead, I wait 10 seconds, and I suddenly see all of the output at once.
Why can't I iterate over stdin one-item-at-a-time?  Why do I have to wait until the producer gives me an EOF before the loop-body starts executing?
Note that I can get to the correct behavior if I change consumer.py to:
# consumer.py
import sys
def stream_stdin():
    line = sys.stdin.readline()
    while line:
        yield line
        line = sys.stdin.readline()

for line in stream_stdin():
    print line

I'm wondering why I have to explicitly build a generator to stream the items of stdin.  Why doesn't this implicitly happen?
Answer: According to the python -h help message:

-u Force  stdin,  stdout  and  stderr to be totally unbuffered.  On    systems where it matters, also put stdin, stdout and  stderr  in
  binary  mode.   Note  that there is internal buffering in xread‐
  lines(), readlines() and file-object  iterators  ("for  line  in
  sys.stdin")  which  is  not  influenced by this option.  To work
  around this, you will want to use "sys.stdin.readline()"  inside
  a "while 1:" loop.


Simplify this rational ${f(x)\over g(x)}$ expression if it is possible

Question: $${1-x^8\over x^{12}-10x^{10}+37x^8-42x^6+26x^4-8x^2+1}$$
I have tried and can't simplify this expression any further.
Can anyone please help me if you can, to simplify this above rational expression?
The denominator, I can't see what are the factors
$y=x^2$
$${1-y^4\over y^{6}-10y^{5}+37y^4-42y^3+26y^2-8y+1}$$
Comment: Is this the original expression that you were asked to simplify?  Or is it the result of previous steps?  If the latter, have you verified that the previous steps are correct?  If the former, what have you tried so far?  The numerator can be factored as a difference of squares.  The denominator factors, but it is not obvious to me how to factor it by hand (i.e. without a CAS).
Comment: this is the original expression
Answer: The given expression, as per substitution, gives
$$G(y)=\frac{f(y)}{g(y)}={1-y^4\over y^{6}-10y^{5}+37y^4-42y^3+26y^2-8y+1}$$
$$={(1-y^2)(1+y^2)\over y^{6}-10y^{5}+37y^4-42y^3+26y^2-8y+1}$$
$$={(1-y)(1+y)(y+i)(y-i)\over y^{6}-10y^{5}+37y^4-42y^3+26y^2-8y+1}$$
Now, $G(1)=G(-1)=\frac{0}{5}=0$
And $G(i)=G(-i)=\frac{0}{11+24i}=0$
This implies, that the denominator and the numerator do not have any common roots, i.e. common factors.
Hence, the given expression is irreducible.
Answer: $$  \left(   x^{12}  - 10 x^{10}  + 37 x^{8}  - 42 x^{6}  + 26 x^{4}  - 8 x^{2}  + 1 \right)  \left(   \frac{  - 5682 x^{6}  - 3843 x^{4}  - 2682 x^{2}  - 5218 }{ 87125 }  \right)  -  \left(   x^{8}  - 1 \right)  \left(   \frac{  - 5682 x^{10}  + 52977 x^{8}  - 174486 x^{6}  + 118055 x^{4}  - 39062 x^{2}  - 81907 }{ 87125 }  \right)  =  \left( -1  \right)  $$
...................
Answer: Here's a session with Pari-GP:
<code>> gp
                      GP/PARI CALCULATOR Version 2.9.3 (released)
              i386 running darwin (x86-64/GMP-6.1.2 kernel) 64-bit version
            compiled: Jul 15 2017, Apple LLVM version 8.1.0 (clang-802.0.42)
                                threading engine: single
                     (readline v7.0 enabled, extended help enabled)

                         Copyright (C) 2000-2017 The PARI Group

PARI/GP is free software, covered by the GNU General Public License, and comes WITHOUT
ANY WARRANTY WHATSOEVER.

Type ? for help, \q to quit.
Type ?15 for how to get moral (and possibly technical) support.

parisize = 8000000, primelimit = 500000
? ?gcd
gcd(x,{y}): greatest common divisor of x and y.
? ?gcdext
gcdext(x,y): returns [u,v,d] such that d=gcd(x,y) and u*x+v*y=d.

? f=x^{12}-10*x^{10}+37*x^8-42*x^6+26*x^4-8*x^2+1
%1 = x^12 - 10*x^10 + 37*x^8 - 42*x^6 + 26*x^4 - 8*x^2 + 1
? g=x^8-1
%2 = x^8 - 1
? gcd(f,g)
%3 = 1
? gcdext(f,g)
%4 = [5682/87125*x^6 + 3843/87125*x^4 + 2682/87125*x^2 + 5218/87125, -5682/87125*x^10 + 52977/87125*x^8 - 174486/87125*x^6 + 23611/17425*x^4 - 39062/87125*x^2 - 81907/87125, 1]
? quit
Goodbye!
</code>
The two polynomials are coprime.
Comment: @WillJagy I trust more Pari-GP than my computations by hand. :-)
Comment: I see, pari puts individual coefficients in lowest terms. I wrote my thing to put all on a common denominator. Nice to see confirmation.
Comment: Right. But this is my own  C++ program (with GMP for large integers), that  puts directly into typeset Latex. Took me some time...


mysql nested query not working with an AND condition

Question: I don't understand this: the two following queries are almost identical, the only bit that differs is the "and o.shop_id=1" part, yet they don't produce the expected results.
The first query:
select count(*) as count
from ek_order o
where 1

and
(
  select
  s.code
  from ek_order_status s
  inner join ek_order_has_order_status h on h.order_status_id=s.id
  where o.id=h.order_id

  order by h.date DESC
  limit 0,1

) in ('preparing_order')

Result of the query: 1
The second query:
select count(*) as count
from ek_order o
where 1

and o.shop_id=1

and
(
  select
  s.code
  from ek_order_status s
  inner join ek_order_has_order_status h on h.order_status_id=s.id
  where o.id=h.order_id

  order by h.date DESC
  limit 0,1

) in ('preparing_order')

Result of the query: 0 (I expected 1!)
My schema structure looks like this:
ek_order:

id: pk
shop_id: nullable fk
...other fields not relevant here

ek_order_has_order_status:

id: pk (I noticed it was not needed, but too late...)
order_id: fk
order_status_id: fk
date: datetime
...other fields not relevant here

ek_order_status:

id: pk
code: str
...other fields not relevant here

The data
The ek_order_has_order_status table has a row that looks like this:

id: 182
order_id: 283,
order_status_id: 7 (this is the 'preparing_order' code from ek_order_status )

and in the ek_order table we can find that shop_id is indeed 1:

id: 283
shop_id: 1

So what I don't understand is why the second query returns 0 instead of 1.
I tested all bits of the query apart and they seem to work (I tested the inner query first, then the outer query, both with success), but then, adding the "and o.shop_id=1" part makes the complete query fail.
Does anybody know why? and/or have a fix.
(I could resort to do two queries, but for the sake of improving my sql knowledge I would prefer to understand the bottom of this).
Ps: basically, I'm trying to get the number of orders containing the 'preparing_order' status as its final/latest status, knowing that an order can have multiple statuses.
Answer: In your second query:
SELECT COUNT(*) as count
FROM ek_order o
WHERE 1
AND o.shop_id=1
...

you are taking a count of the entire ek_order table, and it therefore does not even make sense to speak of the shop_id value for a single record.  I suspect that what you intend is if you find any record which has a shop_id value of 1, then this passes as a logical true.  If so, then you can use EXISTS:
SELECT COUNT(*) as count
FROM ek_order o
WHERE 1
AND EXISTS (SELECT 1 FROM ek_order WHERE shop_id=1)
AND ...

If this doesn't work, then another option would be to take the max value of shop_id:
SELECT COUNT(*) as count
FROM ek_order o
WHERE 1
AND MAX(shop_id) = 1
AND ...

This would make sense if you are certain that this table only has a single record and you just want to inline its value alongside the count.
Comment: Thanks. It worked with the "exists" statement. I'm not sure I understood why though: because the first statement in your answer (with "and o.shop_id=1") returns multiple rows, so count could apply on that, or couldn't it?, but I will try to collect more info on that subject. Thanks again.
Comment: @ling Sort of.  When say `SELECT COUNT(*) without `GROUP BY`, you are telling MySQL to return a single record, but that record has nothing to really do with the single record in your table, if it happens to only have one record.  Think of the count record as a sort of summary.


AIML: not getting the right answer

Question: I'm trying to learn AIML and can't understand where I've gone wrong:
<aiml>
    <category>
        <pattern>I LIKE * ROME</pattern>
        <template>
            I love talking about
            <set name="topic">rome</set>
            too!
            <random>

Did you know that slaves made up 40% of the population of Ancient Rome?

Did you know the Colosseum could sit 250'000 people?

            </random>
        </template>
    </category>
    <topic name="rome">
        <category>
            <pattern>No *</pattern>
            <that>Did you know that slaves made up 40% of the population of Ancient Rome?</that>
            <template>So I've taught you something!</template>
        </category>
    </topic>
</aiml>

The first part works fine, if I enter something like: "I like the history of Rome", I get the expected default answer and one of the random answers.
But then if he gives me the "slave" random answer and I say "No I didn't know that", he doesn't give me the "So I've taught you something" answer". He's getting the answer from somewhere else in his code, but considering that I have set the "topic" and the < that > tag, I have been quite specific and would expect my custom answer.
Answer: There is
<pattern>No _</pattern>

some where in your aiml files.
Answer: The use of the <that> tag is your choke point. For what a picture is worth, I changed your response in the initial template, and it worked.
With respect to the second reply of the bot. If it is used, then the category in the rome topic will never work because the 40$'ers  in the <that> tag has to be the last response by the bot.
There may be some confusion in the chat bot's reply. Before the topic was always changed to "rome", but in order for the pattern in the topic "rome" to work, the chat bot had to talk about the 40%'ers. I just combined the two to get the same result.
Also note that the question mark in the <that> tag was not placed there. The bot will strip it off and store the remaining result.
<?xml version="1.0" encoding="UTF-8"?>
<aiml>
<category>
  <pattern>I LIKE * ROME</pattern>
  <template>
    <random>

Did you know that slaves made up 40% of the population of Ancient <set name="topic">Rome</set>?

Did you know the Colosseum in could sit 250'000 people?

    </random>
  </template>
</category>
<topic name="rome">
  <category>
    <pattern>No *</pattern>
    <that>Did you know that slaves made up 40% of the population of Ancient Rome</that>
    <template>
      So I've taught you something!
    </template>
  </category>
</topic>
</aiml>

Answer: You can use wildcards (*) in <that> tag, so you can match only part of bot's answer (e.g. "DID YOU KNOW THAT SLAVES MADE UP").
Also note, that topic can be set inside <think> tag, which does not displays its content.
I tested the following code with Python AIML interpreter. It works as expected, but when topic name and content of <that> and <pattern> tags were lowercase, it didn't work.
<aiml>
<category>
    <pattern>I LIKE * ROME</pattern>
    <template>
        I love talking about Rome too!
        <think><set name="topic">ROME</set></think>
        <random>

Did you know that slaves made up 40 of the population of Ancient Rome?

Did you know the Colosseum could sit 250'000 people?

        </random>
    </template>
</category>
<topic name="ROME">
    <category>
        <pattern>NO</pattern>
        <that>* DID YOU KNOW THAT SLAVES MADE UP *</that>
        <template>So I've taught you something!</template>
    </category>
</topic>
</aiml>

AIML: not getting the right answer


HTTP response code after redirect to non-ascii domain name

Question: How can I get all headers for domain redirecting to non-ASCII domain?
Related question
The domain www.sendevinci.co.il redirecting to non-ASCII domain www.מגשי-אירוח.co.il.
My code is:

$url = 'http://www.sendevinci.co.il';

$options['http'] = array(
 'method' => "HEAD",
        'ignore_errors' => 1,
        'header' =>
          "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
         "Accept-Language: en-US,en;q=0.8\r\n".
                "Keep-Alive: timeout=3, max=10\r\n",
                "Connection: keep-alive",
 'user_agent' => self::get_user_agent_string($user_agent),
        "timeout" => 3
);

$context = stream_context_create($options);

$body = file_get_contents($url, NULL, $context);

print_r($http_response_header);

The result is:

Array
(
    [0] => HTTP/1.1 301 Moved Permanently
    [1] => Server: nginx
    [2] => Date: Thu, 07 Jun 2018 13:07:30 GMT
    [3] => Content-Type: text/html; charset=UTF-8
    [4] => Connection: close
    [5] => X-Powered-By: PHP/7.2.6
    [6] => Location: https://www.מגשי-אירוח.co.il
    [7] => X-Powered-By: PleskLin
)

The array should include 200 status as well, but it not.
The code works fine for ascii-name domains redirecting to ascii-name domains.
Thanks for you help!
Comment: follow_location should be enabled by default in the context, I would confirm your issue is with the redirect and not the `https://www.מגשי-אירוח.co.il` site.
Comment: I added "follow_location" => true to options, doesn't help
Comment: Well, like I said, I'd confirm the issue is with the redirect and not the site.  Have you tried replacing the $url with the latter site to see if headers are retrieved?
Comment: Did you also try var_dump(http_response_code()); ?
Comment: HTTP/1.1 301 Moved Permanently this is a 301 not a 200
Answer: At the HTTP protocol level, a 200 response code with a Location header does not make sense.  You can use a Location header with 201 or 202, but generally, 3xx is used for sending the client to a new location.  I posit that the response you are receiving is correct.  In bullet form, the HTTP location header is valid with:

201 - new resource created; get appropriate new location
202 - request accepted, still processing, check "here"
3xx - general redirection (301/Permanent, 302/Temporary, etc.)

In other words, your assertion that [t]he array should include 200 status as well is not correct.  The HTTP status code given by the server in the example is 301.
Answer: Actually, file_get_contents works ONLY with ascii domain names. So there are no simple solution to get all http headers...


Using UISearchDisplayController in a child controller

Question: I made a tabbed controller where the tabs are on top. Underneath the tabs I have a subview which will contain a tableViewController as a child controller.
The tableViewController has a searchBar and a UISearchDisplayController. The problem is, when the search is activated, the UISearchDisplayController jutts out above the frame of the tableView and covers a bit of the tabs.
I believe this is caused by the SearchBar expanding itself on top to cover up the navigationBar.
Answer: Sorry but, why are you using a search display controller?
In this case is easier if you use just a tableView with a searchBar as well as your tab.
Then you can develop the same behaviour of the searchDisplayController.
There are developers that have never used the searchDisplayController. In general i use that just when i have a tableViewController within so just a tableView and a searchBar. But in your case, i would not use that. Take your life easier trust me ;)


Can I use time series analysis on short time scales (e.g., with 5 to 30 measurements?

Question: I am studying a complex system. My goal is to understand the impact of a spreading accident (which saturates the filter (sand and plant) and creates puddles). Puddles  decrease the efficiency of the system (depollution of effluent, and moisture content). The impact on the efficiency will decrease with time (more or less depending on the season and meteorological situation).
I want to develop a model of how long the incident will impact on the pilote.
For that I think I should use time series analysis.
My question is:

Can I use time series analysis on short time scales (e.g., with 5 to 30 measurements?
or can I compare the effluent volume with the parameter that I want to study, with a decalage which should not be regular because of its depending with the effluent volume injected?
Answer: Time series nlysis works best if the series is long enough to detect periodicity or trends.  It usually will not work very well on short series.  However if you have several short series and you are looking for differences among them then you should be doing longitudinal data analysis such as repeated measures analysis of variance.
Comment: Thanks, one more question, to use longitudinal data analysis, shouldn't I independant variable?  because I can cut my data in différent periode, especially each time that there was a incident and compared them each-other but I can justify the homoscedasticity. Moreover, my data do not have normal distribution, and until now I did not find a way to intergrate them in order to have a normale distribution, so I shoul use non-parametric test which are less efficient!?
Comment: My answer to non-normality is that it depends on how large a departure from normality your data is.  For mild departures the standard methods will still work pretty well.  For extreme departure you can use nonparamtric methods or try the bootstrap.
Comment: What do you mean by "mild departures or "extreme departures"? (I read a lot french texxt on stat, so I do not have all the meaning of english vocabulary, and I admit that I am not sure of the translation! and thanks again, this will help me a lot.
Comment: @IsabelleMazerie Mild means slight.  So i am saying that if the distribution is only slightly skewed for example the standard inference assuming normality will work okay.


Finding Memory Hogs on Server?

Question: I recently purchased a remote server plan for a few additional services that I need to run, that my previous hosting plan just couldn't support. (JIRA, another separate Tomcat instance, etc.)
I would rate my Unix/Linux knowledge as "fair", but I'm having troubles determining why my server is so strapped for memory.
Attached is a screenshot of top running as root. The memory usage (adding the %MEM columns) is about 16%, but the total amount of memory used as displayed at the top is well over 60%.
I've been trying to configure JIRA for the past day or so, but it is bailing out with memory issues about halfway through the process.
Note: I have submitted a ticket for tech support, and the admins from who I purchased the server are extremely knowledgeable, but it would be great to fix the issue in the meantime and learn a bit as well
Answer: While in top, you can press Shift+M to sort the process list by memory usage.
In your screenshot the memory usage does look quite good: in Linux you calculate the actual free RAM with Total - (free + cached + buffers), so in your case there's more than 400 MB free out of ~780 MB.
However, your server does not seem to have any swap configured. Is that on purpose? Lack of swap can cause all kind of fancy side effects. I bet if you give your server 1-2 GB swap space, Jira installation completes without errors, and it most likely won't even use much of that swap.
Is that a clean Jira install you're trying to install or are you upgrading a previous installation?
Comment: The screenshot is already sorted by memory usage. How then is the 'used' memory calculated? It's a clean JIRA install. I will ask the administrators about the swap. Thanks for the answer. :)
Comment: Used =  actual memory used by processes + cached + buffers (+ some kernel stuff, try out `slabtop`)
Comment: Oh, one more thing: if during Jira install your server actually was tight on RAM and kernel triggered its OOM (Out-of-Memory Killer), command `dmesg` probably shows you traces of it.
Comment: Top(unix) and Task Manager(windows) both do a super-cruddy job of explaining os-level caching to users. This has got to be a top-10 gotcha for new admins.
Answer: And REM is The non-swapped physical memory a task has used. which I always find useful.
I also was recently introduced to htop which I think is pretty cool sudo apt-get install htop if you're on Debian/Ubuntu ;)

Finding Memory Hogs on Server?


Retrieve each values in the Div

Question: This piece of code will loop for several time.
When any user select any of the radio button I want to find which radio button is selected.
With the selected index I want to get address_<selectedIndex> object;. Now I want to access its siblings div values like addressLine_1, addressLine_2, addressLine_3, city, state, zip in a variable.
Please help to me write this piece of jQuery script.

        <input type="radio" name="addressSelected"  value="1" />

gotomedia LLC

2169 FOLSOM ST

STE M301

SAN FRANCISCO

 CA

 94110

Comment: SO is willing to *help* with your homework, but we're not going to *do* it for you.
Comment: Please add more code, preferably something that includes the radio buttons you're talking about.
Answer: I guess this would be your solution.
You have to watch out for the value of the input field as this code checks $(this).val() == "1". Maybe you have to modify it.
var values = [];
$("input[name=addressSelected]:checked")
  .filter( function () { return $(this).val() == "1"  } )
  .parent()           // the parent td
  .siblings()         // the other tds
  .children("div")    // the divs
  .each( function () { values.push ( $(this).text ) } );

That should do the trick
You might change the each line:
 .each( function () { values[ this.className ] = $(this).text } );

so you can access it like: values['addressLine_1'] however you would have to remove your float classes for a good result

Retrieve each values in the Div


A Hausdorff locally convex space is normable iff it can be generated by a finite subfamily of seminorms.

Question: Suppose $X$ is a Hausdorff locally convex space, then we know its topology can be generated by a family of seminorms. Let us call $P$ to this defining family of seminorms on $X$. I need to show that X is normable iff $P$ is equivalent to a finite subfamily $P_0 \subset P$.
To prove it, we of course now that $P_0$ is dominated by $P$ (in the topological sense), i.e. that every open in $P_0$ is open in $P$. So we can reformulate our question by stating that $X$ is normable iff $P$ is dominated by a family subfamily of seminorms.
Using Kolmogorov's criterion I have shown the right to left implication. That is, we assume $P$ can be generated by a finite family of seminorms, and then we can prove that a convex bounded neighborhood of $0$ exists. We can pick and fix any $\epsilon>0$ and let $A$ be the convex hull of $\cup_{i=1}^n p_{\epsilon,i}$ (the union of the $\epsilon$ balls of the $n$ seminorms that generate the topology on $X$. Then it is by construction convex and around 0 and we just need to check it is bounded. I have done this.
Can you help me with the reverse implication? What is some clearer property that the seminorms must have because the space is normable? Maybe I can use this to prove that $P$ is dominated by $P_0$. Thank you.
Answer: Suppose $(X,\tau)$ is normable, let $p$ be the norm on $X$. Suppose $\tau$ is induced by a family of seminorms $(p_i)_{i\in I}$. Let $B$ be the open unit ball w.r.t $p$.
Basic neighborhoods of zero are described as
$$ W(\varepsilon, i_1,\ldots, i_n) := \{x\in X \mid \max _{1\leqslant k\leqslant n}|p_{i_k}(x)| \leqslant \varepsilon\} \quad (i_k\in I,\ n\in\mathbb N,
 \quad\varepsilon>0) $$
Pick a basic NH of zero contained in $B$ and show that those seminorms induce $\tau$.
Comment: Thank you for your answer. I am not sure though I follow the idea of your proof. Once that I check that $p_U$ is a norm inducing the topology on $X$, how does it follow that $P$ is equivalent to a finite subset of seminorms?
Comment: @Sarah misread your question at first. Revised.
Comment: Thanks. I am however stucked.. To prove the topologies are the same, we can try to show that if a sequence converges to 0 in this basic neighborhood topology, then it does in the original one and conversely. Then the identity map would be continuous and its inverse also at 0, and hence the spaces homeomorphic. Can you indicate why if it soncerges in the basic neighborhood topology then it does on the original one?
Comment: And are you saying that any subset of seminorms induce the topology?
Comment: @Sarah your proof idea is a correct one. These basic subsets are a nh basis of zero in $\tau$. That's already known. No, not any subset.
Comment: Dear Alvin, could you be more explicit in the concrete set of seminorms I have to consider? Is it those given by your $W$? I mean should I keep them fixed?
Comment: @Sarah Yes, we pick a $W$ corresponding to some $p_{i_1} ,\ldots, p_{i_n}$. Then we show that the NH basis of zero induced by the fixed seminorms also induces $\tau$.


Is there a way to code percentage change in r?

Question: Hi I am trying to get the percentage change of those in the same type and same year, but different groups. Is there a way to do it?
Here's my data df:
Year    type      Price      Group
2013     A         100       Old
2013     B         200       Old
2014     A         300       Old
2014     B         500       Old
2013     A         500       New
2013     B         100       New
2014     A         600       New
2014     B         700       New

What I'd like to do is to get the percentage change of each type in each year.
For example the percentage change between A in 2013 Old and A in 2013 New.
Is there a way to code it in R?
Answer: For each Year and Type you can calculate the percentage change.
The formula I used is (New - Old)/Old * 100.
library(dplyr)

df %>%
  group_by(Year, type) %>%
  filter(all(c('Old', 'New') %in% Group)) %>%
  summarise(change_perc = (Price[Group == 'New'] - Price[Group == 'Old'])/
                           Price[Group == 'Old'] * 100)

#   Year type  change_perc
#  <int> <chr>       <dbl>
#1  2013 A             400
#2  2013 B             -50
#3  2014 A             100
#4  2014 B              40

data
df <- structure(list(Year = c(2013L, 2013L, 2014L, 2014L, 2013L, 2013L,
2014L, 2014L), type = c("A", "B", "A", "B", "A", "B", "A", "B"
), Price = c(100L, 200L, 300L, 500L, 500L, 100L, 600L, 700L),
Group = c("Old", "Old", "Old", "Old", "New", "New", "New",
"New")), class = "data.frame", row.names = c(NA, -8L))

Comment: I'm getting this error:
Error: Column change_perc must be length 1 (a summary value), not 0

Any idea how to fix it?
Comment: @vt-0307 Probably, you don't have 'New' or 'Old' value for a particular `Year` and `Type`.
Comment: Is there a way to code such that those that don't have a "new" price or "old" price gets removed?
Comment: It does! Thanks so much!


Passing Jackjson JSON object from JSP to JavaScript function

Question: I have a JSON String stored in a database. In one of my JSP pages, I retrieve this string, and I want to be able to pass the String or the JSON object into Javascript function. The function is simply this for test purposes
function test(h){

alert(h);
}

Now I can retrieve the JSON string from the database fine, I have printed it out to the screen to ensure that it is getting it, however when I pass it in like this
        <input  type="button"
                                name="setFontButton"
                                value="Set"
                                class="form_btn_primary"
                                onclick="test('<%=theJSON%>'); return false;"/>

Nothing happens. I used firebug to check what was wrong, and it says there is invalid character.
So I then tried passing in the JSON object like so
Widget widg = mapper.readValue(testing.get(0), Widget.class);

Then pass in it
onclick="test('<%=widg%>'); return false;"/>

Now this will pass in without an error, and it alerts the object name, however I am unable to parse it. Object comes in like with the package name of where the widget class is stored like so
com.package.mode.Widget@ba8af9

I tried using Stringify, but that doesn't seem to work on this Jackson JSON object.
After all that failed, I tried a last resort of taking the String from the database, and encoding it in base64. However, this too fails if I do this
String test = Base64.encode(theString);

and pass that in. However if I do that, print it out to the screen, then copy what is printed out, and send that through it works, so don't quite understand why that is.
So could someone please tell me what I am doing wrong. I have tried soo many different solutions and nothing is working.
The JSON String is stored in database like this

{
     "id":1,
     "splits":[
        {
           "texts":[
              {
                 "value":"Test",
                 "locationX":3,
                 "locationY":-153,
                 "font":{
                    "type":"Normal",
                    "size":"Medium",
                    "bold":false,
                    "colour":"5a5a5a",
                    "italics":false
                 }
              }
           ]
        }
     ]
  }

Would be very grateful if someone could point me in the direct direction!!
Edit:
Incase anyone else has same problem do this to pass the JSON from JSP to the JS function
<%=theJSON.replaceAll("\"", "\\\'")%>

That allows you to pass the JSON in,
then to get it back in JavaScript to normal JSON format
theJSON = theJSON.replace(/'/g,'"');

Should work fine
Answer: I think the combination of double quotes wrapping the onclick and the ones in your JSON may be messing you up. Think of it as if you entered the JSON manually -- it would look like this:
onclick="test('{ "id":1, "splits":[ { "texts":[ { "value":"Test", "locationX":3, "locationY":-153, "font":{ "type":"Normal", "size":"Medium", "bold":false, "colour":"5a5a5a", "italics":false } } ] } ] }'); return false;"

and the opening double quote before id would actually be closing the double quote following onclick= (You should be able to verify this by looking at the page source). Try specifying the onclick as:
onclick='test(\'<%=theJSON%>\'); return false;'

Comment: You were along the right lines, had to escape it, just grabbed it from database then escaped it using replaceAll command, then passed the new string into the javascript
Answer: You can follow the following steps

Fetch the jon string
Using the jackson or any other JSON jar file , convert the json string to json array and print the string using out.println.
Call this jsp  which prints the json string
check in the firebug , you will be able to see your json .
If the Json string does not print , there can be some problems in your json format.

this is a good website for json beautification , http://jsbeautifier.org/ , really makes the string simple to read .
Thanks
Abhi


How to script an Interval in Photoshop

Question: I am trying to script something in Photoshop that has to run every X seconds. In JavaScript it would look like this:
function run() {
    alert('Ran!')
}
setInterval(run, 1000)

But in Photoshop's JavaScript, "setInterval is not a function". Any idea how else I would get any form of interval working?
Comment: Photoshop scripts don't support timers and they block the host app. You'll need a panel (cep) or plug-in (uxp) for that
Comment: This is a gooooood question. The only thing I've managed to do is either set a large loop & some calculations or another loop and check the time elapsed. - Though most would say that's memory hungry.- But hey! it's Photoshop!
Comment: Would you mind posting a simple example of this? I don't exactly understand how you did it.
Answer: This is by no means a good example, however, it stalls for a second. Those that don't know it there's no pause or sleep function in ECMA 3. I don't use a while loop as that's asking for trouble in Photoshop and may lock things up - which may lose your work.
sleepy(1000)

function sleepy(milliseconds)
{
  // Start the fans please! I mean timer
  var dStart = new Date().getTime();

  var longtime = 10000000;
  for(var i = 0 ; i < longtime; i++)
  {
    var now = new Date().getTime();
    if (now > dStart + milliseconds)
      {
        // Stop the fans!
        var dEnd = new Date().getTime();
        var timeTaken = (dEnd - dStart)/1000;
        var msgTime = (timeTaken + " seconds.");
        alert(msgTime);
        // alert("Ran");
        return;
      }
  }
}

or if it's just a second, just calculate the Fibbonaci sequence to 28 spots. It's also machine dependant (and rather slower than expected in Photoshop)
function fibonacci(n)
{
  if (n < 2)
    return n
  else
  {
    return fibonacci(n-1) + fibonacci(n-2);
  }
}

var numOfNums = 28; // 0.91 seconds
// var numOfNums = 29; // 1.47 seconds
// var numOfNums = 30; // 2.39 seconds
// var numOfNums = 31; // 3.8  seconds

var dStart = new Date().getTime();
var msg = "";
for(var i = 0 ; i < numOfNums; i++)
{
  msg += fibonacci(i) + ", ";
}
var dEnd = new Date().getTime();
var timeTaken = (dEnd - dStart)/1000;

// alert(msg);
alert(timeTaken);

Comment: As epic as this is, it still locks up the UI. So I can't loop this to happen every 30s or so. I need something sort of async, so that the user can continue working while this triggers every 30s or whatever.
Comment: Sadly, you'll need to do that another way. See Sergey's comments above

How to script an Interval in Photoshop


nginx redirect without trailing slashes AND case-insensitive

Question: I'm still pretty new to nginx and I came up with this example that works to redirect "domain.com/gis" and "domain.com/gis/" to "domain.com/gis_public". The problem I have is it will not redirect "domain.com/GIS" or "domain.com/Gis".
I like to plan for all scenarios just in case someone types the GIS acronym in it's proper uppercase format or only capitalizes a single character. So I need to make this case-insensitive and I have failed to find a way. Any help will be appreciated.
location ~* ^/gis(?:/(.*))?$ {
  rewrite /gis(.*) https://domain.com/gis_public$1 permanent;
}

Edit
My final code that works:
location ~* ^/gis(?:/(.*))?$ {
  rewrite (?i)^/gis(.*) https://domain.com/gis_public$1 permanent;
}

Thanks everyone for your help!
Comment: ~* should be a case insensitive match. Are you sure you've restarted nginx and you don't have something else in your configuration. http://nginx.org/en/docs/http/ngx_http_rewrite_module.html matching of a variable against a regular expression using the "~" (for case-sensitive matching) and "~*" (for case-insensitive matching) operators.
Comment: I do restart the server before each test. ~* does work for case-insensitive location matching. I couldn't get ~* to work on the rewrite. The marked answer below does work, however it isn't a "clean" solution.
Comment: maybe it doesn't apply to regex, check this out if you're interested in something a little cleaner http://serverfault.com/questions/498855/nginx-case-insensitive-rewrite
Comment: Thank you Drew. Adding (?i) to my rewrite is a cleaner solution. I edited my question to reflect my final code.
Answer: It's just a regex, so you could match on that basis.
rewrite /[Gg][Ii][Ss](.*) https://....

There's probably a cleaner way to do this, but it doesn't come to mind right now.
Comment: Yes this does work! Thank you. A cleaner way is more welcome though.


How to write code to release manged/unmanaged resources in Destructor/Dispose method

Question: Im new to C#, I actually understand the concept of destructor and dipose method and the difference between them and how actually the GC is invoked/prevented from these operations. But when I try to understand what actually we release inside these methods, Im getting stuck.
First thing is that just defining a empty destructor or a console output wont do anything good to release the unused memory. So what should I write inside the destructor, either make the fields of the class as null or what ?. I know that GC will take care of the managed resources, so what If I faced with unmanaged resources
I usually find this familiar example all over the forums and searches but none has the clarity on what should be written to release the unused memory
class Test : IDisposable
{
    private bool isDisposed = false;

    ~Test()
    {
       Dispose(false);
    }

    protected void Dispose(bool disposing)
    {
       if (disposing)
       {
          // Code to dispose the managed resources of the class
       }
       // Code to dispose the un-managed resources of the class

       isDisposed = true;
    }

    public void Dispose()
    {
       Dispose(true);
       GC.SuppressFinalize(this);
    }
}

I understand the example but what code should come in the commented lines inside the dispose method ( // Code to dispose the managed resources of the class  &
 // Code to dispose the un-managed resources of the class ). Can some one give me a sample example that would solve my doubt
Comment: It's great to be curious about how stuff works and I encourage that. But **you do not have nearly enough experience to be writing a class that tracks an unmanaged resource**. I have been writing C# programs for over a decade and was on the compiler team and I have never written a destructor except for test cases. I do not attempt to write classes that track unmanaged resources, and I encourage you to similarly not make the attempt.
Comment: **Do not attempt to write a destructor**.  Writing a correct destructor is one of the hardest things to do in C# and I **strongly advise you to not do so**.  If you have an unmanaged resource that you need to manage, use a safe handle. For a list of reasons why writing a destructor correctly is hard, see https://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/
Comment: I read the question, and was just about to to tear out a comment... Then i looked at the comments, woah, fully summed up
Comment: You shouldn't write any additional code in destructor, call to `Dispose(false)` is enough. After `// Code to dispose the managed resources of the class` you should dispose your managed resources (for example, call `MyManagedResourceInstance.Dispose()`). After `// Code to dispose the un-managed resources of the class` you should dispose your unmanaged resource (for example, release system handle `NativeMethods.CloseHandle(MyUnmanagedResourceHandle)`)
Answer:
I understand the example but what code should come in the commented
  lines

Look, every managed resource(i.e. allocated by .Net that uses no unmanaged resource under the hood) is freed using GC and does not need no disposal at all. All the disposal thing is about unmanaged memory those who were allocated via Win32 API calls or any unmanaged external code.
Now to answer your question, the answer is you have to put the code to release those unmanaged objects inside Dispose, based on the external code or API that you are using, there should be a way(e.g. method) to release the memory.
There may be another question, now that only unmanaged code should be disposed why there is a section to dispose managed resources?
That's because that managed resource relies internally on an unmanaged resource, by calling the Dispose you are freeing that memory, the managed code handled the release code for you (wrapped in Dispose). example of this could be FileStream
Comment: @vasily.sib, tnx for comment, edited my post, I meant pure managed objects, no disposal needed, right?
Comment: As a general rule, any class that implements `IDisposable` should be disposed ([except tasks](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/)).  If the class instance is being accessed transiently, this means wrapping it in a `using block`.  If the instance is a member of a class which shares a lifetime with that class, that containing class should implement `IDisposable`, with the `Dispose` method being used to dispose any `IDisposable` members.  Note that none of this requires you to write a destructor.


Get text value of selected option in Jquery

Question: I have some custom Jquery which grabs the id's from a select list, and populates a secondary select list with those that are selected.
I have this working well, however I need the secondary select list needs to display the text value of the selected option.  Currently I just get the actual id.
Can anybody assist please?
JQUERY
$('#myselect').change(function() {
        var row = $(".chosen-select").val();
        $('#secondSelect').html('');
        jQuery.each(row, function(i, val) {
            $('#secondSelect').append('<option value=' + val + '>' + val) + '</option>';
        });
});

HTML
First select list
<select data-placeholder="Choose cars..." class="chosen-select" name="myselect[]" id="myselect" multiple>
<option value="1">Vauxhall</option>
<option value="2">Volvo</option>
etc...
</select>

Second select list
<select name="secondSelect" id="secondSelect">
    <option value="">Select Model</option>
    should be populated here..
</select>

Comment: I don't really understand what's going on but you can use `.text()` rather than `.val()`.
Comment: OK, I'm quite possibly missing something that is straight forward to you.  I appreciate that I can use text() but how I implement it is where I fall over.
Comment: `$('#secondSelect').html( $('', {value : $(".chosen-select").val(), text : $(".chosen-select").text()}) );`
Comment: check this fiddle, is this what you wanted? http://jsfiddle.net/Lkyvbdsz/
Comment: Hi eg_dac, almost :-) It wasn't populating the id.
Answer: What about this? fiddle
$('#myselect').change(function() {
        $('#secondSelect').html('');
        jQuery.each($("option:selected",this), function(i, val) {
            $('#secondSelect').append($(val).clone());
        });
});


Show Related Terms Block Not Nodes

Question: Hello i have been trying for many a moon to create this View and i cant go on any longer its destrying my life (honest)
I want to show Related Terms (not content) on my taxonomy/term/* page. Example.
White Setter and Black Setter are both in a dogs vocabulary. I have 'related' them via the
taxonomy/term/*/edit-term page.
I want to create a block view that will show Black Setter on the White Setter page and vica versa. I have tried every relationship and every argument with no success at all. Does anyone know if this is possible to make?
Relationships
Taxonomy: Related terms
Arguments
Taxonomy: Term ID
Thanks
Before i post i see that i have asked ths on other peoples posts (and one of mine) they where never resolved. People keep talking about adding nodes in the view but i was wanting to use a term View.
Comment: Which version of Drupal are you using ? 6 or 7 ?
Comment: Sorry Anil Drupal 6.
Answer: As your requirement is to create a block that will show Black Setter on the White Setter page and vica versa, there is another simple way to achieve this.  The function taxonomy_get_related() will do this.
Create a block with input format as php and use above function to print related terms by passing current page term id. Then assign the block to particular region. The following snippet will works,
for eg:
 <?php
    $termid = arg(2);
    $terms = taxonomy_get_related($termid, $key = 'tid');
    //print_r($terms);
    foreach($terms as $term){

       $link = url('taxonomy/term/'.$term->tid);
       echo ''.$term->name.'';
     }
  ?>

Comment: ah brilliant Anoop that seems to be the way to go. It is printing the term fine as hoped but it isnt linking the term to the term page. Would there be a way to sort this? thanks very much.
Comment: i edited answer please check now
Comment: lovely works a dream Anoop. Much appreciated. This really helps me and im sure it will realy help others too.
Comment: is there any way that the output could also be displayed on a node to emulate the " Load default argument from node page, thats good for related taxonomy blocks" way? I was hoping to use this as a menu system. thanks
Comment: As I explained in my answer's comments, Views handling of related terms is broken, so you're left with custom code solutions. That said, avoid leaving snippets of PHP in your database as debugging or mantaining it is way harder than actual code.
Comment: You're better of with a custom block (using `hook_block()`) that checks the current url (`using arg()`) and builds the related term links (using `taxonomy_get_related()` and `theme_links()`).
Answer: It's not really hard:

Create a new taxonomy view.
Add an argument: Taxonomy: Term ID. If argument is not present, provide a default argument: Taxonomy Term ID from URL. Check the Load default argument from term page checkbox.
Add a relationship: Taxonomy: Related terms.
Finally, add a field: Taxonomy: Term. Use the Related term relationship, and check the Link this field to its taxonomy term page option.
Don't forget to create the block display.

Here's a view export: https://gist.github.com/4016927
Comment: Core stores term relationships as "A is related to B" and the Views handler is not wise enought to check that "B is related to A". Therefore, right now, this is broken in Views 6.x-2.x and 6.x-3.x (didn't check 7.x-3.x).
Comment: See http://drupal.org/node/1825688
Comment: thanks barraponto i missed this. yes that was me on drupal.org. i will go look more at this as the view will interest me. Loads to get on with now this is solved but i will return
Comment: barraponto's View does seem to work ok and as i had hoped (including on the node) I need to edit each term and resave them for the 2 way relationship to come into place. Sorry folks im just up and not thinking straight. Sorry Anoop but using a view like barra suggested seems a better way for me to go. thanks for your input though
Comment: @RegGordon unfortunately, saving the related term will break it on the other related term. So right now, what you're left with is custom code.
Comment: @Reg Gordon Are you able to get related terms using this way? Well when i tried am able to show relation one way only, two way not possible.

Show Related Terms Block Not Nodes


creating pdf with solid color as background pdfmake

Question: I'm developing an app that creates pdfs automatically. Using the pdfmake, I can create the pdf easily but I can't find anywhere how to put a background on the pdf. I found how to put images as a background but I can't find how to put a solid color.
var docDefinition = {
  pageSize: 'A3',
  content: [{
    text: $globals.mural.name,
    style: 'header'
  }, {
    image: uri,
    width: size.width,
    height: size.height,
    margin: size.margin,
    alignment: 'center',
  }],
  styles: {
    header: {
      alignment: 'center',
      fontSize: '70',
      font: 'LaneNarrow',
      color: $globals.mural.layout.textColor
    }
  }
};

Answer: As of now pdfMake doesn't seem to support directly adding background color to main content. For this one approach is to use the canvas method.
In doc defination you need to add
    background: function () {
      return {
        canvas: PdfOrderUtilities.getCanvas()
      };
    },

//The actual function
public static getCanvas() {
return [
    {
        type: 'rect',
        x: 0, y: 0, w: 600, h: 840,
        //The background color
        color: '#F4F6F9'
    }
]

}


Anyone can let me know the following syntax in C++?

Question: Why we can access value_type by myType::value_type, any c++ reference talk about it?
class myType{
public:
   typedef double value_type; // the type for elements in the array
   private:
};

Comment: What don't you understand. It's just a typedef.
Answer: In your example, value_type is a member of myType.  It's a name, and
name lookup says that it will be found in myType.  Whether the name
resolves to a typedef, a variable, a function, or whatever can't
influence name lookup, since you have to find the name first, to know
what it means.  (This is a simplification, and there are cases where the
type affects lookup; where depending on the type of symbol found in a
first lookup, a second lookup might occur.)


why my query does not read cache when component mounted and every time component load?

Question: for first time component that has query inside it when mounted , a loading show in the page and when data received data showed . so cache time of data is 5 minutes . I go to another route and very quickly come back to my original route . I expect that data quickly show to users and there is not any loading on page . but in real , my query does not read data from cache and reload again . Login route when mounted fetch data from server first time , then I go to home route and quickly come back to login route but it instead of reading data from cache ,reload again .
function Login() {
  const { data, isLoading, isFetching } = useQuery({
    queryKey: ["/users"],
    queryFn: async () => {
      return fetch("https://jsonplaceholder.typicode.com/users")
        .then((val) => {
          return val.json();
        })
        .then((v) => {
          return v;
        });
    },
    cacheTime : 300000,
  });
  console.log(isLoading, isFetching);
  if (isLoading) {
    return
Loading ...
;
  }
  return (

Login

      {data?.map((eachdata) => {
        return
{eachdata.username}
;
      })}

  );
}
export { Login };

//Home page

function Home() {
  return (

Home

  );
}

Answer: Add staleTime to your query options to specify how long the data is fresh and can be used without refetching.
const { data, isLoading, isFetching } = useQuery({
  queryKey: ["/users"],
  queryFn: async () => {
    // Fetch function
  },
  staleTime: 300000, // 5 minutes
  cacheTime: 300000, // 5 minutes
});

Comment: I test this but it refetch again


Synchronizing load balanced Linux servers

Question: I want to load-balance two dedicated linux servers, I'm planning to do that using round robin DNS, but I can't find a way to synchronize the servers to be identical.
The servers are running a perl script (minimum change) and I think it's possible to synchronize that with a simple bash script of rsync on a cron job.
But the problem is that script depends on a mariadb database that changes a lot and I don't think it's possible to run rsync on two running mysql databases because it will create conflicts in the destination server.
I think it's possible to connect the second server to the first server's database remotely but that doesn't actually balance the load because the first server will have to process the queries of two servers.
Is there a simple solution I'm missing?
Answer: Yes, there is a better solution. A proper load balancer in front of your servers.
Any load distribution without feedback like DNS round-robin does spread the load but can't possibly do this evenly. To have an even load on all backend servers, you need to have a load feedback from servers to the balancer so it knows the actual load on each back end and can use that info when it decides where to send the connection.
Also notice that in master-slave configuration it is impossible to load master and slaves the same way, due to different roles they perform. MySQL/MariaDB has a Galera multi-master cluster solution, where it is possible to distribute load evenly.
Lastly, DNS "load balancing" is susceptible to easy bypass. One can simply use a literal IP address of one of servers instead of DNS name and they will always load that server. With a proper load balancer, it is impossible, since only balancer's IP can be made available for connections so it always able to decide where to forward the connection.
Try haproxy; for your case you'll obviously need a TCP mode and an agent (a simple script with a simple protocol) running on each backend which will be queried regularly by the balancer to obtain information about that server's current load. Start here for the basic setup, and then you'll need to create an agent and add agent-check to haproxy configuration.


Integrating multiple tests Bayes factors

Question: I have been using an Bayesian-centric R package for some genomics analysis to detect mutations in 3 individuals from the same family.
I have to do each analysis for each individual separately due to how the package is written. All 3 individuals test positively when I apply the Bayesian test, and I get a Bayes factor of say 4, 7 and 9 for the three separate tests, which is in the realms of 'substantial' evidence as far as I can tell (e.g. http://en.wikipedia.org/wiki/Bayes_factor#Interpretation)
My question is, as these 3 individuals all carry the mutation (which was also our prior hypothesis), can I integrate these independently tested Bayes factors to provide a sort of 'meta-analysis' Bayes factor, which would presumably be > 10 for the whole family?
Answer: The short answer is no. In a sense, a Bayes factor is equivalent to BIC:
http://www.stat.sc.edu/~hitchcock/stat535slidesday21.pdf
Therefore, your question is similar to asking whether it's possible to figure out BIC for the "global" model that includes all individuals if one knows the three BICs produced by the individual models. Apparently, you'll have to fit the "global" model explicitly for that.
You may be able to analyze the entire dataset with your package by introducing a dummy variable for the individual.


Bagged Decision trees / Random Forests: why ISLR uses validation set instead of OOB to compute out-of-sample MSE?

Question: I am reading the book "An Introduction to Statistical Learning" available here.
Chapter 8.3.3 at page 328 of the book computes a bagged decision tree (which is a random forest where we use all of the predictors at each step). It does so for a regression problem. It then calculates out-of-sample MSE using a separate test set.
The code goes like that:
library(MASS)
library(randomForest)
set.seed(1)

train = sample(1:nrow(Boston), nrow(Boston)/2)

# Bagging = Bootstrap aggregation
bag.boston = randomForest(medv~.,
                          data=Boston,
                          subset=train,
                          mtry=13,
                          importance=T)

yhat <- predict(bag.boston,
                newdata=Boston[-train,])
y <-Boston[-train,]$medv
mse = mean((y-yhat)^2)
print(paste0("MSE: ", mse))

To be truth, at each step the training set is bootstrapped, and the decision tree is trainined on the bootstrapped dataset. Some samples are not drawn during bootstrapping, and are used after training to compute MSE. At least this is how I understood it.
Why the book uses a separate validation set, instead of OOB samples, to compute out-of-sample MSE?
Said otherwise, why the following is wrong?
print(mean(bag.boston$mse))
I have tried it, and the results are as follows. The code:
mse = mean((y-yhat)^2)
print(paste0("MSE: ", mse))

returns 19.88, while the code
print(mean(bag.boston$mse))

returns a much lower 11.72. So it seems that the latter is overfitted, but I don't understand why.
Answer: By a simulation experiment, I discovered that when the sample size is large, the performance metrics calculated in the two ways (OOB and validation set) are numerically very very similar (the maximum difference is 0.1).
I have tried with accuracy, sensitivity, specificity and F1.


What exactly changed in this git commit?

Question: Look at this git commit: https://github.com/ClosedXML/ClosedXML/commit/8fb8848e759c5d599b9079d4a1d102e2dda054e9
This is an example of a commit that I sometimes see. I also sometimes encounter it myself and I would like to avoid it. Initially I thought it was a line break settings (\n vs \r\n), but this isn't the case here.
What exactly changed in this commit?
Comment: Would love to know why the downvote.
Answer: A simple git diff reveals the truth:
~/OSS/ClosedXML $ git diff 8fb8848~1 8fb8848 -- ClosedXML/AttributeExtensions.cs
diff --git a/ClosedXML/AttributeExtensions.cs b/ClosedXML/AttributeExtensions.cs
index 89b8b7f9..be354555 100644
--- a/ClosedXML/AttributeExtensions.cs
+++ b/ClosedXML/AttributeExtensions.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
 using System.Linq;
 using System.Linq.Expressions;
 using System.Reflection;

Commit 8fb8848 removed the  character that used to be the first character of the file.  is an Unicode character that is used as a BOM (byte ordering mark).
More investigation reveals that the file is encoded as UTF-8 (or an encoding that uses one byte for each character).
~/OSS/ClosedXML $ git checkout 8fb8848~1 -- ClosedXML/AttributeExtensions.cs
~/OSS/ClosedXML $ hexdump -C ClosedXML/AttributeExtensions.cs -n 64
00000000  ef bb bf 75 73 69 6e 67  20 53 79 73 74 65 6d 3b  |...using System;|
00000010  0d 0a 75 73 69 6e 67 20  53 79 73 74 65 6d 2e 4c  |..using System.L|
00000020  69 6e 71 3b 0d 0a 75 73  69 6e 67 20 53 79 73 74  |inq;..using Syst|
00000030  65 6d 2e 4c 69 6e 71 2e  45 78 70 72 65 73 73 69  |em.Linq.Expressi|
00000040

The first three bytes (ef bb bf) of the file before commit 8fb8848 are the BOM encoded as UTF-8.
UTF-8 does not need a BOM and some tools had issues handing it. You better configure your editor to not insert a BOM if the files are saved as UTF-8.
Comment: When I do `git diff 8fb8848~1 8fb8848 -- ClosedXML/AttributeExtensions.cs` in Git Bash I don't see the ``. I see one red line: `- using System;` and one green line: `+using System;`
Comment: Hmm... I thought Git is the one that displays the `BOM` this way but maybe it's my terminal application. The output of `hexdump` is doubtless, anyway.


Suppose that we flip a coin until either it comes up tails twice or we have flipped six times. What is the expected number of times we flip the coin?

Question: So this is the answer that I got (where $N$ represents the number of coin flips after which you can stop) but can someone tell me if this looks right?
$P(N=2) = P(TT) = \dfrac{1}{4} $
$P(N=3) = P(HTT , THT) = \dfrac{2}{8} $
$P(N=4) = P(HHTT;HTHT;THHT) = \dfrac{3}{16} $
$P(N=5) = \dfrac{4}{32} $
$P(N=6) = 1 - \dfrac{1}{4} - \dfrac{2}{8} - \dfrac{3}{16} - \dfrac{4}{32} = \dfrac{3}{16}$
$E(N) = 2\left(\dfrac{1}{4}\right) + 3\left(\dfrac{2}{8}\right) + 4\left(\dfrac{3}{16}\right) + 5\left(\dfrac{4}{32}\right) + 6\left(\dfrac{3}{16}\right) = \dfrac{15}{4} = 3.75$
Comment: Looks fine to me.
Comment: Agreed. In general, the probability that the $k$th toss is the one that gets the second tails is $(k-1)/2^k$: there are $2^k$ possible patterns of $H$s and $T$s of length $k$, but the ones we want all end in a $T$ and have a single $T$ among the first $k-1$ letters. So you can do the generalization of the problem to other values of $N$ if you wanted.
Answer: What you are looking at is a right-censored negative binomial distribution.  That is, let $Y = X \wedge 6 = \min\{X, 6\}$ where $X \sim {\rm NegBinomial}(r = 2, p = 1/2)$, where the particular choice of parametrization for $X$ is $$\Pr[X = k] = \binom{k-1}{k-r} (1-p)^r p^{k-r}, \quad k = r, r+1, r+2, \ldots.$$  That is, $X$ counts the total number of trials needed to observe $r = 2$ tails, where each trial is an independent Bernoulli trial with probability of observing tails equal to $p = 1/2$.  Then $Y$ is $X$ right-censored at $6$.  So we can calculate $$\begin{align*} {\rm E}[Y] &= {\rm E}[X \wedge 6] \\ &= \sum_{k=2}^5 k \Pr[X = k] + \sum_{k=6}^\infty 6 \Pr[X = k] \\ &= 6 - \sum_{k=2}^5 (6-k)\Pr[X = k] \\ &= 6 - \frac{9}{4} = \frac{15}{4}.\end{align*}$$


Bash command refuses to run in background with &

Question: I can normally run commands in the background using the command & technique.  However, I cannot run commands involving a music player as background commands.
I have tried two music players so far, pogo and then vlc player.  For each I am only manually typing in the first command, but the second command is run automatically from the first causing it to take up the foreground again.
$ pogo ~/Downloads/cheering.wav &
[2] 18841

$ Checking local path /usr/bin/pogo
Checking global path /usr/share/pogo/pogo
Using pogo version at /usr/share/pogo/pogo
DEBUG    stdout logging level: 10
INFO     Writing log to file "/home/mcgoy/.config/pogo/Logs/log"
INFO     System info: machine: x86_64, platform: Linux-4.15.0-65-generic-x86_64-with-Ubuntu-18.04-bionic, processor: x86_64, python_version: 3.6.8, release: 4.15.0-65-generic, system: Linux, GTK: (3, 22, 30), Glib: (2, 56, 1), PyGObject: (3, 26, 1), GST: GStreamer 1.14.5, Mutagen: (1, 38), PIL: 1.1.7
INFO     Started

The bash command is now paused on the task which was supposed to be a background task.  It remains in the foreground until I close the player window.
The same thing happens with VLC player
$ cvlc ~/Downloads/cheering.wav &
[4] 17686
VLC media player 3.0.8 Vetinari (revision 3.0.8-0-gf350b6b5a7)

$ [000056235c753f00] dummy interface: using the dummy interface module...
 #cursor hangs here

Comment: you are fooling yourself: the command is correctly in background BUT the standard output remains your console. Thus you keep seeing messages, but the run in background
Comment: just hit the enter/return key, and the command prompt will be there.  Frequently people will redirect output to a file as well (`pogo myfile.wav >pogo.out.txt &`)
Comment: StackOverflow is dedicated to helping solve programming code problems. Your Q seems  more appropriate for https://superuser.com or maybe https://unix.stackexchange.com   , but read their help section regarding on-topic questions . AND please read [Help On-topic](https://stackoverflow.com/Help/On-topic) and [Help How-to-ask](https://stackoverflow.com/Help/How-to-ask) before posting more Qs here.  Good luck.
Comment: ok, I guess the background commands I usually run don't have so much output on start up.  Probably why I never noticed before.
Answer: It sounds like you want your output to not be present in the shell.
You can pipe your output to /dev/null if you want to avoid seeing anything, or to any arbitrary file ./my_log_file.txt if you'd rather save the output for later
pogo ~/Downloads/cheering.wav >/dev/null 2>&1 &

Comment: Thanks, you're right.  Also I had to add 2>&1 to eliminate all the output.


Can there be a proper class of $\alpha$-inaccessibles for any ordinal $\alpha$?

Question: A cardinal $\kappa$ is $\alpha$-inaccessible if $\kappa$ is inaccessible and such that for any ordinal $\beta < \alpha$, the set of $\beta$-inaccessibles less than $\kappa$ has cardinality $\kappa$.
For example, a cardinal is 1-inaccessible if it is an inaccessible limit of (0)-inaccessibles. A domain $V_{\kappa_1}$ for ${\kappa_1}$ a 1-inaccessible would have a proper class of 0- inaccessibles. Likewise, a domain $V_{\kappa_2}$ for $\kappa_2$ a 2-inaccessible would contain a proper class of 1-inaccessibles.
However, I think there must be some ordinals $\gamma$ for which there cannot be a proper class of $\gamma$-inaccessibles, but I cannot make this intuition precise enough to prove it. If my intuition is correct, for which ordinals does it fail?
Comment: There is no such $\gamma$. That is, we expect significantly stronger large cardinal assumptions to be consistent.
Answer: If $\kappa$ is Mahlo, then $\kappa$ is $\kappa$-inaccessible. So if there is a Mahlo cardinal $\kappa$, we get that $V_\kappa\models$ "There is a proper class of $\alpha$-inaccessibles for every ordinal $\alpha$." Since the existence of Mahlo cardinals is not currently known to be inconsistent with ZFC - to put it mildly (Mahlo cardinals are incredibly low down in the large cardinal hierarchy) - the answer to your question is (currently) no.
In fact, even the existence of a proper class of Mahlos isn't much to write home about: it holds in $V_\lambda$ whenever $\lambda$ is weakly compact.
And all of this is way, way, way weaker and smaller than even a single measurable cardinals.
Comment: If $\kappa$ is Mahlo, then it is a limit of $\lambda$-inaccessibles for all $\lambda<\kappa$.
Comment: @AsafKaragila Derp, that was silly. Fixed!


Comparing cost changes for different groups of companies

Question: I am conducting a research project where I have a experimental group and control group of companies and a cost data point for a base year and the year after. The years of costs are different for most of the companies so for one company the two costs may be in 2006-2007 while for another they may be from 2001-2002. Also, I do have the costs for other years if necessary.
The base year for each company was chosen because an event occurred during that year and I am trying to see if that event significantly changed a certain cost for that company.
I would like to test to see if the the change in cost is statistically different between the experimental and control group.
Also, I would like to normalize the change in cost in some way, I was thinking of calculating the percent change in cost or dividing each cost by market capitalization but any other suggestions would also be appreciated.
What statistical test/procedure would be best to use in this situation?
Also, considering that the companies can be segmented into various categories like country, market capitalization, etc, would you recommend any other procedures to further analyze the data?
Distributional Assumptions: Company's costs can be considered normal, I checked using a normality test.
Sample Size: N=109 for experimental and control group, for a total of 436 data points.
Comment: may be `difference-in-difference` methodology will work.
Comment: Can you describe your situation, your data & your goals more fully? You mention "market capitalization", so I'm guessing this is econ or finance, not biomedical research, but I'm mostly in the dark here.
Comment: I described my situation a little more and added a little more about my distributional assumptions and sample size.
Answer: 1) If you haven't done it already your cost data should be expressed in values of some base year common for all 218 companies, using some inflation/deflation index 9it doesn't matter which year). This is the least you can do to deal with the fact that data come from different years.
2) Considering the percentage change, it is a sensible thing to do to control for differences in company sizes,and hence cost levels. But note that cost structure is usually not linear in company size. So if companies vary widely in size (as indicated by for example, turnover, headcount, balance sheet value), it is awkward to assume that they belong to the same population.
3) You are referring to an "experimental" and to a "control" group. How each company ended in each group? By some "random draw" procedure? If yes, then your underlying null hypothesis is that all companies belong to the same population as regards their cost-responses, and so the two sub-samples should exhibit same characteristics, namely, sample moments, like the mean and variance. If this null is rejected, you reject the hypothesis that the companies come from the same population -nothing else.
If the companies have been grouped according to some criterion, then your underlying null hypothesis is that this criterion is not statistically significant for cost-responses. This sounds more interesting to test.
4) You write that you cannot reject the hypothesis that both sub-samples follow the normal. Then to test whether the mean value of percentage cost-change is statistically different between the two groups, you can conduct a Welch's t-test which takes into account the fact that the variances of the two sub-samples may be different.
5) You can separately test for the equality of variances, by conducting an F-test, or Levene's test in case you do not feel that the normality assumption is very strong.
6) Finally, use your eyes: obtain an estimate of the graph of the empirical densities of the two samples (say by kernel density estimation): do they look like they match?
Answer: It would be useful to understand the distributional assumptions you have made and also whether the companies are considered independent and to what extent confounding has been considered.
If you can make the assumption of normality and independence then is an independent samples t-test (based on the cost difference across years) appropriate? Anova may also be useful, but again, underlying assumptions must be considered.
Failing the validity of a parametric approach, if you can make some assumptions regarding symmetry, then a non-parametric approach such as a permutation test or Wilcoxon signed rank test may be of use.
Comment: Now that I have updated my questions. Would it be possible for someone to provide a more detailed answer?


Return back value at input with javascript

Question: I have a toggle button with by default value="1" = on offer.Now, with my jQuery, I can change this value to 0, for on request.But, after that, if I want to change it back to value 1, it s blocked with value="0".How can I do to make this revert to my value by default?

function change() {
  var elem = document.getElementById("home-header_on_offer");
  if (elem.value == "1")
    elem.value = "0";
  else if (elem.value = "0")
    elem.value = "1";
}
On offer

  <input onclick="change()" type="checkbox" name="custom7" value="1" id="home-header_on_offer"
checked="checked">

Comment: `else if (elem.value = "0")` will always be true. You need to use `==` or `===` to test equality, not `=`. Also note that changing a control's value at runtime is a bad idea. The whole point of a checkbox is that it sends a value when it's checked, otherwise it sends no value. Therefore you simply need your server-side logic to work with the sent value or null.
Comment: thank you for your answer:) `===` worked for me:)
Answer: In your else if part it would be == instead of =.

== is for comparison two side
=== is for caparison with strict type
= is for assigning.

function change()  {
    var elem = document.getElementById("home-header_on_offer");
    if (elem.value == '1') elem.value = '0';
    else if (elem.value == '0') elem.value = '1';

    console.log(elem.value)
}
On offer

    <input onclick="change()" type="checkbox" name="custom7" value="1" id="home-header_on_offer" checked="checked">

Answer: You have a type in your else condition. Also if you want to compare to 0 or '0' better use strict === comparison:
  if (elem.value === "1") {
    elem.value = "0";
   } else if (elem.value === "0") {
    elem.value = "1";
   }

Answer: This is simple :

function change() {
  var elem = document.getElementById("home-header_on_offer");
  if (elem.value == "1") {
    elem.value = "0";
    alert(elem.value);
  } else {
    elem.value = "1";
    alert(elem.value);
  }
}

On offer

  <input onclick="change()" type="checkbox" name="custom7" value="1" id="home-header_on_offer"
checked="checked">

Answer: The problem is = instead of == (= vs ===)
Alternate solutions for toggling

function change() {
  var elem = document.getElementById("home-header_on_offer");
  elem.value = 1 - elem.value;
  console.log(elem.value)
}
On offer
<input onclick="change()" type="checkbox" name="custom7" value="1" id="home-header_on_offer" checked="checked">

OR Using checked property with unary plus

function change() {
  var elem = document.getElementById("home-header_on_offer")
  console.log(+elem.checked)
}
On offer
<input onclick="change()" type="checkbox" name="custom7" value="1" id="home-header_on_offer" checked="checked">


eigenvalues of certain block matrices

Question: This question inquired about the determinant of this matrix:
$$
\begin{bmatrix}
  -\lambda &1  &0  &1  &0  &1  \\
   1& -\lambda &1  &0  &1  &0  \\
   0&  1& -\lambda &1  &0  &1  \\
   1&  0&  1& -\lambda &1  &0  \\
   0&  1&  0&  1& -\lambda &1  \\
   1&  0&  1&  0&1 & -\lambda
\end{bmatrix}
$$
and of other matrices in a sequence to which it belongs.  In a comment I mentioned that if we permute the indices 1, 2, 3, 4, 5, 6 to put the odd ones first and then the even ones, thus 1, 3, 5, 2, 4, 6, then we get this:
$$
\begin{bmatrix}
-\lambda & 0 & 0 & 1 & 1 & 1 \\
0 & -\lambda & 0 & 1 & 1 & 1 \\
0 & 0 & -\lambda & 1 & 1 & 1 \\
1 & 1 & 1 & -\lambda & 0 & 0 \\
1 & 1 & 1 & 0 & -\lambda & 0 \\
1 & 1 & 1 & 0 & 0 & -\lambda
\end{bmatrix}
$$
So this is of the form
$$
\begin{bmatrix}
A & B \\ B & A
\end{bmatrix}
$$
where $A$ and $B$ are symmetric matrices whose characteristic polynomials and eigenvalues are easily found, even if we consider not this one case of $6\times 6$ matrices, but arbitrarily large matrices following the same pattern.
Are there simple formulas for determinants, characteristic polynomials, and eigenvalues for matrices of this latter kind?
I thought of the Haynesworth inertia additivity formula because I only vaguely remembered what it said.  But apparently it only counts positive, negative, and zero eigenvalues.
Comment: I suppose we could treat it as a symmetric block Toeplitz matrix...
Comment: ...and if we so treat it, does that lead us toward an answer to the question?
Comment: I suppose, but I'll have to dig through my notes to be sure (I do remember these things being well-studied, but I'm hazy on how the eigenproblem simplifies for these).
Answer: We have
$$
\det \left(
\begin{array}{cc}
A & B\\
C & D
\end{array}
\right)
= \det(A-BD^{-1}C) \det(D),
$$
where the matrix $A-BD^{-1}C$ is called a Schur complement. In your case, $A=D=-\lambda I_n$ and $B=C=J_n$ = the order $n$ matrix with all entries equal to 1. So, the RHS is equal to $\det(-\lambda I_n + \frac{n}{\lambda} J_n) \det(-\lambda I_n) = (-n)^n \det(-\frac{\lambda^2}{n}I_n + J_n)$. If I remember correctly, $\det(xI_n + J_n) \equiv x^{n-1}(x+n)$, but you should check whether this is true or not.
Comment: Very nice.  I should have thought of that identity, since I believe I used it when I took a course on the theory of the [Wishart distribution](http://en.wikipedia.org/wiki/Wishart_distribution).
Comment: The only matrices whose determinants remain to be evaluated after what user1551 did above are matrices in which all diagonal entries are equal to each other and all off-diagonal entries are equal to each other.  There is a standard formula, moderately easy to prove, for the determinant of such a matrix.
Answer: I am not sure whether I understand what you want to ask.. but the following are some facts on the matrix of this type
$\det\begin{bmatrix}
A & B \\\\ B & A
\end{bmatrix}=\det(A+B)\det(A-B)$. The eigenvalues of $\begin{bmatrix}
A & B \\\\ B & A
\end{bmatrix}$ are the union of eigenvalues of $A+B$ and the eigenvalues of $A-B$.
Comment: Sorry, it's been a while since you answered with this. Can I say something if the structure is $[A\,\,B\,;\,-B\,\,A]$?
Answer: Your $2n\times 2n$ matrix $M$ acts on the vector space $V=\mathbb C^n\oplus\mathbb C^n$. Now if $W_1=\{(v,v):v\in\mathbb C^n\}$ and $W_2=\{(v,-v):v\in\mathbb C^n\}$, then we also have $V=W_1\oplus W_2$. Moreover, both $W_1$ and $W_2$ are invariant under $M$, so to find the eigenvalues/eigenvectors/characteristic polynomial/etc, it is enough to do it for those restrictions: they are $A+B$ and $A-B$.
This way you obtain, for example, the facts mentioned in Sunni's answer immediately.
Answer: Because the subblocks of the second matrix (let's call it $C$) commute i.e. AB=BA,  you can use a lot of small lemmas given, for example here.
And also you might consider the following elimination: Let $n$ be the size of $A$ or $B$ and let,(say for $n=4$)
$$
T = \left(\begin{array}{cccccccc}
     1     &0     &0     &0     &0     &0     &0     &0\\
     0     &0     &0     &0     &1     &0     &0     &0\\
    -1     &1     &0     &0     &0     &0     &0     &0\\
    -1     &0     &1     &0     &0     &0     &0     &0\\
    -1     &0     &0     &1     &0     &0     &0     &0\\
     0     &0     &0     &0    &-1     &1     &0     &0\\
     0     &0     &0     &0    &-1     &0     &1     &0\\
     0     &0     &0     &0    &-1     &0     &0     &1
\end{array} \right)
$$
Then , $TCT^{-1}$ gives
$$
\hat{C} = \begin{pmatrix}-\lambda &n &\mathbf{0} &\mathbf{1} \\n &-\lambda &\mathbf{1} &\mathbf{0}\\ & &-\lambda I &0\\&&0&-\lambda I \end{pmatrix}
$$
from which you can identify the upper triangular block matrix. The bold face numbers indicate the all ones and all zeros rows respectively.  $(1,1)$ block is the $2\times 2$ matrix and $(2,2)$ block is simply $-\lambda I$.
EDIT: So the eigenvalues are $(-\lambda-n),(-\lambda+n)$ and $-\lambda$ with multiplicity of $2(n-1)$. Thus the determinant is also easy to compute, via their product.

eigenvalues of certain block matrices


Classifying handwritten digits using PCA

Question:
Classify handwritten digits using PCA. Use 200 digits for the train phase and 20 for the test.

I have no idea how PCA works as a classification method. I've learned to use it as a dimension reduction method where we subtract the original data from its mean, then we calculate the covariance matrix, eigenvalues and eigenvectors. From there, we're able to choose principal components and ignore the rest. How should I classify a bunch of handwritten digits? How to distinguish data from different classes? Or does it mean something totally different, that I must use PCA for feature extraction purposes and use a classification method afterwards?
Comment: I crossposted the question [here](http://stackoverflow.com/questions/14610377/classifying-handwritten-digits-using-pca) to receive hints about its matlab code. Apart from that, I need ideas as to what should I do about the problem in general.
Comment: Why do you have to use PCA? Is this a homework problem? Please specify. Otherwise, why do you have to restrict yourself to using PCA?
Comment: The answer in the linked thread on StackOverflow is better than the ones here.
Answer: PCA gives you the directions in feature space along which the variance of the data is maximal, i.e. containing most information about your data (if you assume it to be Gaussian distributed).
Another way to look at it, and the one that best applies here is to see them  as the vectors which give you the best reconstruction of your date in terms of the Euclidean distance. There are a number of ways to derive it. There are many books and tutorials where you can find those derivations. I would recommend you reading this one.
What you would do is to calculate the first $k$ components for each of the character classes. WHen presented a new sample, you calculate the projection of that sample onto each of the principal components (PC) of each class, and take as resulting class the one giving the highest projection, in other words, the one that the sample is closest to.
Last but not least, PCA is rather employed as a dimensionality reduction procedure than as a classifier. For that there are much better approaches. Mixture of probabilistic PCAs, SVMs, and lot more.
Answer: You should use PCA for feature selection before applying a classifier. This usage of PCA in classification has grown common since a 1991 paper on classifying faces using "eigenfaces". The procedure is basically:

Select k orthogonal dimensions of maximum variation (given by the
eigenvectors of the covariance matrix) for all the data together
(after normalization).
Project all data points (training and test) onto these k dimensions to get k-dimensional feature vectors.
Learn and classify the k-dimensional feature vectors using your
    favorite classification method.

The role of PCA in this scheme is to reduce the complexity of the data handled by the classification stage, and thus perhaps afford stronger classifiers. One failure case for this scheme is when there is large intra-class variation in orthogonal directions to the inter-class variation, and thus the inter-class directions are lost. In practice though, the scheme is very commonly used and found to be successful for a variety of problems.
Answer: I know of one way, there might be others.
The probabilistic formulation of PCA, pPCA, is actually a density model-it allows you to estimate $p(x)$. Thus, in a generative approach you can get a predictive distribution via Bayes rule: $p(c|x) \propto p(x|c) p(c)$. Thus, you can do one PCA for each handwritten digit. For a new digit, pick the class for which the reconstruction error of the corresponding PCA (which is proportional to the likelihood) is lowest.


get error when showing dojo simple dialog

Question: I've written a on click function to show a simple dojo dialog, but instead it shows

NO_FAST_DRAW = false

This actually works in Nexus 4, 5 and other devices - but not in Samsung Galaxy S2.
 on(dojo.byId("send_email"), "click", function()
            {
                    console.log("emailClicked1");
                    dijit.registry.byId("emailDialog").show();
                    dojo.byId("emailsText").value="";
                    dojo.byId("dialogFlag").value="emailDialog";
                    console.log("emailClicked2");
            });

I can see the console email Clicked1 and 2 but not able to see the dialog as well in UI.

        <form id="emailDialogForm">

To:

                <input id="emailsText" type="email"
                    style="line-height: 2em; width: 95%; margin: 3px; border: none; padding: 2px; font-size: 0.65em;"
                    placeholder="Enter email ID (Separate multiple IDs by ,)" />

                <input type="submit" id="submitEmail" value="Send" /> <input
                    type="button" id="cancelEmail" value="Cancel" />

        </form>

Answer: In the onclick function handler, "show()" action of dialog is asynchronous. So, any code that deals with the content of the dialog, needs to be done only after the show() is completed. i.e, the deferred action needs to be handled.
console.log("emailClicked1");
var def = dijit.registry.byId("emailDialog").show();
if(def) {
 def.then(function(success) {
   dojo.byId("emailsText").value="";
 });
}
dojo.byId("dialogFlag").value="emailDialog";
console.log("emailClicked2");