Allowing unlimited values for a field in programmatically defined form

Question: I am trying to insert a custom form into a page in my Drupal 8 site. This form has 2 fields which need to accept unlimited values (one textfield, one fieldset).
In my current implementation, I have declared this form as a class, defined in the src folder of a module, and my .module file adds this form to the $build array via hook_node_view_alter():
$build['myform'] = \Drupal::formBuilder()->getForm('Drupal\my_module_hook\Form\MyForm');
My class constructs the form using public function buildForm(array $form, FormStateInterface $form_state). I am not sure how to set up a field such that it can accept unlimited values.
I'm aware that tutorials and answers on this topic using Ajax exist such as this and this, but all such examples are using $form_state as an array, which breaks my code as $form_state is an object.
Is building this form as a class the wrong way to do it? If not, how exactly do I accomplish what I'm trying to do without using $form_state as an array? If so, how can I insert my form into the page otherwise? I'm not understanding how other answers and tutorials on the subject are accomplishing this since these functions are usually shown out of context.
Comment: $form_state as array means those examples are using Drupal 7 where it was an array. Conceptually, it is still example the same, instead of $form_state['something'], you simply use $form_state->get() and ->set().
Comment: This change record helped me a lot: https://www.drupal.org/node/2310411
Comment: Thanks guys, that helped me with my array issues. I am following this simple tutorial: https://rapiddg.com/blog/use-ajax-support-multiple-item-values-custom-drupal-7-forms which is for Drupal 7 but I'm accessing the form as appropriate in Drupal 8. The ajax function executes, but no field is added. I have a hunch it's because I can only use $form_state as a function argument and not &$form_state. Is this worth its own thread do you think?
Comment: @saramm1 take a look at the [examples](https://simplytest.me/project/examples) **(click the drop down and select the 8.x-1.x)** and enable `fapi example` and take a look at the ajax example there. Then take a look at the [source code](http://cgit.drupalcode.org/examples/tree/fapi_example/src/Form/AjaxDemo.php) to see how they did it.
Comment: Thanks @NoSssweat, I'm following this example but I can't get the ajax function to fire at all no matter what I do. I added a ddl($form) to my callback function and my Devel debug report is still empty.
Answer: I have set up a module demonstrating how to allow the user to add unlimited values:
https://bitbucket.org/scotteuser/drupal-8-demo-form-unlimited-values
Here is the Form itself:
<?php

namespace Drupal\demo_form_unlimited_values\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class UnlimitedValuesForm.
 *
 * @package Drupal\demo_form_unlimited_values\Form
 */
class UnlimitedValuesForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'unlimited_values_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // State that the form needs to allow for a hierarchy (ie, multiple
    // names with our names key).
    $form['#tree'] = TRUE;

    // Initial number of names.
    if (!$form_state->get('num_names')) {
      $form_state->set('num_names', 1);
    }

    // Container for our repeating fields.
    $form['names'] = [
      '#type' => 'container',
    ];

    // Add our names fields.
    for ($x = 0; $x < $form_state->get('num_names'); $x++) {
      $form['names'][$x]['first_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First name @num', ['@num' => ($x + 1)]),
      ];

      $form['names'][$x]['last_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last name @num', ['@num' => ($x + 1)]),
      ];
    }

    // Button to add more names.
    $form['addname'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add another name'),
    ];

    // Submit button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Decide what action to take based on which button the user clicked.
    switch ($values['op']) {
      case 'Add another name':
        $this->addNewFields($form, $form_state);
        break;

      default:
        $this->finalSubmit($form, $form_state);
    }
  }

  /**
   * Handle adding new.
   */
  private function addNewFields(array &$form, FormStateInterface $form_state) {

    // Add 1 to the number of names.
    $num_names = $form_state->get('num_names');
    $form_state->set('num_names', ($num_names + 1));

    // Rebuild the form.
    $form_state->setRebuild();
  }

  /**
   * Handle submit.
   */
  private function finalSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Do what you want with the final data here'), 'status');
  }

}

The critical bits are:

$form[#tree] tells Drupal that the form is hierarchical.
$form_state->get() and $form_state->set() are used around the counter num_names
Check the 'op' to see which button the user pressed. If they pressed to add another field, use $form_state->set() to increase the count and $form_state->setRebuild(); to tell Drupal that the form should be rebuilt.

Hope that helps you get it working!
Comment: Thanks Scott, this did work for me, but I would like my form to use Ajax so that it is not reloading the page. The user will likely have to add a field about 10 times on average. Upvoting because this is still a good solution that is pointing me in the right direction.
Comment: In fact I will accept your answer because it works, and I didn't specify that I wanted Ajax and that implementation is another problem entirely.


Error in Python-generated XML

Question: I'm generating some XML code with Python. This code counts the number of occurences of a word in a corpus and matches that word to a number (a probability distribution).
Here's a sample a little of the XML:
<?xml version="1.0" encoding="UTF-8" ?>
    <root>
        <Durapipe type="int">1</Durapipe>
        <EXPLAIN type="int">2</EXPLAIN>
        <woods type="int">2</woods>
        <hanging type="int">3</hanging>
        <hastily type="int">2</hastily>
        <key type="int" name="27p">1</key>
        <localized type="int">1</localized>
        <Schuster type="int">5</Schuster>
        <regularize type="int">1</regularize>
        ....
    </root>

Here's the Python I'm using to generate this:
from __future__ import unicode_literals

import nltk.corpus
from nltk import FreqDist
import dicttoxml

#corpus
words = [w.decode('utf-8', errors='replace') for w in nltk.corpus.reuters.words()]
fd = FreqDist(words)
afd = dict(fd)

# special key for sum
afd['__sum__']=fd.N()

xml = dicttoxml.dicttoxml(afd)

f=open('frequencies.xml', 'w')
f.write(xml)
f.close()

I later ran the XML through XStream to convert it into a Java Map. Unfortunately, XStream cannot convert it due to an error in the XML code, on the occurence of the word 'key'. I can't find an error for the life of me. The XML Error looks like this:
[Fatal Error] frequencies.xml:1:27582: Element type "key" must be followed by either attribute specifications, ">" or "/>".
Exception in thread "main" com.thoughtworks.xstream.io.StreamException:  : Element type "key" must be followed by either attribute specifications, ">" or "/>".
So I have three questions here: What is this error? How can I fix the XML? How can I modify the Python code to generate correct XML?
Sorry for the lengthy question, but I'm inexperienced in both Python and XML. Any help you can give would be much appreciated. Thanks in advance!
Comment: Also, what's the error from XStream? Considering that you're using a library whose error messages are a selling point, it's probably worth posting them here.
Comment: It might be better to add the xstream error message to the body of your question rather than as a comment... Comments get folded, and we are more likely to see it in the question.
Comment: This seems like a use-case for JSON, rather than XML.
Comment: The obvious difference between `key` and the other tags is that it has a `name` attribute and they don't. What is that for?
Comment: Here's the error: "[Fatal Error] frequencies.xml:1:27582: Element type "key" must be followed by either attribute specifications, ">" or "/>"."
Comment: It seems xstream is complaining about a different `` element than the one in your sample. Check what it looks at the exact position indicated (line 1, column 27582). You could use something like `cut -c 27580-27600 frequencies.xml` to help you.
Comment: Extremely late to this party, but this issue should be fixed in version 1.7.3 of dicttoxml.
Answer: nltk.corpus.reuters.words() returns a list that contains some "words" that can not be valid XML element names, for example, .'".
When dicttoxml() encounters such a key in the afd dictionary it generates an element with the name "key" and with an attribute name containing the original (invalid) name, e.g.
<key type="int" name=".'"">1</key>

Clearly this is invalid XML and all XML parsers should (rightly) complain about it. xmllint does and you've found that XStream does too. dicttoxml() is not replacing characters such as double quotes (") with ". To work around this you can call xml_escape() on the keys before running dicttoxml() (see dict comprehension below):
from __future__ import unicode_literals

import nltk.corpus
from nltk import FreqDist
from dicttoxml import dicttoxml, xml_escape

#corpus
words = [w.decode('utf-8', errors='replace') for w in nltk.corpus.reuters.words()]
fd = FreqDist(words)
afd = {xml_escape(k):v for k,v in fd.items()}

# special key for sum
afd['__sum__']=fd.N()

xml = dicttoxml(afd)

f=open('frequencies.xml', 'w')
f.write(xml)
f.close()

Comment: You are a beautiful human being.
Comment: Does it please you to believe that I am a beautiful human being?
Comment: I'll edit the question to show it

Error in Python-generated XML


HTTP server works in Cocoa application but not test case -- run loop issue?

Question: I'm trying to add a GHUnit test case to this SimpleHTTPServer example. The example include a Cocoa application that works fine for me. But I can't duplicate the behavior in a test case.
Here is the test class:
#import <GHUnit/GHUnit.h>
#import "SimpleHTTPServer.h"

@interface ServerTest : GHTestCase
{
    SimpleHTTPServer *server;
}
@end

@implementation ServerTest

-(void)setUpClass
{
    [[NSRunLoop currentRunLoop] run];
}

- (NSString*)requestToURL:(NSString*)urlString error:(NSError**)error
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:1];
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
    NSString *page = nil;
    if (error == nil)
    {
        NSStringEncoding responseEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]));
        page = [[NSString alloc] initWithData:data encoding:responseEncoding];
        [page autorelease];
    }
    return page;
}

- (void)testPortReuse
{
    unsigned int port = 50001;
    NSError *error = nil;
    NSString *path, *url;

    server = [[SimpleHTTPServer alloc] initWithTCPPort:port delegate:self];
    sleep(10);
    path = @"/x/y/z";
    url = [NSString stringWithFormat:@"http://localhost:%u%@", port, path];
    [self requestToURL:url error:&error];
    GHAssertNil(error, @"%@ : %@", url, error);
    [server release];
}

- (void)processURL:(NSURL *)path connection:(SimpleHTTPConnection *)connection
{
    NSLog(@"processURL");
}

- (void)stopProcessing
{
    NSLog(@"stopProcessing");
}

@end

I've tried sending requests via NSURLRequest and also (during the sleep) via a web browser. The delegate methods -processURL and -stopProcessing are never called. The problem seems to be that [fileHandle acceptConnectionInBackgroundAndNotify] in SimpleHTTPServer -initWithTCPPort:delegate: is not causing any NSFileHandleConnectionAcceptedNotifications to reach the NSNotificationCenter -- so I suspect a problem involving run loops.
The problem seems to be with the NSFileHandle, not the NSNotificationCenter, because when [nc postNotificationName:NSFileHandleConnectionAcceptedNotification object:nil] is added to the end of initWithTCPPort:delegate:, the NSNotificationCenter does get the notification.
Answer: if (error == nil)

That should be:
if (data != nil)

error here is the passed-in pointer to an NSError* - it will only be nil if the caller passed nil instead of a reference to an NSError* object, which isn't what your -testPortReuse method does.
It would also be incorrect to dereference it (as in if (*error == nil)), because error arguments are not guaranteed to be set to nil upon error. The return value indicates an error condition, and the value returned in the error argument is only meaningful or reliable if there is an error. Always check the return value to determine if an error happened, then check the error parameter for details only if something did in fact go wrong.
In other words, as it's written above, your -requestToURL:error: method is incapable of handling success. Much like Charlie Sheen. :-)
Comment: Thanks. I fixed this in my code but it doesn't help with the problem I asked about. Right now `data` is always nil, with error "The request timed out".


Xen virtual host is probably FSCKing - how do I verify?

Question: I have a Xen virtual machine that has been running for over a year under a decent load. I restarted it this morning, and it's been several hours booting. I think it's FSCKing itself. xm list shows that's it's using a lot of cpu. I can't xm console into it. xenconsole: Could not open tty '/dev/pts/0': No such file or directory. The filesystem is EXT3.
Is there any way for me to:

See a boot log / console for the VM, so I can verify what it is doing?
Find out how much longer the FSCKing is going to take?
Answer: The console error you are getting is very likely due to xenconsoled not running for some reason. You stated some super uptime, which leads me to believe you are still using Xen 3.1.x, which I believe had a few bugs in that area.
Try re-starting xenconsoled (literally, just type xenconsoled if its not already running i.e. you don't see it in 'ps'), it will correct the PTY references in xenstore and xm console should work again.
Really, that's the only way you're going to see progress of the FSCK, barring actual introspection, if indeed that is the hangup.
Comment: Thank you! Thank you!

It almost seemed like it was waiting for xenconsoled to finish booting.

Life is good again.


Difference between $A\to B\to C$ and $A\to(B\to C)$

Question: As the title says, what is the difference between $A\to B\to C$ and $A\to(B\to C)$? I have tried to reduce these expressions into $A\to B === (A\text{ OR } \text{NOT} B)$ form but didn't get anywhere. Any references will be much appreciated.

After posting here, I just stumbled on Wolfram's: (Wolfram Alpha considers A→B→C to be equal to (A→B)→C, which is wrong as explained in @Yuri's answer). However, the technique is neat.
http://www.wolframalpha.com/input/?i=%28a+implies+b+implies+c%29+vs+%28a+implies+%28b+implies+c%29%29
Comment: What does the left mean? Informally I would read it as $(A \rightarrow B) \wedge (B\rightarrow C)$ but you should check your definitions/conventions...
Comment: Also, assuming $\rightarrow$ is implication, the correct reduction is $(A\rightarrow B) \equiv (B \vee \neg A)$, *not* $(A \vee B)$.
Comment: @user7530 thanks, that was a formatting mistake. ALSO, I was putting NOT on B instead of A. I didn't correct the second so that your comment remains relevant.
Answer: The standard convention is that the implication operation is right-associative. That is, $A\to B \to C$ means $A\to (B\to C)$. Now $(A\to B) \to C$ is not equivalent to $A\to (B\to C)$. Consider what happens when $A = B= C =false$.
Comment: can you provide some reference for → associativity? As you put it, this seems that A→B→C and A→(B→C) are equal.
Comment: See e.g. http://www.springer.com/cda/content/document/cda_downloaddocument/9781447141280-c2.pdf?SGWID=0-0-45-1334404-p174507422 : "Although the implication operator is assumed to be right associative, so that $p \to q \to r$ unambiguously means $p \to (q \to r)$, we will write the formula with parentheses to avoid confusion with $(p\to q)\to r$."
Comment: Or http://www.cs.nott.ac.uk/~txa/g52ifr/html/Prop.html : "Implication is right associative, i.e. we read P -> Q -> R as P -> (Q -> R)."


How to get input value from each input ordered by button using javascript?

Question: I want get userID value for each form separately using javascript api.
I tried :
     <form >
     <input  list="browsers" id="${childSnapshot.val().orderid}" >
     <datalist id="browsers">
       <option value="Order Pending">
       <option value="Order Confirmed">
       <option value="Order Shipped">
       <option value="Order Delivered">
     </datalist>
   </form>
   <input id="${childSnapshot.val().orderid}" value="${childSnapshot.val().userID}"
   <button id="${childSnapshot.val().orderid}"  onclick="reply_click(this.id)" style="padding:1px">Update</button>

function reply_click(clicked_id){
  let valueitem = document.getElementById(clicked_id).value;
  var orderid = clicked_id;
  console.log(orderid+valueitem)
}

The result i'm getting Order id and the option value, but userID its not coming how to fix it ?
Comment: Ids have to be **unique**
Comment: provide more informations
Comment: Does this answer your question? [how to get values of each form javascript?](https://stackoverflow.com/questions/68663433/how-to-get-values-of-each-form-javascript)
Answer: Try the following demonstrative snippet:

const button = document.getElementById('button');

const onClickHandler = (e) => {
  const orderID = e.target.dataset.orderId;
  const userID = document.getElementById(orderID).value;
  console.log(userID + ' ' + orderID);
}

button.addEventListener('click', onClickHandler);
<form>
  <input id="list" list="browsers">

  <datalist id="browsers">
    <option value="Order Pending">
    <option value="Order Confirmed">
    <option value="Order Shipped">
    <option value="Order Delivered">
  </datalist>

  <input id="${childSnapshot.val().orderid}" value="${childSnapshot.val().userID}"></input>

  <button id="button" type="button" style="padding: 1px" data-order-id="${childSnapshot.val().orderid}">Update</button>
</form>
Comment: this work perfectly , but its only read the first order button and the remaining orders buttons no
Comment: @AliAlsaggaf how are you generating your HTML?
Comment: @AliAlsaggaf please remember to mark your question as answered if it got a useful answer.
Answer:     <input id="${childSnapshot.val().orderid}" value="${childSnapshot.val().userID}"
   <button id="${childSnapshot.val().orderid}"  onclick="reply_click(this.id)" style="padding:1px">Update</button>

You can't have two same id in html
Did you try this?
<button onclick="reply_click('${childSnapshot.val().orderid}')" style="padding:1px">Update</button>

Comment: i tried this i got the orderid but userid value no
Comment: You must remove the id from top too in your first input "id="${childSnapshot.val().orderid}"" because you using 3 same id in your html code. And at end of the second input you missing "/>" to close the tag.


Convergence issues with lme4 1.1-20 for models that converged when using earlier version of lme4

Question: I am encountering convergence problems with some models after updating to lme4 1.1-20 that I did not encounter with earlier versions of lme4 (in particular, lme4 1.1-15). I am encountering these new convergence issues for some, but not all models, but the models with convergence issues are generally simple models. Therefore I do not understand why they are not converging.
Here is an example:
Dataset:
library(data.table)
d <- as.data.frame(
  fread("curl http://www.intensivelongitudinal.com/ch4/ch4R.zip | tar -xf- --to-stdout *time.csv")
)

Model:
library(lme4)
fit <- lmer(intimacy ~ time * treatment + (time | id), data = d)

This throws a warning, which reads:
Model failed to converge with max|grad| = 0.00398684 (tol = 0.002, component 1)

This model previously converged without issue when using lme4 1.1-15. In addition, it is able to converge when using a rescaled version of the time variable (time01 in the dataset, which changes the range from 0 to 1 instead of 1 to 15).
Any insight into what lme4 1.1-20 is doing differently?
Thanks.
Session Info:
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: OS X El Capitan 10.11.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] lme4_1.1-20       Matrix_1.2-15     data.table_1.12.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.0      lattice_0.20-38 digest_0.6.18   MASS_7.3-51.1   grid_3.5.2      nlme_3.1-137
 [7] evaluate_0.13   minqa_1.2.4     nloptr_1.2.1    rmarkdown_1.12  splines_3.5.2   tools_3.5.2
[13] xfun_0.5        yaml_2.2.0      compiler_3.5.2  htmltools_0.3.6 knitr_1.22

Answer: tl;dr this is a false positive; you can fix it by switching optimizers back to the old default or tightening tolerances slightly.
The lme4 NEWS file shows for version 1.1-20

changed default optimizer to "nloptwrap" (BOBYQA implementation from the nloptr package) for lmer models. To revert to the old default, use control=lmerControl(optimizer="bobyqa")

(this is the only change relevant to this question).
The ?convergence man page points out that for the new nloptwrap optimizer,

Changing ftol_abs and xtol_abs to stricter values
    (e.g. 1e-8) is a good first step for resolving convergence
  problems, at the cost of slowing down model fits.

Let's try these two approaches to check that this is a false-positive warning:
library(lme4)
## default settings (1.1-20)
fit <- lmer(intimacy ~ time * treatment + (time | id), data = d)
## switch back to pre-1.1-20 default optimizer
fit2 <- update(fit, control=lmerControl(optimizer="bobyqa"))
## tighten tolerances
fit3 <- update(fit, control=lmerControl(optCtrl=list(ftol_abs=1e-8,xtol_abs=1e-8)))

Neither of the latter two examples give convergence warnings.
How much do the estimates differ?  Fixed effects:
cbind(fixef(fit2),fixef(fit3))-fixef(fit)
# [,1]          [,2]
# (Intercept)    -9.325873e-15 -4.618528e-14
# time            5.294376e-15  1.942890e-15
# treatment       1.398881e-14  2.489675e-14
# time:treatment -6.196432e-15 -6.106227e-16

The RE standard deviations and correlations differ much more, but probably still not enough to worry about:
ff <- function(x) {as.data.frame(VarCorr(x))$sdcor}
cbind(ff(fit2),ff(fit3))-ff(fit)
# [,1]          [,2]
# [1,] -4.871044e-05 -2.082594e-05
# [2,]  8.250232e-06  5.907501e-06
# [3,] -5.482109e-05 -4.694410e-05
# [4,]  9.775125e-07  2.717170e-08

PS See ?troubleshooting, ?convergence, and ?allFit for more suggestions about dealing with lme4 problems.
PPS There's a good chance that we will tighten the default nloptwrap tolerances in a future release of lme4.
Comment: Thank you so much, very helpful! I was able to reproduce these fixes no problem on my end. Thanks again.


How do I display a PHP script as html page after calling it using AJAX?

Question: I am trying to call a php file, which will display a html page, using AJAX from my js. This is my php file:
<!DOCTYPE html>

<meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snippet details</title>

    <?php
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

        require "../server_detail.php";

        $con=mysqli_connect($server,$username,$pass);
        $connection=mysqli_select_db($con,$database);

        if(!$connection)
            echo "Connection to database failed! Please try again";
        else{
            $sql="SELECT `Snapshot` FROM `snippet` WHERE `Date`='".$_POST["date"].
                "' AND `newspaper`='".$_POST["newspaper"]."' AND `Subject_desc`='".$_POST["news_desc"]."'";

            $result = $con->query($sql);
            $temp=explode('.',$result->fetch_array()[0]);

            echo "
";

            echo "
{$_POST['newspaper']}
";
            if($temp[count($temp)-1]=="pdf" || $temp[count($temp)-1]=="PDF")
                echo "fetch_array()[0]}' height='200px'>";
            else
                echo "fetch_array()[0]}' height='200px'>";
            echo "
{$_POST["news_desc"]}
";
            echo "
";
        }
        $con->close();
    ?>

I am trying to call this script from my js (when a li is pressed):
document.querySelector('body').addEventListener('click', function(event) {
      if (event.target.tagName.toLowerCase() === 'li') {
        var str=event.target.innerText.split('-');
        $.ajax({
            url: '/all_backend_stuff/view_page.php',
            type: 'POST',
            data:{
                "date":document.getElementById("date").value,
                "newspaper":str[0],
                "news_desc":str[1]
            },
            success:function(response){
                window.open('/all_backend_stuff/view_page.php'); //shows that all my array keys are undefined
            },
            complete:function(){}
        });
      }
});

My POST variables are showing as undefined. Why is that?
Comment: **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
Comment: `nothing happens. Why is that?`...I doubt that _nothing_ happens. Have you checked your browser's Console? After all the only code you've written to make anything happen after the AJAX call has finished is `console.log(response);`. I think maybe you've misunderstood how AJAX works. With an AJAX call, you send a request to the server asynchronously, and the response which comes back from the server (i.e. anything which is echoed by the PHP, in your case) is delivered back to your AJAX/JavaScript code, inside a variable (the `response` variable of your "success" function)...
Comment: `` elements are not designed to be interactive. Without extra work, users can't tab to them with the keyboard and screen readers won't announce them as being clickable. You should make your click targets `` elements (which could be inside `` elements).
Comment: _"My POST variables are showing as undefined. Why is that?"_ - because you are looking at the result of a request, that did not send any POST data to begin with: `window.open('/all_backend_stuff/view_page.php')` - this causes a _new_ request, completely independent from your AJAX request. And it is a GET request as well.
Comment: https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again.
Comment: ... so for now it's just sitting there in that variable, and all you've done is log it to the console. If you want it to show somewhere on your page, you need to write some JavaScript code in the "success" function which tells the browser where within your existing page you want to show that content. It will not do anything automatically - the whole point of AJAX is to allow you to stay on the same page without refreshing everything. And it wouldn't know where in the current page to automatically add the returned content, unless you tell it specifically. Therefore it's up to you to sort it out
Comment: P.S. If you're wanting to include this content from PHP within the existing page which runs the AJAX, then the fact your PHP contains doctype, head and body HTML tags is not good thing - it will end up trying to embed an entire HTML document inside the existing HTML document, and the results may not be good. You should be returning only a snippet of HTML which can then be added into your page. Or, as the answer below says, perhaps you should not be using AJAX at all, and should be using a hyperlink or a form to redirect the browser to your PHP page as a whole new page. Depends what you want.
Comment: `My POST variables are showing as undefined. Why is that?`...because `window.open('/all_backend_stuff/view_page.php');` makes a brand new GET request to view_page.php, entirely separate than the one you've just made via AJAX. It runs all over again, and this time, you didn't send it any data. Again, you still seem to have somewhat misunderstood the purpose and concept of AJAX (and possibly HTTP in general, I'm not sure).
Comment: Then how do I send the POST variables and display the `php` page at the same time?
Comment: Either by the method I've just described above, where you write some JS code to include the response from PHP into the page which ran the AJAX call. Or you forget about AJAX and make a standard HTML form (or a set of forms, if you need) whose action points to the PHP script, which the user submits and the browser posts back in the usual way.
Comment: (Disregarding images and iframes for a moment) There are essentially 3 ways to trigger a HTTP request from a browser - click a link, submit a form, or make an AJAX request. All 3 can also be automated via JavaScript commands. The first two cause the browser to navigate to a whole new page automatically. The last one is asynchronous as we've been describing, and merely sends and receives data, leaving it up to you to decide what to do with the data when you've received it.
Answer: Different ways of accessing URLs behave differently.
If you use  then the browser will load the data from the URL and display it as a new page.
If you use  then the browser load the data from the URL and display the image inline at that point in the current page.
If you use  then the browser will load the data from the URL display the page in a box in the current page.
If you use Ajax then the browser will load the data from the URL and make it available to JavaScript.
That is the point of Ajax.
It doesn't display the result as a new page because Ajax is designed to not do that.
If you want to display the result as a new page then the best thing to do is not use Ajax. Use a regular <form> submission instead.
If you insist on using Ajax then you need to process the data that you are currently were, before you edited the question, logging and change the DOM of the current page using it. Generally, when you do this you will want to request a URL, with Ajax, that returns structured data (e.g. in JSON format) and then selectively update parts of the page instead of loading a whole new HTML document.


How to implement AutoScroll HeaderedItemsControl WPF?

Question: I merged the things I have found out to implement an auto-scroll-to-end Headered Items Control. I cannot manage to do it. What am I doing wrong?
In Resource Directory, ScrollingHeaderedItemsControl is styled as:

The class ScrollingHeaderedItemsControl is defined as here:
public class ScrollingHeaderedItemsControl : HeaderedItemsControl
    {
        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                int newItemCount = e.NewItems.Count;
                if (newItemCount > 0)
                    this.ScrollToEnd();
                base.OnItemsChanged(e);
            }
        }
    }

ScrollToEnd is a static function written specifically for ScrollingHeaderedItemsControl such as:
public static void ScrollToEnd(this ItemsControl control)
        {

            try
            {
                Border border = VisualTreeHelper.GetChild((DependencyObject)control, 0) as Border;
                StackPanel sp = VisualTreeHelper.GetChild((DependencyObject)border, 0) as StackPanel;
                ScrollViewer sv = VisualTreeHelper.GetChild((DependencyObject)sp, 1) as ScrollViewer;
                sv.ScrollToEnd();
            }
            catch(Exception)
            {

            }
        }

ScrollingHeaderedItemsControl is used in the UserControl like this:
    <common:ScrollingHeaderedItemsControl x:Name="MessagesHIC" FontSize="32" Header="Error/Warning/Info Messages"
                                                  Background="Green"
                                      BorderBrush="AntiqueWhite" ItemsSource="{Binding Messages}"
                                      Margin="10" Grid.Row="1" Grid.Column="0"
                                                  ScrollViewer.CanContentScroll="True">
                <common:ScrollingHeaderedItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding MessageString}" Foreground="{Binding MessageColor}" TextWrapping="Wrap" FontWeight="Light" FontSize="26" />
                    </DataTemplate>
                </common:ScrollingHeaderedItemsControl.ItemTemplate
</common:ScrollingHeaderedItemsControl>

Comment: have you breakpointed? is it executing all the lines of code you're expecting it to without any exceptions being thrown?
Comment: Yes, it is executing all the lines. It calls "sv.ScrollToEnd()" and it does not scroll and stays the same.
Answer: Your template contains a stackpanel which doesn't set a height constraint, therefore the scrollviewer is never required to show the scrollbars. Change your Template to the following:

You will then need to change your code behind to:
try
            {
                Border border = VisualTreeHelper.GetChild((DependencyObject)control, 0) as Border;
                Grid sp = VisualTreeHelper.GetChild((DependencyObject)border, 0) as Grid;
                ScrollViewer sv = VisualTreeHelper.GetChild((DependencyObject)sp, 1) as ScrollViewer;
                sv.ScrollToEnd();
            }
            catch (Exception)
            {

            }


Calculating $\hom(\mathbb{Z}_p,\mathbb{Z})$.

Question: I am working on some homework and I am trying to compute $\hom(\mathbb{Z}_p,\mathbb{Z})$. I found a guide that said it would be the set $\{n\in\mathbb{Z}:np=0\}$. But the only element in $\mathbb{Z}$ that fullfill that would be $0$, is that correct? Or is the list help wrong as it seems a bit off and like it should be more.
Comment: Is $\Bbb{Z}_p$ the group of $p$-adic integers or the cyclic group of order $p$?
Comment: Perhaps the guide was identifying such homomorphisms by their action on the element of $\mathbf{Z}_{p}$ represented by $1$?  Every group homomorphism from $\mathbf{Z}_{p}$ to $\mathbf{Z}$ sends $0$ to $0$, but you have a choice in where it sends $1$.  The action of the homomorphism is then completely determined by this choice, since $\mathbf{Z}_{p}$ is cyclic and generated by $1$.
Comment: I never deal with adic numbers so I forget they exist but yes, I mean $\mathbb{Z}/p\mathbb{Z}$
Answer: Let $f \in \operatorname{Hom}(\Bbb{Z}_p , \Bbb{Z})$. Then by the first isomorphism theorem, $\Bbb{Z}_p / \ker f$ is isomorphic to a subgroup of $\Bbb{Z}$. Recall that nontrivial subgroups of $\Bbb{Z}$ are infinite cyclic. But $\Bbb{Z}_p$ has no infinite quotients, so necessarily $\Bbb{Z}_p / \ker f$ is trivial! This implies that $\ker f = \Bbb{Z}_p$, i. e. $f=0$.
Comment: Damn I hate when such easy stuff just goes by without one noticing or thinking. My gut has failed me again! Thank you for this response, it made it clearer.
Comment: NOTE: this proof is valid whenever $\Bbb{Z}_p$ denotes a group with no infinite quotients. In particular it holds for finite groups, for $p$-adic integers, and for any profinite group as well.
Comment: Of course, I understood that, thank you again.
Comment: @Crostul I'm inclined to think that $\hat{\mathbb{Z}}_p/\mathbb{Z}$ is infinite. So, no, the argument won't work for the $p$-adic integers or profinite groups in general (where quotients with respect to *open* subgroups are finite). What can be used in the case of $p$-adic integers is that it's an indecomposable group; a nontrivial homomorphism to $\mathbb{Z}$ would have a projective image.
Comment: @egreg You are right!


What is the rule for rotations about a point not the origin?

Question: I know the rules for $90^\circ$(counterclockwise and clockwise) rotations, and $180^\circ$ rotations, but those are only for rotations about the origin. What is the rule for a rotation above that is not about the origin?
By rule, I mean this: $(x, y) \rightarrow (y, -x)$.
Answer: I suppose there are lots of ways of looking at motions of the plane, but try this:
First, if you're going to turn the plane about the origin through an angle of $\theta$ (positive for counterclockwise), then the rule is:
$$
(x,y)\mapsto(x',y')=(x\cos\theta-y\sin\theta,x\sin\theta+y\cos\theta)\,.
$$
That is, if your point $P=(x,y)$, the rotated point is $P'=(x',y')$.
Now if your center of rotation is not $(0,0)$ but rather $Q=(\alpha,\beta)$, you want to do the operation in three steps: first move your point $P=(x,y)$ leftward by $\alpha$ and downward by $\beta$. (You see that my mental picture is that $Q$ is in the first quadrant; but this is immaterial to the formulas.) This means the new point has coordinates $(x-\alpha,y-\beta)$. Now you apply your rotation of $\theta$, to get the rotated (after translation) point to have coordinates
$\bigl((x-\alpha)\cos\theta-(y-\beta)\sin\theta,(x-\alpha)\sin\theta
+(y-\beta)\cos\theta \bigr)$. Finally, you want to move everything back, but shifting rightward by $\alpha$ and upward by $\beta$. Therefore, your final formula is
$$
(x,y)\mapsto (x',y')=\bigl(\alpha+(x-\alpha)\cos\theta-(y-\beta)\sin\theta, \beta+(x-\alpha)\sin\theta +(y-\beta)\cos\theta
\bigr)\,.
$$
For instance, if your center of rotation is $Q=(1,2)$ and you want to rotate $90^\circ$ counterclockwise about $Q$, the formula would be
$$
(x,y)\mapsto\bigl(1-(y-2),2+(x-1)\bigr)=(3-y,1+x)\,.
$$


Notice: Undefined index em campo tipo file

Question: Tenho um formulário com campos de tipo text e file:
<form id="first-setup" method="post" enctype="multipart/form-data" data-toggle="validator">
    <input type="hidden" id="userkey" value="{userKey}">

    Nome
    <input id="input-firstname" name="input-firstname" data-minlength="2" data-error="Desculpe, seu nome deve possuir no mínimo 2 dígitos." type="text" class="form-control" required>

    Sobrenome
    <input id="input-surname" name="input-surname" data-minlength="2" data-error="Desculpe, seu sobrenome deve possuir no mínimo 2 dígitos." type="text" class="form-control" required>
                                             [...]
    Foto de perfil
    <input id="input-picture" name="input-picture" type="file" class="filestyle" data-iconName="fa fa-spaced fa-folder-open-o" data-input="false" data-buttonText="Envie uma foto de perfil">

    <button id="button-submit" class="btn btn-warning" type="submit">Concluir </button>
</form>

Utilizo ajax pra fazer o envio dele:
$('#button-submit').click(function(e) {
    e.preventDefault();
    // Correção de bug do bootstrap-validator
    // Bug relatado: envia o formulário mesmo com o input[submit] desativado (disabled=true) - ou seja
    // com erros de validação nos valores.
    var disabled = $(this).hasClass('disabled');
    if (disabled) return false;

    var firstname = $('#input-firstname').val(),
        surname   = $('#input-surname').val(),
        fullname  = $('#input-fullname').val(),
        birthdate = $('#input-birthdate').val(),
        city      = $('#input-city').val(),
        bgfile    = $('#input-background').val(),
        picfile   = $('#input-picture').val();

    // validações e eventos na view

    var form = $('#first-setup').serialize();
    $.ajax({
        url: '../application/controller/class.FirstSetupController.php',
        dataType: 'json',
        data: form,
    })
    .done(function(data) {
        console.log(data);
    })
    .fail(function(data) {
        console.log(data);
    });
});

O problema é que no php, se eu fizer um if (isset($_FILES["input-picture"])) ele me retorna false, apenas reconhecendo os input[type=text] do form.
Já verifiquei as configurações do php (file_uploads, post_max_size e upload_max_file_size) e estão ok, meu .htaccess também.
Procurei utilizar as soluções de outras perguntas iguais mas nenhuma resolveu esse problema.
Comment: Acho que o `$.ajax` não faz upload, você tem que usar o `File API`.
Answer: O jQuery.ajax não suporta upload se não usar o File API, portanto acredito que ele converte a variavel input-surname para POST (então no servidor você recebe $_POST['input-surname']).
Você pode usar o File API para fazer o upload, usando $_POST ao invés de $_FILE:
Javascript:
var form = $('#first-setup').serialize();
var file = $('#input-surname').get(0).files[0];
var reader = new FileReader();
reader.onload = function (event) {
    var dados = event.target.result;
    var nome = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'

    form.dataFile = dados;
    form.dataName = nome;

    $.ajax({
        url: '../application/controller/class.FirstSetupController.php',
        dataType: 'json',
        data: form,
    })
    .done(function(data) {
        console.log(data);
    })
    .fail(function(data) {
        console.log(data);
    });
};

PHP:
<?php
$dataFile = $_POST['dataFile'];
$dataName = $_POST['dataName'];

$fp = fopen('upload/' . $dataName, 'w');
fwrite($fp, $dataFile);
fclose($fp);


$T(B_E)$ is closed for $T$ a bounded linear map

Question: Let $T:E\rightarrow F$ be a bounded linear map for E and F Banach spaces, and E reflexive. Let $B_E$ be the unitary closed ball in $E$. How would you argue that $T(B_E)$ is closed?
Answer: If $E$ is reflexive, its closed unit ball is weakly compact, and $T$, being continuous from the weak topology to the weak topology, takes weakly compact sets to weakly compact sets.
Comment: Weakly compact implies weakly closed, and weakly closed implies closed.
Comment: But how do I connect weakly compact with closed?
Comment: why is $T$ continuous with respect to weak topologies?
Comment: Because the weak topology is the weakest topology that makes every lineal function continuous.
Comment: ... every bounded linear functional, that is.  And if $\varphi$ is a bounded linear functional on $F$, $\varphi \circ T$ is a bounded linear functional on $E$.
Comment: @RobertIsrael you are right my bad
Comment: I'm really sorry but I still don't see how is that weakly compact implies closed.


Adicionar objeto dentro de um objeto

Question: é o seguinte, eu tenho 3 tabelas. Cidades, Orgãos e Motivos. 1 Cidade pode ter vários orgãos, e 1 orgão vários motivos.
Meu problema é que em uma só página tem que aparecer todos os orgãos da cidade e dentro do orgão todos motivos do orgão.
Não estou conseguindo colocar os motivos dentro do orgão, questão de lógica mesmo.
Estou fazendo um ng-repeat dos orgãos que são referenciados a cidade
<code>$http.get(base_url + 'controlx/functions/getWhere/orgaos/cidades_id/'
       + $stateParams.cidadeId) // Aqui pega os orgãos referenciado a cidade
.success(function(data) {
  $scope.orgaos = data;
  var i = 0;
  var motivo = [];
  for (let orgao of $scope.orgaos){
    $http.get(base_url + 'controlx/functions/getWhere/motivos/orgaos_id/'+orgao.id) // aqui faz uma repetição referenciado ao orgão.
    .success(function(data) {
      motivo.push(data);
      $scope.orgaos=motivo[i];
      i++;
    });
  }
  console.log(motivo);
  if (data.length === 0) {
    $scope.erro = 'Nenhum Orgão Encontrado';
  }
});
</code>
Então, estava tentando adicionar os motivos dentro de cada orgão. Mas assim não está funcionando.
Eu queria basicamente é colocar os motivos dentro de cada respectivo orgão ($scope.orgaos). Como se fosse dar um .push, mas não funciona em objetos.
Para entenderem como quero:
Comment: Bom dia @ViníciusVilela, vendo seu código, já consigo ter uma pista do que pode estar dando errado. Mas você pode informar se há algum erro no console? e qual o *output* de `console.log(motivo);`?
Comment: Ele retorna arrays (orgãos) com arrays dentro (motivos)
Comment: e nenhum erro no console?
Comment: Não, sem erro no console
Comment: Eu queria colocar os motivos, dentro de cada respectivo orgão ($scope.orgaos) Como se fosse dar um .push, mas não funciona em objetos.
Comment: O que você recebe das duas requests são arrays? Qual é a estrutura destes dados?
Comment: [http://imgur.com/ZDbPSLG] Isso é o que retorna no console.log(motivo). O primeiro orgão tem 2 motivos e o segundo 4
Comment: O que recebo das requests são objects.
Answer: Bom, como você não postou o data schema, vou supor que você recebe um Array de Objetos nas duas requisições. Então você pode fazer o seguinte:
<code>$http.get(base_url + 'controlx/functions/getWhere/orgaos/cidades_id/' + $stateParams.cidadeId) // Aqui pega os orgãos referenciado a cidade
.success(function(data) {

    /*
        Supondo que aqui você recebe um Array de Objetos.
        Seria algo assim:
            [
                { id: 'id_orgao_1' },
                { id: 'id_orgao_2' },
                { id: 'id_orgao_3' }
            ]
    */
    $scope.orgaos = data;

    for (let orgao of $scope.orgaos){
        $http.get(base_url + 'controlx/functions/getWhere/motivos/orgaos_id/'+orgao.id) // aqui faz uma repetição referenciado ao orgão.
        .success(function(data) {

            /*
                Supondo que aqui você recebe um Array.
                Aqui você cria uma nova chave dentro de cada objeto contendo este Array
            */
            orgao.motivos = data

        });
    }

    console.log($scope.orgaos);
    /*

     Sua estrutura final:

            [
              {
                "id": "id_orgao_1",
                "motivos": [
                  "motivo1 do orgao1",
                  "motivo2 do orgao1",
                  "motivo3 do orgao1"
                ]
              },
              {
                "id": "id_orgao_2",
                "motivos": [
                  "motivo1 do orgao2",
                  "motivo2 do orgao2",
                  "motivo3 do orgao2"
                ]
              },
              {
                "id": "id_orgao_3",
                "motivos": [
                  "motivo1 do orgao3",
                  "motivo2 do orgao3",
                  "motivo3 do orgao3"
                ]
              }
            ]
    */

    if (data.length === 0) {
        $scope.erro = 'Nenhum Orgão Encontrado';
    }
});
</code>
Comment: Nossa, seu lindo, valeu. Deu certim :3
Comment: @ViníciusVilela Ótimo! Boa sorte no projeto!
Answer: Amigo. Seria interessante fazermos um javascript básico mesmo e fazer a lógica funcionar com os objetos, ai poderíamos contribuir mais fácil com a solução do problema e replicarmos localmente
segue script básico que fiz, se puder ajustá-lo conforme sua necessidade poderemos avaliar o problema :)

<code>  var orgaos = { "cidade" : ["SP", "RJ"] }

  var i = 0;
  var motivo = [];
  for (let orgao of orgaos.cidade){

      motivo.push('teste');
      orgaos=motivo[i];
      i++;

  }
  console.log(motivo);

</script>
</code>
Comment: Então, vc entendeu errado, a cidade tem orgãos, e os orgãos tem motivos kk
Comment: meu problema não é sintaxe ou algo assim, é na logica mesmo que não está funcionando.
Comment: Que bom que resolveu acima :)

Adicionar objeto dentro de um objeto


Where to use Lambda Expression

Question: What are the different scenario in which we can use Lambda Expression. One of the scenarios is with LINQ Queries.
Answer: Anywhere you want to create a delegate or an expression tree, basically. Some examples outside LINQ:

The old-style List<T>.ConvertAll/FindAll etc methods
Starting new threads / tasks
Attaching event handlers
Providing an action in unit tests (e.g. "this action should throw an exception")
Providing a value on request for Lazy<T>

Where to use Lambda Expression


How to embed Twitter  and E-mail links inside a webform?

Question: I want to embed inside a webform a Twitter and E-mail button,so
as the user to post/share the page to his Twitter account or e-mail it.
How to do that?
Thanks
Answer: There is a module for that, in fact there are many. Since a webform is a node, it makes the possibilities much greater. An example of a module that allows users to share your content in various ways is the Service links module.


What drawbacks does VTP pruning pose?

Question: I'm currently learning a bit about Cisco switch configuration and VLAN configuration, specifically VTP. Reading on Cisco's site, the feature of VLAN pruning appears to not be used on a switch/VTP domain/VLAN by default. From what they give:

All unknown unicasts and broadcasts in a VLAN are flooded over the entire VLAN. All switches in the network receive all broadcasts, even in situations in which few users are connected in that VLAN. VTP pruning is a feature that you use in order to eliminate or prune this unnecessary traffic.

Does it pose a specific drawback, such as certain types of traffic that may not reach their destination or higher memory use/autoconfiguration time, that makes it unfit for use in some configurations/networks?
Answer: Access ports not in the VLAN that the unicast or broadcast originates from don't receive that traffic in the first place. That's the point of VLAN's. The excerpt from that article is making the point that instead of dealing with that traffic, if no access ports exist in the originating VLAN on a particular switch then VTP pruning "prunes" that traffic from that switch, so as to not consume trunk link bandwidth or processing cycles.
Answer: The only time I see it causing a problem could be an STP issue ( I can't tell without seeing a detailed diagram). If you don't have a very complex network structure, I don't think there will be any problems.

What drawbacks does VTP pruning pose?


Android app is crashing after clicking button

Question: Android Studio is showing open app again app-crash when I click sign up button
The app is running fine but when I click the sign up button it crashes, also want to start new activity after sign up but the error is com
I think there is some problem with button click listener or validation code but don't know where this error is coming from.
following is my java file code:
public class SignUp extends AppCompatActivity {
    private static final String TAG = "SignUp";
    private Vibrator vib;
    Animation animShake;
    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputDOB;
    private TextInputLayout signupInputLayoutName, signupInputLayoutEmail, signupInputLayoutPasword, signupInputLayoutDOB;
    private Button btnSignUp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_up_form);
        signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_name);
        signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_email);
        signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_Password);
        signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_DOB);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputName = (EditText) findViewById(R.id.signup_input_email);
        signupInputName = (EditText) findViewById(R.id.signup_input_Password);
        signupInputName = (EditText) findViewById(R.id.signup_input_DOB);

        btnSignUp = (Button) findViewById(R.id.btn_signUp);
        animShake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
        vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
    }

    public void register() {
        submitForm();
        {
            if (!checkName() || !checkEmail() || !checkDOB() || !checkPassword()) {
                Toast.makeText(this, "signup failed", Toast.LENGTH_SHORT).show();
            } else {
                onSignupSuccess();
            }
        }
    }

    public void onSignupSuccess() {
        Intent intent = new Intent(SignUp.this, tab1Petrol.class);
        startActivity(intent);
        finish();
    }

    private void submitForm() {
        if (!checkName()) {
            signupInputName.setAnimation(animShake);
            signupInputName.startAnimation(animShake);
            vib.vibrate(125);
            return;
        }
        if (!checkEmail()) {
            signupInputEmail.setAnimation(animShake);
            signupInputEmail.startAnimation(animShake);
            vib.vibrate(125);
            return;
        }
        if (!checkPassword()) {
            signupInputPassword.setAnimation(animShake);
            signupInputPassword.startAnimation(animShake);
            vib.vibrate(125);
            return;
        }
        if (!checkDOB()) {
            signupInputDOB.setAnimation(animShake);
            signupInputDOB.startAnimation(animShake);
            vib.vibrate(125);
            return;
        }
        signupInputLayoutName.setErrorEnabled(false);
        signupInputLayoutEmail.setErrorEnabled(false);
        signupInputLayoutPasword.setErrorEnabled(false);
        signupInputLayoutDOB.setErrorEnabled(false);
        Toast.makeText(this, "you are successfully Registered", Toast.LENGTH_SHORT).show();
    }

    private boolean checkName() {
        if (signupInputName.getText().toString().trim().isEmpty()) {
            signupInputLayoutName.setErrorEnabled(true);
            signupInputLayoutName.setError("Please enter a Name");
            signupInputName.setError("valid Input Required");
            return false;
        }
        signupInputLayoutName.setErrorEnabled(false);
        return true;
    }

    private boolean checkEmail() {
        String email = signupInputEmail.getText().toString().trim();
        if (email.isEmpty() || !isValidEmail(email)) {
            signupInputLayoutEmail.setErrorEnabled(true);
            signupInputLayoutEmail.setError("Please enter a Valid Email");
            signupInputEmail.setError("valid Input Required");
            requestFocus(signupInputEmail);
            return false;
        }
        signupInputLayoutEmail.setErrorEnabled(false);
        return true;
    }

    private boolean checkPassword() {
        if (signupInputPassword.getText().toString().trim().isEmpty()) {
            signupInputLayoutPasword.setError("Please enter password");
            requestFocus(signupInputPassword);
            return false;
        }
        signupInputLayoutPasword.setErrorEnabled(false);
        return true;
    }

    private boolean checkDOB() {
        try {
            boolean isDateValid = false;
            String[] s = signupInputDOB.getText().toString().split("/");
            int date = Integer.parseInt(s[0]);
            int month = Integer.parseInt(s[1]);

            if (date < 32 && month < 13)
                isDateValid = true;
            if (signupInputDOB.getText().toString().trim().isEmpty() && isDateValid) {
                signupInputLayoutDOB.setError("Enter a valid D.O.B");
                requestFocus(signupInputDOB);
                signupInputDOB.setError("valid input required");
                return false;
            }
        } catch (Exception ex) {
            signupInputLayoutDOB.setError("Enter a valid D.O.B");
            requestFocus(signupInputDOB);
            return false;
        }
        signupInputDOB.setError(null);
        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

}

XML file code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_gravity="center">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/sign_up_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true">

           <EditText
               android:id="@+id/signup_input_name"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:ems="10"
               android:hint="@string/name" />
        </android.support.design.widget.TextInputLayout>
        <android.support.design.widget.TextInputLayout
            android:id="@+id/sign_up_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true">

            <EditText
                android:id="@+id/signup_input_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textEmailAddress"
                android:hint="Email" />
        </android.support.design.widget.TextInputLayout>
        <android.support.design.widget.TextInputLayout
            android:id="@+id/sign_up_Password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true">

            <EditText
                android:id="@+id/signup_input_Password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textPassword"
                android:hint="Password" />
        </android.support.design.widget.TextInputLayout>
        <android.support.design.widget.TextInputLayout
            android:id="@+id/sign_up_DOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true">

            <EditText
                android:id="@+id/signup_input_DOB"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:maxLines="1"
                android:hint="Date of Birth" />
        </android.support.design.widget.TextInputLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/gender_textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="I am"
                android:fontFeatureSettings="Password"
                android:textSize="20dp"
                android:fontFamily="Password"/>
            <RadioGroup
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/gender_textView"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/male_radio"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Male"
                    android:checked="true"/>
                <RadioButton
                    android:id="@+id/Female_radio"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Female"/>
            </RadioGroup>
        </RelativeLayout>

        <Button
            android:id="@+id/btn_signUp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimaryDark"
            android:text="Sign Up"
            android:textColor="@android:color/white" />

    </LinearLayout>

</LinearLayout>

Comment: Please post your logcat errors.
Comment: 1. The logcat tells you exactly where the error comes from. Trace the logic back from the lines mentioned by it. 2. Please read about a [mcve]
Comment: with respect your code is not according to java conventions and have multiple errors.
Comment: First, you have lots of copy paste mistakes(findViewById parts). Second, your logic of checking fields is bad. Please revise them and edit your question.
Comment: When you are giving findviewId to TextInputlayout and edittext your name is same.
Answer: Well for starters you are re-assigning the Input fields here, overwriting the previous one... I'm pretty sure the issue is because of this.
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputName = (EditText) findViewById(R.id.signup_input_email);
signupInputName = (EditText) findViewById(R.id.signup_input_Password);
signupInputName = (EditText) findViewById(R.id.signup_input_DOB);

signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_name);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_email);
signupInputLayoutName = (TextInputLayout)  findViewById(R.id.sign_up_DOB);

The very first thing your code does after onCreate() is checkEmail(), and as I stated above, there is no R.id.signup_input_email assigned to signupInputEmail.
Your code will throw an exception here since checkEmail() refers to a NULL variable.
if (!checkEmail()) { ... }
Comment: Good catch! And the TextInputLayouts as well.


How to set cache expiry date

Question: Trying to cache a large js file on the client browser. When I check firefox's cache information, it shows the js to expire on 12/31/1969. I'm using IIS6 and have tried adding the following code to the web.config:
  <staticContent>
     <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
  </staticContent>

Still the same. How can I get the browser to cache this file?
Answer: You may have to configure that in IIS, I'm not sure that IIS6 honors that web.config setting like IIS7 does.
Answer: In IIS, right click on your Site node and click Properties. Go to the HTTP Headers tab, tick Enable content expiration and set an expiry time.

How to set cache expiry date


Missing NIC and USB devices

Question: Coming into work today, I've found we have a few different computers (different companies/networks/OS versions - all windows based) that are all having the same issue.
1) Network NIC is not able to be viewed from network connections.  If you refresh, its saying the service is not started.  Services state the service is started and running.
2) USB devices are not recognized when plugged in, scan for hardware changes, etc.
We have managed AV, that is kept up to date, and a managed patch policy that has all these machines at the most recent patch.
I'm just wondering if anyone else has experienced these same symptoms, and what they have done to resolve them.
Updates:
11:23 AM -
The issues are spreading, and things are progressively getting worse.  Services are starting to shut down (windows installer, etc), ports are getting blocked.  Rebooting into safe mode (w/ networking) still has these issues.
Patches: No patches went through last night.
Managed AV (McAfee): Nothing new from this point.  This was un-installed and we still had the issues.  No policy changes as far as blocking network access or other have been enabled.
Scanning: We've scanned with malwarebytes, the MS installer service shutdown before we could install any other software.  Nothing came up in the scan.
Connections:  Netstat showed no outgoing connections to any other machines, other than what was expected.
We are working remotely on a site that is 150 miles away.  We have some IT staff on site, but so far nothing.  What a great Thursday. :)
Answer: You didn't say what your AV software is but if you are using SEP11 (Symantec Endpoint Protection) you may have set a policy to disable certain device classes. If you have a different security product it may have similar options. In SEP11 you will find this under Policies->"Application and Device Control" in the Management Console.
Comment: +1 @Matthew Good thought  Have seen that in our test environment.  Too agressieve a policy applied and things stopped working
Answer: Have you scanned for malware with Sopybot, Adaware, malwarebytes or other tools?
Comment: Yes, they resulted in nothing.
Answer: Here are the steps I would take if I had this problem:
Check for recent changes - did a patch get applied recently to the OS or other application? Did a configuration setting get changed recently?
Check the event logs - any errors, warnings, or new event types start popping up recently?
Run spyware scans with multiple products and do manual checking for running programs using HijackThis! or similar.

Missing NIC and USB devices


Lilypond: Set key change signature before D.C. or D.S., and different key in next line

Question: Imagine you have a piece consisting of 3 parts, say A, B, C, and they appear in order A B A C. You want to typeset this in the following form

with Da Capo and a Coda, and a line break after the "D.C.", so that the coda appears on the next line.
Now imagine that A is in B flat major, B is in F major, and C is in E flat major (say). To indicate that, I'd like to have a sign for B flat major at the end of the first line, because that's what the next key will be when you do the jump to the beginning.
I tried to achieve that with
\relative c' {
  % Part A
  \key bes \major a b c d e f g a
  \mark \markup {\musicglyph #"scripts.coda"}
  % Part B
  \key f \major a, b c d e f g a_"D.C."
  \key bes \major
  \break
  \mark \markup {\musicglyph #"scripts.coda"}
  % Part C
  \key es \major
  a, b c d e f g a
}

When compiling this, lilypond outputs a warning about a "conflict with event: `key-change-event'" and discards the second one. The result is

with the wrong key in part C. If I omit the \key bes \major statement before the \break, then I get

which has the correct key in part C, but a misleading signature for E flat major before the D.C. that's going to jump to B flat major.
How can I achieve the result that I want, with the correct keys everywhere but a signature for B flat at the end of the line before the D.C.?
Answer: Assuming you are using (the new) v2.23, there are now some commands for "segno repeats" (i.e. D.C. al fine, D.S. al Coda, etc.).  I've found the syntax to be very tricky to get used to, but also very useful.  In your case they'll save you from using manual rehearsal marks and jump instructions.

It's not clear exactly how you want the end of the first line to look, but I think it looks best with the key signature for the repeat in parentheses, after a single bar line, and before the double barline.
If you don't want the parentheses you can remove that part of the below code, but I think it looks strange to have two key signatures in a row without one of them in parentheses.
One way to get LilyPond to place consecutive key signatures is by placing an invisible grace note in-between them.

Code
\version "2.23.6"

\new Staff {
    \repeat segno 2 {
        \key bes \major
        a'4 4 4 4 |
    }
    \alternative {
        \volta 1 {
            \key f \major
            bes'4 4 4 4 |
            \volta #'() {
                %\bar ""     %% uncomment these lines
                %\grace {s8} %% to remove the single barline
                \once \override Staff.KeySignature.stencil =
                    #(lambda (grob)
                        (parenthesize-stencil
                            (ly:key-signature-interface::print grob)
                            0.1 0.5 1 0.2
                        )
                    )
                \key bes \major
                \grace {s8}
            }
        }
        \volta 2 {
            \section
            \sectionLabel "Coda"
            \break
        }
    }
    \key ees\major
    c''4 4 4 4 |
    \fine
}

Result

The old way of writing codas (or segnos) was by using the same symbol for both the place to jump from and to with the same symbols (as in your image), but the new way is only use the symbol at the first place, and to use words at the second place.
If you want to keep using the old method you can replace \sectionLabel "Coda" with: \sectionLabel \markup {\musicglyph #"scripts.coda"} in the above code.  This will work but the automatic jump instruction will look a bit weird.

A coda really should be on a new staff, either with a space after the main part of the music, or after an indent on a new line.  Unfortunately v2.23 can't be made to do this without difficulty (hopefully future versions will accommodate this).
Comment: Thanks a lot, that's (almost) exactly what I wanted! I didn't know about the new segno repeat syntax, but I've wished for something like that for a while :)
I prefer the end of the first line to *not* set the e flat major (for the next line) at all, since you'll never go to e flat major from there. With an additional

\once \set Staff.explicitKeySignatureVisibility = #end-of-line-invisible

before the \break statement this can be achieved.
Comment: That's a nice idea, and I can use your code then to achieve that. Thanks!
Comment: @MichaelFütterer — Ah yeah that should work.  Perhaps you do want the key sig. for the Coda to appear (in parentheses) before the barline at the end of the A section then?
Answer: Maybe something like this?
{
  \repeat segno 2 {
    \key bes\major
    R1
  }
  \alternative {
    {
      \key f\major
      R1
    }
    {
      \break
      \once\override Staff.KeySignature.stencil =
      #(lambda (grob)
         (if (= (ly:item-break-dir grob) -1)
             (let ((stc (ly:key-signature-interface::print grob)))
               (ly:grob-set-property! grob 'alteration-alist '((2 . -1/2) (-1 . -1/2)))
               (ly:stencil-combine-at-edge stc X RIGHT
                                           (parenthesize-stencil (ly:key-signature-interface::print grob)
                                                                 0.12
                                                                 0.5
                                                                 0.3
                                                                 0.2)
                                           0.8))
             (ly:key-signature-interface::print grob)))
      \key ees\major
      R1
    }
  }
}

Comment: The coda is supposed to be outside of the repeat structure


Bloquear rolagem do scroll pelas telas

Question: como que bloqueia a rolagem do scroll da pagina pelas teclas com jquery, tecla cima(38) e tecla baixo(40),  deixando a rolagem apenas pelo mouse?
Answer: Suponho que esteja falando de qualquer elemento menos textarea, inputs e selects, se for então pode usar regex ou ifs pra verificar o elemento combinado com event.target:
/^(textarea|input|select)$/i

$(document).keydown(function(evt) {
    var key = evt.keyCode;
    if ((key === 38 || key === 40) && !/^(textarea|input|select)$/i.test(evt.target.tagName)) {
       return false;
    }
});

<textarea>teste teste
teste teste
teste teste
teste teste
teste teste
teste teste
teste teste</textarea>

Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste

Se quiser bloquear de qualquer um:

$(document).keydown(function(evt) {
    var key = evt.keyCode;
    if (key === 38 || key === 40) {
       return false;
    }
});

<textarea>teste teste
teste teste
teste teste
teste teste
teste teste
teste teste
teste teste</textarea>

Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste

Vanilla.js

(function () {
    if (document.addEventListener) {
        document.addEventListener("keydown", blockSrollByKeys, false);
    } else if (document.attachEvent) {
        document.attachEvent("onkeydown", blockSrollByKeys);
    }

    function blockSrollByKeys(evt) {
        var key = evt.keyCode;

        if ((key === 38 || key === 40) && !/^(textarea|input|select)$/i.test(evt.target.tagName)) {
           evt.preventDefault();
           return false;
        }
    }
})();
<textarea>teste teste
teste teste
teste teste
teste teste
teste teste
teste teste
teste teste</textarea>

Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste
 Teste

Comment: era isso mesmo, me ajudou bastante u.u

Bloquear rolagem do scroll pelas telas


Can I average z-scores for basic insights?

Question: everyone. I'm new to this so perhaps my question will sound elementary but hopefully you can help.
I have a data set that contains student test scores across several learning areas (English, Biology etc). My goal is to (somehow) quantify who has 'improved' the most across the year with simple software (probably excel) and in as simple a manner as possible.
As an example of what I'd like to do... Imagine that I sit 3 exams (English, Maths and History) in the first half of the year and get 50% for English, 65% for math and 80% for History. Then I sit exams for those same 3 subjects at the end of the year and get different results... Now, if you did the same thing and sat all of your exams (though you might do different subject) is there some way to determine who improved the most between us over the course of the year?
The data that I have access to comes from tests performed twice per year (half-yearly and end-of-year tests). I originally considered calculating the z-scores for each individual's half-yearly and end-of-year test results and then finding the mean for each of these z-score groups.
My question is, can I then calculate something like the percentage increase in each individual's average z-score across the first and second testing period to determine who has 'improved' the most, or is this unsound?
I also considered something like percentile rank but because the scale is not evenly distributed am I right in assuming that this would inflate the results of those in the meaty part of the bell curve? That is, a relatively minor improvement by someone who is performing close to the average can result in a large movement in rank...
Any ideas as to what I could use or how I could improve my idea?
Answer: If you generate the $z$-statistics from conversion of $W$-statistics from Wilcoxon signed-rank test, that would correct for the non-normality of the data. For example, for $N_r \ge 10$, a $z$-statistic can be calculated as $z = \frac{W}{\sigma_W}, \sigma_W = \sqrt{\frac{N_r(N_r + 1)(2N_r + 1)}{6}}$. What that would then be is equivalent to a number of standard deviations of interval change of ranked data. To see whether this interval difference is significant, one converts the $z$-statistic into probability of no difference, and if the probability of no difference is small, e.g., $p<0.05$, one would accept the alternative hypothesis of a significant difference as more likely.
In other words, the above is just a description of what the Wilcoxon signed-rank test, available in most every stats package, does to calculate a probability. In Excel or R-language, this link may help.
The second part of your question relates to what was actually learned. If so, you might consider looking not at marks as percentage, but marks as 100-mark. For example, consider a student who gets a 96 on a final exam before taking the course, and a 98 (on different but similar questions) following the course. What that student did not know then went from (very approximately) 4% of the course material down to 2%, an improvement of twice (but very noisy). Similarly, a student whose mark went from 50% to 75% would have improved as much, proportionately, but still does not likely know as much of the material as the first student did before taking the course.
Summarizing, what answer you obtain depends on how you pose the question. If you want a more exact answer than the above, refine the question a bit more, and I (or someone else) may take a stab at it.
EDIT The OP has refined the question a bit. It now appears to be focused on an improvement of grades, where the information content of courses is arbitrarily assigned equal weights independent of course content, difficulty of material, knowledge of students concerning material and so forth. We still do not know what is on the tests, at least not explicitly. In a classroom environment, a typical assumption is for tests such that the first end semester test covers first semester work, and the end of second semester test covers work for both semesters. In such a case, change of grades is the only measure that is available, and improvement is measured as change in grade point average (GPA), irrespective of which courses are being taken and what the student knows, does not know, or has learned/not learned. The change of GPA can be ranked from best to worst, and the best means greatest improvement in GPA, which is a measure important to some people within the context of some school, but not very meaningful in any other context. One can take the change of GPA scores in each semester, irrespective of how many courses they represent, or what those courses are, and compare them using a one-sample Wilcoxon test, i.e., a particular student improvement compared to all improvements, and extract a one-sided probability, or a $z$ or $W$ stat from that. The probability would then have the meaning that the student's GPA from each semester (i.e., not the overall, cumulative GPA) improved significantly between semesters or not significantly compared to other, individual-semester GPA improvements. What that probability means in more general terms, is, well, not much. I would not want, on a job interview, to be known as the one who ranked first second or third for GPA improvement, or to be known as someone whose GPA improved significantly because it speaks to inconsistent performance, and poor initial performance.
Comment: Thanks, Carl. I think you're right in saying that I probably didn't phrase my question well.
Comment: As an example of what I'd like to do... Imagine that I sit 3 exams (English, Maths and History) in the first half of the year and get 50% for English, 65% for math and 80% for History. Then I sit exams for those same 3 subjects at the end of the year and get different results... Now, if you did the same thing and sat all of your exams (though you might do different subject) is there some way to determine who improved the most between us over the course of the year?
Comment: When I say 'improved', I suppose I'm not sure as to what metric one might use to determine improvement.. that's why I thought that z-scores might be useful as rank will tend to bias people who perform averagely. If there is any weight then I'd prefer for it to bias people who are at the low end of the ability level.
Comment: @Luke Please add this additional information to your question so that it is visible for all readers immediately. Thank you.
Comment: @Luke Need more information, e.g., how to compare 30 students taking English as a second language for children, with 3 students taking Composition for comparative linguistics PhD theses, or semester one of Math: Elements of arithmetic, 30 students with semester two: Tensors for string theory, 1 student.
Comment: @Luke The material being tested on both occasions needs to be considered. For example, is this the same material but slightly different questions? Or, is the material for each test and the course content different and independent during each semester? For some subjects, e.g., Math, course material tends to be hierarchical, and for others, e.g., History, it is less so. Thus, a change in math Grades may be harder to achieve than a change in History grades.


Is it possible to add attribute to a class using JQuery .attr() tag?

Question: I have a JavaScript like this
$(document).on('click', '.transparent-btns_nav', function(event) {
    var images = $('.rslides ').find('img');
    setTimeout(function() {
        images.each(function() { // jQuery each loops over a jQuery obj
            var h = $(this).outerHeight(true); // $(this) is the current image
            var w = $(this).outerWidth(true);
            // alert('source:'+$(this).attr('src'));
            // alert('alto: '+h);
            if (h < 290) {
                $(this).addClass('small');
                var m = 290 - h;
                m = m / 2;

                // alert('less height');
                $('.small').attr('style', 'margin-top:' + m);
                // $('.small').css('margin-top', +m + "px");
                // $('.small').css('margin-bottom', +m + "px");
            }
            if (h > 290) {
                $(this).addClass('big');
                var m = h - 290;
                m = m / 2;
                // alert('less height');
                $('.small').attr('style', 'margin-top:' - m);
            }
        });
    }, 1000);
});

And Media Query something like this
@media only screen
and (min-device-width: 420px)
and (orientation: landscape) {
    #bg {
    }
    #bg img {
        margin - top: 0px;
    }
    .class {
        margin-top: 0px;
        margin-bottom: 0px;
    }
    .big {
        margin-top: 0px;
        margin-bottom: 0px;
    }
}

What I want to do is add attributes to class big and small using the JavaScript and remove the attribute using the MediaQuery  when the mode is Landscape . But I am not able to do it can some one please help me out in this
More Explanation
I am trying to add padding to the image which are bigger or smaller than the div . Like if its height is smaller then equal padding on the top and the bottom .If the height of the image is tooo big then I am trying to add -ve padding at the top and center the image . All these are done dynamically in portrait mode . If the phone is turned into landscape all the padding should be removed
Comment: If you are trying to detect orientationchange you will need to do some reading. http://api.jquerymobile.com/orientationchange/
Comment: lookup jquery css function
Comment: you mean like write in the css file?
Comment: no css will not help they add the attributes in style="" like inline and we can't change an inline attribute using Media Queries
Comment: This seems like shipload of trouble when you could just define new classes and use those.
Comment: @Paulie_D but the height and width of the images has to be calculated  dynamically using JS and then should be added to the class
Comment: Depends on what you are trying to do and why.
Comment: @Paulie_D I am trying to add padding to the image which are bigger or smaller than the div . Like if its height is smaller then equal padding on the top and the bottom .If the height of the image is tooo big then I am trying to add -ve padding at the top and center the image . All these are done dynamically in portrait mode . If the phone is turned into landscape all the padding should be removed
Comment: @LGVentura yes bro updating the .css file but I see its too complicated so is there any other way to do this I have explained what I want to do in the previous comment
Comment: You could bind a function to resize and orientationchange, ill try and write something out later.
Answer: I can give small Input on your code.
Instead "ATTR", you can directly Use "CSS" method to apply inline style to any element.
It will behave same like Attribute Style.
Instead of this:
$('.small').attr('style', 'margin-top:' + m);

You can Use this:
$('.small').css('margin-top',m);

Out put will be same as you Desired:
class="small" style="margin-top:xx"
Answer: I believe what you are really after is not "attributes" but changing "rules", the same as this person:
Changing a CSS rule-set from Javascript
That said, I'm not sure you wouldn't be better off simply using the class selectors to find all of the applicable elements and directly changing their styles. But it can be done.
Comment: saw it bro pretty complicated stuff though . I am just a beginner in JQuery and stuff
Answer: My first suggestion would be for you to look for another option of vertical alignment. Have a look at display: inline-block, or display: table-cell, and see if you can use with vertical-alignment: middle;. - http://css-tricks.com/centering-in-the-unknown/

Second suggestion would be to use the !important statement, inside your media query. That way you could use inline styles (jQuery.css()) to define paddings on portrait, and override on landscape:
@media only screen
and (min-device-width: 420px)
and (orientation: landscape) {
    .big {
        margin-top: 0px !important;
        margin-bottom: 0px !important;
    }
}

Third suggestion would be to write some new css to the page using javascript:
document.write("");


sched_setaffinity fails after I've used cset shield

Question: I am using cset shield to create a user shield with a set of cpus
 cset shield --cpu 1,3,5,7 --kthread on

The idea behind this is to reserve these cpus for my application code, and push all other tasks plus the movable kernel threads onto the other cpus.
In my application I create 4 threads, and in the context of each thread, attempt to use sched_setaffinity to pin each thread onto one of the reserved cpus.
int cpuNum = 1; // each thread gets one of the cpus
pid_t threadId = static_cast<pid_t>(syscall(SYS_gettid));

cpu_set_t cpuSet;
CPU_ZERO(&cpuSet);
CPU_SET(cpuNum, &cpuSet);

if (sched_setaffinity(threadId, sizeof(cpu_set_t), &cpuSet) == -1)
    perror("sched_setaffinity");

However, sched_setaffinity fails with Invalid argument
If I run my application using cset shield --exec ./TestApp then the pinning works
How come the naked sched_setaffinity call fails?
Comment: Can you provide the operating system version and distribution? Kernel version may also be helpful.
Comment: @ewwhite This is suse 11. Will get the rest of the info for you tomorrow.
Comment: Oh bummer... because RHEL had a bug tied to the `sched_setaffinity` interface for awhile. I'm not sure on SuSE.
Answer: Your application code looks correct. Quickly, try this without --kthread on when you create your CPU shields. See if you get the same "Invalid argument" error. I'm wondering if there's an issue with the kernel threads.
Also, is this RHEL? What is the hardware setup (# of cores)? I've seen issues with the sched_setaffinity call on applications moved from Gentoo to Red Hat systems.
Comment: Sadly doesn't work without `--kthread on` either.
Comment: Hardware setup is: 2 sockets, 6 cores per socket, Intel(R) Xeon(R) CPU           X5680  @ 3.33GHz, hyperthreading enabled (but I enforce that no hyperthread cores can be pinned to)
socket 0: cpus: 1, 3, 5, 7, 9, 11; hyperthread_cpus: 13, 15, 17, 19, 21, 23; socket 1:  cpus: 0, 2, 4, 6, 8, 10; hyperthread_cpus: 12, 14, 16, 18, 20, 22


Custom Drupal Analytics with Views- how to track the number of users by role over time?

Question: I am building a social networking website in Drupal.  As users complete their profile, they are awarded different roles.  Now that I have launched the site and have some members, I would like to track the number of users by role over time so that I can see how my site is growing.
I built a view to do this and it shows me the information I want.  However, since I want to measure membership growth I would like to do this over time.  So, currently I simply log into my site and then type the numbers I need into Excel.
Is there a better way to do this?  Ideally, I would like to automatically save an Excel-ready snapshot every week (or in a dream world, have a graph automatically prepared).  Is there some other way (even without views) to track the number of users by role over time?
Comment: i suspect there is no out-of-the box solution ... I keep thinking about improving the "BI" in drupal lately a lot, probably creating something like a new module called "views result persist" would make sense :). The first phase (taking a view and saving its results into a table) should be pretty easy. Creating / altering the table automatically according to changes in the view would be harder :). The results could then be displayed with [forena](http://drupal.org/project/forena) which should [allready allow](http://drupal.org/node/828458) some charts :).
Answer: You should record custom variables in Google Analytics. Download the GA Module https://www.drupal.org/project/google_analytics and Tokens
https://www.drupal.org/project/token
in the bottom of the configuration [yoursite].com/admin/config/system/googleanalytics
expand the SHOWCUSTOM DIMENSIONS section
populate the values with tokens like [current-user:roles]
You can also record an event upon account creation which identifies the type of account
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
you can do a JS event on submit that will record or it probably makes more sense to create a library to record all instances of certain types the way Google Developers is implying.


A sum of a random number of Poisson random variables

Question: in my probability class I was given this question on which I am stuck concerning a sum of random number of Poisson random variables:

Let us define the countable set of independent random variables $ X_i \sim \mathrm{Pois}(\lambda _i) $ and the random variable $N$ independent from the rest of the $ X_i $ which also has a Poisson distribution $ N \sim \mathrm{Pois}(\lambda) $. We are asked to check if the following sum $ Y = \sum_{i=1}^N X_i $ also has a Poisson distribution and if so, with what parameter? As a hint we are asked to look at the characteristic function of the variable to check.

I know the deterministic finite sum of Poisson random variables is again a Poisson random variable with the sum of parameters, but I cannot solve it for a random number of summands that is also Poisson-ly distributed, I know the characteristic function of a Poisson distributed random variable $ \Phi(t) = e^{\lambda (e^{it}-1)} $. I thank all helpers who can show me a way out of this.
Answer: In the case where all $\lambda_j$ are equal, let's say to $\mu$, you can compute
$$ \mathbb E\left[ \exp(itY) \mid N \right] = \exp(\mu (e^{it}-1) N)$$
so that
$$ \mathbb E[\exp(itY)] = \mathbb E [\exp(\mu(e^{it}-1)N] = \exp(\lambda ( \exp(\mu (e^{it}-1))-1))$$
which is not the characteristic function of a Poisson distribution.
However, things are more complicated if the $\lambda_j$ are not all equal.
EDIT: In general, let $s_n = \sum_{j=1}^n \mu_j$.  In particular $s_0 = 0$.  Then
$$ \mathbb E \left[\exp(itY) \mid N \right] = \mathbb E \left[\exp(s_N (e^{it}-1))\right] = \exp(-\lambda) \sum_{n=0}^\infty \dfrac{\lambda^n}{n!} \exp(s_n (e^{it}-1)) $$
Letting $z = 1 - e^{it}$, we want to know if there is a formula
$$ \exp(-\lambda) \sum_{n=0}^\infty \dfrac{\lambda^n}{n!} \exp(-s_n z) =
\exp(-\rho z)$$ where $\rho > 0$.
If this is valid for $z = 1 - e^{it}$, by analyticity it must be valid in the right
 half plane. Now as $z \to +\infty$, the limit of the left side is
$\exp(-\lambda)$ (since $s_0 = 0$), while the limit of the right side is $0$.  So this is impossible: the distribution is not Poisson.
Comment: Thank you Robert the case that all parameters are equal is now clear to me but is there a simple method to determine the distribution if the $ \lambda $s are not equal? Could it be a Poisson distribution
Comment: I figured since N is independent from all other Xs, maybe this can be useful?


Identical linear transformations when their kernel is the same?

Question: Given this subspace $\langle (0,0,0)\rangle$ as a solution set of a homogeneous system of linear equations, so it is a Kernel of a linear transformation.
If two linear transformations have the same Kernel, could they be identical?
Thank you!
Comment: They *could* be identical, but they don't have to.
Comment: $l$ and $2l$ have the same kernel (if you work in characteristic $\neq 2$)
Comment: @DavideGiraudo: What do you mean with characteristic? So we have 2 linear transformations that are not equal with the same Kernel, right?
Comment: I should add "_field_  of characteristic $2$", i.e. such that $1+1=0$. If you work with the field of real or complex numbers, and $l$ is a linear map, then $l$ and $2l$ have the same kernel, but are not identical, except if $l$ is identically $0$.
Comment: @DavideGiraudo: We are working with real numbers, the solution system has the <(0,0,0)> solution as one and only.
Comment: The solutions of $l(x)=0$ are the same as $2l(x)=0$.
Comment: @DavideGiraudo: Thank you!
Answer: Of course, if two linear transformation are equal, then they have the same kernel. But if two linear transformations have the same kernel, we are not sure that they are equal. For example, if $L$ is a linear transformation, so is $2L$, and $2L$ and $L$ have the same kernel. They are equal if and only if $2L=L$ i.e. $L=0$.