Add column to custom field schema

Question: I have created a D8 custom field that extends FieldBaseItem. It is already in use storing data.
How do I get the schema updated in the database, for an existing field?
What I've done:
I have added a new column by adding to propertyDefinitions and schema() accordingly.
Here's an example schema. Let's say I just added the admin column.
  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      'columns' => [
        'state' => [
          'type' => 'varchar',
          'length' => 2
        ],
        'admin' => [
          'type' => 'int',
          'size' => 'tiny'
        ],
        ...

I've found posts on how to do this in hook_update_N in D7, but it's unclear how to do this in D8.
Answer: Since entup is no longer available in Drupal 8 (or 9 or 10), many people have struggled with this, and many modules contain copious amounts of code in their update hooks to deal with this. If you know exactly which field instances need to be updated, you can update their tables directly, but this is not an option if you have a module that provides a FieldType, and you are writing an update hook for that module. You want all instances of your field type to be detected and updated.
This Drupal core issue has some code examples for adding and removing properties from existing field types while updating all instances of that field type: https://www.drupal.org/project/drupal/issues/937442#comment-13760432 . Credit goes to https://www.drupal.org/u/robbinzhao . I just cleaned up the code and made it into a utility class:
<?php

namespace Drupal\my_utilities;

use Drupal\Core\Entity\Sql\SqlContentEntityStorage;

/**
 * Utilities for updating field type definitions.
 *
 * Based on https://www.drupal.org/project/drupal/issues/937442#comment-12586376
 */
class FieldTypeUpdateUtil {

  /**
   * Add a new column for fieldType.
   *
   * @param string $field_type
   *   The ID of the field type definition.
   * @param string $property
   *   The name of the property whose column is to add.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Database\SchemaObjectDoesNotExistException
   * @throws \Drupal\Core\Database\SchemaObjectExistsException
   */
  public static function addProperty($field_type, $property) {
    $database_schema = \Drupal::database()->schema();

    $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();

    // First, get all fields of the provided field type.
    $field_map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType($field_type);

    // Process per entity type (i.e., node, paragraph) all fields.
    foreach ($field_map as $entity_type_id => $fields) {
      $entity_type_storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);

      // Database schema can only be updated, if the values are stored in the
      // database, of course.
      if ($entity_type_storage instanceof SqlContentEntityStorage) {
        foreach (array_keys($fields) as $field_name) {
          $field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id);

          // Database column definition, according to each field property.
          $field_columns = $field_storage_definition->getColumns();

          // Get the table and column names, according to the field definition.
          $table_mapping = $entity_type_storage->getTableMapping([
            $field_name => $field_storage_definition,
          ]);
          $table_names = $table_mapping->getDedicatedTableNames();
          $table_columns = $table_mapping->getColumnNames($field_name);

          // Check if, for the property, the corresponding table exists in the
          // database. If not, create the table column (according to the schema
          // provided by the field definition).
          foreach ($table_names as $table_name) {
            $table_exists = $database_schema->tableExists($table_name);
            $field_exists = $database_schema->fieldExists($table_name, $table_columns[$property]);

            if ($table_exists && !$field_exists) {
              $database_schema->addField($table_name, $table_columns[$property], $field_columns[$property]);
            }
          }

          // Reflect any changes made to the field storage definition.
          $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition);
        }
      }
    }
  }

  /**
   * Remove a property and column from field_type.
   *
   * @param string $field_type
   *   The ID of the field type definition.
   * @param string $property
   *   The name of the property whose column to remove.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\Sql\SqlContentEntityStorageException
   */
  public static function removeProperty($field_type, $property) {
    $field_map = \Drupal::service('entity_field.manager')
      ->getFieldMapByFieldType($field_type);
    foreach ($field_map as $entity_type_id => $fields) {
      foreach (array_keys($fields) as $field_name) {
        self::removePropertyFromEntityType($entity_type_id, $field_name, $property);
      }
    }
  }

  /**
   * Inner function, called by removeProperty.
   *
   * @param string $entity_type_id
   *   The ID of the entity type.
   * @param string $field_name
   *   The ID of the field type definition.
   * @param string $property
   *   The name of the property whose column to remove.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Core\Entity\Sql\SqlContentEntityStorageException
   */
  private static function removePropertyFromEntityType($entity_type_id, $field_name, $property) {
    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_update_manager = \Drupal::entityDefinitionUpdateManager();
    $entity_storage_schema_sql = \Drupal::keyValue('entity.storage_schema.sql');

    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    $field_storage_definition = $entity_update_manager->getFieldStorageDefinition($field_name, $entity_type_id);
    $entity_storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $entity_storage->getTableMapping([
      $field_name => $field_storage_definition,
    ]);

    // Load the installed field schema so that it can be updated.
    $schema_key = "$entity_type_id.field_schema_data.$field_name";
    $field_schema_data = $entity_storage_schema_sql->get($schema_key);

    // Get table name and revision table name, getFieldTableName NOT WORK,
    // so use getDedicatedDataTableName.
    $table = $table_mapping->getDedicatedDataTableName($field_storage_definition);
    // try/catch.
    $revision_table = NULL;
    if ($entity_type->isRevisionable() && $field_storage_definition->isRevisionable()) {
      if ($table_mapping->requiresDedicatedTableStorage($field_storage_definition)) {
        $revision_table = $table_mapping->getDedicatedRevisionTableName($field_storage_definition);
      }
      elseif ($table_mapping->allowsSharedTableStorage($field_storage_definition)) {
        $revision_table = $entity_type->getRevisionDataTable() ?: $entity_type->getRevisionTable();
      }
    }

    // Save changes to the installed field schema.
    if ($field_schema_data) {
      $_column = $table_mapping->getFieldColumnName($field_storage_definition, $property);
      // Update schema definition in the database.
      unset($field_schema_data[$table]['fields'][$_column]);
      if ($revision_table) {
        unset($field_schema_data[$revision_table]['fields'][$_column]);
      }
      $entity_storage_schema_sql->set($schema_key, $field_schema_data);
      // Try to drop field data.
      \Drupal::database()->schema()->dropField($table, $_column);
    }
  }

}

Comment: Great and simple example. Thanks for providing a clear example in the jungle of field operations!
Comment: This is great and super helpful. Works a charm. Thanks!
Comment: While it's not in core, `entup` is still available inside the `Devel` package.
Comment: @Watergate has refactored the code and added more explanatory comments. Thanks! However, I have not tested the new version yet. Anyone please leave a review here in the comments on whether it still works.
Comment: Thanks, @rudolfbyker for applying the suggested changes. I've mainly updated `addProperty()` and used a slightly adjusted version in my own code; it should be correct, but a typo is easily made. Anyway, thanks for the original answer, helped me a lot!
Comment: You should probably contribute your changes to https://git.drupalcode.org/project/drupal/-/merge_requests/1910
Answer: The update hooks are essentially the same as Drupal 7, but it's recommended to use the DB Connection object with the addField() method.
The update hook to add a column might look like this:
$spec = array(
 'type' => 'varchar',
 'description' => "New Col",
 'length' => 20,
 'not null' => FALSE,
);
$schema = Database::getConnection()->schema();
$schema->addField('mytable1', 'newcol', $spec);

Full documentation can be found here: https://www.drupal.org/docs/8/api/update-api/updating-database-schema-andor-data-in-drupal-8
Answer: In fact, like it's a custom field type, your change in the schema can be detected and applied if you launch the drush command drush entity-updates (or drush entup).
All tables which implement this field (like node__field_my_field_type or paragraph__field_my_field_type) will be updated. So you don't need to use an hook_update to update the schema of all these tables.
The big problem with this command is many errors are silent and sometimes, the command don't return errors but the schema hasn't been updated and still proposed by the command to be updated.
Comment: This is exactly my problem, `drush entity-updates` does realize something needs to be updated, and then `Exception thrown while performing a schema update. SQLSTATE[42S22]: Column not found` where it cannot find the new column I want to add to the custom field. What to do in this case?
Answer: This is a function I wrote to add new field(s) to existing field tables.
/**
 * Add a new column for fieldType.
 *
 * @param string   $field_type  ID of the field type.
 * @param string[] $new_fields  Field key(s) that is new to your schema.
 *
 * @return void
 */
function field_type_add_property(string $field_type, array $new_fields) {

  if (!$field_storage_configs = \Drupal::entityTypeManager()
    ->getStorage('field_storage_config')
    ->loadByProperties(array('type' => $field_type))
  ) {
    throw new \Exception('Unable to find field type ' . $field_type);
  }

  // Get schema handler to alter table with.
  $schema_handler = Database::getConnection()->schema();

  // Loop through all configs.
  foreach ($field_storage_configs as $field_storage) {

    // Just to play safe
    if (!($field_storage instanceof FieldStorageDefinitionInterface)) {
      throw new \Exception('Unexpected entity type loaded: ' .
        (is_object($field_storage) ? get_class($field_storage) : var_export($field_storage, true)));
    }

    // get the most updated schema from field stroage
    $schema = $field_storage->getSchema();
    $table_name = str_replace('.', '__', $field_storage->id());
    $revision_table_name = str_replace('.', '_revision__', $field_storage->id());

    // loop through the fields to alter the schema of table.
    foreach ($new_fields as $new_field) {
      $column_name = "{$field_storage->getName()}_{$new_field}";
      if (!$schema_handler->fieldExists($table_name, $column_name)) {
        $schema_handler->addField(
          $table_name,
          $column_name,
          $schema['columns'][$new_field]
        );
      } else {
        // Show some warning message or error
        throw new \Exception(sprintf('Field %s already exists in table %s',
          $column_name, $table_name));
      }
      if (!$schema_handler->fieldExists($revision_table_name, $column_name)) {
        $schema_handler->addField(
          $revision_table_name,
          $column_name,
          $schema['columns'][$new_field]
        );
      } else {
        // Show some warning message or error
        throw new \Exception(sprintf('Field %s already exists in table %s',
          $column_name, $revision_table_name));
      }
    }
  }
}

Add column to custom field schema


Proof that the Hotelling T$^2$ statistic is invariant under the choice of contrast matrices

Question: Consider an one-way repeated measures design with $n$ subjects and $q$ measurements.
It is assumed that $\mathbf{x}_{i}$ are $iid$ q x 1 random vectors that follow multivariate normal distribution,
where $i$ is the index of subjects.
Using the multivariate approach, the null hypothesis for the time effect is $H_{0}:\mu_{1}=\mu_{2}=...=\mu_{q},$ where $\mu_{j}$ is the population mean for the $j$th measurement.
By letting $\boldsymbol{\mu}=[\mu_{1},...,\mu_{q}]^\top,$ the null hypothesis is equivalent to
$H_{0}:\boldsymbol{\mu}=k\mathbf1,$where $k$ is some constant and $1$ is the q x 1 vector of ones.
By picking any (q-1) x q contrast matrix $\mathbf{C}$ such that $\mathbf{C}\mathbf1=\mathbf{0}$ (i.e., each row sum to zero),
the null hypothesis can again be restated as
$H_{0}:\mathbf{C}\boldsymbol{\mu}=\mathbf{0}$
The most natural choice of $\mathbf{C}$ is perhaps something like $\begin{bmatrix} 1 & -1 & 0 & 0 & \dots \\ 0 & 1 & -1 & 0 & \dots \\ 0 & 0 & 1 & -1 & \dots \\\vdots & \vdots & \vdots & \vdots & \vdots &\\ \end{bmatrix},$
which simply contrasts time 1 with time 2, time 2 and time 3, etc., but I can intuitively understand why an arbitrary $\mathbf{C}$ (s.t.$\mathbf{C}\mathbf1=\mathbf{0}$) will do the same job.
Now, the one-sample Hotelling $T^{2}$ statistic is computed as $n(\mathbf{C}\bar{\mathbf{x}})^\top(\mathbf{C}\mathbf{S}\mathbf{C}^\top)^{-1}(\mathbf{C}\bar{\mathbf{x}}), $ where
$\bar{\mathbf{x}}=\frac{1}{n}\sum_{i=1}^{n}\mathbf{x}_{i}, $ and $\mathbf{S}=\frac{1}{n-1}\sum_{i=1}^{n}(\mathbf{x}_{i}-\bar{\mathbf{x}})(\mathbf{x}_{i}-\bar{\mathbf{x}})^\top$
My question is that:
Although it is reasonable to think that this $T^{2}$ quantity will not change with the choice of $\mathbf{C}$
as long as $\mathbf{C}\mathbf1=\mathbf{0}$ (I have tried many different $\mathbf{C}$ and this seems to be indeed the case),
what is the mathematical proof for this result?
Answer: To test the null hypothesis $H_{0}\!:\mu_{1}=\mu_{2}=\ldots=\mu_{q}$ via Hotelling's one-sample $T^2$ statistic, $\mathbf{C} \in \mathbb R^{(q-1) \times q}$ can't be an arbitrary matrix with $\mathbf{C}\mathbf1=\mathbf{0}$. It certainly must have $q-1$ linearly independent rows and can be a matrix $\mathbf{C}=\mathbf{A}\tilde{\mathbf{C}}$ obtained by transforming
$$
\tilde{\mathbf{C}}=
\begin{pmatrix}
1 & -1 \\
& 1 & -1 \\
& & \; \ddots & \ddots \\
& & & 1 & -1
\end{pmatrix}
\in \mathbb R^{(q-1) \times q}
$$
by some invertible matrix $\mathbf{A} \in \mathbb R^{(q-1) \times (q-1)}$ since
$$
\mathbf{C}\boldsymbol{\mu} = \mathbf{0} \iff \tilde{\mathbf{C}}\boldsymbol{\mu} = \mathbf{0}
$$
and
$$
\begin{align}
\left(\mathbf{C}\bar{\mathbf{x}}\right)^\top\left(\mathbf{C}\mathbf{S}\mathbf{C}^\top\right)^{-1}\left(\mathbf{C}\bar{\mathbf{x}}\right)
=\,&\left(\left(\mathbf{A}\tilde{\mathbf{C}}\right)\bar{\mathbf{x}}\right)^\top\left(\left(\mathbf{A}\tilde{\mathbf{C}}\right)\mathbf{S}\left(\mathbf{A}\tilde{\mathbf{C}}\right)^\top\right)^{-1}\left(\left(\mathbf{A}\tilde{\mathbf{C}}\right)\bar{\mathbf{x}}\right)\\
=\,&\bar{\mathbf{x}}^\top\tilde{\mathbf{C}}^\top\mathbf{A}^\top\left(\mathbf{A}\left(\tilde{\mathbf{C}}\mathbf{S}\tilde{\mathbf{C}}^\top\right)\mathbf{A}^\top\right)^{-1}\mathbf{A}\tilde{\mathbf{C}}\bar{\mathbf{x}}\\
=\,&\bar{\mathbf{x}}^\top\tilde{\mathbf{C}}^\top\mathbf{A}^\top\left(\mathbf{A}^\top\right)^{-1}\left(\tilde{\mathbf{C}}\mathbf{S}\tilde{\mathbf{C}}^\top\right)^{-1}\mathbf{A}^{-1}\mathbf{A}\tilde{\mathbf{C}}\bar{\mathbf{x}}\\
=\,&\left(\tilde{\mathbf{C}}\bar{\mathbf{x}}\right)^\top\left(\tilde{\mathbf{C}}\mathbf{S}\tilde{\mathbf{C}}^\top\right)^{-1}\left(\tilde{\mathbf{C}}\bar{\mathbf{x}}\right).
\end{align}
$$
Comment: Don't know why it didn't get a single upvote. Anyway +1 for the clarity.


Is the google cloud instance id will be reused?

Question: Today lots of peoples/developers are using VM's in google cloud, so keeping in this mind there are lots of VM's were getting created and deleted every day.
Also, Google compute engine allocates an ID (auto-generated) to each instance in the cloud at the time of VM creation.
So, Is there any chance that this ID gets reused(repeated) considering this same ID was assigned to an instance but now that instance got deleted?
Thanks
Comment: A 19-digit ID? probably not.
Comment: Thank, Is there any documentation? because I am searching a lot but didn't find any, if you have please post the link,
Answer: As per the documentation states, the instance ID is a unique numerical identifier generated by Google Compute Engine.
You can check the documentation here:
https://cloud.google.com/compute/docs/storing-retrieving-metadata
In a technical context a unique identifier is defined as a numeric or alphanumeric string associated with a single entity within a given system.
The aim of using unique IDs is to univocally identify entities by their ID's.
However, you are asking if it's possible that this ID could be repeated, understanding by "repeated" being used in two different instances in the same moment in time, I don't think the ID can be used by 2 instances at the same time, since the documentation clearly states that the ID it's unique.
But I don't see any inconvenience on reusing the ID of an instance that was created but has been deleted and does not exist anymore (it will still be unique).
Can you specify a little bit more your use case or describe what you're trying to achieve with the instance ID?

EDITED: adding here a comment from below this answer for better reading:
To ensure the unicity of a GCE instance, for software licensing you can use an instance identity token
https://cloud.google.com/compute/docs/instances/verifying-instance-identity

A GCE instance requests a signed token from the metadata API. This token identifies the instance and is signed by Google.
The GCE instance provides this signed token to a verification server.
The verification server checks the signature from Google in the token, confirming the instance is who it says it is.
The verification server authenticates the instance and provides whatever is needed to it.
Comment: Not sure if you wanted to add more info after "here is my use case:" or you meant that your use case is software licensing.

You can think of Google Compute Engine instance id's as unique identifiers, because even if they get reused, in practice, there will never be an instance id linked to 2 instances in the same moment in time.

Hoping this covers your question.
Comment: Sorry for incomplete reply, If the customer has purchased a bundle of hundred licenses and he starts using the key from this bundle to activate application then the licenses count will decrease. We are planning to keep track of VM instance ID on which license key was used, so, If customer upgrade it's VM instance to fresh higher version of OS (e.g ubuntu 14 to 16) and again use a license key for the activation on the same instance then this time license count will not decrease, as the machine is not changed. IF ID is getting reused then above model will fail and user will get more activations
Comment: To ensure the unicity of a GCE instance, for software licensing you can use an instance identity token
https://cloud.google.com/compute/docs/instances/verifying-instance-identity
1. A GCE instance requests a signed token from the metadata API. This token identifies the instance and is signed by Google.
2. The GCE instance provides this signed token to a verification server.
3. The verification server checks the signature from Google in the token, confirming the instance is who it says it is.
4. The verification server authenticates the instance and provides whatever is needed to it.


Mysql dynamic InnoDB Buffer Pool Size

Question: Since 5.7 its possible to set "dynamic" Buffer Pool Sizes with:

innodb_buffer_pool_chunk_size * innodb_buffer_pool_instances

How exactly does that work?
I have a fairly small server with 4 Cores and 16GB RAM with a PHP business application on it.
I now have located 8GB as static Pool Buffer(around 70-80% Key Efficiency & 99% Buffer usage).
On the server is also a Java MassMailer that runs on average once per day, so i keep ~8GB free for the mailer. I have programmed the MassMailer in a way that he will just load as many emails as the memory allows.
Can i use that new dynamic Buffer Pool feature to allocate during the normal workload to around 12GB and take some while sending mails? Can i ajust it manually or does the MySQL server that automatically? Will the server give some memory back if the mailer wants more or will it throw a "out of memory" exception?
Answer: The chunk_size setting is for dynamically changing innodb_buffer_pool_size.  I see no use for changing the buffer_pool_size except for experimenting.
Memory:

16GB of RAM
8GB for Java -- does this include Java uses other than the MassMailer?
That leaves 8GB for MySQL
Set the buffer_pool to about 70% of that, namely 5.6G.
If you see swapping then the buffer_pool should be shrunk further.
Dynamically changing the buffer_pool_size will block MySQL activity (to some extent).

If you dynamically give more room to MySQL, you need to simultaneously take RAM away from Java.  This seems too clumsy and error prone to attempt.
I would expect the Mailing program to be network-bound, hence trying to optimize RAM is probably not worth doing.
(MySQL DBA questions beong in dba.stackexchange.com ,)

Mysql dynamic InnoDB Buffer Pool Size


Generators of von Neumann algebras

Question: Let us suppose that M is a von Neumann algebra on some hilbert space $H$ such that $M = A''$ for some $C^*$-algebra $A\subseteq B(H)$.
I am wondering when $A$ will be dense in $M$ and by which topology. I also want to know that if I have two functional $S,T \in M^*$ such that $S|_A=T|_A$, can I say that $T=S$?
Thank you very much.
Answer: Let $K\subseteq H$ be the closed subspace generated by $AH$.  Then von Neumann's double commutant theorem says that if $K=H$, then $M$ is the closure of $A$ in the weak operator, strong operator, ultraweak, or ultrastrong topologies.  If $K$ is a proper subspace of $H$, then $A=A|_K\times \{0\}|_{K^\perp}$, $A''=(A|_K)''\times \mathbb C I_{K^\perp}$, and $A$ is weakly dense in $(A|_K)''\times \{0\}$ but not $M$.  The condition $K=H$ is also known as $A$ acting nondegenerately on $H$.  In particular, it holds if $A$ contains the identity operator on $H$.
So assuming that $A$ acts nondegenerately, $A''=M$ is equivalent to density of $A$ in $M$ in various topologies that are coarser than the norm topology.  If $M^*$ is the set of norm-continuous linear functionals on $M$, then it is possible in general for distinct functionals in $M^*$ to agree on $A$, if at least one of them is not ultraweakly continuous.  $A$ is a norm-closed subspace of $M$, so if $A\neq M$ then there are nonzero continuous functionals on the Banach space $M/A$, hence by composing with the quotient map, there are nonzero continuous functionals on $M$ that vanish on $A$.
Comment: If two elements of $M^*$ are in the form of $f(\cdot)=\langle \cdot \xi,\eta\rangle$ and  $g(\cdot)=\langle \cdot \xi',\eta'\rangle$  for some $\xi', \eta', \xi', \eta'\in H$. Then what can we say about $f$ and $g$, if $f|_A=g|_A$?
Comment: @unknownismylastname: Those functionals are continuous in the weak operator topology, so WOT density of $A$ in $M''$ says that $f=g$.

Generators of von Neumann algebras


access $node in form breaks ajax call

Question: I built a custom form that works well, however I updated my custom module to create a custom content type and add the form via hook_node_view().
Everything works, until I access the $node object in the form (e.g. to set default values).
Scenario 1: The node is created but we do not access $node object to set default values. In this case everything works.
Scenario 2: The node is created and we do access $node object to set values in the $form. In this case ajax breaks.
See below for code:
function quickform_node_info(){
    $t = get_t();
    $items = array(
        'quickform' => array(
            'name' => $t('MAGNIFI QuickForms'),
            'base' => 'quickform',
            'description' => $t('Create Artist, Photo, Music, and Record Label Forms'),
            'help' => '',
            'has_title' => 1,
            'title_label' => $t('Record Label Name'),
            'locked' => 0,
        )
    );
    drupal_alter('node_info', $items);
    return $items;
}

function quickform_node_view($node, $view_mode, $langcode){
    $form = drupal_get_form('quickmulti_form', $node);
    $node->content['quickmulti_form'] = array(
        $form
    );
}

function quickmulti_form($form, &$form_state, $this_node = false) {
    #$this_nod

    $form = array();
    #include this entire file whenever this form is included
    #form_load_include($form_state, '.php',        'quickform','quickform.module');
    $form['#tree'] = TRUE;
    $_SESSION["anonymous-tracker"]=time();
    $form['#attributes']['enctype'] = 'multipart/form-data';

    $form['headingtext1'] = array(
        '#markup' => t('PROMOTE ON MAGNIFI'),
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['headingtext2'] = array(
        '#markup' => t('Join over 17,000 artists that are leveraging the MAGNIFI platform to connect with concert-going fans. MAGNIFI is 100% focused on connecting music to concert dates and sales! '),
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['headingtext3'] = array(
        '#markup' => t('Fill out the below form to get started.'),
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['contact_info']=array(
        '#type'=>'fieldset',
        '#title'=>t('Contact Info'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE
        );

    $form['contact_info']['first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['contact_info']['last_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Last Name'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['contact_info']['email1'] = array(
        '#type' => 'textfield',
        '#title' => t('Email'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['artist_info']=array(
        '#type'=>'fieldset',
        '#title'=>t('Your Artists'),
        '#description'=>t('All fields are required'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '
',
        '#suffix' => '
',
        '#tree' => TRUE,
    );

    $form['artist_info']['tos_c'] = array(
        '#type' => 'checkbox',
        '#title' => t('I Accept'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['artist_info']['tos_p'] = array(
        '#markup' => t("I certify that (1) I am authorized to submit this webform as the Artist named herein or on behalf of this Artist; (2) this Artist controls all rights in the compositions, recordings and images authorized in this webform for MAGNIFI's service, or this Artist has the necessary permissions from all rightsholders to so authorize; (3) I understand and agree as this Artist or on behalf of this Artist to the MAGNIFI Artist Terms of Use Agreement, and warrant that the compositions, recordings, images and other content & information provided in this webform are not in violation of the MAGNIFI Artist Terms of Use Agreement."),
        '#prefix' => '
',
        '#suffix' => '
',
    );

    // artists_count =  added by internal user, defaults to 1
    // next_artists = for end user to add more
     if(!empty($this_node->field_artist_names['und'][0])){
        $form_state['artists_count'] = count($this_node->field_artist_names['und']);
        $form_state['next_artists'] = $form_state['artists_count'] + 1;
    }elseif (empty($form_state['artists_count'])){
        $form_state['artists_count'] = 1;
        $form_state['next_artists'] = $form_state['artists_count'] + 1;
    }

    $total_artists = $form_state['artists_count'];

    for ($x = 0; $x < $total_artists; $x++){
        // Grab node information
        if(!empty($this_node->field_artist_names['und'][$x])){
                $this_artist = $this_node->field_artist_names['und'][$x];
            }
        $form['artist_info'][$x] = array(
            '#type' => 'container',
            '#prefix' => "
", #should be different for each artist
            '#suffix' => '
',
            '#tree' => TRUE,
        );

        $form['artist_info'][$x]['artist'] = array(
            '#type'=>'fieldset',
            '#title'=>t('Artist @num', array('@num' => $x+1)),
            #'#description'=>t('All fields are required'),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
        );

        $form['artist_info'][$x]['artist']['account_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Artist @num Name', array('@num' => $x+1)),
            '#size' => 255,
            '#maxlength' => 255,
            #'#required' => TRUE,
            '#default_value' => (!empty($this_artist) ? $this_artist : ''),

        );

        $form['artist_info'][$x]['artist']['music_text'] = array(
            '#markup' => t('List titles in the same order as music files, one per line.'),
            '#prefix' => '
',
            '#suffix' => '
',
        );

        $form['artist_info'][$x]['artist']['titles'] = array(
            '#type' => 'textarea',
            '#title' => t('Album/Track Titles'),
            #'#size' => 255,
            #'#maxlength' => 255,
            #'#required' => TRUE,
        );

        $form['artist_info'][$x]['artist']['music'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'music[]',
            '#description' => t('Submit high-quality music files.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('mp3 wav aiff aac m4a ogg flac'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

        $form['artist_info'][$x]['artist']['photos'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'photos[]',
            '#description' => t('Submit high-quality photos.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('png jpg jpeg'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

    }#end artist_count loop

    $next_artist = $form_state['artists_count'];

    $form['artist_info'][$next_artist] = array(
        '#type' => 'hidden',
        '#title' => "add another artist",
        '#name' => "artist{$next_artist}",
        '#prefix' => "
", #should be different for each artist
        '#suffix' => '
',
    );

    if($form_state['next_artists'] == $form_state['artists_count']){
        $x = $form_state['next_artists'];
        $form_state['next_artists']++;

        $form['artist_info'][$x] = array(
            '#type' => 'container',
            '#prefix' => "
", #should be different for each artist
            '#suffix' => '
',
            '#tree' => TRUE,
        );

        $form['artist_info'][$x]['artist'] = array(
            '#type'=>'fieldset',
            '#title'=>t('Artist @num', array('@num' => $x)),
            #'#description'=>t('All fields are required'),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
        );

        $form['artist_info'][$x]['artist']['account_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Artist @num Name', array('@num' => $x)),
            '#size' => 255,
            '#maxlength' => 255,
            #'#required' => TRUE,
        );

        $form['artist_info'][$x]['artist']['music_text'] = array(
            '#markup' => t('List titles in the same order as music files, one per line.'),
            '#prefix' => '
',
            '#suffix' => '
',
        );

        $form['artist_info'][$x]['artist']['titles'] = array(
            '#type' => 'textarea',
            '#title' => t('Album/Track Titles'),
            #'#size' => 255,
            #'#maxlength' => 255,
            #'#required' => TRUE,
        );

        $form['artist_info'][$x]['artist']['music'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'music[]',
            '#description' => t('Submit high-quality music files.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('mp3 wav aiff aac m4a ogg flac'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

        $form['artist_info'][$x]['artist']['photos'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'photos[]',
            '#description' => t('Submit high-quality photos.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('png jpg jpeg'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

    }

    //Add another file button
    $form['artist_info']['add_more_artists'] = array(
        '#type' => 'submit',
        '#name' => "add_more_artists{$next_artist}",
        '#value' => t('Add Another Artist'),
        '#submit' => array('artists_add_more'), #increment $form_state['artists_count']
        '#ajax' => array(
            'callback' => 'artists_add_more_callback', #function that returns elements
            'wrapper' => "artist{$next_artist}", #replace this wrapper with the returned elements
            'method' => 'append',
        ),
    );

    $form['submit'][] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );

    $form['#submit'][] = 'quickjoin_form_submit';
    return $form;
}

function artists_add_more($form, &$form_state) {
    $form_state['artists_count']++;
    $form_state['rebuild'] = TRUE;
}

function artists_add_more_callback($form, &$form_state) {
    $this_artist = $form_state['artists_count'];
    $form_state['rebuild'] = TRUE;
    return $form['artist_info'][$this_artist];
}

Comment: When you say ajax breaks, what do you mean exactly? Also are there any errors in your watchdog or server logs?
Comment: found the error: I was accessing '$this_node->field_artist_names['und'][$x]' instead of '$this_node->field_artist_names['und'][$x]['value']
Comment: wow, what a way to waste a day ;)
Comment: by the way, what was happening is that it was inserting empty  elements instead of adding a new artist field set
Comment: If you add that as an answer and select it as the correct answer it will mark this question solved.
Comment: it wont let me select the original one as the answer
Comment: You have to actually write the answer first. What you wrote above is a comment so you can't select it as the correct answer..
Answer: I found the error :
 I was accessing $this_node->field_artist_names['und'][$x] instead of $this_node->field_artist_names['und'][$x]['value'].

access $node in form breaks ajax call


How does FIFA shortlist the final 23 players for Ballon d'OR?

Question: On what basis does FIFA select the 23 player shortlist for Ballon d'OR?
Like what kind of attributes they consider
Comment: Here is a similar question with the list of journalists that help determine the finalists https://sports.stackexchange.com/questions/17444/how-are-the-ballon-dor-scores-determined
Answer: There isn't really much insight into how the 23-man shortlist is generated, other than who decides. It's presumably no different than yourself and friends discussing who should be on the shortlist however.
The shortlist is decided by the FIFA committee and some experts from France Football as shown here
prdp is referring to the actual voting on players on the shortlist.
Answer: FIFA elects a committee to decide which all players should be nominated to 23 man shortlist. Its based on their performance not a code but a guideline. Like academy award jury. I read across a report that Real Madrid President Florentino Perez will be a part of that committee for 3rd consecutive year.
p.s -Jumpingcode, i changed my answer, review this one
Comment: Next time, [edit](http://sports.stackexchange.com/help/editing) your [original answer](http://sports.stackexchange.com/a/5864).
Answer: It is awarded based on votes by coaches and captains of international teams, as well as selected journalists from around the world. The players with maximum votes are shortlisted. Its just for fan fair i think. The voting closes way before the shortlists are out.
Comment: This is incorrect
Comment: Here is a question with the correct answer and the list of *journalists* that pick the winners from the finalists https://sports.stackexchange.com/questions/17444/how-are-the-ballon-dor-scores-determined


How do I per-variation add to cart button In Views with no selection?

Question: I have a table that displays rows of products with there attributes, the last item on each row has the variation add to cart form.
The view's self sorts on the product id to display all the variations for the product.
The issue is it can't select the variation for each row automatically, it always expects the user to choose the right variation from a dropdown.
Any changes that do not have the drop-down displayed defaults to only the first product item in the table.
I have tried the relationship to the product and product id and variation cart form modules but these also failed to deliver.
I there a way in views to add a per-variation add to cart button with no selection in views table?
Answer: You can also be done using the Drupal module Direct Checkout
You can then build your own Drupal commerce buy now link or button in any view using the global custom text, by simply adding the following code.
Add to cart

Answer: I finally found the answer from help on this post. here  Although, I still had a few issues and mine ended up being slightly different, so I will lay out what I did to achieve this.
I am using a view table but really any sort of display using fields with grids should work the same.

Install the module Add to cart link
Create a new display on your product variation called what you like I am using 'view' with only the add to cart link field.
In your view add the display type you require.
Add Relationship: variations (Relate each Product with a variations set to the product variation.)
Add Relationship: Product
Add contextual filter: Product: ID - Provide default value Product ID from URL
Add Field Rendered entity - Product variation
Select your display from the view mode.
Save, add your view and output your view to your product page.

Now you will see all the Add to cart buttons displayed for each variation on the product with the right token add to cart link for each.


Which of the following is not a possibility for the sequence $k_1\leq k_2\leq k_3\leq k_4$?

Question: Let $T$ be a linear transformation which is represented by a $4\times 4$ matrix and $T^4=0$.Let $k_i=\dim$ Ker $T^i$ for $1\leq i\leq 4$.Which of the following is not a possibility for the sequence $k_1\leq k_2\leq k_3\leq k_4$?
$1.3\leq 4\leq 4\leq 4$
$2.1\leq 3\leq 4\leq 4$
$3.2\leq 4\leq 4\leq 4$
$4.2\leq 3\leq 4\leq 4$
What I tried:
$\dim Ker T^i=m\implies$ the matrix  $ A $ has $4-m$ non-zero columns.I think that 1  is possible as we can take $A=$\begin{bmatrix} 0 & 0 & 1 &0\\0  & 0 & 0 & 0\\0 &0 &0 &0 \\0 &0 &0 &0 \\\end{bmatrix}
Similarly we can find a matrix for $4$.But I am not sure for $2,3$;Is this approach correct? Or is there any alternative easy approach?
Answer: If you know Jordan normal form, then you know that the matrix of $T$, that I also call $T$ is similar to a block diagonal matrix $T^\prime $ with blocks of the form:
$$J=\begin{pmatrix}
0 & 1 & & \\
  & 0 & \ddots & \\
  &   & \ddots &  1\\
  &   &   & 0
\end{pmatrix}
$$ As $T$ has dimension $4$, those $J$ block matrices can have dimension $2$, $3$ or $4$. Then look at the different cases:

$T^\prime $ has $0$ Jordan block. Then $P^\prime=P=0$ and the $k_i$ sequence is $4 \le 4 \le 4 \le 4$.
$T^\prime $ has one block of dimension $2$. Then the $k_i$ sequence is $3 \le 4 \le 4 \le 4$.
$T^\prime $ has two blocks having dimensions $2$. Then the $k_i$ sequence is $2 \le 4 \le 4 \le 4$.
$T^\prime $ has one block having dimension $3$. Then the $k_i$ sequence is $2 \le 3 \le 4 \le 4$.
$T^\prime $ has one block having dimension $4$. Then the $k_i$ sequence is $1 \le 2 \le 3 \le 4$.

There are no other options.
Finally the only case that cannot occur is the case #2.
Answer: consider the options $2$,  $rank T=3$ and $rank T^2=1$. We know that $rank T^2\ge rank T + rank T-4 \implies rank T^2\ge 2 $. But $rank T^2=1$. So, (2) is not possible.


Statistical conclusions from incompatible measurement results

Question: I assume that the following situation is not uncommon in scientific practice:

Two research groups analyse two samples.

The reported results concern the same physical quantity at the same location and at the same time.

The analysis methodologies are different.

The reported results are calculated differently from the raw data that were measured.

But: The reported results are incompatible, i.e. the sum of their bell curves has two peaks, i.e. is bi-modal.

As a specific example one may consider the atmospheric carbon dioxide concentration at the south pole

directly measured from atmosphere and

measured by an ice core.

These are for example the time series from atmospheric measurements at the south pole compared to ice core  measurements at Law Dome:

When the two samples are not identical (as in the example: one sample was gaseous, the other sample was solid) the first guess to explain the discrepancy is by the difference of the samples (1). To exclude this (for the sake of my argument/question) let me assume that the samples are identical. Discrepancies may occur nevertheless.
The next guess then to explain the discrepancy is by the difference of measurement methodologies (3) and/or calculations (4). Let me assume that both seem sound for both research groups, so both measurements may have the same a priori credibility.
For the sake of simplicity let me assume that both standard deviations are the same.
Now I am at the heart of my question:

Which conclusions can be drawn from the two incompatible results (bell curves)?

How wrong must at least one of the results be (with respect to mean and standard deviation)?

What can be assumed to be the "true" mean and the "true" standard deviation?

Remember that two measurements (reported values) are supposed to be "incompatible" when the sum of their bell curves has two peaks, i.e. is bi-modal.
I further suppose that a measurement (a reported value) is "wrong" when the true value falls outside the two standard deviation interval of the reported mean.
Comment: Why does being two standard deviations from the mean make a measurement wrong? Why does being four standard deviations from the mean make a measurement wrong? At least for a Gaussian distribution, points four standard deviations from the mean should happen $0.00633\%$ of the time. This is infrequent, sure, but they should happen from time to time.
Comment: Why have you chosen to define bimodal as "incompatible"? Why do you consider values more that one standard deviation from the mean as "wrong"? Nearly 1/3 of results would meet this criteria in a normal distribution.
Comment: I have to be more explicit about this. Bimodal = wrong in the case that there is only one "true" value - isn't this a (or even the) typical case?
Comment: I changed "one standard deviation" to  two standard deviation".
Comment: Doesn't this change in the presence of a conflicting result (of equal credibility)?
Comment: This post appears to describe "systematic error" (a form of *measurement error* sometimes called "bias"--but beware the many different meanings of that term!)  All one can conclude in the generality with which this question is posed is that one or both of the measurement methods has detectable systematic error.  You don't describe any data, information, or assumptions to support conclusions about the correctness of either system.
Answer: The question is interesting. I will use a simple example to illustrate what I believe the core idea is.
Let $y_i$ denote a noisy measurement of $x$ and let each measurement have its own measurement error. In particular, let
\begin{equation}
y_i = x + \varepsilon_i
\end{equation}
where $\varepsilon_i \sim \textsf{N}(0,\sigma_i^2)$. We can re-express this as
\begin{equation}
p(y_i|x) = \textsf{N}(y_i|x,\sigma_i^2) .
\end{equation}
Suppose we have two such measurements. The likelihood of $x$ is given by
\begin{equation}
p(y_1,y_2|x) = p(y_1|x)\,p(y_2|x) = \textsf{N}(y_1|x,\sigma_1^2)\, \textsf{N}(y_2|x,\sigma_2^2) .
\end{equation}
We can re-express the likelihood of $x$ as
\begin{equation}
p(y_1,y_2|x) \propto \textsf{N}(x|m,s^2) ,
\end{equation}
where
\begin{align}
m &= s^{2}\left(\frac{y_1}{\sigma_1^2} + \frac{y_2}{\sigma_2^2}\right) \\
s^2 &= \left(\frac{1}{\sigma_1^2}+\frac{1}{\sigma_2^2}\right)^{-1} .
\end{align}
Thus, the likelihood of $x$ is unimodal regardless of how far apart the measurements are relative to their variances.
Now let us examine the likelihood of the model. Let us assume the prior for $x$ is
\begin{equation}
p(x) = \textsf{N}(x|\mu,\tau^2) .
\end{equation}
The likelihood of the model is given by
\begin{equation}
p(y_1,y_2) = \int p(y_1,y_2|x)\,p(x)\,dx = \frac{e^{-\frac{(m-\mu )^2}{2 \left(s^2+\tau
   ^2\right)}}}{\sqrt{2 \pi } \sqrt{s^2+\tau
   ^2}}
\end{equation}
In order to simplify the exposition, let us assume the measurement errors are the same: $\sigma_1 = \sigma_2 = \sigma$. We also assume $y_1 \ne y_2$. Then,
\begin{equation}
\lim_{\sigma\to 0}\ p(y_1,y_2) = 0 ,
\end{equation}
which means that in the limit the measurements are completely incompatible with the model.
A numerical illustration may prove helpful. Let $y_1 = 1$, $y_2 = -1$, $\mu = 0$, and $\tau = 1$. With these values,
\begin{equation}
p(y_1,y_2) = \frac{e^{-\frac{1}{\sigma ^2}}}{2 \pi  \sigma
   \sqrt{\sigma ^2+2}} .
\end{equation}
In this case,
\begin{equation}
p(y_1,y_2) \approx \begin{cases}
3\times 10^{-2} & \sigma = 1 \\
4\times 10^{-3} & \sigma = 1/2 \\
5\times 10^{-8} & \sigma = 1/4
\end{cases} .
\end{equation}
The likelihood of the model falls off dramatically as $\sigma$ decreases from one. The model with $\sigma = 1/4$ is roughly one million times worse than the model with $\sigma = 1$.
If one is confident that $\sigma = 1/4$ is correct, then very likely there are other assumptions of the model that are incorrect. The way to procede then is to identify those parts of the model and correct them. For example, perhaps
\begin{align}
y_i &= \xi_i + \varepsilon_i \\
\xi_i &= x + u_i ,
\end{align}
where $u_i \sim \textsf{N}(0,\omega_i^2)$.
In any event, I think it is a mistake to try to horse-out the "truth" from a model that is so completely "false."


How to change font-weight based on a condition and then change color based on a different condition without overriding? (JS)

Question:       if (Math.abs(decimalChange) > .025){ //bold significant changes
        tdChange.style = 'font-weight:bold;';
      }

      if (decimalChange >= 0){
        tdChange.style = 'color:green;';
      }
      else {
        tdChange.style = 'color:red;';
      }

Above there are 2 conditions that determine two separate properties of a TD element tdChange based on the contents of a number decimalChange.  I am finding that whichever of the 2 conditions I put last works as desired, while the one that comes first is ignored.  I can easily presume that I am overwriting one with the other, however when I try substituting the right side of the equation of the second property to be updated with
tdChange.style + 'theSecondPropertyIAmAdjusting';

I find that neither property is implemented.  How can I go about determining the font weight of an element based on one condition and then subsequently determining the font color of that same element based on a different condition without overriding the results of the first property implemented?
Comment: By not using `.style` at all for this, but CSS classes instead. Don't define your styling in code unless you absolutely have to.
Answer: Several options. One possibility is using object.style.property syntax. This way you can define multiple properties.
The way you were declaring it, the properties would always get overridden.

var tdChange = document.getElementById('tdChange');

var numbers = [.03, .18, -.018];
var randNumber = numbers[Math.floor(Math.random() * numbers.length)];
if (Math.abs(randNumber) > .025){ //bold significant changes
    tdChange.style.fontWeight = 'bold';
}

tdChange.style.color = randNumber >= 0 ? 'green' : 'red';

This is a paragraph

You could also use the toggleClass method in jQuery. This will check whether an element has a class. If it doesn't it will add the class, if not it will remove it.

var tdChange = $('#tdChange');
var numbers = [.03, .18, -.018];
var randNumber = numbers[Math.floor(Math.random() * numbers.length)];

if (Math.abs(randNumber) > .025) {
    tdChange.toggleClass('bold');
}

tdChange.toggleClass(randNumber >= 0 ? 'green' : 'red');
.bold { font-weight: bold; }
.green { color: green; }
.red { color: red; }

This is a paragraph


Mudar formato de exibição de data na View

Question: Tenho o seguinte campo que me retorna a data da seguinte forma: 09/17/2018 11:52 AM
Como colocar ele dentro do padrão pt-br. Já tentei colocar o .ToString("dd/MM//yyyy") no model.dtProtoclo mas não funcionou.

    @Html.LabelFor(model => model.Dtprotocolo, htmlAttributes: new { @class = "control-label col-md-4" })

         @Html.TextBoxFor(model => model.Dtprotocolo, new { disabled = "disabled", @readonly = "readonly", @class = "form-control" })
         @Html.ValidationMessageFor(model => model.Dtprotocolo, "", new { @class = "text-danger" })

Não precisei detalhar tando, só o comentário a baixo solucionou meu problema
Comment: Possível duplicata de [Como configurar a validação do ASP.NET MVC para aceitar datas pt-BR?](https://pt.stackoverflow.com/questions/87796/como-configurar-a-valida%c3%a7%c3%a3o-do-asp-net-mvc-para-aceitar-datas-pt-br)
Answer: Na sua ViewModel, adicione um DataAnnotation para o campo DateTime:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime Dtprotocolo { get; set; }

Comment: Coloquei esse código lá, fui fazer um add-migration nele não causou impacto algum. É isso mesmo? P.S. Coloquei no model de protocolo
Comment: Igonre, só adicionando o código do display format resolveu meu problema.

Obrigado


Integration on f(-x)

Question: Suppose that for some function $f(x)$ such that $\int_{-\infty}^{\infty} f(x)$ exists, then will that necessarily imply that
$$\int_{-\infty}^{\infty} f(x)=\int_{-\infty}^{\infty} f(-x)?$$
Comment: f(-x) is the reflection of f(x) about the y axis. Can you see why now, by the definition of a definite integral, why the two must be equal?
Comment: Consider $y=f(x)= \log(x) $
Answer: We have that
$$\int_{-a}^{a}f(x)\mathrm{d}x=\int_{a}^{-a}f(-x)\mathrm{d}(-x)=\int_{-a}^{a}f(-x)\mathrm{d}x$$
And take the limits. It will imply that the integral of $f(-x)$ is the same as the integral of $f(x)$, if it exists. Can you prove that it exists?
Answer: Maybe a more intuitive way of thinking about this:
Consider $g(x):=f(x)-f(-x)$, then $g(-x)=f(-x)-f(x)=-g(-x)$, then:
$$\int_{-\infty}^{\infty} f(x)-f(-x) dx=\int_{-\infty}^{\infty} g(x)dx=0$$since $g(x)$ is odd.
Hence $\int_{-\infty}^{\infty} f(x) dx=\int_{-\infty}^{\infty} f(-x)     dx$
(P.S. I did not intend to argue in a very rigorous way)

Integration on f(-x)


Max of algebraic equations

Question: I am going through Dynamic Programming and Optimal Control text by Dimitri Bertsekas, on p. 18 - he derives these equations ...
$$\begin{equation}\begin{aligned}
\text{open-loop probability of win} &=
\max(p_w^2(3-2p_w), p_wp_d+p_w^2(1-p_d)) \\
&= p_w^2+p_w(1-p_w)\max(2p_w,p_d)
\end{aligned}\end{equation}\tag{1}\label{eq1}$$
and then...
$$\begin{equation}\begin{aligned}
\text{value of information} &=
p_w^2(2-p_w)+p_w(1-p_w)p_d \\
&- p_w^2-p_w(1-p_w)\max(2p_w,p_d) \\
&= p_w(1-p_w)\min(p_w,p_d-p_w)
\end{aligned}\end{equation}\tag{2}\label{eq2}$$
Please can someone help explain:

In equation 1 - how one would go about deriving line# 2 from line# 1, and
In equation 2 - how and why max turns into min?

Where:
$p_w$ and $p_d$ are probabilities of winning and drawing the game respectively.
Answer:
$\max(a+b,a+c) = a+\max(b,c)$, and $\max_i \{k f_i\} = k \max_i \{f_i\}$ for $k\ge 0$
$\max_i\{f_i\} = -\min_i \{-f_i\}$
Comment: thank you very much, for guiding without giving the game away! This helped me solve and arrive at the results.

Max of algebraic equations


Turing Machine calculator

Question: Can someone give me a code of example for Turing Machine Calculator
which can accept these inputs
30+25x3-2/5=

and the output is 104.6
this calculator cant accept these input
3+52-2
43+1=12
0+12+1=
2+0+x2=
1x02=
+2+3=
x19x1=
12x2x=

Answer: This sounds like a homework assignment, so I won't give you the code, but in general what you'll need to do is parse the input into a tree structure based on order of operations, and then resolve it recursively. There are several ways to achieve this but it is likely, if this is a homework assignment, that your professor has recently talked about the specific way he or she would like you to solve it.
You will essentially be reimplementing the *nix "bc" program. The GNU implementation is free software, and you can get the code to inspect here: https://www.gnu.org/software/bc/

Turing Machine calculator


Nine people in an elevator

Question: Assume there are nine people who enter a nine-floor building. Each person can exit on each floor with the same probability. What is the probability that the elevator stops on each floor if:

the building has basement
the building does not have basement

My aproach.
(A) Building has basement
In this case the setting seems to be simple. Let's denote with $f_i$ the floor chosen by $i^\text{th}$ person. Then we could consider all possible values of tuple $(f_1, f_2, ..., f_9)$ with $f_i \in \{1, ..., 9\}, i=\overline{1,9}$. There are $9^9$ possible values in total and $9!$ possible values where all $f_i$'s are different. Thus, the final probability is $$p=\frac{9!}{9^9}$$
(B) Building without basement
This case is much more difficult for me. Let's consider the same tuple $(f_1, f_2, ..., f_9)$ but with $f_i \in \{2, ..., 9\}, i=\overline{1,9}$. The number of possible values is $8^9$ now. Next, we need to count the number of possible values of the tuple such that it contains all numbers from $\{2, ..., 9\}$.
Eight of of nine people could pick 8 different floor in $8!$ ways while the last one could pick any of 8 floors. Thus the total number of interest is $8\cdot8!$. And final probability is $$p=\frac{8\cdot8!}{8^9}=\frac{8!}{8^8}$$ which contradicts intuitition since it is equal to the probability for the problem (A) but for 8 people. But adding extra person should have increased the probability.
Help much appreciated in validating part (A) and helping with solving part (B).
Answer: Case A and B are not clearly stated in the question. Assuming in a building with basement, all $9$ people enter at the basement and there are $9$ floors where they can exit, then your answer for case (A) is correct.
Case (B): If there is no basement, you seem to be  assuming everyone enters on the ground/first floor and there are $8$ floors where they can exit. In that case,
Exactly two people will exit on the same floor and one person each on remaining $7$ floors. So we choose the floor where we have two people exit and we choose two people who exit together and then remaining $7$ people exit on remaining $7$ floors in $7!$ ways. So the probability is,
$\displaystyle P = 8 \cdot {9 \choose 2} \cdot 7! \ / \ 8^9 = \frac{9!}{2! \cdot 8^8}$
Answer: Part (B) is analogous to an eight faced die thrown $9$ times, and the valid ways can be expressed as the product of two multinomial coefficients, viz $\binom{9}{2,1,1,1,1,1,1,1}\binom{8}{1,7} = \frac{9!}{2!}\frac{8!}{7!}$
You can now compute the probability

Nine people in an elevator


How can I setup multiple Django Apps using Supervisor (including Gunicorn and Nginx)? bind() to [::]:8090 failed (98: Address already in use)

Question: I already deployed a Django/Wagtail App using Supervisor, Gunicorn and Nginx (on Debian Buster), so I can reach it with http://xx.xxx.xxx.xxx:8090.
<code>/etc/nginx/sites-available/cms

server {
    server_name xx.xxx.xxx.xxx;
    listen 8090;
    listen [::]:8090 ipv6only=on;
    error_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log;
    access_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/www.mysite.com/www/my-site/cms/admin_panel;
    }
        location /media/ {
        root /home/www.mysite.com/www/my-site/cms/admin_panel;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock;
    }
}
</code>
<code>/etc/supervisor/conf.d/guni-mysite-admin.conf

[program:guni-mysite-admin]
command=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/bin/gunicorn admin_panel.wsgi:application --config /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py
user=www.mysite.com
autostart=true
autorestart=true
</code>
<code>/etc/supervisor/conf.d/nginx-mysite-admin.conf

[program:nginx-mysite-admin]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
stderr_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-error.log
stdout_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-access.log
stderr_logfile_maxbytes=2MB
stdout_logfile_maxbytes=2MB
</code>
<code>/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py

workers = 3
keepalive = 5
user = 'www.mysite.com'
proc_name = 'admin_panel'
loglevel = 'error'
errorlog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log'
accesslog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log'
bind = 'unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock'
raw_env = ['DJANGO_SETTINGS_MODULE=admin_panel.settings.production']
pythonpath = '/home/www.mysite.com/www/mysite/cms/admin_panel'
</code>
Now I added 2 more Django Apps the same way. Unfortunately Supervisor can´t bring them up. Sometimes 1 out of 3 runs, but most of the time none of them work. In case it works it creates 3 processes (idk if that´s how it is supposed to be).
<code>$ sudo lsof -i:8090

COMMAND  PID     USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
nginx   3631     root   16u  IPv4 961301189      0t0  TCP *:8090 (LISTEN)
nginx   3631     root   17u  IPv6 961301190      0t0  TCP *:8090 (LISTEN)
nginx   3632 www-data   16u  IPv4 961301189      0t0  TCP *:8090 (LISTEN)
nginx   3632 www-data   17u  IPv6 961301190      0t0  TCP *:8090 (LISTEN)
nginx   3633 www-data   16u  IPv4 961301189      0t0  TCP *:8090 (LISTEN)
nginx   3633 www-data   17u  IPv6 961301190      0t0  TCP *:8090 (LISTEN)
</code>
Nginx error log gives 98: Address already in use, even on port 81 (took it as default port because Apache is using 80), which is not used. Apache should not be the problem, because it doesn´t work, even when Apache is turned off.
<code>/var/log/nginx/error.log

...
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:4020 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:8090 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:81 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:8070 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:8080 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24927#24927: bind() to [::]:4030 failed (98: Address already in use)
2021/08/06 12:41:54 [emerg] 24928#24928: still could not bind()
...
</code>
Output - $ sudo service nginx status
<code>● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2021-08-07 10:27:49 CEST; 50s ago
     Docs: man:nginx(8)
  Process: 25364 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 25366 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 25367 (nginx)
    Tasks: 3 (limit: 4915)
   Memory: 4.1M
   CGroup: /system.slice/nginx.service
           ├─25367 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ├─25368 nginx: worker process
           └─25369 nginx: worker process

Aug 07 10:27:49 xxxxxxx.server.linevast.org systemd[1]: Starting A high performance web server and a reverse proxy server...
Aug 07 10:27:49 xxxxxxx.server.linevast.org systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
Aug 07 10:27:49 xxxxxxx.server.linevast.org systemd[1]: Started A high performance web server and a reverse proxy server.
</code>
Output - $ sudo supervisorctl status all
Gunicorn processes are running fine, Ngnix processes try to start, but break. Nginx Error Log gives bind() to [::]:8090 failed (98: Address already in use)
<code>guni-csd-admin                   RUNNING   pid 25564, uptime 0:06:44
guni-csd-phrases                 RUNNING   pid 25567, uptime 0:06:44
guni-kc-admin                    RUNNING   pid 25566, uptime 0:06:44
nginx-csd-admin                  STARTING
nginx-csd-phrases                RUNNING   pid 31118, uptime 0:00:01
nginx-kc-admin                   RUNNING   pid 31103, uptime 0:00:02
</code>
Comment: It looks like you try to start nginx via supervisor but there is an inastance that is running already (managed by systemd or init).
Comment: Indeed it does look like there´s already something running. That´s why I stopped Nginx and Supervisor, so the needed ports are definitely not used. `sudo lsof -i:8070`for example has no output. It looks like Supervisor or Nginx blocks itself for some reason.
Comment: Try "sudo service nginx status" and see what it says.
Comment: Sure I added it to the question.
Comment: As you can see in the output there is a running instance of nginx loaded by systemd. To avoid conflict you should pick one method to start and manage nginx daemon either systemd or supervisor. In my opinion it is better to use default method (systemd).
Answer: Solution
With following setup I successfully run two clients, three API´s, a Wordpress and Php Analytics Site without conflicts: As an example one of the API´s has Apache2 HTTP Server as Proxy (listening to port 80) which is forwarding to Nginx (not controlled by Supervisor which actually is the solution!) Gunicorn is conntrolled by Supervisor. So I just quit using Supervisor for Nginx processes. It may would work without using ipv6only, but I want to use it for sake of better control over IP bindings. So I´m fine with this.


Is it possible to rename php.ini to something else?

Question: It's possible in apache's configuration httpd.conf to set up .htaccess so that it is named something different, using the AccessFileName .htaccess directive.
Is there any way to set up PHP so it looks for the php.ini file under a different name? (I'm not trying to symlink - thanks)
Update
For those of you who are curious about why I would want to do such a thing:
I would be looking at changing the name of the file on the development machine, not the production machine. I've already set up a different .htaccess name on my local machine and it's been great. I can rsync between remote and local and keep different copies of both files on each machine, and yet only the proper file has effect. I can then diff the two files locally, which is nice.
These files both have more to do with the web sever configuration, and less to do with the web applications. Perhaps it is important to set up different include paths, or other such variables which are server specific. That sort of thing. Ideally your development server is a duplicate of the production server, but if you work on several different remote servers, especially with shared hosting, this is the kind of thing which is really convenient.
So basically having a different config file name for these local files and the remote files just allows keeping both copies side by side.
Comment: ... why? What's wrong with `php.ini`?
Comment: I hope you're not thinking that doing such things will aid security. The person why could directly access those files can also look at the Apache config to find out what names you're using.
Comment: It'll also confuse the hell out of someone else having to fix a broken server.
Comment: ditto on @ceejayoz: What reason could you possibly have to rename this file? I can think of numerous reasons **not** to change this file name.
Comment: I've updated the question to give you some insight.
Comment: "Ideally your development server is a duplicate of the production server". Perfectly correct and you can solve your issues more easily by configuring exceptions for whatever sync method you use so that things like .htaccess and php.ini are not synced.
Comment: ...but I *do* want them synced
Answer: You could setup a symbolic link
Comment: Definitely the right way to solve the problem (you can sync the /usr/local/etc/live.php.ini and /usr/local/etc/test.php.ini but leave the link at /etc/php.ini alone. B syncing files in /etc would be a bad idea.
Answer: It looks like the answer is "maybe"
PHP CLI has an arg, "-c", that lets you specify the path in which to search for the php.ini file, or the full path to the file itself.
PHP run as an Apache module has only directives to specify the path in which to search for the file, not the name of the file itself.
Finally, using a symlink as suggested will only work for the CLI version of PHP. A symlink to a directory in which to search for php.ini may work, but a symlink to the file will only work if the name of the symlink is "php.ini" which is not quite what your question asked to accomplish.
References
http://www.php.net/manual/en/configuration.file.php
The question from me is, "Why?" Why would you want to do this? I have a few instances of configuring services where at the time, I changed the name the configuration file to something related to the company or group or product or whatever that I was supporting with the service. i.e., Something different from the default. In pretty much all of those cases I've learned the hard way that doing so was a bad idea, from the point of view of maintainability, manageability, supportability, handoff to colleagues, etc.
Answer: I think you are searching for  ---exclude=php.ini --exclude=.htaccess switches of rsync. If you sync with script, add these two switches to it and rsync willn't copy these files anymore.
Anyway, I do not think renaming php.ini (even if it is possible) is a good idea. Do not do it.
Answer: The name .htaccess can be changed in httpd.conf or apache2.conf. And for php.ini, that may be buried in some apache include or in some c source itself. Would it be enough to symlink it?


What's the earliest known example of music written for an electronic instrument?

Question: The other day I stumbled upon Joseph Schillinger's First Airphonic Suite, a 1929 orchestral suite that includes a part for theremin. Since this was written 10 years after the invention of the theremin, I was curious to see if there are any earlier known electronic music pieces. The next earliest one I was able to find was Bohuslav Martinu's Fantasia for Theremin, Oboe, String Quartet, and Piano, which didn't premiere until 1945, so perhaps I'm not going about this search in the correct way. Anyone know of any earlier ones?
Answer: TL;DR
Theremin is considered the first electronic instrument in terms of the modern development of such instruments. The first piece composed specifically for Theremin was Andrey Pashchenko's "Symphonic Mystery" (1923).

The earliest score for an electronic instrument (that I've found so far) is from 1916: Luigi Russolo's "Awakening of a City" (see score below).

NTL;DR (Not too long; did read)
The first known electronic instrument (though, while it employed electricity, it's debated whether the sound itself was produced electronically) is the Denis d'or (Golden Dionysus), invented by Václav Prokop Diviš in or around 1748.
I first encountered mention of it at mmmmaven.com, and Wikipedia has an entry. There is also a write-up with documentation at 120 Years of Electronic Music.
Next came the Clavecin Électrique, invented in 1759 by Jean-Baptiste Delaborde. The original instrument still exists, and is in Paris at the French national library. (See also: Wikipedia.)
The earliest reference to compositions for electronics, given in Brittanica, is from Luigi Russolo, who invented "noise instruments", but "Russolo's instruments and most of his music apparently vanished during World War II." IMSLP includes one item of Russolo's, the book L'arte dei rumori (The Art of Noises) (1916), which includes a score for "Risveglio di una città" ("Awakening of a City").

It's interesting to note an early use of graphical notation.
The theremin, invented in 1919 (Wikipedia), is generally considered the first electronic instrument to directly impact modern development. According to Everything Everywhere:

The first song ever played on the theremin in that first demonstration was The Swan by Camille Saint-Saëns. The Swan has been compared for theremin players as to what Stairway to Heaven is for guitar players. It is one of the first things which everyone learns.

The first Theremin concert was given in November 1920, according to the website of the  Philharmonic Academic Symphony Orchestra and A History of the Theremin.
Peter Theremin's post on Theremin World ("First Composition for Theremin") indicates that the first composition for the instrument was by Soviet-era composer Andrey Pashchenko: "Symphonic Mystery" (1923).


Standard way to report covariates with multiple levels in regression table?

Question: Is there a standard way to report regression coefficients for control variables that have multiple levels?  For example, I have a control variable that tracks a participant's "State" -- that contains 50 levels.  Reporting each of these in a regression summary table generates a very long report.  I can't recall seeing such long tables in other publications, so I'm wondering how to deal with it.
Answer: Where are you "reporting" this?  In a paper submission?  If so, you can truncate the table for the main body, and see APPENDIX for entire list.


Composite Observable

Question: I have the following code:
Observable.FromEvent<ModelEventArgs>(
        h => ValuesController.ModelAdded += h,
        h => ValuesController.ModelAdded -= h)
    .Subscribe(m => context.Connection.Broadcast(m));

Observable.FromEvent<ModelEventArgs>(
        h => ValuesController.ModelDeleted += h,
        h => ValuesController.ModelDeleted -= h)
    .Subscribe(m => context.Connection.Broadcast(m));

What would be cleaner would be:
Observable.[SOMETHING](
        Observable.FromEvent<ModelEventArgs>(
                h => ValuesController.ModelAdded += h,
                h => ValuesController.ModelAdded -= h),
        Observable.FromEvent<ModelEventArgs>(
                h => ValuesController.ModelDeleted += h,
                h => ValuesController.ModelDeleted -= h))
    .Subscribe(m => context.Connection.Broadcast(m));

I can't seem to figure out what that [SOMETHING] needs to be, I don't want to wait for ModelAdded to Complete, i just want them both to emit (m) for each event.
Go easy on me, I'm an Rx newb
Comment: Most documentation uses the .FromEvent method, and I'd rather have type safety than save a line of code passing a string
Comment: You can probably switch to [FromEventPattern](http://msdn.microsoft.com/en-us/library/hh229221%28v=vs.103%29.aspx), it's a bit cleaner.
Comment: @JoeFlateau - They changed the name from `FromEvent` to `FromEventPattern` but then reintroduced `FromEvent` with a different purpose! `FromEvent` is for non-standard events. `FromEventPattern` is for the standard pattern. Both are available in strongly-typed overloads. You should use `FromEventPattern`.
Comment: Well shoot... I kinda like my little baby Actions over big brother EventHandler
Comment: @JoeFlateau - Sorry, if you're using `Action` then use `FromEvent` by all means. That's why it's there. I assumed you were using standard events because of the `ModelEventArgs` class name.
Comment: Oh, @JoeFlateau, don't forget to do the @ Enigmativity in your comment otherwise I would generally not see your reply. It was just luck that I refreshed the page.
Answer: I think you're looking for Merge:
Observable.Merge(
        Observable.FromEvent<ModelEventArgs>(
                h => ValuesController.ModelAdded += h,
                h => ValuesController.ModelAdded -= h),
        Observable.FromEvent<ModelEventArgs>(
                h => ValuesController.ModelDeleted += h,
                h => ValuesController.ModelDeleted -= h))
    .Subscribe(m => context.Connection.Broadcast(m));

Comment: Thanks, I did see that but thought it wasn't working.

Turns out my Deleted Broadcast is breaking SignalR (silently) and that's why i didn't catch the subsequent Broadcasts

Composite Observable


Which statistical test to use for comparing the same population before and after an improvement?

Question: I need to do a statistical test for one of my study but I'm not sure which test is appropriate.
This is my experiment:
I measured performance of 30 tools (F1 scores) on classifying a pair of documents as similar or not. Then, I applied an enhancement process to every tool and measured the tools performance again (they are the same set of tools before and after the process). I found that the enhancement can increase the F1 scores of every tool. However, I would like to test if the performance "improvement" has statistical significance. The 30 tools work deterministically.
I read from a few places that it would be a either a parametric paired t-test or a non-parametric Wilcoxon test depending on the normality of my data. So I tried using Shapiro–Wilk test on both the before and after data, they're not normally distributed (p-value = 5.177e-05 and 0.008338).
So should I go for Wilcoxon test? If not, could you please recommend a test that I should use?
Answer: Paired :-)test because you're measuring the same group of documents. Is this numerical or categorical data?

I'm sorry, I believe not paired because the two types of analysis you're comparing are not related. A simple t test with pooled variance should work, unless you believe the two sets of data have a different variance.
Comment: Your two different answers have been edited together. Please edit your answer to choose a single position, but offer better support for whichever it is you now think is correct.


How do I access these functions from DefinitelyTyped in typescript?

Question: I am trying to create an Angular2 app that works with money amounts.  I am trying to use dinero.js to represent money values, but I am having a hard time using certain features in Typescript.
As the instructions suggested, I installed the DefinitelyTyped mappings for dinero.js using this command
npm install @types/dinero.js --save

The type mappings for this library are declared here.
I import the library into my code like this:
import * as Dinero from 'dinero.js';

This allows me to use the factory function Dinero.  The problem is, that declaration lists some functions (namely maximum and minimum) that I want to use, but can't seem to get to.
If I try Dinero.maximum(...), I get:
"export 'maximum' (imported as 'Dinero') was not found in 'dinero.js'

If I try to import those functions directly:
import {maximum, minimum} from 'dinero.js';

and call by maximum(...), I get:
"export 'minimum' was not found in 'dinero.js'

How do I actually get to these functions?
Comment: You have to import `Dinero` like this `import Dinero from 'dinero.js'`
Comment: When I do that, my IDE yells at me saying `This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.`  Is enabling this bad practice or is it fine? If it's fine, why is it disabled by default?
Comment: Either way, I tried enabling that flag, and now I am getting this error:
`core.js:6260 ERROR Error: Uncaught (in promise): TypeError: dinero_js__WEBPACK_IMPORTED_MODULE_2__ is not a function`
Answer: you need to install these first :
npm install dinero.js --save

npm install @types/dinero.js --save

and then import and use it like this :
import  Dinero from "dinero.js";

const some_currency: Dinery.Currency = 'USD'
const some_val: Dinero.Dinero = Dinero({amount: 0, currency: some_currency})

this is the stackblitz url which is working :
https://stackblitz.com/edit/angular-ivy-spxp5x?file=src%2Fapp%2Fapp.component.ts
Comment: Thsi stackblitz contains your solution , please have a look https://stackblitz.com/edit/angular-ivy-spxp5x?file=src%2Fapp%2Fapp.component.ts


How find the $\frac{1}{e}\le R\le 1$

Question: Qustion:

let $a_{n}> 0$,and such $\displaystyle\sum_{n=1}^{\infty}a_{n}$ converge,let
  $$b_{m}=\sum_{n=1}^{\infty}\left(1+\dfrac{1}{n^m}\right)^na_{n}$$.
show that
  $$\dfrac{1}{e}\le R\le 1$$
  where the $R$ is the radius of convergence of $\displaystyle\sum_{m=1}^{\infty}b_{m}x^m$

My try:I know this therom:
If the radius of convergence of $\sum_{n=0}^{\infty}a_{n}x^n$ and $\sum_{n=0}^{\infty}b_{n}x^n$ are $R_{1}$ and $R_{2}$, then

the radius of convergence $R$ of $\sum_{n=0}^{\infty}a_{n}b_{n}x^n$ satisfies $R\ge R_{1}R_{2}$

But for my problem,I can't work this.Thank you
Comment: I cannot understand $1/e \leq R\leq 1$ ? $a_n=0$ Then $1/e \leq R <\infty$ ?
Comment: @HeeKwonLee,oh,I think $a_{n}>0$?
Answer: For every $m\geqslant1$ and $n\geqslant1$, one has $1\leqslant\left(1+\frac1{n^{m}}\right)^n\leqslant\left(1+\frac1{n}\right)^n\leqslant3$. Hence, if every $a_k$ is nonnegative, $\alpha\leqslant b_m\leqslant3\alpha$ for every $m\geqslant1$, where $\alpha=\sum\limits_{k=1}^\infty a_k$.
Thus, as soon as every $a_k$ is nonnegative, not every $a_k$ is zero, and the series $\sum\limits_ka_k$ converges, the radius of convergence of the series $\sum\limits_{n=1}^\infty b_mx^m$ is $1$.
Comment: No idea where the comparison with 1/e comes from. OP: What is the source of this exercise?
Comment: It's my frend ask me,I think this maybe $(1+\dfrac{1}{n})^n=e?$?
Comment: "It's my frend ask me"... Hmmmmm.
Comment: mabybe is from book.he sent me this picture,
Comment: Which book, then?
Comment: I don't know which book,sorry.my frend
Comment: Riddles in the dark...

How find the $\frac{1}{e}\le R\le 1$


How to set Varnish so that it doesn't cache a specific URL with a query string?

Question: Server setup: Ubuntu 12.10, Varnish 3.0.2, Nginx 1.3.14, with a WordPress 3.5.1 install.
We are using the "Random Redirect" plugin which shows a random blog post at the URL http://example.com/?random
I would like to set Varnish to not cache the above URL, since currently the "random" post keeps showing the same post.
A specific snippet to show what to put in default.vcl would be super helpful. Thanks.
Answer: Putting the following block in vcl_recv should do it:
if ( req.url ~ "^/\?random" ) {
  return (pass);
}

When you return(pass), you will jump past the opportunity to look up the request in the cache.
The default behavior is to do a bunch of tests to see if it is likely that the content is dynamic (does it set cookies, does it require authentication, is it a POST-request, things like that) - if none of those conditions are met, Varnish falls back to return(lookup)
Comment: I tried almost the exact code before posting my question and it didn't work. I tried your code and it also didn't work. I got the following errors: Command failed with error code 106
Message from VCC-compiler:
Syntax error at
('input' Line 48 Pos 16)
if ( req.url ~ '^/?random' ) {
---------------#--------------
Running VCC-compiler failed, exit 1
VCL compilation failed
Comment: I'm sorry, I misquoted -- one should use `""` and not `''` ... It compiles in my test.
Comment: The double quotes do compile correctly, but the random link stay the same for me still.
Comment: I forgot to add escaping of the ?, since it was interpreted as a part of the regular expression.  Again, sorry about that.
Comment: Yes, I think that fixed it up. Thanks Kvisle. (Giving you the check mark and voting up.)


Problem with Hall's marriage theorem

Question: Let $P_1=\{A_1,A_2,...,A_{10}\}$ and $P_2=\{B_1,B_2,...,B_{10}\}$ be two distinct partitions of a set of $100$ people into groups of $10$.
Let $G$ be a bipartite graph with $P_1$ and $P_2$ as bipartitions. There is an edge between $A_i$ and $B_j$ if $A_i$ and $B_j$ are disjoint.
Show $G$ has a matching.
Comment: Do you mean *not* disjoint? If $A_1$ has one element in common with each of the $B_j$, then I don't see how there can be a matching.
Comment: Ah,  i saw just now your comment.
Answer: As far as i can see this is not true. Suppose we arrange people in table $10\times 10$, so that each field of table contains exactly one person. If we think that $P_1$ is a set of columns and $P_2$ a set of horizontal lines then we see that this graph has no edge and so no matching.
Answer: On the other hand if we do as Gerry suggested, so $$A_i\sim B_j \Longleftrightarrow A_i\cap B_j \ne \emptyset$$
then there is a perfect matching. Take any $X \subset P_1$ and let $N(X)\subset P_2$ be the set of all neighbors of vertices in $X$. Say $|X|=k$ and $|N(X)| = l$. Then we have $$\bigcup _{A\in X} A \subseteq\bigcup _{B\in N(X)} B  $$
since set on left and sets on right are disjoint we have $$10k= \sum  _{A\in X} |A|\leq \sum _{B\in N(X)} |B| =10l $$ we have $k\leq l$ so $|X|\leq |N(X)|$ and so Hall condition is fulfilled and we are done.

Problem with Hall's marriage theorem


Friendly url with the same name of the files

Question: I'm trying to use friendly url this way:
RewriteRule ^index/([1-9]{1,5})$ /index.php?id=$1 [L]
RewriteRule ^contact/([1-9]{1,5})$ /contact.php?id=$1 [L]

But this is not working and i think it's because i'm using the name of the file in the RegEx.
This works fine:
RewriteRule ^home/([1-9]{1,5})$ /index.php?id=$1 [L]
RewriteRule ^emailus/([1-9]{1,5})$ /contact.php?id=$1 [L]

I did not know that is not possible to use the name of the file in the friedly urls, please, somebody knows a way to modify this configuration? In other case i'll have to change all the name of my files.
Comment: you can always turn on rewrite logging to see what's going on: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#logging level `trace3` will show the basic path through the rules and rewrite operations, allowing you to see HOW this isn't working.
Answer: This sounds like a case of Multiviews and mod_negotiation rearing its ugly head when its unwanted.
What's probably happening is that you have mod_negotiation seeing the request is /contact/123 and notices that there is a /contact.php file, and then immediately serves that file and bypasses mod_rewrite entirely. You'll need to turn it off:
Options -Multiviews


MongoDB: compare two output and merge to one

Question: I have two collections:

history

<code>{"_id":{"$oid":"1"},"name":"Josh","attachment":{"salary":"110","give":null}},
{"_id":{"$oid":"2"},"name":"Josh","attachment":{"salary":"110","give":1615988342517}}
</code>

salary

<code>{"_id":{"$oid":"1"},"salary":"110","history":["1","2"]}
</code>
I would like to implement to salary the history collection so i use aggregate:
<code>[
  {
    '$unwind': {
      'path': '$history'
    }
  }, {
    '$lookup': {
      'from': 'history',
      'let': {
        'history_id': '$history'
      },
      'pipeline': [
        {
          '$addFields': {
            'Type': {
              '$toString': '$_id'
            }
          }
        }, {
          '$match': {
            '$expr': {
              '$eq': [
                '$Type', '$$history_id'
              ]
            }
          }
        }
      ],
      'as': 'getSalary'
    }
  }
]
</code>
but my problem is that i get two output not one, because of unwind the history field
so now with this aggregation the result is :
<code>{"_id":{"$oid":"1"},"salary":"110","history":["1","2"],"getSalary": [{"_id":{"$oid":"1"},"name":"Josh","attachment":{"salary":"110","give":null}}}]}
AND
{"_id":{"$oid":"1"},"salary":"110","history":["1","2"],"getSalary": [{"_id":{"$oid":"2"},"name":"Josh","attachment":{"salary":"110","give":1615988342517}}}]}
</code>
i would like to achieve this result:
<code>{"_id":{"$oid":"1"},
"salary":"110",
"history":["1","2"],
"getSalary": [
{"_id":{"$oid":"1"},"name":"Josh","attachment":[{"salary":"110","give":null},{"salary":"110","give":1615988342517}]
]}
</code>
So if the salary _id is the same i would like if the getSalary contain all of the result from history collection
Any help would appreciate!
Answer: You need to use $project,$group and then $addToSet after $lookup like this:
<code>[
  {
    '$unwind': {
      'path': '$history'
    }
  }, {
    '$lookup': {
      'from': 'history',
      'let': {
        'history_id': '$history'
      },
      'pipeline': [
        {
          '$addFields': {
            'Type': {
              '$toString': '$_id'
            }
          }
        }, {
          '$match': {
            '$expr': {
              '$eq': [
                '$Type', '$$history_id'
              ]
            }
          }
        }
      ],
      'as': 'getSalary'
    }
  },
{"$project":
 {
  "_id":"$_id",
  "salary":"$salary",
  "history":"$history",
  "getSalary":"$getSalary"
 }
},
{"$group" : {
    "_id" : "$_id",
    "salary": { "$first": "$salary" },
    "history": { "$first": "$history" },
    "getSalary" : {
        "$addToSet" : {
            "_id" : "$getSalary._id",
            "name":"$getSalary.name",
            "attachment":"$getSalary.attachment"
        }
    }
   }
  }
 ]
</code>
Comment: hey thank you for the comment, the result is almost what i search, but now the getSalary is an array that contain object (which number is depend on how many history is) the object contain the attachment which contain an object which contain the first and second output. It's a bit messy because of this lot of nested doc
Is there a solution where the getSalaray is contain just the attachment and inside in the two expected output ?
Comment: Of course, sorry it was my mistake i write badly above:
"getSalary": [
{"_id":{"$oid":"1"},"name":"Josh","attachment":[{"salary":"110","give":null},{"salary":"110","give":1615988342517}]
]
```
Comment: Oh goted .. you want attachment inside one array.
Comment: yes exactly! is there a solution for this ?
Comment: Okay Let me figure out the way. Mark the above solution correct please.
Comment: Why aren't you storing userId in the history collection . I mean if you are storing userId along with name in the history collection. Then we can use another group on the basis of userId  and get the exact result you need.


Discrete math: Set theory and Power sets

Question: So, I'm stuck at these questions in set theory.

What is |P({∅,{∅},{∅,{∅}}})|
What is |P({{∅,{∅},{∅,{∅}}}})|
Write every element in P({∅,{∅},{∅,{∅}}}) and in P({{∅,{∅},{∅,{∅}}}}).

I know that the way to find the power set is $ 2^n $ in which n is the number of elements. My guess would therefore be that the the answer to question 1 should be 8 since it contains 3 elements. However, I don't really see any difference between that and the set in question 2. Why are they two different sets?
Regarding question 3, I don't really know where to start there.
Comment: The first asks about the set which contains the three elements $\varnothing, \{\varnothing\}$ and $\{\varnothing, \{\varnothing\}\}$. The second asks about the set containing the single element $\{\varnothing, \{\varnothing\},\{\varnothing, \{\varnothing\}\}\}$
Answer: 2: Example: Consider the set $\{a, b\}$. This set has two elements: $a$, and $b$. Now, consider the set $\{\{a, b\}\}$. This set has one element, which is "the set containing $a$ and $b$."
3: To write power sets, it may be helpful think of every element of the set as though it were a light switch that you could independently turn on (to indicate that the element should be in the set) or off (to indicate that it's out). The four elements of $P(\{a, b\})$ are
$$\{\}, \{a\}, \{b\}, \{a,b\}$$
so if we wanted to write that in set notation, we string the elements together inside brackets:
$$P(\{a,b\}) = \{\{\}, \{a\}, \{b\}, \{a,b\}\}.$$
Here, the light switch interpretation of these four elements is: "off and off, on and off, off and on, on and on," respectively. When we consider $P(\{\{a,b\}\})$, we again recall that it is a set with just one element -- so the power set will have just $2^1$ elements, corresponding to whether that one element is in or out. That is,
$$P(\{\{a,b\}\}) = \{\{\}, \{\{a,b\}\}\}.$$


How to SetError React Hook form and React-dropzone

Question: I'm working on a React hook form project and I'm using react-dropzone to upload some images, I want to display a React hook form's ERROR when the type of file is not an image, I can console.log Error but I don't know how to use SetError and block form submition until the file format is accepted..
This is my Sandbox code
Any idea please ?
Answer: The easiest way to block form submission is to use the disabled property of the input when the length of the fileRejections array is greater than zero:
<input type="submit" disabled={fileRejections.length > 0}/>

The whole form code is:
    <form onSubmit={handleSubmit(onSubmit)}>

          <input {...getInputProps()} name="upload" />

Drag 'n' drop some files here, or click to select files

          (Only *.jpeg and *.png images will be accepted)

Accepted files

{acceptedFileItems}

Rejected files

{fileRejectionItems}

      <input type="submit" disabled={fileRejections.length > 0}/>
    </form>

Comment: Yes thank you, but what about if I want to display an error to prevent user ? because I will have other input fields in my form too :)
Comment: @Tania12 Can you please supplement the question with a description of the error behavior, preferably with a screenshot? Perhaps it will be enough to display the "Rejected files" block with a list of files only in case of an error?
Comment: @Tania12 Perhaps it is better to use the error handling available in react-hook-form, but for this, depending on the situation, you need to register the components of the form, or use Controller.


What to do with important features?

Question: I am currently solving the titanic problem in kaggle. The data of the problem consists of several features such as "sex", "class in society", etc., and you are to predict whether a person survived the titanic incident or not. According to the analysis of other people, females are more likely to survive than males. They analysed the data using graphs. Given that information, am I supposed to do anything so that my model would know that the "sex" feature is important? Or is the analysis only important for data science (i.e. for the sake of knowing which gender survived the most).
Answer: If your data "shows" that females have a greater probability of survival, then your learning algorithm should be able to use this information. Notice, that what are you saying is that you have some subjective feeling that some predictors should be used in your model and you want to include this feeling in your model. Generally, this kind of approach is possible if using Bayesian methods where your result is:
$$ \text{estimation result} \propto \text{prior knowledge} \times \text{information encountered in data} $$
However in this approach your prior knowledge should be prior to data, i.e. it does not make much sens to use the same information twice (first learn it from data and then ask your model to learn it from data considering the fact that you learned if from data before doing estimation).
So general answer is no, there is no need to both tell your algorithm what do you assume from the data and to ask it to learn the same information from the data.

What to do with important features?


Setting Host Fingerprint on New EC2 Instances

Question: TL;DR
Can I tell AWS EC2 to launch an instance from AMI but keep the host keys -- the ones in <code>/etc/ssh</code> that were saved with the AMI -- instead of generating new keys and overwriting the ones saved with the AMI.
The full question:
On AWS, I'm setting up an EC2 instance to serve as a SFTP host. An automated system (managed by customer) will deliver files into there on regular basis. Those systems will authenticate via public keys provided by the customer.
In front of the EC2 instance there will be an elastic IP. This IP needs to remain constant "forever", since the automated system connecting to us relies on that constancy.
Behind the scenes, I would like to retain the ability to swap this EC2 instance with a different one at any point, and re-associate the existing IP address with the new server. (Some reasons to do this would be in order to launch a more powerful instance, or to consolidate various other servers into a single instance).
This kind of re-association needs to be transparent to the automated system that delivers the files. However, I expect that the automated system would freak out when I make such a switch, because it would detect that the host's fingerprint has changed. Maybe normally that's a good thing, but I believe in this case, since one host is supposed to replace another, it's appropriate to preserve the identity.
So, whenever I swap instances as described, I need to copy the original host's public key(s) into the new host. I actually half expected that this   would happen automatically — if I use the same AMI to launch both hosts, but it appears that EC2 deliberately assigns new public keys to the new instance, overwriting whatever keys were saved with the AMI.
My question is what's the easiest way to achieve the desired behavior. I know how to do it manually, by copying the keys over from the old server onto the new server and overwriting the ones that were assigned to the new server. But I wonder if EC2 has an automated or idiomatic way to do this.
Comment: EC2 merely gives you a virtual machine. Within that machine, things are managed as you would any other linux host.
Answer: I'd advise leaving the system instance as is for administration duties, and instead creating a 2nd instance of SSHd that runs with your shared key.
Copy your shared set of SSH keys to your AMI image and save them to a differently named file (e.g. /etc/ssh/shared_host_rsa_key).
Next, make a copy of the SSH server configuration (/etc/ssh/sshd_config -> /etc/ssh/sshd_shared_config), modify said configuration to listen on a new port (e.g. 2222) and use to your shared host keys.
Configure your 2nd sshd instance to start on boot, and tell your customer that from now on, they'll need to connect to port 2222.
You can even go further and harden the 2nd sshd configuration more so than the one you use for generic system administration.
Comment: Thank you! It didn't occur to me that it's possible to have multiple instances of SSHd. I assume that the 2nd SSHd's keys will remain intact when I launch an instance from an AMI that was saved with this configuration.