Why subscribe/unsubscribe button in the custom entity named group cannot appear?

Question: I have created a custom render in group_module.js exactly as the example Rendering Entities with the exception of the line items['group/%'] = { instead of items['team/%'] = {. All other content nodes but group nodes (group/%) show ok. Group nodes show no subscribe/unsubscribe button and no menu tabs mentioned below in the groups_menu_module.js. I suppose that this module, groups_menu_module.js, is not loaded somehow.
I have to mention that without the custom rendering of entity group and with 2 LOCAL_TASK_MENU menu tabs, everything works perfect.
groups_menu_module.js
function groups_menu_module_menu() {
  try {
    var items = {};
    items['group/%']={
      title: 'view',
      page_callback: 'drupalgap_get_entity',
      page_arguments: ['groups_menu_module_default_page', 'node', 1]
    };
    items['group/%/provoli'] = {
      title: 'view',
      type: 'MENU_DEFAULT_LOCAL_TASK'
    };
    items['group/%/melh'] = {
      title: 'members',
      type: 'MENU_LOCAL_TASK',
      page_callback: 'groups_menu_module_melh_page',
      page_arguments: [1],
      title_callback: 'groups_menu_module_melh_page_title',
      title_arguments: [1],
      access_callback: 'groups_menu_module_page_access',
      access_arguments: [1],
      options: {
        reloadPage: true
      }
    };
    items['group/%/anarthseis'] = {
      title: 'posts',
      type: 'MENU_LOCAL_TASK',
      page_callback: 'groups_menu_module_anarthseis_page',
      page_arguments: [1],
      access_callback: 'groups_menu_module_page_access',
      access_arguments: [1],
      options: {
        reloadPage: true
      }
    };
    return items;
  }
  catch (error) {
    console.log('groups_menu_module_menu - ' + error);
  }
}

function groups_menu_module_default_page(node) {
  try {
    var content = {};
    content['title'] = { markup: node.title };
    return content;
  }
  catch (error) {
    console.log('groups_menu_module_default_page - ' + error);
  }
}

I have to mention that all functions needed are present in the actual .js file, i just opted them out because i think they are irrelevant.
The pageshow function of the other module is as the example in the above link:
group_module.js
function example_team_pageshow(nid) {
  node_load(nid, {
    success: function(node) {
      var content = node.title; // Add other content here...
      $('#' + example_team_container_id(nid)).html(content).trigger('create');
    }
  });
}

So to conclude the question is how to make the subscribe/unsubscribe button appear in the custom entity render? How to call og_ui_field_formatter_view() from my module to make the button appear?
I don't know if i made my self clear what is needed. If anyone need more information please ask so in the comments below to clarify some points.
Answer: Since you are taking over the display of Organic Groups nodes using your custom page callback path group/%, DrupalGap doesn't know to apply the field format view functions to your fields. Essentially you need to manually create/render your own widgets in your page_callback:
var content = {};
content.title = { /* ... */ };
content.subscribe = { /* ... */ };
return content;

There are helper functions in the og.js file related to joining/leaving groups that will be of help. From there just use simple HTML/CSS/JS to build your button(s) (perhaps with an onclick handler) to help the user interact with the group subscriptions.
If you want to call the og_ui_field_formatter_view() function directly (not recommended) you can, you just need to pass it all the correct parameters:
(entity_type, entity, field, instance, langcode, items, display)

the entity_type is typically 'node'
the entity will be the fully loaded JSON of the entity (already delivered to your page_callback)
the field and instance can be retrieved from http://api.drupalgap.org/7/global.html#drupalgap_field_info_field and http://api.drupalgap.org/7/global.html#drupalgap_field_info_instance respectively.
the langcode will most likely be und unless you are using a multi-lingual site
the items will be the value(s) within the field itself
the display you should default to { type: 'og_group_subscribe' }.

Not the easiest things to do to be honest, and you'll probably find yourself happier in the long run by building your own custom widget to subscribe/unsubscribe from the Group.
Feel free to copy any code you need from the og.js file to make your life easier.
Comment: @tyler-frankestein So there is no other way of calling `og_ui_field_formatter_view()` from my module or altering the onclick handler? Of what i understand, what you suggest is making the button from scratch?
Comment: I've updated my answer to include details about calling the function directly, but as you noticed, I'd really recommend just building the widget from scratch, that way you have complete control over it.


How do I manage breadcrumbs when the node uses multiple vocabularies?

Question: I have a blog in Drupal 8 and it uses the Categories vocabulary to display breadcrumbs as Home > Blog > [Category] > Post title.
I added taxonomies from the Tags vocabulary, which means every post can have one category, and multiple tags. Since I added the Tags vocabulary, it has taken over the breadcrumbs on individual blog posts, which are now Home > Blog > [Tag] > Post title.
Is it possible to control which vocabulary should have priority when it comes to displaying breadcrumbs?
Is it possible to control which vocabulary is displayed on blog posts based on where the user came from? For example, if the user is on the individual Tag page (Home > Blog > [Tag]) and clicks on a blog post belonging to that tag, the blog post should display the breadcrumbs using the Tags vocabulary (Home > Blog > [Tag] > Post title). However, if the user is on the individual Category page (Home > Blog > [Category]) and clicks on a blog post belonging to that category, the blog post should display the breadcrumbs using the Category vocabulary (Home > Blog > [Category] > Post title).
Comment: Afaik, default drupal breadcrumbs match the url path. Adding or removing tags wouldn't affect breadcrumbs unless the url pattern depended on them. It sounds like you're probably not using the default breadcrumbs so the first thing I'd do is try to determine how your breadcrumbs are currently being created.
Comment: Do you have a single field with both vocabs enabled, or one field for each vocab?
Comment: Each vocab has a dedicated field (unique machine name).
Comment: Blog post URL does not contain category, nor the tag. It's just /blog/post-title for every blog post.
Answer: Here's a solution that worked for me.
<code>function [YOUR-MODULE-NAME]_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {

  // Control Blog Post Breadcrumb Taxonomy Trail
  $blogPostBreadcrumb = new BlogPostBreadcrumb();
  $blogPostBreadcrumb->alter($breadcrumb);
}

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Entity\EntityBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Exception;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class BlogPostBreadcrumb
 *
 * The purpose of this class is to control Blog post breadcrumbs, as described here:
 *
 * RULE 1:
 * When the user is on the Tag page (Home > Blog > Tag) and clicks on a blog post, the blog post breadcrumbs will
 * display: Home > Blog > [Tag Name] > Blog Post Title
 *
 * RULE 2:
 * When the user is on the Category page (Home > Blog > Category) and clicks on a blog post, the blog post breadcrumbs
 * will display: Home > Blog > [Category Name] > Blog Post Title
 *
 * RULE 3:
 * When the user loads the blog post directly (i.e. Home > Blog, or comes from other sources unrelated to
 * Category or Tag), the blog post breadcrumbs should default to Category:
 * Home > Blog > [Category Name] > Blog Post Title
 *
 */
class BlogPostBreadcrumb
{
  /**
   * @param Breadcrumb $breadcrumb
   */
  public function alter(Breadcrumb &$breadcrumb): void
  {
    try {
      // current node
      $current_node = $this->currentNode();

      // nothing found, nothing to do
      if (empty($current_node)) {
        return;
      }

      // what is the current content type
      $content_type = $this->getField($current_node, 'type');

      // apply rule only to blog_post content type, otherwise let's stop the madness right here
      if ($content_type !== 'blog_post') {
        return;
      }

      // determine if the tag can be extracted from referrer. If not, default it to college_tag
      $altered_breadcrumb = $this->getTaxonomyLabelAndUrlByReferrer()
        ?? $this->getTaxonomyLabelAndUrlByCollege($current_node);

      // nothing matched - just let it be. Display blog_tags rather than nothing.
      if (empty($altered_breadcrumb)) {
        return;
      }

      // modify existing breadcrumb list by replacing the third link with proper tag
      // (Home > Blog > [college_tag/blog_tag] > Blog Title)
      $breadcrumb->getLinks()[2]->setText($altered_breadcrumb['label']);
      $breadcrumb->getLinks()[2]->setUrl($altered_breadcrumb['url']);

      // we have to disable caching, otherwise whichever taxonomy opens first, it will get cached!
      // load menu_link_content entity
      $entity =  \Drupal::entityTypeManager()
        ->getStorage('menu_link_content')
        ->load($current_node->getEntityTypeId());
      // disable caching
      $breadcrumb->addCacheableDependency($entity);
    } catch (Exception $e) {
      // if any exception is thrown, we don't want to stop the page from loading.
      // Worse case scenario, it will load blog_tags into breadcrumbs.
    }

  }

  /**
   * Get Field from node
   * Helper method for retrieving field value from given node.
   *
   * @param EntityInterface $node
   * @param string $fieldName
   * @return mixed|null
   */
  protected function getField(EntityInterface $node, string $fieldName)
  {
    return $node->get($fieldName)->getValue()[0]['target_id'] ?? null;
  }

  /**
   * Load node from current url
   *
   * @return EntityBase|null
   */
  protected function currentNode():? EntityBase
  {
    if ($nid = \Drupal::routeMatch()->getParameter('node')) {
      return Node::load($nid->id()) ?? null;
    }
    return null;
  }

  /**
   * Determine Taxonomy Breadcrumb Label and Url by referrer
   * We want to display Breadcrumb category depending from where the user is coming from:
   * Blog College (category) or Blog tag page
   *
   * @return array|null
   */
  protected function getTaxonomyLabelAndUrlByReferrer():? array
  {
    // capture referrer the "Drupal way"
    $route_parameters = $this->referrer();

    // if type is not a taxonomy term, it's not used to us
    if (empty($route_parameters['taxonomy_term'])) {
      return null;
    }

    // load node (taxonomy term)
    $term = Term::load($route_parameters['taxonomy_term']);

    // get taxonomy type
    $taxonomy = $this->getField($term, 'vid');

    // check if taxonomy belongs to college_tags or blog_tags
    if (empty($taxonomy) && !in_array($taxonomy, ['college_tags', 'blog_tags'])) {
      return null;
    }

    // if we can't find the url or the label
    if (empty($term->url() || empty($term->label()))) {
      return null;
    }

    return [
      'label' => $term->label(),
      'url' => Url::fromUserInput($term->url())
    ];
  }

  /**
   * Determine Taxonomy Breadcrumb Label and Url by college
   * This method will be used when referrer page doesn't exist, or the referrer is not Blog Category or Blog Tag page
   *
   * @param EntityInterface $node
   * @return array|null
   */
  protected function getTaxonomyLabelAndUrlByCollege(EntityInterface $node):? array
  {
    // blog can have one college tag (category)
    $taxonomy_id = $this->getField($node, 'field_college');
    $term = Term::load($taxonomy_id);

    // if we can't find the url or the label
    if (empty($term->url() || empty($term->label()))) {
      return null;
    }

    return [
      'label' => $term->label(),
      'url' => Url::fromUserInput($term->url())
    ];
  }

  /**
   * Referrer node
   * Load referrer node the "drupal way"
   *
   * @return mixed
   */
  protected function referrer()
  {
    // this would be college_tag or blog_tag page
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    // fake the request to previous page, so we can get more info
    $fake_request = Request::create($previousUrl);
    // build url object.
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      return $url_object->getRouteParameters();
    } else {
      return null;
    }
  }
}
</code>


How do I set random effects of an lme model to zero or BLUP values?

Question: According to Modern Applied Statistics, 4th Ed, page 276, it states
"Random effects are set either to zero or to their BLUP values."
My question is: how do i code that in my call to predict.lme?  I thought I'd need something in the newdata variable to do that but I understand that setting the effects to zero is not the same as removing the random term. I don't understand why not.  What should my newdata look like?
My formula:
bee.lme <- lme(Resp ~ Season *  Rate, random = ~ 1|Hive,
                          data = data_sel, na.action = "na.omit")

version
                 _
  platform       x86_64-pc-linux-gnu
  arch           x86_64
  os             linux-gnu
  system         x86_64, linux-gnu
  status
  major          3
  minor          5.0
  year           2018
  month          04
  day            23
  svn rev        74626
  language       R
  version.string R version 3.5.0 (2018-04-23)
  nickname       Joy in Playing

Perhaps a better example is to use the model in the MASS book: pet5.lme <- lme(Y ~SG + VP + V10 + EP, random = ~ 1 + EP |No)
Comment: Perhaps a better example is to use the model in the MASS book:
Answer: To control the type of predictions you obtain you need to use the level argument of predict.lme(). Namely, if you set level to 0 you get the predictions for which the random effects are set to zero. In the case of linear mixed models, these correspond to population predictions. If you set level to 1 in your case, you get group-specific predictions which condition on the BLUPs of the random effects.
Comment: To my understanding, level =  0 would be the same as omitting the random term, but I've been informed that is not so.  Why is it different?
Comment: In the case of linear mixed models, and because you have the identity link function, the predictions you get by settling `level = 0` are population predictions. However, if you have a generalized linear mixed model for a categorical response variable, and because there you need a nonlinear link function, the predictions calculated omitting the random effects are not population predictions.
Comment: Are population predictions what are given by the default newdata term in the call to predict()?
Comment: The default is group-specific predictions, not population predictions.


Proof by induction, the difference of the same number is zero

Question: So I need to proof $n - n = 0$ for all n in the natural numbers, what we are allowed to use is: The predecessor and the $(-)$ operation
The predecessor base case: $P(0) = 0$
The predecessor step case: $P(S(n)) = n$, where $S(n)$ is the successor of $n$
$(-)$ base case: $n - 0 = n$
$(-)$ step case: $n - S(m) = P(n-m)$
My attempt:
For the base case: $0-0=0$ using base case of $(-)$
My induction hypothesis is that $n-n=0$ for all n in the natural numbers
Then my step case: $$S(n)-S(n)=P(S(n) -n)$$
I'm stuck right here I didn't know what to apply next. If I was able to switch $S(n)-n$ then I'll be able to apply the step case of $(-)$ then would have got my answer
Answer: What we want to use is that $P(j-k) = P(j)-k$. This would be useful in your last step as then $S(n)-S(n) = P(S(n) - n) = P(S(n))-n = n-n$. So we only have to prove that which is done by induction over $k$:
First we have that $P(j-0) = P(j) = P(j)-0$ by the definitions. Now assume that $P(j-k) = P(j)-k$ then we have:
$$P(j-S(k)) = P(P(j-k)) = P(P(j)-k)) = P(j)-S(k)$$
which proves the statement is true for the successor of $k$ as well and therefore by induction for all $k$.
To complete your proof we have that $S(n)-S(n) = P(S(n)-n) = P(S(n)) - n = n - n = 0$ which means that if the statement is true for $n$ then it's true for $S(n)$ too and by induction true for all $n$.


Is it possible to generate an $M$-order Hilbert Curve without consuming $O(M^2)$ memory?

Question: This question is admittedly very programming related, but I felt that it is better suited to the Mathematics crowd than Stack Overflow.

I would like to generate Hlibert walks through the pixels in an image (or really, any 2d coordinate space), but I would like to consume as little memory as possible.  However, given how the Hilbert curve is defined, I would be required to generate the moves (N, S, E, or W) all at once, consuming much more memory that I would like.
Is it even possible to generate a Hilbert curve in an "online" fashion, with sub-linear memory space with respect to the order of the curve?

For reference, this is the definition of the Hilbert curve that I'm using, giving relative directions:
$$\begin{align}
hilbert(order) &= A_{order+1} \\
A_0 &= [\,] \\
B_0 &= [\,] \\
C_0 &= [\,] \\
D_0 &= [\,] \\
A_n &= [B_{n-1}, N, A_{n-1}, E, A_{n-1}, S, C_{n-1}] \\
B_n &= [A_{n-1}, E, B_{n-1}, N, B_{n-1}, W, D_{n-1}] \\
C_n &= [D_{n-1}, W, C_{n-1}, S, C_{n-1}, E, A_{n-1}] \\
D_n &= [C_{n-1}, S, D_{n-1}, W, D_{n-1}, N, B_{n-1}]
\end{align}$$
An ideal implementation would be implementable as a "iterator" (C#, etc) or "sequence" (Haskel, etc)
Comment: Do you want 'the' Hilbert curve, or do you want _a_ Hilbert curve - that is, one that iterates over all of the 'pixels' in a $2^m\times 2^m$ grid stepping from one to another?  What criteria do you have on your path?
Comment: I would like to generate "the" Hilbert curve, which I would then adapt to my specific use case.  My only criteria is that the interface is a sequence of relative moves (N, S, E, W) and that it consumes a linear or sub-linear amount of memory with respect to the order.
Comment: That makes sense.  I believe it's possible in something like $O(\log m)$ time per step (and possibly even amortized to a total of $O(m^2)$ for all $m^2$ steps), similar to e.g. finding the value of the ruler function for the first $m$ values would be, but I'd have to do some more digging to be sure.  Can you possibly describe your particular use case?  It's certainly possible that you don't need 'the' curve at all...
Answer: I believe that I have found a solution, but I need help verifying its memory complexity.  I believe it to be O(n) with respect to the order of the curve, since the stack never grows beyond order elements, and each element is a constant size.
private static Dictionary<char, string> replacements = new Dictionary<char, string>
{
    { 'A', "BNAEASC" },
    { 'B', "AEBNBWD" },
    { 'C', "DWCSCEA" },
    { 'D', "CSDWDNB" },
};

private static IEnumerable<char> Hilbert(int order)
{
    if (order <= 0)
    {
        throw new ArgumentOutOfRangeException("order", "Must be a natural number.");
    }

    // Initialize the stack with A
    var stack = new Stack<string>(order);
    stack.Push(replacements['A']);

    while (true)
    {
        // Find the first non-empty string, clearing the stack of empty ones and terminating if none are found.
        var element = "";
        while (element == "")
        {
            if (stack.Count == 0)
            {
                yield break;
            }

            element = stack.Pop();
        }

        // Read the next command, c, from the found element and push the rest of the commands back on the stack.
        var c = element[0];
        stack.Push(element.Substring(1));

        switch (c)
        {
            // If the command is a movement, yield it.
            case 'N':
            case 'S':
            case 'E':
            case 'W':
                yield return c;
                break;

            // Otherwise, the command is a replacement.  Push the replacement onto the stack, unless the replacement should be empty.
            default:
                if (stack.Count < order)
                {
                    stack.Push(replacements[c]);
                }

                break;
        }
    }
}

Comment: ahh, I see - you're implicitly walking the tree, very similar to a DFS of all the positions of some game tree.  Yeah, this should work perfectly well and with a minimal space requirement - it looks good to me.
Comment: @Steven, I don't think that I will actually have 3/4 of the full path on the stack, since the elements in the stack are stored unexpanded.  Only when I encounter a replacement do I push the expanded form onto the stack.

This is essentially equivalent to a recursive solution, but is easier to implement as an iterator.
Comment: @StevenStadnicki: FYI, I'm treating the strings themselves as queues by taking a substring of all but the first character for each replacement.
Comment: @StevenStadnicki: Cool, thanks for your help!


Corollary to Preissman's theorem

Question: Preismann's theorem states (ref. Petersen's "Riemannian Geometry", chapter 6):

On a compact manifold with negative sectional curvature, any abelian subgroup of the fundamental group is cyclic.

A corollary is stated:

No compact product manifold admits a metric with negative curvature.

I don't understand how the corollary follows from the thoerem. Of course it would if, on a product manifold, there are always non-cyclic abelian subgroups of the fundamental group. Is this true? (It seems like it shouldn't be, taking for example the product of simply connected manifolds.)
Answer: Recall Cartan-Hadamard: If $K\le 0$ and $M^n$ is complete, then the universal covering space of $M$ is $\Bbb R^n$.
Comment: I don't understand how this helps. Can you explain a bit more?
Answer: Suppose that $M$ and $N$ are smooth compact manifolds. Suppose that $L=M\times N$ admits a metric of negative curvature. First, note that $\pi_1(L)$ is torsion-free: One can prove this by observing that, by Cartan's theorem, every finite group acting on a simply-connected complete manifold of nonpositive sectional curvature always has a fixed point (see Theorem 23, p. 164, in Peterson's book). Alternatively,  notice that a finite nontrivial group $G$ cannot act freely on a contractible manifold as $G$ has infinite cohomological dimension, while a free action on a contractible manifold would yield a finite-dimensional classifying space $K(G,1)$. In either case, if $\pi_1(L)$ contains a nontrivial element of finite order, the fundamental group cannot act freely on the universal cover of $L$, which is a contradiction with the basic covering theory.
Thus, unless $\pi_1(L)$ contains ${\mathbb Z}^2$, either $M$ or $N$ is simply-connected. Assume that $\pi_1(M)$ is trivial; in particular, $M$ is orientable. Since $M$ is compact, there exists $k\in [2, dim(M)]$ such that $H_k(M)\ne 0$ (you can take $k=dim(M)$). Therefore, if $X=M\times \tilde{N}$, is the universal cover of $L$, then $H_k(X)\ne 0$ (use Kunneth formula). This contradicts Cartan-Hadamard theorem which says that the universal cover of a compact manifold of nonpositive curvature is diffeomorphic to a Euclidean space.
Answer: Consider a product $M\times N$ with negative sectional curvature.
If $M$ has nonnegative sectional curvature, it would be a contradiction.
So abelian subgroup of fundamental group of $M$ is $0$ or ${\bf Z}$, since it has no torsion.
Hence $\pi_1(M\times N)=\pi_1(M)\times \pi_1(N)$ has abelian subgroup in ${\bf Z}^2$.
From given theorem, so abelian subgroup of
at least one factor of $M\times N$, say $M$, is $0$. Hence it is simply connected so that $M={\bf R}^n$. It contradicts to compactness.

Corollary to Preissman's theorem


Dynamically adding SQL Logins to DSC for Azure Automation Credentials

Question: I have a SQL Server on a VM being setup using a DSC file. I have been able to use SQL Login in the past (https://github.com/dsccommunity/SqlServerDsc/wiki/SqlLogin) but that only allows me to use it one at a time. I am trying to take all logins attached to my Azure Automation Credentials account and ensure the SQL Server has a login for each credential but I have not been able to figure out how to make it dynamic. I tried the following
<code>$logins = Get-AzAutomationCredential -ResourceGroupName "resourceGroup" -AutomationAccountName "automationAccount"

    foreach($login in $logins.Where{$_.UserName -like "*dbuser*"})
    {
        Write-Output "Creating Login"
        Write-Output $login.Name
        SqlLogin 'Add_User'
        {
            Ensure = 'Present'
            Name = $login.Name
            LoginType = 'SqlLogin'
            InstanceName = 'Instance'
            LoginCredentials = Get-AutomationPSCredential -Name $login.Name
            LoginMustChangePassword = $false
            LoginPasswordExpirationEnabled = $false
            LoginPasswordPolicyEnforced = $true
        }
    }
</code>
But, it seems like I cannot use Powershell when I am setting up the DSC so I am wondering if it is even possible to make this dynamic. Does anyone know how to do this dynamically?
Comment: Can you expand on what you mean by this "But, it seems like I cannot use Powershell when I am setting up the DSC"
Answer: Every DSC-resource that is added to your configuration needs to have a unique name, so that might be where the problem is. Could you change your SqlLogin 'Add_User' to maybe have a username part of its name, so it's SqlLogin "Add_User_$($login.Username)" and see if that helps.
It should be able to work as you have set it up. Though it is not completely dynamic, as it will create a mof-file that will then contain the variables you push in with the extra powershell scripting you are using.


Adding "email" and "profile" scopes to https://code.google.com

Question: Drive SDK API configuration still points to the old form at code.google.com, and it has a problem with the new "email" and "profile" scopes we need to add instead of the deprecated ones (https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email).
The problem is that the console doesn't allow this format: "email" / "profile" and fails with the error message:
<code>An unexpected error has occurred. We're looking into it.
</code>
Does anyone have a workaround for that?
Answer: These scopes have been deprecated for a long time and not otherwise suggested to be used even though it says that these scopes will be maintained for backward compatibility. If you still haven't done so, I'd suggest you to migrate to the profile and email scopes.
Comment: It looks like you haven't read the entire message. We are trying to migrate to the new scopes (email and profile), but the console doesn't allow them.
Comment: Excuse me for that, I think I misunderstood the issue at the moment. Does this issue still exist?
Comment: Yes, the issue still exists even in the new console (at https://console.developers.google.com). What I see is the same error message when trying to save "email" and "profile" instead of the deprecated url-like scopes: http://i.imgur.com/GRNC8SS.png. The scopes I'm trying to save are the following: http://i.imgur.com/GW49P6S.png


Proof of Cauchy-Schwarz in a Complex Inner Product space.

Question: Setup: Given a complex inner product space $V$ the Cauchy-Schwarz inequality is
$$
|\langle x,y \rangle|\leq \sqrt{\langle x,x \rangle} \sqrt{\langle y,y \rangle}.
$$
I know that the RHS is just the product of the induced norms that come from our inner product, but I don't want to pass to any properties of a norm function. I took the standard proof approach (I think?) but I'm not very comfortable with complex variables so I don't know if I'm doing any arithmetic that is invalid over $\mathbb{C}$. Any help would be appreciated!
Proof Attempt:
Define a function $f(t) = \langle x+ty,x+ty \rangle$. We can expand this inner product as
\begin{align*}
\langle x+ty,x+ty \rangle &= \langle x,x+ty\rangle + \langle ty,x+ty \rangle, \textrm{ linear in first arg.} \\
&=\langle x,x\rangle +\langle x,ty \rangle +\langle ty,x \rangle +\langle ty,ty \rangle, \textrm{ linear in second argument.}\\
&=\langle x,x \rangle + \overline{t} \langle x, y \rangle + t\langle y,x \rangle +t\overline{t} \langle y,y\rangle, \textrm{ conjugate linearity in second argument.}
\end{align*}
Now because $t \in \mathbb{C}$ we know that $t\overline{t} = |t|^2$. We also have by conjugate symmetry that
$$
\overline{t}\langle x,y \rangle= t \langle y,x \rangle.
$$
Now because the inner product is positive definite, we can conclude that
$$
0 \leq \langle x,x \rangle + 2\overline{t}\langle x,y \rangle +|t|^2 \langle y,y\rangle.
$$
Now just like in the case where we are over the reals, I would like to conclude by making the claim that this is a quadratic in $t$ that opens upwards, meaning it has no real roots and hence the discriminant $b^2-4ac \leq 0$ but I don't know if that's valid. It seems fair-ish because $\langle x,x \rangle$ and $\langle y,y \rangle$ are both real numbers, but is there a way to conclude that $\langle x,y \rangle $ is also a real number? I think I need $\langle x,y \rangle$ to be real to apply the quadratic formula right? I suppose intuitively $\langle x,y \rangle $ must be real because there's no ordering on $\mathbb{C}$ so for the inequality to make sense it has to be real?
Maybe more importantly, does it even make sense to think of it as a quadratic because I'm using $|t|^2$ and $\overline{t}$ as the parameters?
Comment: this $\overline{t}\langle x,y \rangle = \overline{\overline{t}\langle x,y \rangle} $ is false for a sesquilinear product. What you have is that $\overline{t}\langle x,y \rangle = \bar t\overline{\langle y,x \rangle} $
Comment: the usual proof decomposes $w$ in the product $\langle v,w \rangle $ as a sum of two orthogonal vectors, one of the form $rv$ for some $r\in \mathbb{C}$.
Comment: this $\overline{t}\langle x,y \rangle= t \langle y,x \rangle$ is still wrong. There you are assuming that $\bar zw=z\bar w$ for arbitrary complex numbers $z,w\in \mathbb{C}$, however if you took $z=1$ and $w=i$ you see that it cannot be true.
Comment: @AndreyYanyuk You may be interested in [this](https://math.stackexchange.com/questions/4419667/when-the-equality-in-the-cauchy-schwarz-inequality-holds/4419685#4419685).
Comment: Yeah i just realized as I was writing over but I can't figure out what the right approach is, trying to fix it now.
Comment: They are still equal though right @Masacroso, if I actually write out $t = \alpha+\beta i$ and $\langle x,y \rangle = a+bi$ then they do agree unless my arithmetic is wrong. Also is there a way to just modify my approach? We proved CS without leveraging orthogonality.
Comment: Yeah I just worked it out and saw my arithmetic was wrong. Is there any way to salvage this? Or I need to use orthogonality?
Answer: The correct formula is
$$(x + ty, x + ty) = (x, x) + (ty, ty) + 2\Re((x, ty)) = \|x\|^2 + 2\Re(\bar{t}(x, y)) + |t|^2\|y\|^2.$$
If you want to apply calculus wrt $t$, then let's assume that $t \in \mathbb{R}$. Then we get
$$0 \leq (x + ty, x + ty) = \|x\|^2 + 2t\Re((x, y)) + t^2\|y\|^2.$$
Then, since this is a parabola that opens upward and is above the $x$-axis, it has at most one real zero, so
$$4\Re((x, y))^2 -4\|y\|^2\|x\|^2\leq 0,$$
i.e.
$$|\Re((x, y))| \leq \|x\|\|y\|.$$
Now for any $\alpha \in \mathbb{C}$ with $|\alpha| = 1$, we can replace $x$ with $\alpha x$ to get
$$|\Re(\alpha(x, y))| \leq \|x\|\|y\|.$$
Cauchy's inequality comes from $\alpha = \frac{|(x, y)|}{(x, y)}$.
Comment: $x, y$ are arbitrary elements of $V$. We choose $\alpha$ because it yields Cauchy's inequality when you plug it in. In fact, our choice of $\alpha$ maximizes the lhs.
Comment: @AndreyYanyuk You can also view the parabola trick as minimizing the rhs of the first inequality over $t$. So the entire proof consisted of introducing auxiliary parameters, getting inequalities involving the parameters,  and then choosing the parameters to get the best inequality.
Comment: Yeah that's essentially what I did. You are just introducing $\alpha$ earlier than I am. Your $\alpha$ is the complex conjugate of mine.
Comment: So what is this choie of $\alpha$ doing? Are we forcing $\langle x,y \rangle $ to be real?
Comment: Thanks its a lot clearer now. What do you think about assuming that $\langle x,y \rangle$ is strictly positive without loss of generality? Because if pick an $\alpha \in \mathbb{C}$ for which $\langle x ,\alpha y \rangle$ is strictly positive, we have $|\langle x, \alpha y \rangle | = |\alpha| \langle x,y \rangle$ and $\sqrt{\langle \alpha y, \alpha y \rangle} = |\alpha| \sqrt{\langle y,y \rangle}$ so the addition of this $\alpha$ term has no bearing on the CS inequality? Does that make sense?
Comment: Ah I hadn't put it together! Thank you very much!


Devel 'Display Query Log' not showing any queries

Question: I've enabled 'Display Query Log' in the Devel Settings but I don't see any logged at the bottom of my page when I load a page. I just get 'Queries exceeding 5 ms are highlighted.'.
I'm running Drupal on PHP 5.3.2 with a mySQL database.
The issue is present in both the Admin theme and my custom theme.
Other Devel outputs seem to display fine.
Any ideas why the queries aren't showing?
Comment: May be your queries are getting executed before 5 ms. :) try with 1ms. and ' Collect query info' is also checked ?
Comment: I've tried this. Doesn't seem to be working.
Comment: worst case scenario uninstall the devel module and install it again.
Answer: You need to check 'Collect query info' in the devel settings: /admin/settings/devel
Otherwise no logs can be shown.
Answer: The admin module routinely breaks this. Try disabling it.
Answer: I often forget to set appropriate user permissions on the devel module when I re-enable it.
Comment: Probably not in OP's case, where he can see the 'Queries exceeding 5 ms are highlighted.' line.
But others might not see any output at all, because of the permissions you mention.


Difference of notation between cross entropy and joint entropy

Question: Although it is clear to me, how the two concepts differs, it has been difficult for me to find a notation that would make it clear, to which type of entropy we refer.
From wikipedia, we can see that joint entropy of two random variables are defined in terms of the probability of the possible outcomes:
https://en.wikipedia.org/wiki/Joint_entropy
However, for the slightly more subtle definition of cross entropy, which is not symmetric, uses the concept of ditribution, but the notation is the same:
https://en.wikipedia.org/wiki/Cross_entropy
This "misleading" notation for cross entropy is also shown on the wikipedia page for Kullback-liebler definition: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence
To me, it looks like $H(X,Y)$ is fine for defining joint entropy, but what should I use then for cross entropy ?
Answer:
Note that this notation for cross-entropy is non-standard. The normal notation is H(p,q). This notation is horrible for two reasons. Firstly, the exact same notation is also used for joint entropy. Secondly, it makes it seem like cross-entropy is symmetric. This is ridiculous, and I'll be writing Hq(p) instead.

Reference from link:
http://colah.github.io/posts/2015-09-Visual-Information/#fn4
Also, possible duplicate of :
https://math.stackexchange.com/questions/2505015/relation-between-cross-entropy-and-joint-entropy
Comment: Relevant blog post, and the answer from the possible duplicate (although the initial question was different) makes sens. Writing $H_p(q)$ makes much more sense as it emphasize that the reference for optimal coding is p, and the target of the analysis in this framework is distribution q
Comment: Here's a new one on notation for cross-entropy: https://chris-said.io/2020/12/26/two-things-that-confused-me-about-cross-entropy/


Action for changing the color of layer?

Question: My game consists of a single scene which is a LayerColor. However, as I transition between "levels", I would like to change the background color via a smooth transition.
For example, if the
 rgb values of level 1 is (100,50,70) , and the
 rgb values of level 2 is (200,30,123).
Over a period of a few seconds, I would like to slowly modify the rgb values of the layer color from the level 1 value to the level 2 value.
Is it possible to do this using a cocos2d action ?
EDIT:
I do not wan't to tint all the children of my layer.
My scene is of type layer color:
class MyScene : public cocos2d::LayerColor

In Init I set the color:
bool MyScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !LayerColor::initWithColor(Color4B(10, 20, 200, 255) )) {
        return false;
    } ....

I don't wan't to tint the entire scene. I only want to change the color.
Answer: Use cocos2d::TintTo action:
auto layer = cocos2d::LayerColor::create(cocos2d::Color4B(100, 50, 70, 255));
...
layer->runAction(cocos2d::TintTo::create(2.0, 200, 30, 123));

Comment: Sorry - I guess I wasn't clear. I don't want to tint the entire scene and all the children. I just want to change the background color.
Comment: `cocos2d::LayerColor::setColor` doesn't change color of it's children, unless You called layer->setCascadeColorEnabled(true);

Action for changing the color of layer?


How to evaluate $\lim\limits_{x\to 0}\frac{e^{5x}-(1+x)^9}{\ln(1+x)}$ without L'Hôpital's rule?

Question:
Evaluate: $$\lim\limits_{x\to 0}\frac{e^{5x}-(1+x)^9}{\ln(1+x)}.$$

This is an exercise problem from my book. I couldn't solve the problem without using L'Hôpital's rule. Here is my solution that uses L'Hôpital's rule:
Since we achieve $\frac00$ in the limit, we can use L'Hôpital's rule. Then, we have
$\lim\limits_{x\to 0}\frac{e^{5x}-(1+x)^9}{\ln(1+x)}$ $=\lim\limits_{x\to 0}\frac{5e^{5x}-9(1+x)^8}{\frac{1}{1+x}}\\ =(1+0)(5e^0-9\cdot 1^8)\\ =-4$
I need a solution that doesn't use L'Hôpital's rule.
Comment: Can you do a Taylor expansion ? If not, what are your tools ?
Answer: \begin{align}
\lim_{x\to 0}\frac{e^{5x}-(1+x)^9}{\ln(1+x)}&=\lim_{x\to 0}\frac{x}{\ln(1+x)-\ln1}\left(\frac{e^{5x}-1}{x}-\frac{(1+x)^9-1}{x}\right)\\
&=\frac1{\left.\left(\ln(1+x)\right)'\right|_{x=0}}\left(\left.\left(e^{5x}\right)'\right|_{x=0}-\left.\left((1+x)^9\right)'\right|_{x=0}\right)\\
&=5-9\\&=-4
\end{align}
Comment: You are cheating a little bit by using a "personalized" proof of L'Hôpitals rule instead of the rule itself.
Comment: @KayK. Don't get me wrong, I like this approach...
Comment: This is a clever answer but I can't imagine this is what the question asker (professor, textbook author, not OP) had in mind
Comment: @PierreCarre This usually doesn't work in general, because when the numerator is separated into sum of two terms then usually each of two terms doesn't converge individually. But, in this case it does. So there's no reason to not do this way.
Comment: But you don't need to separate the terms right? Just write $e^{5x} - (1+x)^9 = x \left( \frac{e^{5x} - (1+x)^9 - 0}{x}\right)$.
Comment: @ArcticChar Yeah I just realized after I saw PierreCarre's solution.
Answer: Just use Taylor Expansion, $$e^{5x}=1+5x+\frac{25}{2!}x^2+\frac{125}{3!}x^3+....$$
$$(1+x)^9=1+9x+36x^2+^9C_3x^3+^9C_4x^4+....$$
$$\ln(1+x)=x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}+...$$
Plugging in the above equation $1$ cancels out in the numerator and taking  $x$ common from numerator and denominator and cancelling it out gives answer=$-4$ as rest of the terms have a power of $x$ and become =$0$ on applying the limit.
Note: I didn't write the further terms to save time as anyways all powers of $x$ will vanish on applying the limits.
Answer: I'll assume that you can use some "known" limits...
\begin{align*}
\lim_{x\to 0}\frac{e^{5x}-(1+x)^9}{\ln(1+x)}=&\lim_{x\to 0}\dfrac{e^{5x}-(1+9x+36x^2+ \cdots)}{\ln(1+x)}=\lim_{x\to 0}\dfrac{e^{5x}-1}{5x}\dfrac{5x}{\ln(1+x)} -\\
& \lim_{x\to 0}\dfrac{9x}{\ln(1+x)} -\lim_{x\to 0}\frac{36 x^2 + \cdots}{\ln(1+x)} = 5 -9 -0 = -4
\end{align*}

$$
\lim_{x\to 0} \frac{e^x-1}{x} = 1
$$
$$
\lim_{x\to 0}\frac{\ln(1+x)}{x} = 1
$$
Answer: Another way:
$$\begin{aligned}\lim_{x\to 0}\frac{e^{5x}-(1+x)^9}{\ln(1+x)}&=\lim_{x\to 0}\frac{e^{5x}-1+1-(1+x)^9}{\ln(1+x)}\\&=\lim_{x\to 0}\left(\frac{e^{5x}-1}{5x}\cdot\frac{5x}{\ln(1+x)}-\frac{(1+x)^9-1}{\ln(1+x)}\right)\\&=\lim_{x\to 0}\left(\frac{e^{5x}-1}{5x}\frac{5x}{\ln(1+x)}-\frac{e^{9\ln(1+x)}-1}{9\ln(1+x)}9\right)\\&=5-9\\&=-4\end{aligned}.$$
I would also recommend taking a look at this somewhat related answer.


R's stats::aov and nlme::lme produce conflicting results

Question: I want to use both anova and linear models to test the assumption that my some of my categories have different means than the rest.
I am using stats::aov for anova and nlme::lme for linear modelling. The full code is available in this notebook.
Basically I end up getting:
Error: ID
          Df  Sum Sq  Mean Sq F value Pr(>F)
Residuals  6 0.01198 0.001997

Error: Within
          Df  Sum Sq  Mean Sq F value Pr(>F)
COI        7 0.01926 0.002752    1.92 0.0903 .
Residuals 42 0.06020 0.001433

and
Fixed effects: ER ~ COI
                      Value  Std.Error DF   t-value p-value
(Intercept)      0.00200000 0.01465712 42 0.1364525  0.8921
COIemotion-hard  0.05600000 0.02023699 42 2.7672098  0.0084
COIscrambling-06 0.04218045 0.02023699 42 2.0843242  0.0433
COIscrambling-10 0.02094737 0.02023699 42 1.0351029  0.3065
COIscrambling-14 0.00685714 0.02023699 42 0.3388420  0.7364
COIscrambling-18 0.02085714 0.02023699 42 1.0306445  0.3086
COIscrambling-22 0.04885714 0.02023699 42 2.4142493  0.0202
COIscrambling-26 0.02742857 0.02023699 42 1.3553681  0.1825

Which means that lme is telling me 3 groups may significantly lie outside the range of the others, while aov is telling me the probability of ANY GROUP AT ALL being different from the others is not significant (using a p=0.05 cutoff).
What am I to make of this?
Do I understand these results correctly?
Comment: It is a well-known fact that a non-significant omnibus test does *NOT* imply that none of the comparisons subsumed under that omnibus test are significant. This has nothing to do with `aov()` vs. `lme()`.
Comment: That's probably because you're testing the combined effect (7 degrees of freedom) at .05 in the first case, whereas you're testing each difference with the reference category separately at .05, 1 degree of freedom at a time (more power, but also higher Type I error rate)
Comment: You don't have to choose because the two methods do not contradict each other in any way. One presents the omnibus test while the other tests the individual contrasts. As I already said: "*It is a well-known fact that a non-significant omnibus test does NOT imply that none of the comparisons subsumed under that omnibus test are significant.*" The following document I found online may be useful to you: http://www4.uwsp.edu/psych/cw/statmanual/plancomp.html#The%20Meaning%20of%20the%20Omnibus%20F
Comment: Is CDIscrambling actually a continuous variable that you've made categorical? To be clear, it's still continuous if, even though you've collected values 06, 10, 14, etc., other values are possible.
Comment: so what should I trust? lme or aov? Are the inflated lme significances because of multiple comparison bias? is lme making the same error I would make by doing pairwise t-tests?
Comment: @JakeWestfall - wouldn't what you are saying amount to "it is normal for omnibus tests (here ANOVA) to lead to false negatives"? From your reference: "So, it is possible to find a non-significant F when some components would have been significant if you had specifically tested for them." this sounds like the typical example for multiple comparison bias - so if I run lme I would have to define a priori which conditions interest me, and simply picking the most significant ones a posteriori means I'm data mining? :( I don't want to be data mining but lme gives me awesome (+ unexpected) results...
Comment: I would say the answers to your two questions are Yes and Yes.
Comment: Jake Westfall, the linked stats manual is in error.  "Whenever the omnibus F (overall F test from SRD ANOVA) is significant... At least two of the groups are significantly different..." That isn't true. You can easily generate a simulation that proves as much. ANOVA is, as is stated elsewhere there, sensitive to the average effect and thus can generate significant F's due to multiple differences averaging to significant with no significant paired test.
Comment: @John Thanks for pointing out this correction. I must admit I didn't read most of the document and was only looking for something to corroborate what I wrote earlier about non-significant F not implying no significant contrasts.
Answer: (Converted from a set of comments.)
You don't have to choose because the two methods do not contradict each other in any way. One presents the omnibus test while the other tests the individual contrasts. It is a well-known fact that a non-significant omnibus test does NOT imply that none of the comparisons subsumed under that omnibus test are significant. This has nothing to do with aov() vs. lme().
The following document I found online may be useful to you:
The Meaning of the Omnibus F

wouldn't what you are saying amount to "it is normal for omnibus tests (here ANOVA) to lead to false negatives"?

Yes.

so if I run lme I would have to define a priori which conditions interest me, and simply picking the most significant ones a posteriori means I'm data mining?

Yes.
Comment: All hypothesis tests tend to find a preponderance of false negatives. There's very little effort put out to control the beta rate.
Comment: @John Hear hear!
Comment: Just to be clear: I choose the "COI" as the measure of interest (a priori). In the plot I see that one category (A) in "COI" is always null. To test whether it truly is outside the range of all the others I run aov. It kind of isn't (p=0.09). I have heard linear models are better than anova, so I do lme. I find out that lme says the most likely categories to be out of range are B, C, and G - and in fact, not A. What conclusion can I draw from this?  Also here 3 of 8 categories are out of range .Can 4 of 8 be out of range? If so which ones will lme anotate as significant?
Answer: The analyses being presented aren't being fairly compared so there's no way to know if they're actually saying different things. They could be perfectly compatible. You could use lm (what underlies aov) and get the treatment effects just as you have for lme. You can also find omnibus F's using lme. Then you could compare things a little better but that's not really how you decide between mixed models and repeated measures ANOVA for a particular case. Regardless, the omnibus F in an ANOVA is not about simple effects so what you're comparing is apples and pizza.
The lme and aov commands use very different kinds of analysis methods. Baayen (2008) and others have demonstrated that the mixed models used in lme are generally more powerful compared to conventional repeated measures ANOVA and they also have fewer assumptions (e.g. sphericity). That said, there is the issue that mixed models are more sensitive to normality in residuals partially because with repeated measures ANOVA you benefit from the CLT to generate normality. There are many differences and the modelling methods function differently. You should be selecting one based on theoretical grounds and not particular results. A few years ago I was pretty much told by every statistician I met that you just should never use repeated measures ANOVA. I don't think that's as universal advice as they thought it was but perhaps that will help you.
It is possible that lme is finding effects not found in your simple ANOVA using aov. It's not practically possible to get truly comparable results to decide what to believe because they are doing different things and any tests mean (slightly) different things. That said, you could at least try anova(mylmeModel) to get omnibus F tests of the mixed effects model. Then you've got something substantially more comparable than what you're presenting here.
NOTE: I also asked if CDIscrambling was a continuous variable because it's a terrible habit of those who typically use repeated measures ANOVA to turn continuous variables into multiple categories. When using mixed models don't do that. You'll get much more power out of being able to treat it as a continuous variable. If it's not linear that's a different question and you can deal with that separately.
Comment: The continuousness is a bit complicated, emotion is continuous and scrambling is continuous. And I plan to do a ER~scrambling*emotion later. But right now I just want to see if any one category is special and cannot be compared to the others by these continuous metrics because at 100% emotion something different (qualitatively) happens than at 40% emotion and all scrambling steps.
Comment: Perhaps somethings special happens but if that's your question you should really make a new one about that. Nothing you've presented here can come close to answering that. In the new question try to define what makes one "special" and add a plot or plots. Also mention why your categorization is theoretically important for the specialness. Aside, you seem to be taking the effects in the regression as *the* effects and imbuing them with extra meaning. They're just each level compared to the first in the sorted factor. That's unlikely a good way to define special.
Comment: I actually [already did ask the question](http://stats.stackexchange.com/questions/74967/data-in-one-condition-significantly-different-from-data-in-other-conditions-test), though I did fail to include a figure (tell me if you still think the question needs one after reading it) and that is where I got the suggestion of using a linear model instead of anova. You seem to hold that linear models aren't the right way of going at this - what is?
Comment: And here is actually [an other very similar question of mine](http://stats.stackexchange.com/questions/76609/rs-statsaov-and-nlmelme-functions-for-repeated-measurement-anova) with a figure reflecting what my data looks like. I'm actually sorry for asking similar questions over and over again, but with every new method I try it turns out that's not right either :-/
Comment: Also, by your initial answer do you mean to say that linear models are not an alternative to anova but rather a sub-calss which anova uses - and that lme4/nlme ARE in essence ANOVAS but they simply use a linear model which is superior to aov's? could I get the same kid of output `nlme::lme` gives me from `stats::aov`
Comment: That's a lot of questions sort of inappropriate for comments this way. ANOVA is a linear model, as is lme. You can get an omnibus *F* from lme just like you get from ANOVA, as I said `anova(mylmeModel)`. My suggestion was just that instead of breaking your continuous predictor into separate units you figure out the shape of the relationship and model that. (BTW, you should mark up answers that are helpful and select a correct one for you if there is one. People will stop answering if you don't.)
Comment: I am trying to get to the point where there is an answer I find clarifies the issue for me. I'm sorry it takes so long. So you are saying I need to make a series of different linear models and do an analysis of deviance? But in this first instance I just want to see if one category performs differently in my measure from all others. Is it safe to say "the linear model finds 3 factors significally different from the one I suspected to be different based on the graphic (here the base intercept) but 4 which are not. Therefor I conclude that there is no significant effect anywhere"?


Probability that the first person to be done with the test will leave after at most 41 minutes?

Question: Assume that the amount of time it takes for a student to finish a Math 425 midterm is a random
variable with uniform distribution between 40 and 60 minutes.
Suppose that there are 130 people in the class. What is
the probability that the first person to be done with the test will leave after at most 41 minutes?
How do you account for it to be that first person? Where do I start?
Answer: Assume the students are i.i.d. - Then, student $i$'s waiting time is Uniform(40,60), call this $U_i$. Then, you want $$P(min(U_1,\ldots,U_{130}) \leq 41) \\
= 1 - P(min(U_1, \ldots, U_{130} )> 41) = 1 - P( U_1 > 41, U_2 > 41, \ldots, U_{130}>41)$$
Now, use iid to get that $P(U_1>41, \ldots, U_{130}>41) = \prod_i P(U_i > 41) = P(U_1 > 41)^{130}$
Comment: Okay... I'm still a little confused. Forgetting the 130 students for a minute, I believe that the P(x > 41) = 0.95, correct?
Comment: Where is $X$ in this? $U_i$ is the time for the $i$-th student to finish, so $\min_i U_i$ is the time the first student finishes. Then, you're just using the fact that $P(\min_i U_i > c) = P(U_1 > c, U_2 > c , \ldots)$ and using i.i.d.-ness of the $U_i$ to turn that into $P(U_i > c)^n$ where there are $n$ students.
Comment: The x was just a place holder, really. P(U_i > 41) = 0.95 though, isn't it? Cause if so then you would take that value to the 130th... But the homework says it is incorrect.
Comment: You're concerned with $P(\min(U_1,\ldots,U_{130}) \leq 41)$. Look at my answer.
Comment: Ahhh, makes sense now. Got it. Thank you!


Send mail to product owner only when the email adress is available

Question: As a follow up to previous questions asked by me:
Send mail to product owner with Rules and Fetch Customer Profile from Line Items. I have the following question.
I created a rule to send an e-mail to the product owner of a product in my commerce webshop. The email address is added to the product by hand in a custom field. The rule is working when the email address is available but when not available it sends out an error. How can I check to see if the e-mail address is there and only then send the e-mail.
This is my rule:
<code>{ "rules_svds_send_mail_to_product_owner" : {
"LABEL" : "SVDS: Send mail to product owner",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"TAGS" : [ "SVDS" ],
"REQUIRES" : [ "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "commerce_order", "value" : [ "commerce-order" ] },
      "PROVIDE" : { "variable_added" : { "commerce_order_value" : "Commerce Order" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "line_items" : "Commerce Line Items" },
      "DO" : [
        { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-items" ] } }
      ]
    }
  }
]
}
}
</code>
The component I use in the loop is like this:
<code>{ "rules_perform_an_action_on_a_selected_line_item" : {
"LABEL" : "Perform an action on a selected line item",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" },
  "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : {
        "type" : "commerce_product",
        "id" : [ "selected-line-item:commerce-product:product-id" ]
      },
      "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
    }
  },
  { "entity_fetch" : {
      "USING" : { "type" : "commerce_order", "id" : [ "commerce-order:order-id" ] },
      "PROVIDE" : { "entity_fetched" : { "fetched_customer" : "Fetched user" } }
    }
  },
  { "mimemail" : {
      "USING" : {
        "key" : "[commerce-order:order-id]",
        "to" : "[product-fetched:field-e-mailadres-product]",
        "subject" : "Product ordered",
        "body" : "E-mail body text",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
]
}}
</code>
Thanks in advance
Answer:
The email address is added to the product by hand in a custom field

I supouse that the field for entering email, is an email field (must enter a 'valid email' in format: firstname.lastname@example.com, avioding a 'blah blah email'), if so:
then in your rule add a condition: [your_email_field] is not empy, if that condition is far away to be implemented in rules area: condition, then use rules conditional module, when your a ready to implement 'send email' in your rule, before that accion, add condition: [your_email_field] is not empty, if user entered a 'fake email', drupal will send email, but it will not go anywhare, this way you can avoid your error, and only valid emails will be delivered.
Comment: Thanks, I indeed wasn't able to get to the [your_email_field]. But installing a module to get this to work was a bit to much for me. I ended up making the [your_email_field] required.
Comment: if it was usefull my answer please up vote it, regards.


How to resolve a merge conflict on a file that has been deleted in 1st branch and renamed in 2nd branch?

Question: I am working on a branch where I have deleted some folders. In the meantime on the master branch all the root folders have been renamed, so the path of all files (including the ones I have removed) has been renamed.
When I attempt to merge I get a conflict on all the files of all the folders that have been both deleted (on my branch) and renamed (on master). I made a list of these (1000+) files which appear like this in git status's Unmerged paths :
added by them:   FolderRenamed/File1.ext
added by them:   FolderRenamed/File2.ext

I would like to restore them at this occasion, from the "theirs" version when I attempt to merge master in my branch (although you could have expected me to want to do the opposite, and have the files deletion been confirmed ; which would be the same concept with "ours" instead of "theirs").
I thought I could simply call the following command for every file :
git checkout --theirs FolderRenamed/File1.ext

But it does not seem like calling this command on a file achieves any change. My file is still in the "Umerged paths" list.
Can somebody help me identify what I am doing wrong ? Is git checkout not working as I expected because the local version had been deleted ?
Answer: TL;DR: you just need to git add them.
Longer

When I attempt to merge I get a conflict on all the files of all the folders that have been both deleted (on my branch) and renamed (on master) ...

Yes: when you run, e.g.:
git checkout branch
git merge master

Git:

identifies your current commit (HEAD aka  branch: these select one particular commit by hash ID, which is the commit you have in your index and work-tree right now as well), also known as local or --ours, but I just call this L (left/local);
identifies the other commit (aka master), also known variously as remote, other, and --theirs, but I just call this R (right/remote);
finds the merge base between these two commits.  That's the most recent commit-in-common.  I call this B for base.

(Note that if you check out master and run git merge branch you are just swapping L and R for this part of the process.)
Git then, in effect, runs two git diffs with rename detection enabled:
git diff --find-renames B L > /tmp/b-vs-l.patch
git diff --find-renames B R > /tmp/b-vs-r.patch

The result is a list of everything you did in L since the base B, and everything they did in R since the same base B.  Git then combines these changes.
If you renamed a file and they deleted "the same" file (as detected by the rename detection), this is a rename/delete conflict.  If they renamed a file and you deleted it you get the same conflict.  Either way Git has a conflict.
In the special case of conflicts (but not in ordinary cases), Git will leave, in your index, all three versions of every file: the one from B, which Git leaves in the index as "stage 1"; the one from L, which Git leaves in the index as "stage 2" or --ours; and the one from R, which Git leaves in the index as "stage 3" or --theirs.
These higher-numbered stage files are how Git remembers that you are in the middle of a conflicted merge.  Normally, all the files in the index are at "stage zero".  If Git were able to resolve the conflict on its own, it would erase the three higher stages and leave just a stage-zero resolved file in place.
The files in your work-tree are (mostly) independent of the files in your index, and of course you work-tree has no stage slot numbers.  There can only be one somepath/file1.ext.  In the case of a rename/delete conflict, there's a stage 1 entry for the base file and a stage 2 or stage 3 entry for the --ours or --theirs file.  The other stage-slot (3 or 2 respectively) is left empty.  The git status command shows this to you as added by us (1 and 2 occupied, 3 empty) or added by them (1 and 3 occupied, 2 empty).
Running git checkout --ours tells Git to copy the stage-slot-2 version to the work-tree.  Running git checkout --theirs tells Git to copy the stage-slot-3 version to the work-tree.  In either case, nothing happens to the stage-slot-1 entry, and the stage-slot-zero entry remains empty.
Running git add tells Git to copy the file from the work-tree to the stage-zero slot, wiping out the remaining slots entirely.  The file is now resolved.
Since Git leaves the renamed file in the work-tree (under the new name), all you need to do in this case is git add the renamed file.
That's not the only way to do it though
If you run git checkout commit-specifier -- path, Git extracts the given path from the given commit-specifier.  When Git does this, it copies the path into slot zero of the index.  This wipes out any slot 1-3 entries for that path, so a side effect of checking out a file from a specific commit is that this resolves the file.
This is different from git checkout --ours and --theirs because those extract from the existing index entries, so they don't write into slot zero.
Hence you can also use git checkout MERGE_HEAD -- paths to extract the renamed files into their renamed names, resolving the merge conflict in the process.
Answer: Turns out the right way to proceed here was simply (as suggested by git...) :
git add FolderRenamed/File1.ext

Or, as I want to restore all the files inside my renamed folders, simply :
git add FolderRenamed

(And I would have used git rm if I had wanted to remove the folders and their content...)
Git is so powerful :).
Answer: git checkout --theirs does checkout "their" version, but it's checking out from the index, not updating it, and that doesn't mark the conflict resolved.
Checking out from a named commit updates the index, and the name of an in-flight merge's "theirs" tip is MERGE_HEAD.  So
git checkout MERGE_HEAD -- paths/to/files`

to simply declare those the correct versions.
Of course git add also updates the index, so you could git checkout --theirs, inspect the result to be sure it's what you meant, then git add it.


Is it possible to use JIL with asp.net core rc2?

Question: I'm trying to use Jil with asp.net core rc2, but there are no available package in nuget. Is it possible to start using jil + asp.net core rc2 today?
Comment: If this package supports dnxcore50 then yes.
Comment: @Pawel: ASP.NET Core is independent from .NET Core. It can also run against the full .NET Framework, so if the library supports .NET 4.5 or higher it can be used. Just not with .NET Core ;)
Comment: @Tseng - You are right - I did not read the question carefully.
Answer: Jil 2.15.0 supports .Net core. (netstandard1.6).
Check this nuget link
https://www.nuget.org/packages/Jil/2.15.0


Expected a truncated byte

Question: When I pass 2 size of bits as follow:
iex(11)> <<2 :: size(2)>>

I've got as output in the iex(I determine the size of the bit)
<<2::size(2)>>

But when I write following in the iex
iex(12)> <<3 :: size(2)>>

I've got
<<3::size(2)>>

but expected
<<1::size(2)>>

And by 4
iex(13)> <<4 :: size(2)>>
<<0::size(2)>>

I've got zero and for it is right, but with 3 why I've got 3 instead 1?
Answer: size(2) means 2 bits, which can hold 4 (2^2) values: 0, 1, 2 or 3.
It seems like you were looking to store 1 bit if you expected 3 to become 1. For that, use size(1):
iex> <<3::size(1)>>
<<1::size(1)>>

Expected a truncated byte


Criar classe com imports comuns material-ui e react

Question: Gostaria de criar uma classe comum em minha aplicação com react e material-ui. Tenho, por exemplo, que criar uma série de elementos com tabelas. Toda vez que uso tenho que importar algumas libs. Por exemplo:
const Table = require('material-ui/lib/table/table');
const TableBody = require('material-ui/lib/table/table-body');
const TableFooter = require('material-ui/lib/table/table-footer');
const TableHeader = require('material-ui/lib/table/table-header');
const TableHeaderColumn = require('material-ui/lib/table/table-header-column');
const TableRow = require('material-ui/lib/table/table-row');
const TableRowColumn = require('material-ui/lib/table/table-row-column');

Gostaria de fazer algo similar há:
/* <path>/Template/index.jsx */

const React = require('react'),
ReactDOM    = require('react-dom'),
Router      = require('react-router'),
mui         = require('material-ui'),
Icon        = mui.Icon;

class Template extends React.Component {
    render() {
        return (
            {this.props.element}
        );
    }
};

module.exports = Template;

/* <path>/Table/index.jsx */

const Template    = require('../template'),
Table             = require('material-ui/lib/table/table'),
TableBody         = require('material-ui/lib/table/table-body'),
TableFooter       = require('material-ui/lib/table/table-footer'),
TableHeader       = require('material-ui/lib/table/table-header'),
TableHeaderColumn = require('material-ui/lib/table/table-header-column'),
TableRow          = require('material-ui/lib/table/table-row'),
TableRowColumn    = require('material-ui/lib/table/table-row-column');

class Table extends Template {
    render() {
        return (
            <Template element={this.props.element}/>
        );
    }
};

module.exports = Table;

/* <path>/home/index.jsx */

var Table = require('../../../common/table');

var _rows = [];
for (var i = 1; i < 100; i++) {
    _rows.push({
        id: i,
        title: 'Title ' + i,
        count: i * 100
    });
}

class Item extends Table {
    handleOnClick: function(event) {
        event.preventDefault();
        this.props.setApplicationDetails("item", this.props.item);
    },

    render: function() {
        return (
            <TableRow selected={true}>
                <TableRowColumn>
                     {this.props.item.id}

                </TableRowColumn>
                <TableRowColumn>{this.props.item.Title}</TableRowColumn>
            </TableRow>
        );
    }
};

class ItemItem extends Table{
    mixins: [Router.Navigation, Router.State],
    setApplicationDetails: function(pageData, item) {
        this.transitionTo("/home?id=" + item.id);
    },
    render: function() {
        var self = this;
        var state = {
            fixedHeader: true,
            stripedRows: false,
            showRowHover: false,
            selectable: true,
            multiSelectable: false,
            enableSelectAll: false,
            deselectOnClickaway: true,
            height: '300px',
        };

        var item = _rows.map(function(item, index) {
            return (
                <Item item={item} index={++index} setApplicationDetails={self.setApplicationDetails} key={index} />
            );
        });

        return (

                <TableHeader enableSelectAll={state.enableSelectAll}>
                    <TableRow>
                        <TableHeaderColumn colSpan="3" tooltip='Super Header' style={{textAlign: 'center'}}>
                        Super Header
                        </TableHeaderColumn>
                    </TableRow>
                    <TableRow>
                        <TableHeaderColumn tooltip='The ID'>ID</TableHeaderColumn>
                        <TableHeaderColumn tooltip='The Name'>Name</TableHeaderColumn>
                        <TableHeaderColumn tooltip='The Status'>Status</TableHeaderColumn>
                    </TableRow>
                </TableHeader>
                <TableBody deselectOnClickaway={state.deselectOnClickaway}
                    showRowHover={state.showRowHover} stripedRows={state.stripedRows}>
                    <TableRow selected={true}>
                        <TableRowColumn>1</TableRowColumn>
                        <TableRowColumn>John Smith</TableRowColumn>
                        <TableRowColumn>Employed</TableRowColumn>
                    </TableRow>
                </TableBody>

        );
    }
};

module.exports = ItemItem;

Ou seja, criar uma classe que encapsule essas libs e depois em cada elemento que use tabela extender essa lib.
Alguma sugestão?
Answer: É possível mas de certa forma, não é recomendável, vou explicar depois o porque, mas o que você precisa é algo assim:
Coloque isso em um arquivo como components/table/index.js, assim você consegue importa-lo apenas usando o nome da pasta,
mas isso é opcional ok? Sendo assim, tem duas opções:
export const { Table } = require('material-ui/lib/table/table');
export const { TableBody } = require('material-ui/lib/table/table-body');
export const { TableFooter } = require('material-ui/lib/table/table-footer');
export const { TableHeader } = require('material-ui/lib/table/table-header');
export const { TableHeaderColumn } = require('material-ui/lib/table/table-header-column');
export const { TableRow } = require('material-ui/lib/table/table-row');
export const { TableRowColumn } = require('material-ui/lib/table/table-row-column');

ou
export.Table = require('material-ui/lib/table/table');
export.TableBody = require('material-ui/lib/table/table-body');
export.TableFooter = require('material-ui/lib/table/table-footer');
export.TableHeader = require('material-ui/lib/table/table-header');
export.TableHeaderColumn = require('material-ui/lib/table/table-header-column');
export.TableRow = require('material-ui/lib/table/table-row');
export.TableRowColumn = require('material-ui/lib/table/table-row-column');

Depois você pode carrega-los assim:
import { * as TableElements } from './components/table'

ou
const TableElements = require('./components/table')

E para usa-los: TableElement.Table, ou TableElement.TableBody e por ai vai.
Agora porque não é recomendável?
Se você estiver usando algum task runner como gulp ou grunt, isso de fato, não vai fazer diferênça, porém, se você estiver usando webpack, você pode acabar injetando mais código no seu projeto final do que deveria.
De modo simples, o webpack é inteligente o suficiente para importar e injetar no seu projeto, apenas os módulos que você esteja usando, então se por exemplo, você esteja usando apenas alguns módulos do material-ui, apenas os módulos que você importar, serão adicionados no seu projeto final. No caso do gulp ou grunt, eles importam o material-ui inteiro para o seu projeto e no fim você vai ter módulo que você talvez nem esteja usando, fazendo um volume desnecessário no seu projeto.
Espero que tenha ajudado.


What are similarity measures between a line and a set of points?

Question: A colleague discussed about a concept of similarity between two different entities line and a set of points. My first guess for solution was considering distances squared ($d^2$) as in LS. So for the following demonstration in which the black line is fitted by means of Least Squares method is more similar to the points (and vice versa) compared to the orange line.

What do you think about this method?
Any more rigid and statistically mature answer for the question?
Comment: I don't think this is a meaningful question, given the usual meaning of similarity. You can measure how close points are to a line, and do so various ways, including median absolute deviation and mean squared deviation. But is this really "similarity"? I think, to riff on Lewis Carroll, that this is like asking how similar a raven is to a writing desk.
Comment: but could you not simply represent the line as a vector of points?
Comment: A "statistically mature" answer would begin with *questions* about the objective here, recognizing that "similarity" can mean so many different things.  What do the points represent--a sample of something, something measured with error, a population of things, an xy scatterplot of results of a controlled experiment?  What is the purpose of measuring "similarity" to a "line"?  (What is a "line", even: a Euclidean line or perhaps just a line *segment*?)  What would it cost your client to accept suboptimal solutions?
Comment: @PeterFlom Well, I had the same feeling when I was asked to answer the question. However as @Jeff mentioned I thought it should be some ways. The way I am thinking about is to consider the set of points as one entity say, `object1`. Then it does not look odd at all thinking about similarity between two objects, the line and the `object1`, I think.
Answer: Great question!  Your intuition was good.  There is indeed a strong relationship between methods of linear regression and metrics for measuring similarity between a line and a set of points.
The correspondence betwen linear regression and similarity metrics.  Here is the relationship.  Let $d(\ell,S)$ be a similarity metric that measures the similarity between a line $\ell$ and a set $S$ of points.  Then, linear regression is basically the following problem: given a set $S$ of points, find the line $\ell$ that minimizes $d(\ell,S)$.  Consequently, each different similarity metrics gives rise to a different flavor of linear regression.  And, dually, from any particular flavor of linear regression, you can extract a corresponding similarity metric that the regression method is minimizing.
Notation: if $\ell$ is a line, I will write $\ell(x)$ for the $y$-coordinate on the linear corresponding to $x$.  In other words, I'll treat $\ell$ as a function of $x$.
Example 1. Ordinary least squares regression corresponds to the distance measure you mention: namely, $d(\ell,S) = \sum_{(x,y) \in S} (\ell(x) - y)^2$.  Thus, for each point in $S$, we consider the vertical distance from the point to the line $\ell$, square it, and take the sum of these squared residuals.  Pictorially, we're summing the squares of the lengths of the orange lines in this picture:

Example 2. If you did ordinary least squares regression, but with the role of $x$ and $y$ swapped, then that would correspond to a slightly different similarity metric: namely, $d(\ell,S) = \sum_{(x,y) \in S} (\ell^{-1}(y) - x)^2$.  This corresponds to taking the horizontal distance from each point to the line $\ell$, and summing these squared distances.  We're summing the squared lengths the orange lines in this picture:

Example 3. If you did principal components analysis (PCA) (also known as orthogonal regression or total least squares (TLS)), that would correspond to a slightly different distance measure, namely, the orthogonal distance from each point to the line $\ell$, squared and summed.  Now we're summing the squared lengths of the orangle lines in this picture:

Summary so far.  There are many possible similarity metrics.  Which one you choose will depend upon the nature of your application and your model for the data.
How to choose a similarity metric. OK, so there are many possible similarity metrics.  How should choose which one to use?  As already suggested, to answer this, you will need to have some model or hypothesis for how your data were generated.
Ordinary least squares starts from the following model: it assumes that, for each point $(x_i,y_i)$, $y_i$ was generated as a probabilistic (stochastic) function of $x_i$.  It assumes the process went something like this: there's some line $\ell$ (not known to us a priori), and given the input $x_i$, we first calculate $\ell(x_i)$ (the $y$-coordinate on the line corresponding to $x_i$), then we randomly generate some noise/error value $e_i$ from a normal distribution with mean 0 and standard deviation $\sigma$ (where $\sigma$ is not known a priori), and then we set $y_i = \ell(x_i) + e_i$.  Since each $e_i$ is assumed to be iid Gaussian, a reasonable measure of how closely a hypothesized line $\ell'$ fits this model is to take the sum of squares of the inferred $e_i$ values.  For the correct line $\ell$, we will have $d(\ell, S) = \sum_i e_i^2$, which has expectation $n \sigma^2$.  For an incorrect line $\ell'$, we will have $d(\ell', S) = \sum_i (e_i \pm \ell'(x_i)-\ell(x_i))^2$, which has
expectation $n \sigma^2 + \sum_i (\ell'(x_i)-\ell(x_i))^2$, which you might notice is larger than the expectation for $d(\ell, S)$.  In other words, starting from a particular stochastic model for how the data was generated, OLS uses a particular distance measure that is well-suited to testing how closely the observed data fits the presumed model.
Of course, this is not the only plausible model for how your points might have been randomly generated (as a function of the line $\ell$).  Given a different process, we might end up with a different similarity metric.
Hypothesis tests. Finally, let me mention one more topic that you didn't bring up, but you could have.  Let's say you have a stochastic model for how your points were randomly generated.  Let's say that the line $\ell$ is the parameter of this random process.  Then another interesting question we could ask is: given the observed set of points $S$, test the hypothesis that the points $S$ came from the aforementioned random process, using line $\ell$ as parameter.  One could work out a way to compute a $p$-value for the likelihood that $S$ were generated according to that distribution.  If the $p$-value is very small, you might reject the hypothesis that the points were generated from this particular random process with parameter $\ell$ (roughly speaking, this would amount to saying that the points $S$ don't seem to correspond to the line $\ell$).  If the $p$-value is not too small, you might proceed as though the hypothesis is potentially true (roughly speaking, this would amount to saying that the points $S$ are consistent with the hypothesis that they came from your random model with line $\ell$).  So, hypothesis tests might be another way to, very roughly speaking, measure whether the points seem to be consistent with any particular line.
Credits. I gratefully acknowledge @JD Long for these excellent pictures.  See also his answer explaining different forms of regression for more insight.
Comment: +2 Thanks for answering. There are some interesting points in your answer. Your guess is correct: they come from stochastic processes. I need to read your answer thoroughly, so.
Comment: This is a great answer written very well!
Answer: First you need to determine exact similarity by yes or no.  A line is a set of points, this set of points in a line is an infinite set.  There would be a null set of points which would be similar to every line feasible.  There would also be a set of points that only has one point, and it would be similar to an infinite set of lines that pass through it, all with varied slopes.  Once your set of points contains two points you are now limited to a specific line as any two points form a line, and they will be exactly similar to only this line.  Any more points than two and the case can only be made where the points are similar to a specific line.  This would indicate the points are all contained in line or not.  Once this is ironed out that the set is or isn't exactly similar to a line or lines, you could then determine how dissimilar the set of points are from a line.   Which line would you be talking about though.  Your least squares method would determine the line of which it is most similar, but this set would still have a similarity or dissimilarity to all other lines.  There would also be an infinite number of distinct sets of points that would be just as similar to that same line.  Given some framework like this you could use this to determine the similarity of a set of points to a line using yours or any other distance.


smtp.Send(message) error

Question: I am building a hotel site for my final year project, I am trying to send an automated
email to the customers once they have book.
used this code:
<code>System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(email.Text);
message.Subject = "Hotel Reservation";
message.From = new System.Net.Mail.MailAddress("firstname.lastname@example.com");
message.Body = ("Dear" + first_name.Text + "Your reservation made for " + rates.Text +" " + nor.Text + " " + "is successful. Please print out this email for reference while checkin. Thank you");
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost"); smtp.Send(message);
</code>
when i run it shows me this error highlighting smtp.Send(message);:
SmtpException was unhandled by the user code and
Failure sending mail.
Comment: Trap the exception, and examine the inner exception (if there is one). That may tell you more about what is going wrong. You should write mail sending code with the expectation that mail sends will fail from time to time, so handling that situation should be included in your code.
Comment: That's not a lot to go on.  Perhaps you could add code that handles the `SmtpException`, as the error message suggests?
Comment: Thanks for ur reply.. :) Actually i thought of it.. and i added `using System.Net.Mail.SmtpException;`.. It still gave me an error then i added `smtp.EnableSsl = true;` it still gave me error.. i dont really know how about to do it.. I tried searching online couldnt really find the sample code.. :( it will be really kind of you if you could help me out.. Please.. :|
Comment: This may be helpful http://stackoverflow.com/questions/372742/can-i-test-smtpclient-before-calling-client-send (especially the second answer).
Answer: There are several reasons for this error.

To Email is invalid
You have not specified credentials. (UserName / Password)
There might be a firewall problem
SMTP port might be other than 25

smtp.Send(message) error


How to check my code style in the following way

Question: You can help to see if you can do some code style checks such as tslint during yarn build
Comment: https://stackoverflow.com/help/how-to-ask
Comment: What is this here supposed to be? A question?
Answer:
such as tslint during yarn build

Add a prebuild script target. Any prefoo script would run if you run yarn foo. Same for build


How can I keep a log of users logging in and out?

Question: I am creating an admin panel to log breakdowns, save tasks, log errors and much more. I currently have the following piece of code at the top of the screen which checks if a user is logged in, if not they are sent to the login / create a user page.
<?php
session_start();

        include 'login/config.php';

        if(!isset($_SESSION['username'])){
            header('location:login/index.php');
            exit();
        }

?>

I feel that there may be better ways of doing this and also more secure ways.
A username and password are required to login and get to the initial dashboard and user status levels & permissions will be added later on.
QUESTIONS::
How can I make the system more secure by improving the code or adding additional security features?
AND
How can I log to my SQL database when a user logs in and out of the admin system?
Answer: As for security, I'm no expert there, so I'll rather wait and see what the other people tell you, since it's a very interesting topic. But I'll give you my thoughts anyway.
First of all, you should take care of SQL injections on your login, always validate the input data from the users, specially on CRUD operations. I think protecting your pages with sessions should be good enough, as long as the login itself is secure, for example you could implement a system that would block the IP after few failed attempts to login etc...
About the second part, you can create a table i.e. userlog which would contain the fields you want, user_id, action(login/logout), time.
Then everytime the user does login/logout, you just insert a new record to the table. That piece of code would be located where you set/unset the session.
Not sure about the efficiency of this method, but this is a way to implement what you are saying.
Comment: thankyou for the feedback, I have a table in the database called 'eventlogs' and there are a lot of components within the system that will require logging, however the main one is the logging in and out initially, the fields are event name, event user, event category, and using the current timestamp feature it records the time of the log too
Comment: Would you by any chance know of a way to change my code above so that if they do not have a required user level, for example Manager then they can't access the page? I have a field in the database with permission levels but calling it for use is proving difficult.
Comment: You are storing the `username` on a session, so if that field is `unique` in your database, you could build a query and fetch the user group of that user and then check it to access or not the page, same way you are checking that the session is set. You could always store the `user_id` instead of the username, that makes more sense to me.
Or you could also store the user group on a session, but it's best practice to keep the session data low. Let me know if I was clear enough!
Comment: Also, for security reasons you should *never* log login attempts to non-existent users. At least if you have some sort of interactive login. That non-existent user could be a password, and the next user who logs in could be the one that password belongs to.
Answer: you can create table like login_history which have field loginTime and logoutTime as per system time. When user login,loginTime  inserted and when he logout record updated with logoutTime.


Is it possible that two independent variables were insignificant when present alone in the model, but when together in the model become significant?

Question: I did learn about collinearity issue where it is possible that 2 significant independent variables when used together in the model can make either or both insignificant. However does the vice-versa case exist? and under which circumstances?
Comment: +1 first, i think the answer is yes, but i am struggling to give you a numerical example.
Comment: See this thread, especially about "suppressor variables".  https://stats.stackexchange.com/questions/73869/suppression-effect-in-regression-definition-and-visual-explanation-depiction
Comment: Although it's unclear what the "vice-versa" case might be, we have [many posts explaining how significance can change as variables are introduced in regression](https://stats.stackexchange.com/search?q=regression+significant+not+score%3A40) -- and they cover all the possibilities.
Answer: In general and dismissing collinearity , linear models become more representative as variables are introduced even though R^2 is relatively low in business application. Literature exists explaining this rational. During data exploratory practice one may find two less significant variables resulting in higher significance when clustered (unsupervised data mining ).
Comment: This answer is here is lacking and unclear. It may behoove the OP and other readers here to provide a more thorough explanation. Otherwise this answer may be deleted for being low quality.


How to swap Hashtable's key with Value

Question: I have solved it by following.
Since it is long, i need a better one.
//Code
class Program
{
    static void Main(string[] args)
    {
        Hashtable hsTbl = new Hashtable();

        hsTbl.Add(1, "Suhas");
        hsTbl.Add(2, "Madhuri");
        hsTbl.Add(3, "Om");
        List<object> keyList = new List<object>();
        List<object> ValList = new List<object>();

        Console.WriteLine("Key          Value");
        foreach (DictionaryEntry item in hsTbl)
        {
            Console.WriteLine(item.Key + "      " + item.Value);
            keyList.Add(item.Value);
            ValList.Add(item.Key);

        }
        hsTbl.Clear()

//Swapping

        for (int i = 0; i < keyList.Count; i++)
        {
            hsTbl.Add(keyList[i], ValList[i]);
        }

//will display hashtable after swapping

        foreach (DictionaryEntry item in hsTbl)
        {
            Console.WriteLine(item.Key + "      " + item.Value);
        }
    }
}

Is there any other better solution?
Comment: What's the reason of usage `HashTable` instead of generic `Dictionary`?
Comment: Simply create a new list with key as value and value as key in a foreach loop and forgot the old. Is swap really needed?
Comment: Do you need to consider the scenario whereby a specific key's value may be the same as another value in the same collection? Also, you may want to consider using a Dictionary for type safety and performance
Comment: No reason behind that. Just to start.
Answer: You could do it slightly simpler using an additional array and the CopyTo method rather than 2 lists but without creating an additional HashTable as follows:
//Code
using System;
using System.Collections;

class Program
{
  static void Main()
  {
      Hashtable hsTbl = new Hashtable();

      hsTbl.Add(1, "Suhas");
      hsTbl.Add(2, "Madhuri");
      hsTbl.Add(3, "Om");

      DictionaryEntry[] entries = new DictionaryEntry[hsTbl.Count];
      hsTbl.CopyTo(entries, 0);
      hsTbl.Clear();

      foreach(DictionaryEntry de in entries) hsTbl.Add(de.Value, de.Key);

      // check it worked

      foreach(DictionaryEntry de in hsTbl)
      {
         Console.WriteLine("{0} : {1}", de.Key, de.Value);
      }
  }
}

Note that, in general, no method is guaranteed to work because some of the values in the original hashtable may be duplicated and therefore be unsuitable as keys.
Answer: You can use generic Dictionary<string,int>, which is easy to create with Linq:
var dictionary = hsTbl.OfType<DictionaryEntry>()
                      .ToDictionary(e => (string)e.Value, e => (int)e.Key);

If you really need Hashtable, then:
Hashtable table = new Hashtable();
foreach (DictionaryEntry entry in hsTbl)
    table.Add(entry.Value, entry.Key);

But make sure that all values are unique, if you want to swap value and key.

How to swap Hashtable's key with Value


modular arithmetics - remainder

Question: I need to find the remainder of
${1011}^{10}+{10}^{11}$
when divided by $101$.
According to this website it is 55 but I fail to see how.
For 1011, we can write it as $1$ because $1011=10*101+1$ so ${1011}^{10}$ is $1$.
For ${10}^{11}$, I wrote the $11$ like $8+2+1$ or $2^3+2^1+2^0$
Then multiplying the results $10\cdot100\cdot1$ and taking the remainder of 101 I got 91.
$$1000=9\cdot101+91$$
So overall I have 92 for the answer, but the website says 55.
Was my method or understaning wrong or is there is a problem or limitation on large numbers in that calculator?
Also is there any website or mehtod to check myself with this kind of big numbers?
Comment: You did fine. I would do the $10^{11}$ part as follows:
$$10^2=100\equiv-1\pmod{101},$$
so
$$10^{11}=(10^2)^5\cdot10\equiv(-1)^5\cdot10=-10\equiv91\pmod{101}.$$
Looks like that website doesn't deliver.
Comment: Even simpler than what I did, thanks a lot for showing me this way and for the answer.
Answer: I don't think it's the web-site's fault.  The input on that page was 1.1156078e30.  You're not giving it the correct number $1011^{10} + 10^{11}$, which is 1115607835569227940375059334601, just the first $8$ decimal digits.  All the digits matter here!
Comment: I took whatever google gave as a result, with e+, so the mistake was indeed on my side, what did you use to get the full number?
Comment: Example how to calculate full number
http://codepad.org/5JsuDZ6z
Comment: Oh codepad.org is indeed a nice website, thanks a lot.
Answer: $$1011^{10}+10^{11}\equiv (101\times 10+1)^{10}+10\times 100^5\equiv(0\times10 +1)^{10}+10\times(-1)^5\equiv1-10\equiv92\mod101$$
Comment: @kotomord Fair point, I was correcting it... Sorry it is hard to write from my smarphone.
Comment: sorry, -9 mod 101  is 92...
Answer: Try codepad.org
python works with the big number correctly
http://codepad.org/mZ9HW4zW
Comment: Or you could try [Wolfram Alpha](http://www.wolframalpha.com/input/?i=1011^10+%2B+10^11+mod+101).
Comment: Thanks you both for the websites, it will be very helpful later on.
Comment: Provided that using a calculator for big numbers to solve a problem of modular arithmetics is very silly to begin with.

modular arithmetics - remainder


Prove that if $f''(x)+25f(x)=0$ then $f(x)=Acos(5x)+Bsin(5x)$ for some constants $A,B$

Question: Suppose $f: \mathbb{R} \rightarrow \mathbb{R}$ is twice differentiable.
Prove that if $f''(x)+25f(x)=0$ then $f(x)=Acos(5x)+Bsin(5x)$ for some constants $A,B$

Consider $g(x):= f(x)-Acos(5x)-Bsin(5x)$ where $A$ and $B$ are chosen so that $g(0)=g'(0)=0$ [this portion is given, so can someone explain why it is important?]
For reference, we note that
$g(x):= f(x)-Acos(5x)-Bsin(5x)$
$g'(x):= f'(x)+5Asin(5x)-5Bcos(5x)$
$g''(x):= f''(x)+25Acos(5x)+25Bsin(5x)$
Consider the derivative of $\frac{25}{2}g(x)^2+\frac{1}{2}g'(x)^2$
$25g(x)g'(x)+g''(x)g'(x)$ if and only if $g'(x)[25g(x)+g''(x)]$
Following substitution, we conclude that
$g'(x)[25g(x)+g''(x)]=g'(x)(0)=0$
Therefore, by the Constancy Theorem, $\frac{25}{2}g(x)^2+\frac{1}{2}g'(x)^2=C_0$, where $C_0$ is a constant
$25g(x)^2+g'(x)^2=C$, where $C$ is a constant
Thus,
$25(f(x)-Acos(5x)-Bsin(5x))^2 + (f'(x)+5Asin(5x)-5Bcos(5x))^2=C$

Where do I go from here?
Comment: @ArpitKansal: That's what has to be proved, I think.
Comment: Note that $cos(5x)$ and $sin(5x)$ are solutions of your second order equation. and any solution will be linear combination of these solutions.
Answer: By steps: $g(0)=g'(0)=0$ is important because you have a homogenous differential equation, therefore zero initial data implies that the solution is zero everywhere.
After obtaining that $25(f(x)-A\cos(5x)-B\sin(5x))^2 + (f'(x)+5A\sin(5x)-5B\cos(5x))^2=C$, use initial data $g(0)=g'(0)=0$.
We chose $A$ and $B$ to get $f(x)-A\cos(5x)-B\sin(5x)=0$  and $f'(x)+5A\sin(5x)-5B\cos(5x)=0$ at $x=0$. Therefore we can find $C$ by putting $x=0$:
$$25(f(x)-A\cos(5x)-B\sin(5x))^2 + (f'(x)+5A\sin(5x)-5B\cos(5x))^2=C = 25(f(0)-A\cos(0)-B\sin(0))^2 + (f'(0)+5A\sin(0)-5B\cos(0))^2=0.$$
Hence  $$\forall x\quad 25(f(x)-A\cos(5x)-B\sin(5x))^2 + (f'(x)+5A\sin(5x)-5B\cos(5x))^2 =0.$$
You have the sum of squares equal to zero, therefore each term is zero itself. We can conclude that $\forall x\, (f(x)-A\cos(5x)-B\sin(5x))^2=0$ and, therefore,
$$\forall x\quad  f(x)=A\cos(5x)+B\sin(5x).$$
We conclude that all solutions of the initial differential equation has the above form.
Answer: In your expression involving $\frac {25}2g^2+\frac 12 g'^2=C$ you can set $x=0$ to determine the constant (this is where the bit you have been given is important). Then you have the sum of two squares equal to [?].

Note: you get the first part - the values of $A$ and $B$ from the values of $f(0)$ and $f'(0)$ if these are given, because $f(0)=g(0)+A$ so you want $A=f(0)$ and $f'(0)=g'(0)+5B$ so that $B=\frac 15 f'(0)$. Hence you can always find $A$ and $B$ which work.
If the initial conditions are given by the values of $f(x)$ at two distinct values of $x$ you get $A$ and $B$ by solving a couple of simultaneous equations.
Once you have filled in the details, this gives a proof that all the solutions of the original equation are of the requisite form, and justifies using that form to find solutions without replicating the proof every time.
Answer: Since this is a differential equation with a right side equal to zero, we say that it is homogeneous. Thus, we solve the auxiliary equation associated with the equation:  f′′(x) + 25 f(x) = 0  ------>   r^2 + 25 = 0
This yields:
r = +/- 5i
Solution will be of the form: f = Ae^(5i) + be^(-5i)
Which using Euler's method yields:
f = ACos(5t) + BSin(5t).
Differentiating f twice and plugging into the original diff. eq. should yield zero.
Is this what you wanted?
Answer: I don't remenber the general formula, you can find in some book of ODE. You have this y= f(x)=> y'' + 25y=0. We make the substitution $y=\exp{rx}$. Then $r^2e^{rx}+25e^{}rx=0$ and $e^{rx}(r^2+25)=0$. We find the roots of polinomial $r^2+25$ there are $r=5i$ and $r=-5i$ for the properties of the solutions of the ode we can say $y = (e^{5xi}+e^-{-5xi})/2=cos(5x)$ is a solution or $y = (e^{5xi}+e^-{-5xi})/2=i sin(5x)$
Answer: Is it easier just to substitute?
$$f(x)=Acos(5x)+Bsin(5x)$$
then
$$\dot f(x)=-5Asin(5x)+5Bcos(5x)$$
$$\ddot f(x)=-25Acos(5x)-25Bsin(5x)$$
finally:
$$-25Acos(5x)-25Bsin(5x)+25( Acos(5x)+Bsin(5x)) =0 $$
?
Comment: I think the goal of this exercise is to show that there are no other solutions.
Comment: this only implies that f(x) is a solution.