which hook to change the node order in a view?

Question: I have a custom view but now I want to put the nodes created by a specific user role on top.
I want to do this using code so I can easily implement this throughout multiple web pages.
I'm thinking to alter the query or to put an array sort before the nodes are rendered.
But I don't know which hook would be useful for this.
edit:
using hook_views_pre_render as suggested by Jimajamma
function vacancies_views_pre_render(&$view) {
  dsm($view->result);
  $view->result = array_reverse($view->result);
  dsm($view->result);
}

But that doesn't change the order of the nodes in the view ( putting a dsm($view); in the if statement ensures me that it is this view that is called. )
Answer: You can use View's prerender hook to modify the view's results anyway you want.
For example,
function YOURMODULE_views_pre_render(&$view) {

   if ($view->name=='xyzzy') {

      // modify/sort the $view->result array to your heart's content here
      // for example, reverse it...
      $view->result=array_reverse($view->result);

   }

 }

Basically $view->result is an array of row results, so, just go through it and grab the rows you want first, then follow that up with the remaining rows.
ADDITION:
I created a quick view and did the above reversing and it certainly reversed the order so I am not sure what you are doing ever so slightly wrong to not see similar behavior on your site.
Comment: Changing the result order in hook_views_pre_render() definitely works.
Comment: Helpful, but changing the $view->result order doesn't change the order that is output on the screen. ( while removing items does remove nodes from the view ) but no matter what items I remove the order doesn't change.
Comment: see code addition above...not sure what you are doing differently
Comment: Thanks for testing jimajamma and rooby for confirming that this works. Must be something else that's wrong in my installation. But for the question asked this is the answer so I'll accept it. I'll post an update if I find what was wrong.
Comment: feel free to post your code -- these tiny little errors are sometimes right there and all it takes is a second person to look and see them.
Comment: Yeah i know, or a good night sleep but the strange thing is that my array is reversed in the $view->result So I can only guess that there is something else wrong. anyway I'll update my question with the code I'm using.
Comment: strange... using [hook_views_post_execute()](http://api.drupal.org/api/views/views.api.php/function/hook_views_post_execute/7) it does work... but that is actually called before hook_views_pre_render()
Comment: `hook_views_pre_render` change only the order of view results by paginations, what we really need is a solution to act on view results global order at once time.
Answer: Since this is still high on the list of search results: in Drupal 9 (unsure of which versions this , the index property of each view row determines the order, not the array of rows itself.
So, if you get the row objects ordered to your liking, you can do something like this:
// Optionally set the array keys to start at zero and count up first.
$my_ordered_results_array = $array_values($my_ordered_results_array);

// Iterate over the rows and set index values.
foreach ($my_ordered_results_array as $key => $row) {
  $row->index = $key;
}

Answer: I came across this looking for a possible solution using Drupal 10.1, and I got something that seems to be working well. I believe this will also work on Drupal 9, but I have personally not tested it. I combined a couple of the previous solutions together:
function vacancies_views_pre_render(&$view) {
  // Reverse the resulting array order
  $newResultOrder = array_reverse($view->result);

  // Now we have the new order so we can set the indexes for each result row.
  $newResultOrder = array_values($newResultOrder);
  foreach ($newResultOrder as $key => $row) {
    // Set index for each result item since it is now in the correct order.
    $row->index = $key;
  }

  $view->result = $newResultOrder;
}

I also created a ViewExecutable object that I was able to change the order (in my own case) based upon contextual items in an array. You could replace this with whatever order you need them. This was tested and is working on Drupal 10.1 at the moment:
$view = Views::getView('whatever_view_machine_name');

if (is_object($view)) {
  $view->setArguments($argsIfYouNeedThem);
  $view->setDisplay('default');
  $view->preExecute();
  $view->execute();

  // If $resultOrder was built, handle re-ordering.
  // This checks if there was a result order from context (code not shown),
  // but this array could be any array with Node ID values in
  // the order you need the final results to be in.
  if ($resultOrder) {
    $newResultOrder = [];
    // Get the current results.
    $results = $view->result;

    // Loop through the final resulting Node ID order.
    // (from my example, $resultOrder is an array of Node IDs from context).
    foreach ($resultOrder as $newResultNid) {
      // Loop through view results to compare order of IDs.
      foreach ($results as $result) {
        // Get the Node ID so we can compare against our $newResultNid
        $currentResultNid = $result->nid;

        if ($currentResultNid == $newResultNid) {
          $newResultOrder[] = $result;
          break;
        }
      }
    }

    // Now we have the new order so we can set the indexes for each result row.
    $newResultOrder = array_values($newResultOrder);
    foreach ($newResultOrder as $key => $row) {
      // Set index for each result item since it is now in the correct order.
      $row->index = $key;
    }

    $view->result = $newResultOrder;
  }

  // Since I am rendering in a twig template, we are setting a variable
  // for the view results to be passed back.
  $variables['rc_view'] = $view->buildRenderable('default', $args);
}


Array communication: convert C doubles to chars, then java bytes to doubles

Question: I'm having trouble sending an array of doubles from a C application to a java application (over UDP).
At the moment I am casting my double data, like this
char* dataChars = (char*) dataDoubles;
int charsLen = sizeof(double)*doublesLen;

and sending this data over UDP to java, which gets a packet containing the correct number of java double entries (ie doubles seem to be the same size in both).
On the java side I recieve a byte[], then I am using:
ByteArray b = ByteArray.wrap(byteData);
for(...){
   doubleData[i] = b.getDouble();
}

When I send a packet with data defined in C as
double TEST_DATA[4] = {1.0, 2.0, 4.0, 8.0};

In java I get, reliably
 3.03865E-319 3.16E-322 2.0553E-320 4.079E-320

It looks like the bits are getting scrambled, but I dont know what would correct this.
Comment: it seems like you need to make sure that the bytes are send and decoded in the correct endianness. Also, you might want to use and (unsigned char*)
Answer: As suggested by Miky Denescu's, the following modifiation solves the problem:
doubleData[i] = b.order(ByteOrder.LITTLE_ENDIAN),getDouble();


How do I put all types implementing a certain generic interface in a dictionary?

Question: Given a particular interface ITarget<T> and a particular type myType, here's how you would  determine T if myType implements ITarget<T>. (This code snippet is taken from the answer to an earlier question.)
foreach (var i in myType.GetInterfaces ())
    if (i.IsGenericType
        && i.GetGenericTypeDefinition() == typeof(ITarget<>))
        return i.GetGenericArguments ()[0] ;

However, this only checks a single type, myType. How would I create a dictionary of all such type parameters, where the key is T and the value is myType? I think it would look something like this:
var searchTarget = typeof(ITarget<>);
var dict = Assembly.GetExecutingAssembly().[???]
             .Where(t => t.IsGenericType
                    && t.GetGenericTypeDefinition() == searchTarget)
             .[???];

What goes in the blanks?
Answer: var searchTarget = typeof(ITarget<>);

var dict = Assembly.GetExecutingAssembly()
    .GetTypes()
    .SelectMany(t => t.GetInterfaces()
                      .Where(i => i.IsGenericType
                          && (i.GetGenericTypeDefinition() == searchTarget)
                          && !i.ContainsGenericParameters),
                (t, i) => new { Key = i.GetGenericArguments()[0], Value = t })
    .ToDictionary(x => x.Key, x => x.Value);

Note that if you have multiple classes implementing ITarget<> and using the same generic type argument -- for example, class Foo : ITarget<string> and class Bar : ITarget<string> -- then the ToDictionary call will fail with an ArgumentException complaining that you can't add the same key twice.
If you do need a one-to-many mapping then you have a couple of options available.

Use ToLookup rather than ToDictionary to generate a Lookup<K,V>:
var dict = Assembly.GetExecutingAssembly()
    .GetTypes()
    .SelectMany(/* ... */)
    .ToLookup(x => x.Key, x => x.Value);

If you prefer to work with something like a Dictionary<K,List<V>> then you could do this:
var dict = Assembly.GetExecutingAssembly()
    .GetTypes()
    .SelectMany(/* ... */)
    .GroupBy(x => x.Key, x => x.Value)
    .ToDictionary(g => g.Key, g => g.ToList());

Comment: Alternate:  `AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes(). //etc`
Comment: Worked perfectly! Thanks very much. One question, though: what is the motivation for adding `!i.ContainsGenericParameters`?
Comment: `!i.ContainsGenericParameters` excludes `class C : ITarget { ... }`.
Comment: @Luke: I think the limitation you noted is fine, as I only have one implementer of `T` for any suitable `T` of `ITarget`. Just out of curiosity, though, is it possible to have the `ToDictionary` call create a _list_ of suitable types as its value instead of only a single type?
Comment: @James: You could call `ToLookup` to generate a `Lookup` instead, or you could use `GroupBy` and then generate a `Dictionary>` or something similar. I've updated my answer with a few details.
Comment: This is a great answer. Thanks Luke! Also, Will: in my particular case I do actually want only the types in my assembly, not all loaded assemblies, but your way is good to know about too.


regression - statistical significance query

Question: 1) Why do we do statistical tests to check if the independent variables used in the regression are statistically significant or not, when it can be checked using correlation?
2) My understanding is when we have only one continuos variable - we check if the data given is normally distributed or not and then compute statistics for the historical data - which we better coin this term as descriptive statistics.
Not sure where it is used in real -life, normally my understanding is that continuous variables are better understood based on the context of one dim. Let me know your thoughts on this?
Answer: There main reason is that we want to be sure that the "correlation" between the two variables (meaning the coefficient of the regression) did not occur by pure random chance. There are a lot of assumptions that go in to making this valid, but if those assumptions hold, statistical significance is one way to decide how confident we are in the results.


Symfony2 Relationship entities + forms

Question: I'm trying to write one form for submitting against MySQL DB, but I can't get it working, I've tried a lot of things (separate forms, create an ->add('foo', new foo()) to a field, and trying to parse plain SQL with a normal HTML form is my only solution, which is obviously not the best.
This is my DB structure:
![enter image description here][1]
As you can see I need to insert the comments textarea to ticketcomments among the user who wrote it, etc.
On crmentity the description field.
Then on ticketcf the fields that I need to submit from form, are this (because you wont know if I don't tell you because of the field names):
tcf.cf594 AS Type,
tcf.cf675 AS Suscription,
tcf.cf770 AS ID_PRODUCT,
tcf.cf746 AS NotificationDate,
tcf.cf747 AS ResponseDate,
tcf.cf748 AS ResolutionDate,

And, of course, every table needs to have the same ticketid id for the submitted form, so we can retrieve it with one simple query.
It will be easy to do with plain SQL instead of using DQL and Symfony2 forms, but is not a good way to do it.
EDIT
This is my new created entity Ticket.php, which has relations to the tables above... if someone could check it out and tell me if it's okay...
ticket.php
<?php
namespace WbsGo\clientsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * VtigerTicketcomments
 *
 * @ORM\Table(name="vtiger_troubletickets")
 * @ORM\Entity(repositoryClass="WbsGo\clientsBundle\Entity\TicketsRepository")
 */

class Tickets
{
    /**
     * @var \WbsGo\clientsBundle\Entity\VtigerCrmentity
     *
     * @ORM\OneToOne(targetEntity="WbsGo\clientsBundle\Entity\VtigerCrmentity")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="ticketid", referencedColumnName="crmid", unique=true)
     * })
     * @ORM\Id
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="ticket_no", type="string", length=100, nullable=false)
     *
     */
    private $ticketNo;

    /**
     * @var string
     *
     * @ORM\Column(name="groupname", type="string", length=100, nullable=true)
     */
    private $groupName;

    /**
     * @ORM\ManyToOne(targetEntity="VtigerContactdetails")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parent_id", referencedColumnName="contactid", unique=true)
     * })
     */
    private $parentId;

    /**
     * @ORM\ManyToOne(targetEntity="VtigerAssets")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="assetsid", unique=true)
     * })
     */
    private $productId;

    /**
     * @var string
     *
     * @ORM\Column(name="priority", type="string", length=100, nullable=true)
     */
    private $priority;

    /**
     * @var string
     *
     * @ORM\Column(name="severity", type="string", length=100, nullable=true)
     */
    private $severity;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="string", length=100, nullable=true)
     */
    private $status;

    /**
     * @var string
     *
     * @ORM\Column(name="category", type="string", length=100, nullable=true)
     */
    private $category;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255, nullable=true)
     */
    private $title;

    /**
     * @var text
     *
     * @ORM\Column(name="solution", type="text", nullable=true)
     */
    private $solution;

    /**
     * @var text
     *
     * @ORM\Column(name="update_log", type="text", nullable=true)
     */
    private $updateLog;

    /**
     * @var integer
     *
     * @ORM\Column(name="version_id", type="integer", nullable=true)
     */
    private $versionId;

    /**
     * @var string
     *
     * @ORM\Column(name="hours", type="string", length=255, nullable=true)
     */
    private $hours;

    /**
     * @var string
     *
     * @ORM\Column(name="days", type="string", length=255, nullable=true)
     */
    private $days;

    /**
     * @var integer
     *
     * @ORM\Column(name="from_portal", type="integer", nullable=true)
     */
    private $fromPortal;

    /**
     * @ORM\OneToMany(targetEntity="VtigerTicketcomments", mappedBy="ticketid")
     *
     */
    protected $comments;

    /**
     * @ORM\OneToOne(targetEntity="VtigerTicketcf", mappedBy="id")
     */
    protected $ticketcf;
    /**
     * @ORM\OneToOne(targetEntity="VtigerCrmentity", mappedBy="crmid")
     */
    protected $crmtable;
}

VtigerTicketcf.php
<?php

namespace WbsGo\clientsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * VtigerTicketcf
 *
 * @ORM\Table(name="vtiger_ticketcf")
 * @ORM\Entity
 */
class VtigerTicketcf
{
    /**
     * @var string
     *
     * @ORM\Column(name="cf_546", type="string", length=255, nullable=true)
     */
    private $cf546;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_556", type="string", length=255, nullable=true)
     */
    private $cf556;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_589", type="string", length=3, nullable=true)
     */
    private $cf589;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_590", type="string", length=3, nullable=true)
     */
    private $cf590;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_592", type="string", length=100, nullable=true)
     */
    private $cf592;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_593", type="string", length=255, nullable=true)
     */
    private $cf593;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_594", type="string", length=255, nullable=true)
     */
    private $cf594;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_675", type="string", length=50, nullable=true)
     */
    private $cf675;

    /**
     * @var float
     *
     * @ORM\Column(name="cf_689", type="decimal", nullable=true)
     */
    private $cf689;

    /**
     * @var float
     *
     * @ORM\Column(name="cf_690", type="decimal", nullable=true)
     */
    private $cf690;

    /**
     * @var float
     *
     * @ORM\Column(name="cf_691", type="decimal", nullable=true)
     */
    private $cf691;

    /**
     * @var float
     *
     * @ORM\Column(name="cf_693", type="decimal", nullable=true)
     */
    private $cf693;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_746", type="string", length=50, nullable=true)
     */
    private $cf746;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_747", type="string", length=50, nullable=true)
     */
    private $cf747;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_748", type="string", length=50, nullable=true)
     */
    private $cf748;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_761", type="string", length=255, nullable=true)
     */
    private $cf761;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_763", type="string", length=255, nullable=true)
     */
    private $cf763;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_764", type="string", length=255, nullable=true)
     */
    private $cf764;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_765", type="string", length=255, nullable=true)
     */
    private $cf765;

    /**
     * @var string
     *
     * @ORM\Column(name="cf_770", type="string", length=50, nullable=true)
     */
    private $cf770;

    /**
     * @var \WbsGo\clientsBundle\Entity\Tickets
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="WbsGo\clientsBundle\Entity\Tickets")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="ticketid", referencedColumnName="ticketid", unique=true)
     * })
     *
     */
    private $id;
}

VtigerTicketcomments.php
<?php

namespace WbsGo\clientsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * VtigerTicketcomments
 *
 * @ORM\Table(name="vtiger_ticketcomments")
 * @ORM\Entity
 */
class VtigerTicketcomments
{
    /**
     * @var string
     *
     * @ORM\Column(name="comments", type="text", nullable=true)
     */
    private $comments;

    /**
     * @var integer
     *
     * @ORM\Column(name="ownerid", type="integer", nullable=false)
     */
    private $ownerid;

    /**
     * @var string
     *
     * @ORM\Column(name="ownertype", type="string", length=10, nullable=true)
     */
    private $ownertype;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="createdtime", type="datetime", nullable=false)
     */
    private $createdtime;

    /**
     * @var integer
     *
     * @ORM\Column(name="commentid", type="integer")
     * @ORM\Id
     */
    private $id;

    /**
     * @var \WbsGo\clientsBundle\Entity\Tickets
     * @ORM\OneToOne(targetEntity="WbsGo\clientsBundle\Entity\Tickets")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="ticketid", referencedColumnName="ticketid", unique=true)
     * })
     *
     */
    private $ticketid;
}

VtigerCrmentity.php
<?php

namespace WbsGo\clientsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * VtigerCrmentity
 *
 * @ORM\Table(name="vtiger_crmentity")
 * @ORM\Entity
 */
class VtigerCrmentity
{
    /**
     * @var integer
     *
     * @ORM\Column(name="smcreatorid", type="integer", nullable=false)
     */
    private $smcreatorid;

    /**
     * @var integer
     *
     * @ORM\Column(name="smownerid", type="integer", nullable=false)
     */
    private $smownerid;

    /**
     * @var integer
     *
     * @ORM\Column(name="modifiedby", type="integer", nullable=false)
     */
    private $modifiedby;

    /**
     * @var string
     *
     * @ORM\Column(name="setype", type="string", length=30, nullable=false)
     */
    private $setype;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="createdtime", type="datetime", nullable=false)
     */
    private $createdtime;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="modifiedtime", type="datetime", nullable=false)
     */
    private $modifiedtime;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="viewedtime", type="datetime", nullable=true)
     */
    private $viewedtime;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="string", length=50, nullable=true)
     */
    private $status;

    /**
     * @var integer
     *
     * @ORM\Column(name="version", type="integer", nullable=false)
     */
    private $version;

    /**
     * @var integer
     *
     * @ORM\Column(name="presence", type="integer", nullable=true)
     */
    private $presence;

    /**
     * @var integer
     *
     * @ORM\Column(name="deleted", type="integer", nullable=false)
     */
    private $deleted;

    /**
     * @var integer
     *
     * @ORM\Column(name="crmid", type="integer")
     * @ORM\Id
     */
    private $crmid;

}

And this is my repository method...
public function findByIdAndCustomerId($id) {
        $query = $this->getEntityManager()
                ->createQuery(
                        '
                        SELECT
                        IDENTITY(t.id) AS id,
                        t.ticketNo AS Ticket,
                        t.title AS Asunto,
                        t.status AS Estado,
                        t.updateLog AS LOG,
                        t.hours AS Horas,
                        t.solution AS Solucion,
                        t.priority AS Prioridad,
                        tcf.cf748 AS F_Reso,
                        tcf.cf747 AS F_Resp,
                        tcf.cf746 AS F_Noti,
                        tcf.cf770 AS IDPROD,
                        tcf.cf594 AS Tipo,
                        tcf.cf675 AS Suscripcion,
                        c.comments AS Comments,
                        CONCAT (CONCAT(s.firstname, \' \'), s.lastname) AS Contacto
                        FROM WbsGoclientsBundle:Tickets t
                        JOIN t.parentId s
                        JOIN t.ticketcf tcf
                        JOIN t.comments c
                        WHERE  t.ticketNo = :ticketNo

        ')
        ->setParameter('ticketNo', $id)
        ;

        try {
            //return $query->getSingleResult();
            return $query->getResult();
        }
        catch (\Doctrine\ORM\NoResultException $e)
        {
            return null;
        }
    }

I can retrieve an array of X ticket even if I just search by ONE ID, because if ID1 has 4comments, then I got 4 same tickets, one per comment... How can I make it only ONE ticket with comments => array(...) so I can iterate inside that comments array inside twig?
And also VtigerCrmentity.Description doesn't work either, it returns this error...

Notice: Undefined index: crmid in
  /var/www/wbsgo/dev.wbsgo/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php
  line 826

I don't have getter and setter because I'm re-generating them again, if annotation are OK, the entities will update correctly with get/set and my forms will be able to submit using relationships, right?
Answer: You may embed a form that does represent an underlying entity field by setting mapped option to false, e.g.:
->add('comments', 'collection', array(
    'type'   => new VtigerTicketcommentsType(),
    'mapped' => false
))

However, be careful when assigning form data, since $form->submit($data) will not set data to underlying collection of comment objects. You'll need to process them manually inside the controller. You may access the data that has been flagged as non-mapped using $form->getExtraData() after the data is submitted to the form.
If you'd like Symfony to automatically set data to comments, you'll need to construct a relationship between VtigerTroubletickets and VtigerTicketcomments entities, which, according to the question title, you don't have and try to avoid.
Edit:
A form type is bound to a given entity class. By default, each field you add to a form type must have an underlying property in a declared entity class (or getter/setter pair if property is not defined public). When you construct a form object from form type (OpenTicketType) and data (new VtigerTroubletickets()):
$form = $this->createForm(new OpenTicketType(), new VtigerTroubletickets());

the form get bounds with data present in the object you just created. The object does not have comments property, even more, the form itself knows the field is not mapped and it will not try to populate it from the object, so naturally the collection is rendered as empty, as no data about comments was passed.
To get past this, you may pass array of data instead of newly created object (note: the values may be empty, however comments array must have length > 0 - the comment has to exist, though without actual data).
[
  "title"    => "...",
  "priority" => "...",
  "solution" => "...",
  "comments" => [
    0 => [/* comment 0 data */],
    1 => [/* comment 1 data */],
    .......
  ]
]

This is the form creation. When the form is POST-ed, there is one additional step beside constructing the form. The request data has to be bound onto form, so you do $form->submit($request). Now the form AND underlying entity object will get populated with fresh data.
The $form->getExtraData() is simply a method for accessing the data that form holds and is not mapped to an underlying object - which comments field is, since we flagged it as such.
Alternatively to using getExtraData - extracting data from form manually - you may add a property comments to VtigerTroubletickets entity with getters/setters and not mark it as a db column. That way, you may remove the mapped => false option at form type, and form will automatically read/populate comments property.
Still, when persisting, these comments will not be considered for storing, so you'll have to handle them manually. Likewise, when fetching an object from database, the comments property would be empty, so prior to creating a form, you'd have to add some comments to an object, e.g.:
$tickets = new VtigerTroubletickets();
$tickets->setComments(....);
$form = $this->createForm(new OpenTicketType(), $tickets);

Comment: Exactly, I don't have it and I try to avoid because the DB is used by another platform so I don't want to change anything to avoid conflicts. The way you are saying (using `collection`) I don't see anything rendered, the only way I actually get it working is using `->add('comment',
     new VtigerTicketcommentsType()
   )` this way everything renders good, but I don't know how it will work when I press submit, you mentioned `$form->getExtraData()` but how exactly this works in my case? Also, thanks for your reply.
Comment: Thank you, can you explain more where you say `To get past this, you may pass array of data instead of newly created object`? I don't understand what you say about `comments array must have length > 0 - the comment has to exist, though without actual data).`
Comment: What I meant is that you were getting nothing rendered when using "collection" because none of the comments existed when form was constructed. In order to get them rendered, you have to add at least one comment to the entity or form (depends on whether you chose to map data from entity to form or not).
Comment: I'm trying to do what you are saying but I'm getting this error `Entities passed to the choice field must be managed. Maybe persist them in the entity manager?` doing this `$entity = new Tickets();
        $entity->setTicketcf(new VtigerTicketcf());
        $form   = $this->createForm(new TicketsType(), $entity);`
Answer: I think @usoban has taken you most of the way.  Think of these as two long comments as opposed to answers.
It seems you have a ticket entity and a comment entity with a 1 to many relationship between them but you don't want to actually establish a formal relationship between them because the "DB is used by another platform"?  What exactly does that mean.  Are you sharing php code with another application?  Are you using doctrine 2?  With Doctrine 2 you can establish the relationship without changing the actual database.
You really should look at adding a getComments to your ticket entity.  It will make your S2 life much easier.
Comment: Thank you for your comment, I don't want to change the DB because I'm using vTiger CRM, and then this other app using S2 with the same database (so no PHP is shared, ONLY the DB) Actually, as you can see there are more than just `comments` table, if I could make relationship for the diagram I've posted that'll be great but I'm a bit lost on how to make everything work, I've never used S2 before so I'm a newbie on here... Reading a lot of documentation 'n stuff...
Answer: This answer is built on what @usoban said about using an array but takes a slightly different approach.
// In the controller
$formData = array();
$formData['ticket'] = new Ticket(),
$formData['comments'] = array(new Comment(), new Comment());

$form = $this->createForm(new TicketCommentsType(), $formData);
$form->handleRequest($request);

if ($form->isValid())
{
    $formData = $form->getData();
    $ticket   = $formData['ticket'];
    $comments = $formData['comments'];

    // Persist ticket

    // Persist comments

TicketCommentsFormType simply brings the two different entities into one form.
class TicketCommentsFormType

public function buildForm(

    $builder->add('ticket',new OpenTicketType());
    $builder->add('comments','collection',array(
            'type' => new VtigerTicketcommentsType()

With this approach there is no need to have any direct relation between Ticket and Comment.
Comment: I assume that `controller` part is for once the form has been submitted and not for the creation itself?
Comment: I've changed my whole code trying to use relationships without updating the DB (so only with Doctrine) but I think something is wrong...
Answer: I've found the way to do it, and the problems.
The relations are this:
crmentity.id > Main, this table has not relationships
troubleticket.ticketid > This one has relation with crmentity.id
ticketcf.ticketid > this one has relation with troubleticket.ticketid
So the order when you insert needs to be crmentity->troubleticket->ticketcf
But in Symfony2, when you make forms, you must create the last table element as the first form to be generated, so I'll post my code in case someone has the same problem as me.
http://pastebin.com/wLPyXvbj
:)

Symfony2 Relationship entities + forms


If $f(0)=g(0)=0$ and $\int_0^{\epsilon} f(x)g(x) dx >0$ for any small $\epsilon>0$, do $f(x)$ and $g(x)$ have same sign near $x=0$?

Question: Let $f,g : [0,\infty) \to \mathbb{R}$ be smooth functions such that

$f(0)=g(0)=0$

$\int_0^{\epsilon} f(x)g(x)dx >0$ for any small $\epsilon>0$.

Then, I would like to investigate about the sign of $f(x)$ and $g(x)$ near $x=0$. Is it possible to conclude that there exists some $\epsilon'>0$ such that $f(x)g(x) \geq 0$ for $x \in [0,\epsilon']$ ?
Comment: hmm good question. Would anything be lost if you just let $h = fg$ and think only in terms of $h(x)$ ?
Comment: I didn't assume monotinicity. Who tagged it??
Comment: See my answer, if define $h(x)=\int_0^x f(t)g(t)dt$, then your OP is equivalent to ask about the monotonicity of $h'(x)$ at the neighborhood of $0$.
Comment: Yes, I add this @DavidRaveh
Comment: Oh, my next step is to think of integrating the fraction $g/f$ provided that $f(x)$ is nonzero near $x=0$. That is why I facforized into two functions.
Comment: In the tags you call the function(s) monotone. If you want $f$ and or $g$ to be monotone, please repeat it in the question's body
Comment: @MathFail please edit your post to explain this, in current form it isn't clear to me
Answer: Define: $h(x)=\int_0^x f(t)g(t)dt$, we can simplify your question as:

Suppose $h(x)\ge0$ at the neighborhood of $0$, and $h(0)=0, h'(0)=0$, does it implies $h'(x)\ge0$ at the neighborhood of $0$?

The answer is false. Let $$\begin{align}h(x)&=\frac{x^{3/2}}2+x^2\sin\left(\frac1x\right),~~~\text{if}~~x\neq 0\\
\\
h(0)&=0\end{align}$$
Easy to verify, it satisfies all above conditions. But $h(x)$ is NOT monotonic increasing on any neighborhood of $0$.
Answer: Sadly, the answer is false.
We have several ways of constructing counterexamples. I post a seemingly complicated, but intuitive way of construction. The idea is to glue an alternating series of rescaled bump functions, such that the negative bumps are extremely smaller than adjacent positive bumps.
We choose $f(x)=x$. The choice of $g$ will be technical.
Let $\psi\in C^\infty_c(\mathbb{R})$ be a non-negative bump function supported on $[1,2]$ such that $\psi([4/3,5/3])=\{1\}$.
We choose
$$g(x)=\sum_{j=1}^{\infty}2^{-2^j}\psi(2^{2j}x)-\sum_{j=1}^{\infty}2^{-10^j}\psi(2^{2j+1}x).$$
You can check smoothness of $g$ by direct calculation. Naively speaking, although we are attaching shrinking copies of unit bump function $\psi$, the size shrinks extremely faster than the shrinking support, so we have that.
You can also check that $g$ is negative on intervals $[\frac{4}{3}2^{-2j-1},\frac{5}{3}2^{-2j-1}]$, in particular $g$ is not non-negative on any interval of the form $[0,\epsilon]$.
Since $g$ is negative on the intervals $[\frac{4}{3}\cdot2^{-2j-1},\frac{5}{3}2^{-2j-1}]$, so we have $\int_0^t f(x)g(x)dx>0$ for every $t>0$ once we showed for $j\in\mathbb{N}$:
$$\int_{\frac{4}{3}2^{-2j}}^{\frac{5}{3}2^{-2j}}x2^{-2^j}\psi(2^{2j}x)dx>\int_{\frac{4}{3}2^{-2j-1}}^{\frac{5}{3}2^{-2j-1}}x2^{-10^j}\psi(2^{2j+1}x)dx,$$and this is just change of variable ($d(2x)$).


Can this algorithm be reversed?

Question: Hi I have the following python code.

Note... yes, I am asking you to solve my algorithm.. I have become burnt out
  working on it. If you fancy a challenge give it a go.

dataListEdited = [0,1,1,1,0,0,1,0,1,0,1,1,0]    #This is just random 1's and 0's

patternsNotAllowed = [[1,1,1],[0,0,0],[1,0,1,0,1],[0,1,0,1,0],[1,1,0,0,1,1],[0,0,1,1,0,0]]

#Condition data
def conditionData(dataListEdited,patternsNotAllowed):
    offset=0
    for x in range(len(dataListEdited)):
        print(dataListEdited[:x+1])
        for notAllowed in patternsNotAllowed:
            if(len(dataListEdited[:x+1])> len(notAllowed)-1):
                if((dataListEdited[(x+1)-len(notAllowed):x+1]) == notAllowed):
                    print("Matched"+str(notAllowed))
                    lenToFlip = len(dataListEdited) - x +1
                    print(dataListEdited)
                    print("Swap @" + str(lenToFlip-1))
                    for y in range(lenToFlip-1):
                        if(not(dataListEdited[-y-1]) == True):
                            dataListEdited[-y-1] = 1
                        else:
                            dataListEdited[-y-1] = 0
                    print(dataListEdited)
                    offset = x
                    break
    return dataListEdited

Please analyse if you wish, but it basically looks at the list dataListEdited and makes sure that it doesn't contain any of the lists in patternsNotAllowed.
It does this by checking if there is a case in patternsNotAllowed which matches a portion of the sequence dataListEdited, if a match is found it flips the last bit that caused the match in dataListEdited and all bits to the right of that bit are also flipped.
My question is this;

Is the process above reversible?

I have been trying to figure this out myself the last week and I just can't... Below is some code I have tried. (it goes backwards doing the same thing, but obviously doesn't work). Also I am aware you could store the locations where flips have happened to reverse them but I want to avoid doing this. (but i'm starting to think it's impossible).
def unconditionData(dataListEdited,patternsNotAllowed):
    for x in range(len(dataListEdited)):
        if(not(dataListEdited[-1-x]) == True):
            dataListEdited[-1-x] = 1
        else:
            dataListEdited[-1-x] = 0
        #print(dataListEdited)
        for notAllowed in patternsNotAllowed:
            #print(dataListEdited[len(dataListEdited)- x - len(notAllowed):len(dataListEdited)-x])
            if(dataListEdited[len(dataListEdited)- x - len(notAllowed):len(dataListEdited)-x] == notAllowed):
                print("Matched " + str(notAllowed))
                lastFlipPoint = len(dataListEdited)- x
                break

    return dataListEdited

Any help would be appreciated,
Thanks,
Woody
Comment: Intuitively it doesn't seem reversible. How can you tell if a bit is the result of flipping or the original value?
Comment: `len(dataListEdited[:x+1])` isn't that the same as `x`?
Comment: x+1 but yes @Barmar
Comment: I guess my question is more along the lines of how would I do this :L perhaps even changing the way I avoid the sequences I don't want needs to be changed?
Comment: I don't understand that question. What are you really trying to do?
Answer: No, it's not reversible.
If patternsNotAllowed = [[0]], you'll get the same result [1, 1] from an input list [0, 1] and [1, 1].
Since there are multiple inputs with the same output, there's no way to tell which input produced the output, so you can't reverse it to the actual input.
Answer: To add to Barmar's answer, it is not reversible using your own patternsNotAllowed list, either. There are 2^13 = 8192 different lists of length 13 containing just 0s and 1s, and we can try them all using itertools.product:
>>> len({
...     tuple(conditionData(list(a), patternsNotAllowed))
...     for a in itertools.product((0, 1), repeat=13)
... })
...
178

(I removed all the print statements to test this.) By putting them into a set and finding the length, we can see there are only 178 distinct outputs, so each output has on average 8192/178 ≈ 46 different pre-images.
Comment: More generally, I think all the intermediate states that the list goes through are possible inputs that will produce the same output.

Can this algorithm be reversed?


Allow only single product in Cart

Question: Is there any way to allow user only one product in cart. I used uc_restrict_qty but After that i can add more than one products also.
Comment: Also check this http://drupal.org/project/uc_product_minmax
Comment: There is no need for a carts if you can't have products in them. If you want your users to buy one at a time, why not to just remove cart altogether and add "buy now" button? I can't imagine anyone else wanting basically useless cart. On the other hand, if you want only one product of a given type, uc_restrict_qty should do that - report bug there if it doesn't.
Comment: uc_restrict_qty - If you already had a copy of that product in your shopping cart, you should empty your cart and add it again. Due to the way the module works, it won't restrict quantities on products already in customers' shopping carts.
Answer: If the module uc_restrict_qty not working file your issue there. Alternatively You can achieve this with help of hook hook_uc_add_to_cart
hook_uc_add_to_cart($nid, $qty, $data)

Performs extra processing when an item is added to the shopping cart.

Inside hook you can check your conditions, and prevent your new item to add.
uc_cart_get_contents() can used to get existing contents of cart. If it is greater than 1 you can do your logic here, either remove previous one and add the current one or remove the new item
Comment: thanku.... I used hook_uc_add_to_cart and empty the cart if qty is 1..
Comment: @NikhilM oh yes.. :D

Allow only single product in Cart


Uso do .append() ou .html() - jQuery

Question: Não estou conseguindo inserir html em um elemento.
JS
function carregaAgendamento() {
var url = "http://prestoexpress.com.br/vistoria/json.php";
$.getJSON(url, function(result) {
  console.log(result);
  $.each(result, function(i, field) {

    var id = field.id;
    var dataVistoriaAgenda = field.dataVistoriaAgenda;
    var tipoImovel = field.tipoImovel;
    var tipoVistoria = field.tipoVistoria;
    var codImovel = field.codImovel;

    $("#vistoria-agenda").append('

'
      +codImovel+" "+dataVistoriaAgenda+'

'
      +"Tipo: "+tipoVistoria+" Tipo Imóvel: "+tipoImovel+'

');
   });
 });
};

HTML

Vistorias Agendadas

Comment: https://jsfiddle.net/k9n3jLd3/2/ aparentemente seu código esta ok
Comment: Ezequiel verifique se o seu retorno realmente possui alguma coisa, veja: http://pt.stackoverflow.com/a/175701/14262 a pergunta e bem similar, e o erro do rapaz era o retorno json
Comment: @MarceloBonifazio está retornando sim    [{"id":"1","dataVistoriaAgenda":"2017-02-06","dataVistoria":"0000-00-00 00:00:00","endereco":"Rua São Rafael, 34","tipoImovel":"Residencial","comentarios":"","tipoVistoria":"Saída","status":"Pendente","codImovel":"16524"}]
Answer: Ezequiel, o site encontrava-se indisponível no momento da minha resposta, então criei um arquivo json.php para servir como teste e colei o seu json que você escreveu no comentário nele. Removi as interrogações(??) do meio do json pra não dar erro. Chamei a sua função e rodou de boa.
Exemplo de output:

Vistorias Agendadas
16524 2017-02-06
Tipo: Saída    Tipo Imóvel: Residencial

Segue o código utilizado para testar:
json.php
[{"id":"1","dataVistoriaAgenda":"2017-02-06","dataVistoria":"0000-00-00 00:00:00","endereco":"Rua São Rafael, 34","tipoImovel":"Residencial","comentarios":"","tipoVistoria":"Saída","status":"Pendente","codImovel":"16524"}]

index.php
<!DOCTYPE html>

<title>Teste Carrega Agendamento</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Vistorias Agendadas

Comment: Consegui resolver usando o listvivew('refresh'); no final do append.. Pode ser algum conflito pois estou usando Jquery Mobile. obrigado

Uso do .append() ou .html() - jQuery


How do I escape curly braces {...} in powershell?

Question: I need to generate multiple lines of xml tag with a GUID in them:
<xmltag_10 value="{ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ}"/>
<xmltag_11 value="{ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ}"/>

and so on
I have this line in a loop where $guid is generated each iteration, and it prints the guid without surrounding braces
Write-Host ('<xmltag_{0} value="{1}"/>' -f $i,$guid)
<xmltag_10 value="ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ"/>

Adding a set of curly braces, I get
Write-Host ('<xmltag_{0} value="{{1}}"/>' -f $i,$guid)
<xmltag_10 value="{1}"/>

How do I escape the outer curly braces? I've tried using `{{1}`} to escape but I get
Error formatting a string: Input string was not in a correct format..

Adding my code for copying and testing:
$i=10
while($i -lt 21)
{
    $guid = ([guid]::NewGuid()).ToString().ToUpper();
    Write-Host ('<xmltag_{0} value="{1}"/>' -f $i,$guid)
    $i++
}

Answer: To escape curly braces, simply double them:
'{0}, {{1}}, {{{2}}}' -f 'zero', 'one', 'two'
# outputs:
# zero, {1}, {two}
# i.e.
# - {0} is replaced by zero because of normal substitution rules
# - {{1}} is not replaced, as we've escaped/doubled the brackets
# - {2} is replaced by two, but the doubled brackets surrounding {2}
#   are escaped so are included in the output resulting in {two}

So you could to this:
Write-Host ('<xmltag_{0} value="{{{1}}}"/>' -f $i,$guid)

However; in your scenario you don't need to use -f; it's a poor fit if you need to use literal curly braces. Try this:
$i=10
while($i -lt 21)
{
    $guid = ([guid]::NewGuid()).ToString().ToUpper();
    Write-Host "<xmltag_$i value=`"$guid`"/>"
    $i++
}

This uses regular variable substitution in a double quoted string (but it does require escaping the double quotes using `" (the backtick is the escape character).

Another option would have been to use a format specifier.  i.e. Format B causes a GUID to be surrounded by braces.  Sadly it also formats the GUID in lowercase, so if the case of the output is part of your requirement, this would not be appropriate.
Write-Host ('<xmltag_{0} value="{1:B}"/>' -f $i, $guid)

Comment: While -f is not required, just for future reference if you do need it: Write-Host ('xmltag_{0} value="{{{1}}}"/>' -f $i,$guid)
Comment: thanks @EBGreen.  I would have picked yours as the better answer


How can I pass two option arrays for the same dropdown component in react js?

Question: I want to reuse my dropdown component in two other containers by passing two different set of array.
Example: One dropdown menu used for creating a breakfast option menu and the other for dinner option menu.
I've tried creating two arrays in state part of the class. but when i call the array it shows no options
class DropDownDropper extends React.Component {

    constructor(props){
      super(props);
      this.state = {options: [
        breakfast: [
          { label: "Location 1", value: 1 },
          { label: "Location 2", value: 2 },
          { label: "Location 3", value: 3 },
          { label: "Location 4", value: 4 },
          { label: "Location 5", value: 5 },
          { label: "Location 6", value: 6 },
        ] ,
        dinner: [
          { labe: "Venue 1", value: 1 },
          { labe: "Venue 2", value: 1 },
          { labe: "Venue 3", value: 1 },
          { labe: "Venue 4", value: 1 },
          { labe: "Venue 5", value: 1 },
      ]
        ]
    }
    }

  render() {
    return(

            <Select options = { this.props.options
           } />

    );
  }
}

Comment: You have a couple of typos in your syntax: `options: [` should be `options: {` and the respective closing bracket should be corrected. Also in the dinner array you're missing an "l" in label. Try fixing that and see if you manage to do what you want
Comment: Okay i made changes to the syntax but still not solved
Comment: @ravibagul91 but if i do this i'll have to write the component again and there in the i can mention this.state.options[]. Is there a better way
Answer: You need something to return in render method. The best option would be to create a component that returns a dropdown list and pass the dropdowns data from the class in which you want to display the dropdown.
Comment: i have put up a dropdown part in the render
return(

    );
can you suggest me how should call the dropdown in two diiferent pages with two different option menus
Comment: You can find here a lot of usefull thinks about react and options: https://scriptverse.academy/tutorials/reactjs-select.html
Answer: here my solution for you :
App.js
    import React from "react";
import ReactDOM from "react-dom";
import Dropdown from "./Dropdown";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      categories: [
        {
          name: "Breakfast",
          options: [
            { label: "Location 1", value: 1 },
            { label: "Location 2", value: 2 },
            { label: "Location 3", value: 3 },
            { label: "Location 4", value: 4 },
            { label: "Location 5", value: 5 },
            { label: "Location 6", value: 6 }
          ]
        },
        {
          name: "dinner",
          options: [
            { label: "Venue 1", value: 1 },
            { label: "Venue 2", value: 1 },
            { label: "Venue 3", value: 1 },
            { label: "Venue 4", value: 1 },
            { label: "Venue 5", value: 1 }
          ]
        }
      ]
    };
  }
  render() {
    return (

        {this.state.categories.map(cat => (
          <Dropdown options={cat.options} title={cat.name} />
        ))}

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

i have recreated your state because you cannot create a array inside array ! you need object for that.
so state has a categories array which has name and options.
Dropdown.js
    import React from "react";

const Dropdowm = ({ options, title }) => (

{title}

    <select>
      {options.map(option => (
        <option value={option.value}>{option.label}</option>
      ))}
    </select>

);

export default Dropdowm;

codesandbox
Comment: Hey thanks for a detailed solution, your answer cleared some of my concepts but i'm still having a little trouble. so if i want to call the dropdown in the breakfast page it should show breakfast 1, breakfast 2, etc. and the same with dinner page i.e dinner 1, dinner 2, etc . Sorry i'm very new to react js so bear with me
Comment: Yes you can filter your array using name in each page like this : `this.state.categories.filter(cat=>cat.name=[your value])`
Comment: so where should i declare both the arrays ? in the dropdown component or somewhere else ? Here you have declared in the app component which is fine, but for me what do you think i should do ?
Comment: @okaycharm I suggest  you to use  global state management like redux,mobx... this will help you hold  all your app state in one file which is called a store, so you can share this state to all your component.
Comment: I'm thinking to use the redux part after some time because i've yet understand it properly. But is there an other way by using static props. Meaning is it possible to create an option.js which stores both arrays and when i call the dropdown i can just use . Can that happen? As of now i need to get the static part done for a demo and when i'm dealing with data i'll integrate redux to it
Comment: @okaycharm yes you can do with exporting the array and importing it in any component.


How to make one view with different taxonomy terms in different rows?

Question: I want to make a view with 3 rows of lets say fruits, with 6 fruits max for each row. Spring, Summer and Autumn fruits.
And I don't want them to be mixed in one array so I could style them in view-template. How can I do it correctly?
Answer: I wanted to post this as a comment but my rep is not high enough. I had asked a similar question and received an answer here: Separate grid rows by field value
Comment: Looks good but it doesn't give me 6 for each taxonomy term. My general number of elements that are displayed is 18. Do you know how to make it?
Comment: In Views, under Format, select Grid for Format and specify 6 for "Number of columns." That  doesn't work? Sorry, I'm an amateur at Drupal myself.


Need to create a button that displays a specific picture, then hides it after a specified ms duration

Question: Not sure how to approach the task or what specific code would work but am thinking a nested function might do it.I just don't know exactly how to properly implement it.
I can create the button in HTML and have it display the picture but am unsure how to code/incorporate the setDuration (I'm assuming here) function part. Being somewhat new to JS so looking for best practices for a hopefully simple task. Sincerely appreciate any assistance/input!
Comment: You can use [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) for that
Answer: Give your image an id and use:

setTimeout(()=>{
    document.getElementById("id").remove();
},200)
Answer: You can use setTimeout to time when your picture will disappear. It will something like this.
function displayPicture() {

    // code that displays picture
    image.display = "block";

    setTimeout(()=> {
    // code that hides the picture
    image.display = "none";

    // the picture will disappear in 5 seconds
    }, 5000);
}

Answer: you can use on click event to show picture and hide it using setTimeout.
HTML:

<button id="btnId">Hey Click me!</button>

Javascript
    // add click event to button
    document.getElementById("btnId").addEventListener('click', function() {
        //show image
        document.getElementById('imageID').style.display='block';
        // hide image after 1 sec.
        setTimeout(function() {
          document.getElementById('imageID').style.display='none';
        }, 1000);
    });

Comment: Dear Babbar, thank you sooooo much for taking the time and providing a complete answer - very much appreciated! Your code works exactly as I intended.


Creating a new object within namespace javascript

Question: I'm trying to create a function within a namespace that will get me a new object instance.
I get syntax error trying to do the following:
var namespace = {
    a : function(param){
        this.something = param;
    },
    a.prototype.hi = function(){
        alert('hi');
    },

    b : function(){
        var t = new a('something');
    }
};

What is the correct syntax for doing this? Is it not possible to do within the namespace object? I don't want to declare the namespace first. Thanks
Comment: Duplicate.  See this SO answer for a way of doing it: http://stackoverflow.com/questions/7137860/javascript-namespace-declaration-with-function-prototype
Comment: Thanks Eli - I knew there had to be a simple way to do this, seems very common to me. Unfortunately I have to do some code refactoring now but I don't think it will be too bad.
Answer:
I don't want to declare the namespace first.

You can do weird things like this:
var namespace = {
    init: function() {
        a.prototype.whatever = function(){};
    },
    a: function(x) {
        this.x = x;
    }
}
namespace.init();
var myA = new namespace.a("x");

But why not try the module pattern if you want to encapsulate everything?  It's way cleaner:
var namespace = (function() {
     function a() {};
     function b(name) {
          this.name = name;
     };
     b.prototype.hi = function() {
          console.log("my name is " + this.name);
     }
     return {
          a: a,
          b: b
     }
})();

Comment: Thanks I think I will refactor to use the module pattern.
Answer: A javascript namespace is an object so you can only use key: value couples but no code (as you do with : a.prototype.hi = function() {...}).
You should thus separate that in two : declaration and then code :
var namespace = {
    a : function(param){
        this.something = param;
    },
    b : function(){
        var t = new a('something');
    }
};

namespace.a.prototype.hi : function() { ... }

Comment: I'm not sure what your comment means "no code" - that's clearly not true.
Comment: Yes, probably is it badly formulated, here it is the "key" `a.prototype.hi` which is impossible in a javascript object, but in the value you can add whatever code you want!
Answer: I do not exactly know what you want, but this works:
var namespace = {

    a: function() {

        function a() {

        }

        a.prototype.hi = function() {
            console.log("hi");
        }

        return new a;

    }

}

var obj = new namespace.a();
obj.hi()

// -> 'hi'


What is the easiest way to programmatically extract structured data from a bunch of web pages?

Question: What is the easiest way to programmatically extract structured data from a bunch of web pages?
I am currently using an Adobe AIR program I have written to follow the links on one page and grab a section of data off of the subsequent pages. This actually works fine, and for programmers I think this(or other languages) provides a reasonable approach, to be written on a case by case basis. Maybe there is a specific language or library that allows a programmer to do this very quickly, and if so I would be interested in knowing what they are.
Also do any tools exist which would allow a non-programmer, like a customer support rep or someone in charge of data acquisition, to extract structured data from web pages without the need to do a bunch of copy and paste?
Answer: If you do a search on Stackoverflow for WWW::Mechanize & pQuery you will see many examples using these Perl CPAN modules.
However because you have mentioned "non-programmer" then perhaps Web::Scraper CPAN module maybe more appropriate?  Its more DSL like and so perhaps easier for "non-programmer" to pick up.
Here is an example from the documentation for retrieving tweets from Twitter:
use URI;
use Web::Scraper;

my $tweets = scraper {
    process "li.status", "tweets[]" => scraper {
        process ".entry-content",    body => 'TEXT';
        process ".entry-date",       when => 'TEXT';
        process 'a[rel="bookmark"]', link => '@href';
    };
};

my $res = $tweets->scrape( URI->new("http://twitter.com/miyagawa") );

for my $tweet (@{$res->{tweets}}) {
    print "$tweet->{body} $tweet->{when} (link: $tweet->{link})\n";
}

Answer: I found YQL to be very powerful and useful for this sort of thing. You can select any web page from the internet and it will make it valid and then allow you to use XPATH to query sections of it. You can output it as XML or JSON ready for loading into another script/ application.
I wrote up my first experiment with it here:
http://www.kelvinluck.com/2009/02/data-scraping-with-yql-and-jquery/
Since then YQL has become more powerful with the addition of the EXECUTE keyword which allows you to write your own logic in javascript and run this on Yahoo!s servers before returning the data to you.
A more detailed writeup of YQL is here.
You could create a datatable for YQL to get at the basics of the information you are trying to grab and then the person in charge of data acquisition could write very simple queries (in a DSL which is prettymuch english) against that table. It would be easier for them than "proper programming" at least...
Answer: There is Sprog, which lets you graphically build processes out of parts (Get URL -> Process HTML Table -> Write File), and you can put Perl code in any stage of the process, or write your own parts for non-programmer use.  It looks a bit abandoned, but still works well.
Answer: I use a combination of Ruby with hpricot   and watir   gets the job done very efficiently
Answer: Are commercial tools viable answers?  If so check out http://screen-scraper.com/  it is super easy to setup and use to scrape websites.  They have free version which is actually fairly complete.  And no, I am not affiliated with the company :)
Answer: If you don't mind it taking over your computer, and you happen to need javasript support, WatiN is a pretty damn good browsing tool.  Written in C#, it has been very reliable for me in the past, providing a nice browser-independent wrapper for running through and getting text from pages.


Minimizing Mean Squared Error for Exponential Function

Question: I have a function that I'm trying to model using an exponential function and I'm trying to determine the constants for the exponential. I know I could optimize it using trial-and-error in R or another language, but I'd like to learn an analytic solution.
I figured that minimizing mean squared error would be the way to go about this, so I have:
$$\underset{r,k}{\operatorname{argmin}}\sum_{t=0}^T (s(t)-\hat{s}(t\mid r,k))^2$$
Where $s(t)$ is the function that I'm trying to model and $\hat{s}(t)$ is $(1+r)^{t+k}$ .
The only constraint I could come up with was $r>0$. I suppose I could also assume $k>0$ for now.
I learned about Kuhn-Tucker constraints as an extension to Lagrange constraints (which I already know) but I wasn't able to solve it.
Am I even going about this the right way? If I am, how can I solve this problem?
Thanks in advance!
Answer: Your setup is fine.  This sort of problem will not (usually) have an analytic solution.  You have a two-dimensional non-linear minimization problem.  There are  many numeric routines that can solve this in libraries, and they are discussed in any numerical analysis text.  They really consist of informed trial and error, where the informed part comes from keeping track of past trials to build up information about the error function.
Comment: Thank you for the answer! That's a bit disappointing to hear though. Are there constraints or other pieces of information I could add to allow for an analytic solution?
Comment: @AndyBromberg:  no, the problem is that equations involving sums of non-integral powers usually can't be solved except numerically.  Think of $1.45^{2.3+x}+1.45^{4.7+x}=10000$  You would like to take logs of both sides, but the log of a sum is not the sum of the logs, so it doesn't help.
Comment: Thanks again for the response. So if I removed the $k$ term from the equation so all I had was $(1+r)^{t}$, that would be solvable? Or is the issue that there's a variable exponent in the first place?
Comment: @AndyBromberg:  it might be if all your $t$'s are integers and not too big (no more than four or larger and you get lucky).  But problems like this usually have more data points than that.  One-dimensional root finding is much easier, so if you don't need $k$ for a decent fit it would be nice to remove it.  But with one fewer parameter, you may have more trouble fitting.


jQuery code firing twice

Question: I don't know why and how, but my jQuery code appears to be firing twice on any event.
Here's a part of my code:
commmon.js:
$(document).ready(function() {

    $(".fpbtn-one").click(function() {
        console.log("Click recorded!"); // Gets logged twice on click
        $(this).parent().next().slideToggle();
    });

    // The rest of the code...

});

$(window).load(function() {

    console.log("Setting up slides"); // Gets logged 2 on page load

    // These get initialized twice
    $("#div-1").responsiveSlides({
        auto: true,
        pager: true,
        pause:true,
        nav: false,
        timeout: 3000,
        speed: 500,
        maxwidth: 482,
        namespace: "transparent-btns"
    });

    $("#div-2").responsiveSlides({
        auto: true,
        pager: false,
        pause:true,
        nav: false,
        speed: 2000,
        maxwidth: 320,
    });

});

HTML:
<!doctype html>

<link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" />
<link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/>
<link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" />

<meta charset="utf-8" />
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />

<link href="/assets/custom/files/favicon.ico" rel="shortcut icon" />
<link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" />
<link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" />
<link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" />

<meta content="" name="description" />
<meta content="" name="keywords" />
<meta content="NOINDEX, NOFOLLOW" name="ROBOTS" />
<title>Some title</title>

<link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" />
<link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" />
<link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" />

What could be the reason?
Comment: If you want a solution you should post your html or a fiddle. Its all up to you.
Comment: I moved all JS includes to the head of the page and it solved the issue. It works but i don't know why :(
Comment: use 'one' instead of click
Comment: @CodingAnt that does not make any sense.
Comment: was just a suggestion , can you provide jsfiddle for that
Comment: A jsFiddle won't help here. The same thing is happening to the rest of the code.
Comment: Can you post your html?
Comment: @TilwinJoy What exactly would you like to see?
Comment: The only reason for the handler firing twice is if you're adding it twice. I don't see any reason for that in what you've posted. I suspect you have duplicate code in your actual site.
Comment: @Barmar check out my HTML - i am not adding it twice. The code is in `common.js`
Comment: If you can't replicate this in jsfiddle, can you provide a link to the actual site?
Comment: use e.stopPropagation();
Comment: http://www.1stformations.co.uk/frontpage/
Comment: @chuckfinley i don't see any multiple logs in the page you shared other than something like `setting up slides`
Comment: @TilwinJoy That's the problem he's talking about. There's only one `console.log()` that does that in the `$(window).load()` handler, it shouldn't be logging twice.
Comment: I'm not sure where it's happening, but it looks like something is reloading common.js dynamically.
Comment: @Barmar i added a debugging point in `$(window).load()`. Everything is  being executed twice. This is just unreal.
Comment: I see that. When it hits that debugging point the second time, it's it's in a file called VM####, where #### is a number that changes each time. That's why I think the file is being reloaded dynamically. I don't see where that's happening, though.
Comment: does this have anything to do with the js animating `html` ? will it trigger another load after the animation?
Comment: I highly doubt it. It was working just fine yesterday
Comment: @chuckfinley you should really add that as an answer and accept it
Answer: Could it be that your code was manipulating the element that the code was loading into?
This answer may be the reason why it was happening:
jQuery $(document).ready () fires twice
Answer: Try putting the stuff in the body inside divs.
example.

I hope that works. :)
Answer: be careful for beginning use good practice when calling jquery :
!function( $ ) {
   your code

}( jQuery )

like that you avoid conflict...
Then be careful when adding js script in html, you can add it twice, for example you call one js in a html file, ok but in the js you load in callback for example another page with the js inside, it will call twice your code.... i had the same probleme before with a recursive call, the js never stop to call it !!
in the main page it is better if your js will be called in several files otherwise you have to debug it....
moreover you don't paste all your code we can't help you, we can just tell in my opinion.... not a good advices often...
Answer: May be you have included your script file commmon.js twice. Check your references to it in your code.
Answer: It might be event bubbling. Use event.preventDefault(), it will prevent the default event from occuring or event.stopPropagation() will prevent the event from bubbling up.
$(document).ready(function() {

    $(".fpbtn-one").click(function(event) {
        event.stopPropagation();
        console.log("Click recorded!"); // Gets logged twice on click
        $(this).parent().next().slideToggle();
    });

    // The rest of the code...

});

Comment: The same thing is happening for every single block of code. This can't be it
Comment: What about `$(window).load()`? That doesn't bubble.
Answer: The simplest explanation is that you have included the common.js twice by mistake.
Look into individual scripts and see if you have referenced common.js on top of your main file.
Comment: Please look at the question and you will notice that i am not including the file twice.
Comment: @chuckfinley firebug reported the script is imported again dynamically.
Answer: Your relevant code is required, but from the snippets above; try putting all the codes in the document ready method.
Comment: It's already in the ready handler. If it weren't, it probably wouldn't fire at all, not fire twie.

jQuery code firing twice


How to see the call stack of the functions being called in a page

Question: I am beginning to work on a project that has quite a few modules(around 20) which I am not really familiar with. Is there a tool or suggestion, besides dpm-ing the function name, to detect the functions and modules being used in a random page?
Answer: If you want to see the complete callstack of the functions being called, you should set up a debugging environment for doing so.
The quickest way to do is by downloading the Quickstart: Prebuilt Drupal Development Environment, which is a virtual machine copy of preconfigured ubuntu. The netbeans IDE is configured for debugging the Drupal code. It also has an display to look at the callstack at the bottom of the IDE, when in debug mode.

What all is included in it:

Support for Drupal 7 and Drupal 6
Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
Firefox (with developer plugins) and Chrome
Drush, drush make, and custom drush commands
Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
Netbeans and Eclipse, configured with XDebug
XHProf and Webgrind profilers. Emails logged as files
cvs, subversion, git, bazaar

You can have a look at its dedicated youtube channel for helpful screencasts.


How to convert mat to array2d?

Question: I created dll for the dlib face landmark code there used array2d to get the image, but i like to read an image using Mat and to convert to array2d because dlib supports only array2d. Can any one say how to convert mat to array2d ??
Answer: Convert a cv::Mat image to dlib::array2d:
In case of a BGR image, you can follow this:
dlib::array2d<dlib::bgr_pixel> dlibImage;
dlib::assign_image(dlibImage, dlib::cv_image<dlib::bgr_pixel>(cvMatImage));

And, if you have a grayscale image, simply use <unsigned char> instead of <bgr_pixel>:
dlib::array2d<unsigned char> dlibImageGray;
dlib::assign_image(dlibImageGray, dlib::cv_image<unsigned char>(cvMatImageGray));

Answer: Firstly convert the Mat to cv_image of dlib. Then using the assign_image() of dlib you can convert the cv_image to array2d.
Answer: #include "opencv2/core/core_c.h" // shame, but needed for using dlib
#include <dlib/image_processing.h>
#include <dlib/opencv/cv_image.h>

dlib::shape_predictor sp;
dlib::deserialize(path_to_landmark_model) >> sp;

cv::Rect r;
cv::Mat I;
dlib::rectangle rec(r.x, r.y, r.x+r.width, r.y+r.height);
dlib::full_object_detection shape = sp(dlib::cv_image<uchar>(I), rec);

Comment: i edited my question sir,can u please say the necessary steps
Comment: maybe i misunderstood you, but use a `dlib::cv_image(Mat)` . look at last line of code.
Comment: thank u ...i did like
cv::Mat src = cv::imread("image_path",1);
img=dlib::cv_image(src);
buti got the error like this Mr.berak **error: no match for 'operator=' (operand types are 'dlib::array2d' and 'dlib::cv_image')**
Comment: I used it but i got the same error  ** error: no match for 'operator=' (operand types are 'dlib::array2d' and 'dlib::cv_image')**   the full code can be viewed by clicking. [click_here](https://jayabalaji1394.wordpress.com/2015/03/18/code-used/)
Comment: I got the issue as ** "pixel type given doesn't match pixel used by the open cv Mat object"** when i used like this                                                      Mat src = imread(argv[1],CV_LOAD_IMAGE_COLOR);
cv_image img(src);
load_bmp(img,"input.bmp");     can u suggest some ideas
Comment: again, you will need a **grayscale** image to get the landmarks
Comment: even i got the same error when i used a gray scale image  Mr.berak, please help me in solving that issue

How to convert mat to array2d?


Why are Vue dynamic components destroyed inside loop every re-render?

Question: I run into an issue with Vuejs 2.x version (latest). While rendering a list of item inside a loop, if I make changes to the items then the normal components are not destroyed but the dynamic components will always be destroyed:
I have put a short sample code here:
https://gist.github.com/yellow1912/fc1c053e07c1ca136148484cf7f79d1a
I have also put a codepen here:
https://codepen.io/raineng/pen/zYGOXYY?editors=1111
<nl-test inline-template>

 increase here please

 decrease here please

                printing
                <component :is="getItem()" :key="key"></component>
                <nl-test inline-template>

                        this is a test here

                </nl-test>

</nl-test>

To see what I mean, open the console tab on codepen, click the add item and you will see that the dynamic component items are destroyed and re-created everytime.
Answer: I found out why, I need to use keep-alive:
https://v2.vuejs.org/v2/guide/components-dynamic-async.html
To quote:

When switching between these components though, you'll sometimes want
to maintain their state or avoid re-rendering for performance reasons
Recreating dynamic components is normally useful behavior, but in this
case, we'd really like those tab component instances to be cached once
they're created for the first time. To solve this problem, we can wrap
our dynamic component with a  element

Wasted 2 days on this issue and then I found the answer just a moment after posting this on StackOverflow. Hope it helps someone.


How to prove a derivative is measurable?

Question: If f is differentiable, what can we say about f'? Continuous a.e or even measurable? I couldn't find anything online but was hoping for some insight.
Answer:
Using the sequence of functions $f_n(x)=\frac{f(x+1/n)-f(x)}{1/n}$ we can show that the derivative is indeed Borel-measurable (also, see @AndreCaicedo's comment).
However, it needn't be continuous a.e., as demonstrated by the Volterra function.
Comment: Borel-measurable. In fact, preimages of open sets are $F_\sigma$.


Encountering an issue while attempting to fetch data from an API

Question: Here i am trying get a data from the url using axios. I am getting a data when i console log response.data
this is the log i get but when i try console log response.data.trees then it shows undefined. How can i solve this issue.
Fetch1 {
  "trees": [
    {
      "id": 1,
      "name": "Bao",
      "species_name": "Adansonia",
      "image": {
        "src": "https://upload.wikimedia.org/wikipedia.jpg",
        "alt": "A large African baobab tree."
       }
    },
    {
      "id": 2,
      "name": "Red Mangrove",
      "species_name": "Rhizophora mangle",
      "image": {
        "src": "https://upload.wikimedia.org/wikipedia.jpg",
        "alt": "A free-standing red mangrove tree.",
      }
    }
  ]
}

Fetch2 undefined

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('url');
        setTrees(response.data.trees);
        console.log('Fetch1',response.data)
        console.log('Fetch2',response.data.trees)
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

Answer: The response you are receiving from the API is in JSON format. It is not an object. In order for you use it like an object like you expect, use let data = JSON.parse(response.data) and then do data.trees to access the element you want.
You can read more about JSON.parse() here.
Hope this helps!
Comment: i get this error i do that
Error fetching data: SyntaxError: Expected double-quoted property name in JSON at position 691 (line 19 column 7)
    at JSON.parse ()
    at fetchData
Comment: Can you validate your API response? Check if the response returned is serialized properly as JSON or not. If the JSON string is valid, parse should work as expected.
Comment: Yes, the data is properly serialized as JSON. It follows the JSON (JavaScript Object Notation) format, with key-value pairs, arrays, and nested objects. Each property is enclosed in double quotes, and the structure is well-formed, making it valid JSON data.
Comment: Would you be able to provide the JSON snippet here for line 19 as the error states?
Comment: {
      "id": 2,
      "name": "Red Mangrove",
      "species_name": "Rhizophora mangle",
      "image": {
        "src": "https://upload.wikimedia.org/wikipedia/en/1/16/Red_mangrove-everglades_natl_park.jpg",
        "alt": "A free-standing red mangrove tree growing in shallow water in the backcountry of the Cape Sable area of Everglades National Park.",
      }
    },
Comment: Please remove the comma at the end of the "alt": "A free-standing red mangrove tree growing in shallow water in the backcountry of the Cape Sable area of Everglades National Park.",  as it is not required in the JSON structure. This is the issue that prevents the parse.
Comment: is this because of the , in the end of the alt object?
Comment: Yes. Comma at the end violates the JSON structure.
Comment: Thank you. that helps. Do you know how can i remove it from the public API?
Comment: Validate this by copying the JSON from the response and do the change and see if the parse is happening. If that is the case, contact the team  of the API or raise an issue if possible.


Fast solutions to simple geometry problem

Question: What is an elegant (read: computation-minimal) solution to the following problem?
Find $v_{\alpha}\in\mathbb{R}^3$ such that the angle between $v_{\alpha}$ and $w=(1, 1, 1)^T$ is $\alpha$.
Answer: The angle between non-zero vectors $u,w\in\mathbb{R}^3$ is defined by
$$\cos\alpha = {u\cdot w\over ||u||\;||w||},$$
where $\cdot$ denotes the dot product in $\mathbb{R}^3$.
In your case, you know the vector $w$ and the angle $\alpha$.
Answer: $w\,\cos\alpha+u\,\sin\alpha$, where $u=\sqrt{3/2}\,(1,0,-1)^T$.
If OP gives some context, I may add details, but without that I can't know which details they need. It's just one solution out of infinitely many, so I wonder why it wouldn't matter which one you get.
Comment: There is no context, I made this up while trying to think of problems, which would normally be solved by computation, but also admit a quick geometric argument.


creating a new arrays from a existing array of arrays

Question: How can I create a new array without doing for each? The new array should be as follows
labels : ["Direct", "Organic Search", "Referral"]

any suggestion using javascript?
Comment: Use `for-loop`/`Array#map` then..Do share your code instead of image...
Comment: `Input.map(function(item){ return item[0]; })`
Comment: without doing for each ,you need to write all steps for create array ! Longer code will be...
Comment: What are these numbers?
Answer: Ok. Don't want Array.forEach()? Try using Array.map function with ES6 arrow function expression for such case:
// supposing arr is your initial array
var labels = arr.map((v) => v[0]);
console.log(labels);  // ["Direct", "Organic Search", "Referral"]

Comment: ES6... Much incompatible. OP didn't tag the question with ES6, nor hinted at using it. This answer is in a different language than the question is.
Comment: ES6 ... we believe in future and technical progress
Comment: Envy? No. This answer is incompatible with the question, in it's current form.
Comment: @Cerbrus, I have encountered numerous similar questions on SO which has "successful" ES6 answers(at least, they were accepted by Ops)
Comment: Because the answers conveniently fail to mention compatibility issues, which the OP will find out after using the code for a few weeks. If you're answering a JS question, always explain that you used ES6.
Comment: @Cerbrus, I've added a note, how about that?
Answer: You can try following
var arr1 = []; // your main array

var labels = arr1.map(function(item){
   return item[0];
});

For reference, map
Answer: It's not possible to do this without any kind of loop, but as you're suggesting, a manual iteration like a foreach isn't what you're looking for, indeed.
Array.prototype.map() is the function you need in this case. ("under the hood", it's still a loop)
Here's how you can use map to get your desired result:

var myArray = [["a", 1, 2], ["b", 3, 4], ["c", 5, 6]];
var result = myArray.map(function(current){ // For each item in `myArray`
    return current[0];                      // return it's first element.
});                                         // And use that in `result`.

console.log(result)

Note that myArray.map does not change the value of myArray. You'll need to store the returned value from .map somewhere.
If you don't need to worry about supporting anything but the latest browsers, you can make this slightly shorter, using ES6:

var myArray = [["a", 1, 2], ["b", 3, 4], ["c", 5, 6]];
var result = myArray.map((c) => c[0]);

console.log(result)


Chance that sample contains more individuals from one group than from another

Question: Question:

18 men and 12 women have agreed to participate in a randomized
controlled experiment. A simple random sample of 15 of these 30 people
is chosen as the treatment group; the others form the control group.
a) Find a decimal value for the chance that the treatment group contains more women than men.
b) Find the chance that all the women are in the same group.

For a) I chose the hypergeometric distribution as it is sampling without replacement. I set it up in the following way:
$\frac{\binom{12}{8} \cdot \binom{15}{7}}{\binom{30}{15}} + \frac{\binom{12}{9} \cdot \binom{15}{6}}{\binom{30}{15}} + ... + \frac{\binom{12}{12} \cdot \binom{15}{3}}{\binom{30}{15}}$
Is this a correct approach to the problem?
for b) I am confused why it can't be $\frac{\binom{12}{12} \cdot \binom{15}{3}}{\binom{30}{15}}$. I think the $\frac{1}{2}$ should also be taken into account for choosing between either the Treatment Group or Control group, but I don't know how to use this information.
Answer: Your approach for a) is correct.
As for part b),you must multiply by 2 instead of $\frac{1}{2}$. Another way to calculate this is $2\cdot\frac{\binom{18}{15}}{\binom{30}{15}}$, i.e. by looking at the 15 men in the other group.
Comment: does the 2 only come from the fact that it could be in one group OR the other?
Comment: Right, this is the reason!


How to code custom entity to access more than one database table?

Question: I have an entity that uses two tables, when I describe it in hook_entity_info() as far as I know I can only tell it about the base table. The base table is subscriber, I also have a table disease_catagories which stores the results of a select list. (stores the subscriber id, and the taxonomy term id. It can store any number of items with the same subscriber id and different taxonomy term ids)
I need the entity to contain an array of those taxonomy term ids, but I don't know how to connect that database table with the base table. are there any good articles that discuss how to attach a second table to the entity (maybe as field data)?
Comment: Entity API only knows how to work with one. Other related data would be considered field data I think
Comment: Do you know of any good articles about how to work with field data in this case?
Comment: 'Fraid not. Maybe you could edit the question and add some more specific details about the architecture/what's in the tables etc. Might make it easier to understand what you're looking for and how core/contrib can help
Comment: You should be able to tack on anything you like as property data but you'll be responsible for that in your load function.
Comment: Do you know of any good articles/documentation/videos that explain how to do that? I have been looking, but so far everything has either been way too complicated or not addressed the issue.
Answer: Entity API itself can only interact with one base table for joining to fields, querying with EntityFieldQuery, loading/saving revisions, etc, but you can use more than one table for storage if you implement your own storage controller which you can specify in your hook_entity_info().
You'll want to subclass DrupalDefaultEntityController and override the load() method and buildQuery() method if you want some EntityFieldQUery support.
If you are using Entity API module, you'll want to extend EntityAPIController and override the save(), load(), and delete() methods for full CRUD support.


A company hires 13 new people who has to be distributed over 2 cities --- 5

Question: A company hires 13 new people who has to be distributed over 2 cities --- 5 in New York and 8 in Tokyo. Bob and Jim are in this group of new employees. How many ways can these 13 people be assigned so that Bob and Jim do not work in the same city ?
Please help!
Answer: HINTS

Each valid way assigns other 11 employees into groups of $5-1=4$ and $8-1=7$.
For each of these assignments, we can have Jim with 4 and Bob with 7 or vice versa.
Answer: Let's re-frame this problem - a method which tends to be useful in many types of math problems (particularly in my opinion statistics problems).
Consider the group without Bob and Jim, we will deal with them later!
You are then left with 11 employees, of which 4 need to go to New York, and 7 need to go to Tokyo. This is a much simpler problem! Simply take $11 \choose 4$ to pick the 4 which need to go to New York! (Note it would have been equally acceptable to take $11 \choose 7$ which is equal to $11 \choose 4$!)
If you are unable to see why this is the case, then I would recommend reading up on some more basic combinatorial problems (i.e. books on a bookshelf!)
Now, you can either have Bob join New York, or Bob join Tokyo (this forces Jim to Tokyo or New York, respectively). This is the same as asking "How many ways can you have two people, work in two different cities?" The answer is of course $2$.
So, we know that, there are $11 \choose 4$ ways to arrange the other $11$ individuals (which equals $330$) and then there are 2 ways to arrange Bob and Jim. $2 \times 330 = 660$.


Distributive Property: How come I get a different answer by distributing than by solving inside the parenthesis first?

Question: Consider the closed phrase:
$$-(2\cdot2\cdot2\cdot2)$$
If I distribute $-1$, I get:
$$-1(2\cdot2\cdot2\cdot2)=
   -2\cdot-2\cdot-2\cdot-2=
    16$$
If I solve in the parenthesis first:
$$-(2\cdot2\cdot2\cdot2)=-(16)=-16$$
Aren't both of these valid ways to solve this phrase?
Comment: multiplication does not distribute over multiplication
Comment: @LordSharktheUnknown Ah, that *would* make a difference. Thank you!
Comment: The distributive property would tell you that $-1 \times(2 + 2 + 2 + 2) = -1 \times 2 + -1 \times 2 + -1 \times 2 + -1 \times 2 $.
Comment: You would be correct to say that the $-1$ multiplies everything in the bracket ... but you would need to understand that $2 \times 2  \times 2 \times 2$ only counts as one thing.
Comment: @DonaldSplutterwit Right! One term. So the distributive property applies only to terms within a group?
Comment: That's right ... littleO's example illustrates several terms ... yours only has one.
Comment: Thank you all! I would be happy to accept an answer that explains that I was mis-using the distributive property.
Answer: The distributive rule says that if $a,b,$ and $c$ are numbers then
$$
a(b + c) = ab + ac.
$$
However, there is no rule which says that
$$
\underbrace{a(bc) = (ab)(ac)}_{\text{usually false}}.
$$


Como calcular e exibir o resultado de uma operação, pegando os dados de um formulário, e enviando a resposta na mesma página abaixo do form?

Question: <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Calc PHP</title>

        <form method="post" action="index.php" id="form">
            Valor 1: <input type="number" name="num1" id="v1">

            Valor 2: <input type="number" name="num2" id="v2">

            <select name="cal" id="campo">
                <option value="add">Somar</option>
                <option value="sub">Subtrair</option>
                <option value="mult">Multiplicar</option>
                <option value="div">Dividir</option>
            </select>
            <button type="button" value="submit"     onclick="mostraResultado()">Calcular</button>
        </form>

Comment: Qual o erro amigo?
Comment: Posta o html tbm.
Comment: Então, é uma coisa bem simples que eu quero, o form pega os dois valores e escolhe qual operação quer realizar, depois aperta no botão enviar. Até ai tudo bem, mas o problema é que eu quero o mostrar o resultado do cálculo abaixo do botão, tipo "O resultado deu tal". E eu não consigo fazer isso. Ele não aparece nada quando eu aperto no enviar
Comment: Ele não vai aparecer porque o seu button é um submit. Troca o type do seu button para button mesmo... <button type="button"...
Comment: Eu arrumei isso, mas não aparece nada mesmo assim
Comment: `valor1` e `valor2` são os elementos do DOM, você não precisa pegar os valores deles, não? Algo como `valor1.value + valor2.value`?
Comment: eu já alterei isso, e mesmo assim não ta aparecendo nada
Comment: Então atualiza a sua pergunta com o código atual.
Comment: Já atualizei o código
Comment: Por quê `resultado.value`? Por favor, preste mais atenção no que está fazendo e, principalmente entenda o que está fazendo. Tentativa e erro não levará a nada.
Comment: Segue exemplo: https://jsfiddle.net/r6kjsbmv/5/
Answer: Seu código faltou algumas coisas como pegar o valor do que está sendo digitado e transformar o valor em tipo number.

function mostraResultado(){
    var form = document.getElementById("form"); // acho que não precisa
    var valor1 = document.getElementById("v1").value;  // pega os valores
    var valor2 = document.getElementById("v2").value;
    var opcao = document.getElementById("campo").value;
    var divMostrar = document.getElementById("mostrarResultado");

    switch(opcao){
        case "add":
          var resultado = Number(valor1) + Number(valor2); // altera para number
          divMostrar.textContent = "O resultado é " + resultado;
        break;
        case "sub":
          var resultado = Number(valor1) - Number(valor2);
          divMostrar.textContent = "O resultado é " + resultado;
        break;
        case "mult":
          var resultado = Number(valor1) * Number(valor2);
          divMostrar.textContent = "O resultado é " + resultado;
        break;
        case "div":
          var resultado = Number(valor1) / Number(valor2);
          divMostrar.textContent = "O resultado é " + resultado;
        break;
     }

}

   <form method="post" id="form">
       Valor 1: <input type="number" name="num1" id="v1">

       Valor 2: <input type="number" name="num2" id="v2">

       <select name="cal" id="campo">
          <option value="add">Somar</option>
          <option value="sub">Subtrair</option>
          <option value="mult">Multiplicar</option>
          <option value="div">Dividir</option>
       </select>
       <button type="button" value="submit"     onclick="mostraResultado()">Calcular</button>
    </form>

Comment: Ok, mas ainda não é o resultado que eu queria. Pq eu quero o resultado na mesma página e não em outra. O resultado teria que aparecer embaixo do formulário na mesma página, entende?
Comment: Só que como vc quer mostrar o resultado em uma div no próprio form, se a função está no botão de submit do form? Quando apertar o botão Calcular ele vai enviar o form, não vai ter tempo de mostrar nada.
Comment: O que tá acontecendo é que o script limpa a tela antes de mostrar o resultado. Ou seja, ele apaga o form. Eu quero que não apague o form, e o resultado apareça embaixo do form
Comment: Mas é claro que vai limpar, pq como disse a função está associada ao botão que envia o form.
Comment: Então como eu poderia fazer pra não acontecer isso?
Comment: Esta index.php que é pra onde o form é submetido é a mesma página que está o form? Qual é a página que tem o form?
Comment: O form ta na index.php
Comment: Editei a resposta, veja se é istoi.
Comment: Teria que ser depois do botão, mas é isso aí. Eu também já consegui aqui. Valeu mesmo cara ;)


Capitalizing first word of a book title

Question: Have to make the following test pass:
require 'book'

describe Book do

  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      @book.title.should == "Inferno"
    end

I'm not sure what I have to do. I have the following code:
class Book
@book = Book.new
def title
    x = @book
    y = x.split("")
    y[0] = y[0].upcase
    z = y.join("")
    z
end

end

but it won't pass, what am I supposed to do?
Comment: "_It won't pass_" is not an adequate problem report. What data did you feed in? What results were you expecting? What did you actually get? What steps have you taken to try and fix the issue?
Answer: Write customized Book#title= and Book#title methods to pass the RSpec tests.
class Book
  def title=(t)
    @title = t.capitalize
  end

  def title
    @title
  end
end

Capitalizing first word of a book title


PHP Storm, identação

Question: Olá, alguém sabe como mudar, ao identar automaticamente o código no PHP Storm as chaves não pularem a linha?
Answer: Você pode alterar isso em:
<code>"File" > "Settings" > "Code Style" > "PHP" > "Wrapping and Braces"
</code>
Terá o seguinte campo:

Enquanto estiver "Next line" ele irá pular a linha, se estiver "End of line" manterá na mesma linha.

PHP Storm, identação