What's wrong in my rule for sending e-mails using VBO?

Question: I am trying to send a mail to a set of users when a node is created, so I made a users view including VBO field and a rule for it. You can see the settings below. It's about D7.

But when the rule gets in action, no mails sent and the following messages appear in admin/reports/dblog:

Unable to evaluate loop.
Unable to get variable entitylistem, it is not defined.
Unable to evaluate action views_bulk_operations_action_load_list.
Unable to get a data value. Error: Invalid data value given. Be sure it matches the required data type and format. Value at user():

What is wrong?
Comment: I've never really had much luck with loading entity objects. I usually fetch the entity ids, then loop and fetch the users with that and then the email field should be available.
Comment: Thanks for your comment. I have to use VBO since I need to filter the view by a taxonomy term if I could achieve to pass this error.
Comment: Your prior comment was posted while I was preparing my answer. Am I right in assuming that you meen something like "I have to use a view since I ned to filter the view by taxonomy term"? If so then you can perfectly do so using my plan-B answer ... would you agree?
Comment: @Xtrageik I meant the other VBO action that only loads IDs.
Comment: @Niall the other option works with no errors but since it only fetchs the entity id's, it's not suitable for my case.
Comment: @Pierre.Vriens thanks for your great response, I am reading it now, I think it will be really helpful.
Comment: Hey you there @NiallMurphy ... I don't get your prior (cryptic) comment, wanna retry (if you hurry you can still edit it ...) PS to Xtrgeik: You only "*think*" so? Fine for me, for now. After you had the time to digest it all, don't forget to update us with your feedback ...
Comment: Apologies for being cryptic. It's just a combination of Rules Fetch and VBO Fetch. Actions: Load a list of entity IDs from a VBO view > Loop UIDs > Fetch Entity by ID (list-item) > Send email.
Comment: @Pierre.Vriens your Plan B works like a charm as a component. Now I am dealing with the other parts of the rule. Thanks a lot!
Comment: Aha, so your "*I think*" from a prior comment now seems to require a fix like "*I'm convinced*". But, before moving on, and since you seem to be pretty new on this site (bien venue!), please ALSO read what's written [here](http://drupal.stackexchange.com/help/someone-answers). If you think my "Plan B" answer fits with what's written there, then maybe you also want to indicate so?
Comment: Merci for the accept (and upvote) ... Enjoy your next rules challenge you may run into (as per your "*dealing with the other parts of the rule*"). If needed (ie you can't get it sorted out), don't forget to use [this link](http://drupal.stackexchange.com/questions/ask).
Answer: Obviously "something" is wrong in what you're trying to get to work. I suggest you enable the typical the Rules debugging (to find more details about what's happening and causing your error), as detailed in "How can I display the value of a variable inside a condition?". If needed, add a copy of the Rules execution log as an update to your question.
Maybe also checkout the tutorial "How to process the results of a VBO enabled view via Rules?".
Plan B
A possible alternative that should work also, is to get the Views Rules module involved in the puzzle you're trying to solve (instead of using VBO). Some details about this module (from its project page):

Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

Create a view (using Views) so that you have 1 Views result (row) for each user to be eMailed, whereas that view has fields (columns) for each of the fields that you want to use to create your eMail. So your existing view could already be pretty close (if you just remove the VBO field). Important: use a Views display type of "Rules".
Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop".
For each iteration step in your Rules loop, perform a Rules Action to ... euh ... right ... Send an eMail. At that point you'll have all data from each column of your Views results available as so called Rules Parameters. So at that point it's a piece of cake to create an appropriate eMail.
The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). In your case: your existing Rules Event should also be fine. Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Easy, no?
PS: I'm assuming this question is about D7 ...
Comment: Yeah it's about D7. Your Plan B works like a charm as a component. Now I am dealing with the other parts of the rule. Thanks a lot!
Answer: I would suggest you to simply write your custom rules action like this
function mymodule_rules_action_info() {
 return array(
  '_send_new_content_mail' => array(
    'label' => t('Send Mail to users for new content'),
    'parameter' => array(
    'node' => array('type' => 'node', 'label' => t('Current Node')),
    ),
    'group' => t('custom'),
  ),
 );
}

Define your callback:
function _send_new_content_mail($node) {
  global $base_url;
  $query = db_select('users', 'u');
  $query->join('users_roles', 'r', 'u.uid = r.uid');
  $query->leftJoin('field_data_field_first_name', 'n', 'u.uid = n.entity_id');
  $query->leftJoin('field_data_field_last_name', 'l', 'u.uid = l.entity_id');
  $query->fields('u', array('mail', 'name'));
  $query->fields('n', array('field_first_name_value'));
  $query->fields('l', array('field_last_name_value'));
  $query->condition('r.rid', ROLE_ID, '=');
  $result = $query->execute()->fetchAll();

  foreach ($result as $val) {
    $alias = drupal_get_path_alias('node/' . $node->nid);
    $data = 'Hi ' . $val->field_first_name_value . ' ' . $val->field_last_name_value . ', new content has been published of your interest. ';
    $data .= 'Click ' . l('here', $base_url . '/' . $alias) . ' to see the content.';
    $key = 'new_content_mail';
    $subject = 'New content published';
    $to = $val->mail;
    _get_mail_content($data, $to, $key, $subject);
  }
}

Now define your mail content function:
function _get_mail_content($data, $to, $key, $subject) {
  $mail_content = _mail_content($data, $key);
  $params = array(
   'body' => $mail_content,
   'subject' => $subject,
  );
  $mail = drupal_mail('module_name', $key, $to, language_default(), $params, 'firstname.lastname@example.com', TRUE);
  if ($mail['result']) {
   return TRUE;
  }
  else {
    $error_msg = 'Failed to send the email!';
    watchdog('new-content-email', $error_msg, array(), WATCHDOG_ALERT);
    return FALSE;
  }
}

Define _mail_content:
 function _mail_content($data , $key) {
   switch ($key) {
    case 'new_content_mail':
      return theme('mymodule_new_content_mail', array('data' => $data));
    break;
   }
 }

Now define the template file in your hook_theme() and print $data inside it.
function mymodule_theme() {
  return array(
    'mymodule_new_content_mail' => array(
      'template' => 'mymodule-new-content-mail',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'variables' => array('data' => NULL),
    ),
  );
}

Now add new rule, select the event node-after publishing new content, add the node type in the condition for which you want to send mail and select _send_new_content_mail in action which will be present under 'custom'.
Comment: Interesting alternative for those who prefer to build their custom module for this. I haven't tested it (have you?), but IMO there is at least 1 (possible 2) errors near the top: (1) ***hook_*** cannot be correct and (2) are you sure there is nothing missing to invoke the **_send_new_content_mail** function (I think something is missing, no)?
Comment: thanks for reminding. Yes I have implemented this and hook obviously needs to be replaced with your module name.
Comment: My question was not if you implemented this, bit if you "tested" this. And the main reason why I doubted is exactly because of the (appropriate!) correction you now applied in revision 2 of your answer. How about you try to make it perfect by changing the "***hook_***" to "***mymodule_***" also (like you already did for the theme function in the end). If you do, you get my +1 (because I like it as a sample to illustrate another solution using custom code). OK?
Comment: Well that's your choice whether you  give +1 or not :).
Hope you understand the functionality that how its working.
Comment: merci for accepting my suggestion!
Answer: It is very well possible that your "issue" (the errors produced in your first Rules Action) is because of the Rules Event you're using (= "after saving new content"), which might simply not be the right event. Don't believe me ... yet ... read on to get surprised ...
Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that After saving something actually happens ... Before saving something (which is not a bug, simply how the Rules module  works ...).
A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).
Comment: Yeah I did tHat before, I set the whole thing as a component and executed manually. The result is same. When I am asking the question, to be clear and ask about the next steps easily, I asked as if I am doing this in a triggered rule. :)
Answer: There seems to be a bug in the latest version of VBO.
Check out https://groups.drupal.org/node/516374#comment-1153591 for a fix
Comment: This might be considered a link-only answer though probably correct. Thank you for adding it and hopefully it is useful to others.


Is an LFO applied to pitch the same as a modulator from an FM synth with a low frequency?

Question: I am new to sound synthesis and the programming language (FUZE4 on the Nintendo Switch) I am using has only a frequency modulator function. The modulator as I understand in general FM synth applications adds an additional frequency to the carrier frequency.
Is this the same behavior of an LFO applied to pitch?
I wonder if I am able to create LFO effects with this modulator function even if I have no explicit LFO functionality.
I am not sure if an LFO just modifies the carrier frequency or if it also adds an additional signal to it.
thank you for clarifying.
Comment: "Modulator" could mean lots of different things; there are lots of kinds of modulation. Tell us which function of which programming language you're using, and we'll be able to give a good answer.
Comment: Thank you for your comment. With modulator, I mean the modulation, done by an [FM synth](https://youtu.be/vvBl3YUBUyY). The language is [FUZE4](https://fuzearena.com/help/view/setModulator), running on Nintendo Switch. Its a language to develop games. The modulator implemented in FUZE4 works the same as a modulator on a FM synth. As I understood FM Synth: two oscilators, and the second is modulating the first one. I am not even sure, what is the meaning of "one is modulating the other", would it not be the same as they are just played together? Thanks for more comments.
Comment: Thanks for clarifying. If you have a moment please [edit] your question so that the additional details are included as if they had been there from the start.
Comment: I edited the question to reflect that its about FM Synth and FUZE4.
Answer: Yes, "an LFO applied to pitch" is the same basic structure as "FM synthesis". In both cases, you have a sound-producing (carrier) oscillator and a modulation oscillator (whether it is called LFO or not), and the sound-producing oscillator's frequency is increased or decreased according to the instantaneous value of the modulation oscillator's output.
However, there are some further restrictions needed in order to get good-sounding FM synthesis:

The output of the modulation oscillator must be symmetric — extending equally above and below zero. If this is not done, then increasing modulation depth (the amplitude of the frequency variation) will change the perceived pitch of the note as well as changing timbre, which is usually considered undesirable if you are trying to stick to a musical scale.
The change in frequency must be linear. This is sometimes referred to as "modulating frequency rather than pitch". This means that how far the carrier is modulated is equal up and down in Hz rather than in semitones. Again, if this is not done correctly then modulation will change the perceived pitch of the note.
Optional: The modulation oscillator's frequency should have a simple ratio with the carrier oscillator's unmodulated frequency. If the ratio is not simple, then the result is "inharmonic": it contains frequency components that are not just integer multiples of the carrier frequency. These sounds will be heard to change in timbre as they play, quickly or slowly, and are often referred to as "bell-like".

If you ignore some of these rules, you'll still get a frequency-modulated sound but it may not be as "conventionally musical".

That's the big picture, now I'll comment on some of your wonderings:

The modulator as I understand in general synth applications adds an additional frequency to the carrier frequency.

This is not really true. In general, "modulation" means "change some parameter according to some other signal". In the case of FM, we change the main oscillator frequency, but there are lots of other parameters that could be modulated, such as amplitude, filter cutoff, wave shape, and so on.
Also, "add another frequency" is a rather ambiguous phrase. For example, if I take two oscillators at two different frequencies and add their output signals, then I have a signal to which I have "added another frequency", but that's not FM, that's just playing two notes at once. It's okay to say you "added" something when the signal flow is already established, but when we're trying to talk about what the signal flow is,, it's not very specific at all.

I wonder if I am able to create LFO effects with this modulator function evene if I have no explicit LFO functionality.

If you can turn the FM ratio low enough, then yes. (I'm assuming, being a digital FM synth, that it offers you a "FM ratio" control rather than a "modulator frequency" control.) But since in FM synthesis we usually want the modulator to stick to a certain ratio with the carrier, you'll find that when you play a higher note the rate of the modulation also increases (e.g. one octave up ⇒ twice as fast modulation), whereas a LFO would usually stick to the same low frequency.

Disclaimer: I'm fairly new to synthesis in a musical context myself, and haven't actually worked with digital FM synthesis, and some of my terminology may be a bit off. Suggestions welcome.
Comment: This was very, very helpful. I am happy I finally posted this here. You are fairly new to synthesis, ok, but then you have a gift for it. Thank you for your time and your answer.
Comment: I don't exactly understand yet, how the sound differs, if one oscilator is frequency modulated by a modulation frequency, or if just two oscilators are creating a signal at the same time. I opened [another thread](https://music.stackexchange.com/questions/100524/is-a-frequency-modulated-in-an-fm-synth-signal-perceived-by-our-ears-as-the-sa]) for that discussion.


How to open/close clicked div generating inside loop with angular js?

Question: I am having my divs generating inside ng repeat tag like accordion and now on click of particular div I want to show/hide that clicked div only.
This is my code:

      {{ ::item.Name }}

        <button ng-click="closeClickedDiv()"></button>

//div 1

//div 2

{{ ::item1.subName }}

Js:
  $scope.showDiv = false;//by default all divs will be closed

 $scope.closeClickedDiv = function () {
      $scope.showDiv = !$scope.showDiv;
    };

But here problem is when I click on 1 div all divs get opened.I want to open/close clicked div on this button click.
Answer: Use 'hide' property binded to the item, not the scope:
$scope.closeClickedDiv = function (item) {
  item.hide = !item.hide;
};

<button ng-click="closeClickedDiv(item)"></button>

Comment: no need to be declared, just set initial state for example in an ngInit directive, or invert the logic, use a notVisible property and ng-hide directive
Comment: so i should declare this showDiv  property inside my item array??
Comment: Sorry can you please add in your answer as i am new in angular js
Answer: Call a method on ng-click and pass $index in it
ng-click="ShowDetailed($index)"

Now declare empty array and pass this in ng-show
ng-show="detailedShow[$index]"

Here is the method -
What it does
1. Will open on click and close on second click
2. If you opened first and clicked on second, it will close first and open second.
$scope.detailedShow = [];
var lastIndex = null;
var currentIndex = null;
$scope.ShowDetailed = function(index) {
  currentIndex = index;
  if (lastIndex) {
    if (lastIndex !== currentIndex) {
      if ($scope.detailedShow[lastIndex]) {
        $scope.detailedShow[lastIndex] = !$scope.detailedShow[lastIndex];
      }
      $scope.detailedShow[index] = !$scope.detailedShow[index];
      lastIndex = currentIndex;
    } else {
      $scope.detailedShow[index] = !$scope.detailedShow[index];
    }
  } else {
    $scope.detailedShow[index] = !$scope.detailedShow[index];
    lastIndex = currentIndex;
  }
};


Convert 'String' to 'SQlCommand' in vb.net

Question: I am a novice vb programmer. I am sure it's simple but I can't get it right.

Value of type 'String' cannot be converted to 'SQLCommand'

It is the error.
Public Sub InsertPackageDetails(ByVal PackageName As String, ByVal PackageDescription As String, ByVal DateOfInstallation As DateTime, ByVal ImportPackageStatus As String)
    Dim SQL As String = "Insert into PackageInstallation(PackageName,PackageDescription,DateOfInstallation,ImportPackageStatus) values('" + PackageName + "','" + PackageDescription + "','" + DateOfInstallation + "'," + ImportPackageStatus + ") "
    DBHelper2.ExecuteNonQuery(SQL)
End Sub

How can I convert SQL which is the string to SQLCommand?
I appreciate the help.
Comment: [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/)
Comment: There's no implicit conversion between a string and SqlCommand. You need to create a new instance of the SqlCommand class and pass the query text to it.
Answer: You can see the various ways to create a command here. https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.-ctor?view=dotnet-plat-ext-3.1
You should use Using...End Using blocks so that your connection and command will be closed and disposed but you will need to have these objects in the local method where they are used.
I had to guess at the type and size of your fields in the database. Check in the database and correct the code accordingly.
Public Sub InsertPackageDetails(ByVal PackageName As String, ByVal PackageDescription As String, ByVal DateOfInstallation As DateTime, ByVal ImportPackageStatus As String)
    Dim SQL As String = "Insert into PackageInstallation(PackageName,PackageDescription,DateOfInstallation,ImportPackageStatus)
                          Values(@PackageName, @PackageDescription, @DateOfInstallation, @ImportPackageStatus;"
    Using cn As New SqlConnection("Your connection string"),
            cmd As New SqlCommand(SQL, cn)
        With cmd.Parameters
            .Add("@PackageName", SqlDbType.VarChar, 100).Value = PackageName
            .Add("@PackageDescription", SqlDbType.VarChar, 100).Value = PackageDescription
            .Add("@DateOfInstallation", SqlDbType.DateTime).Value = DateOfInstallation
            .Add("@ImportPackageStatus", SqlDbType.VarChar, 100).Value = ImportPackageStatus
        End With
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub


Permutation as an algebraic structure

Question: Following the definition of an algebraic structure as a set with a collection of $n$-ary operations (https://en.wikipedia.org/wiki/Algebraic_structure) we must consider a set with a permutation (as a unary operation) as an algebraic structure.
The structure is much simpler then a set with a binary operation, so we could expect multiple properties to be defined on the structure first and then applied to more complex structures.
An example of such properties is the decomposition of a finite permutation onto disjoint cycles that becomes the decomposition onto cyclic subgroups of an abelian group.
But instead, we have disconnected terminologies developed for permutations and for magmas/semigroups/groups independently.
One of the most prominent disconnections is the difference between the notions of a cyclic permutation and a cyclic group (Power of an element of a permutation).
Is this a result of a lack of a definition of an algebraic structure of a permutation?
Is there a name for such a structure?
Comment: For the lack of better terminology, I am just going call such an algebraic structure a permutation.
Comment: You're right that there is some disconnected terminology there, but the notions are not totally unrelated. Typically permutations are thought about as being algebraic objects themselves, but rather as elements of a larger algebraic object (permutation groups), so this is probably why there are discrepancies in the terminology. I'll expand more in a full answer.
Comment: @Anonymous We have a similar situation with ordered structures. But there is a name "ordered" for them. In case of a permutation there is no even a name "permutative" or "permutational"... What should I say when addressing a set with a permutation?
Comment: The question is similar to this one: https://math.stackexchange.com/q/1106387/427611
Answer: As far as I am aware, there is no name for such a structure, so I will simply call it a permutation. I think there is little use in group theory for allowing infinite permutations to be cyclic, whereas allowing the infinite group $\mathbb{Z}$ to be cyclic is useful for the classification of finitely generated abelian groups. Nonetheless, one could certainly extend the definition of a cyclic permutation to be a permutation $\sigma:X\to X$ such that there exists $x_0\in X$ such that for all $x\in X$ either there exists $n\in\mathbb{Z}$ such that $\sigma^n(x_0)=x$, or $\sigma(x)=x$ (i.e. there is at most one orbit which has more than one element). The "or $\sigma(x)=x$" could be removed to better match the definition of a cyclic group as something which is generated by one element, but the traditional definition of cyclic permutation requires this caveat. I will call $\sigma$ primitive cyclic if the "or $\sigma(x)$" condition can be dropped (i.e. there is exactly one orbit).
In the class of permutations, appending two disjoint permutations together corresponds to a coproduct (i.e. disjoint union) in the category of these algebraic objects. As far as I am aware, there is not too much we can say about this category since permutations are a fairly simple algebraic object, but we do get one theorem analogous to the fundamental theorem of finitely generated abelian groups. Namely, any finitely generated permutation (or even non-finitely generated permutations for that matter) can be decomposed into a coproduct of primitive cyclic permutations.
$\textit{Proof}.$ Let $\sigma:X\to X$ be a permutation. We can define an equivalence relation by declaring $x\sim y$ iff there exists $n\in\mathbb{Z}$ such that $y=\sigma^n(x)$ (i.e. the equivalence class of $x$ is the subpermutation of $(X,\sigma)$ generated by $x$). For each equivalence class, choose a representative and denote the collection of these representatives by $\{x_\alpha\}_{\alpha\in I}$. I claim
$$(X,\sigma)\cong\coprod_{\alpha\in I}\langle x_\alpha\rangle$$
where $\langle x_\alpha\rangle$ denotes the substructure of $(X,\sigma)$ generated by $x_\alpha$ which is clearly a primitive cyclic permutation. Let $\iota_\alpha:\langle x_\alpha\rangle\to X$ be the inclusion maps (which are clearly homomorphisms between these algebraic structures), let $\tau:Y\to Y$ be a permutation, and let $f_\alpha:\langle x_\alpha\rangle\to Y$ be a collection of homomorphisms (i.e. functions such that $\tau f_\alpha=f_\alpha\sigma\vert_{\langle x_\alpha\rangle}$). Then we can define a function $f:X\to Y$ as such: Given $x\in X$, there exists a unique $\alpha\in I$ such that $x\in\langle x_\alpha\rangle$, so take $f(x):=f_\alpha(x)$. By uniqueness of $\alpha$, this is well-defined, and because $\tau f_\alpha=f_\alpha\sigma\vert_{\langle x_\alpha\rangle}$ for all $\alpha$, we see $\tau f=f\sigma$ (i.e. $f$ is a homomorphism). Furthermore, we clearly see $f_\alpha=f\iota_\alpha$ for every $\alpha$. Thus, $(X,\sigma)$ satisfies the universal property of the coproduct, so there is a canonical isomorphism between $(X,\sigma)$ and $\coprod_\alpha\langle x_\alpha\rangle$.
Comment: @AlexC I think you misunderstood that comment. They wrote "(cycle of length $>1$)" after the initial definition because the initial definition was only valid for cycles of length $>1$. However, the more formal notions of cyclic permutation they give below that are valid for cycles of length $1$. Also, the "length $>1$" comment doesn't necessarily exclude infinite length. This is supported again by the more formal definition they give below the initial one.
Comment: After reviewing Wikipedia, it seems that their definition actually allows cyclic permutations to be infinite, although all there examples are all finite (https://en.wikipedia.org/wiki/Cyclic_permutation).
Comment: I tried to find that in the article, but at the definition part they explicitly say that it is a cycle of length > 1. I assume it means it has a length, meaning it is finite. And, by the way, they excluded cycles with length 1, which is nonsense.
Answer: I can't recall coming across a special term for a permutation as an algebraic structure. However, slightly more generally, from George Weaver, The First-Order Theories of Dedekind Algebras (2003):

A Dedekind Algebra is an ordered pair $(B,h)$ where $B$ is a non-empty set and $h$ is an injective unary function on $B.$

More generally still, from Unary algebra - Encyclopedia of Mathematics:

A unary algebra with a single basic operation is called mono-unary, or a unar. An example of a unar is the Peano algebra $\left\langle P, f \right\rangle,$ where $P = \{1, 2, \ldots\}$ and $f(n) = n + 1.$

["Mono-unary algebra": a mixture of Greek, Latin and Arabic roots!]
Even more generally, there is the concept of a mono-unary partial algebra, one mention of which is on p.16 of Ito et al. (eds.), Automata, Formal Languages and Algebraic Systems - Proceedings of AFLAS 2008 (2010).
From Symmetric inverse semigroup - Wikipedia:

In abstract algebra, the set of all partial bijections on a set $X$ (a.k.a. one-to-one partial transformations) forms an inverse semigroup, called the symmetric inverse semigroup (actually a monoid) on $X.$ $[\ldots]$ When $X$ is a finite set $\{1, \ldots, n\},$ the inverse semigroup of one-to-one partial transformations is denoted by $C_n$ and its elements are called charts or partial symmetries. The notion of chart generalizes the notion of permutation. $[\ldots]$ The cycle notation of classical, group-based permutations generalizes to symmetric inverse semigroups by the addition of a notion called a path, which (unlike a cycle) ends when it reaches the "undefined" element; the notation thus extended is called path notation.

(This is no mere sterile generalisation for generalisation's sake. Apart from whatever technical applications it has in pure mathematics - Lipscomb's book on the subject covers those thoroughly, no doubt - it is needed to understand the notion, familiar to everyone since childhood, of counting a finite set, for which one needs a version of the Dedekind-Peano axioms with a partial successor function. As this is a hobby horse of mine, however, I'd better say no more about it!)
Comment: Great references. Thank you.

Permutation as an algebraic structure


Using symlinks / multisite to display one drupal site at two domains

Question: Does it create any problems for me to use symlinks to display the same drupal site at more than one domain? It appears to work, but I'm not sure if bugs might appear in the future due to scripts being misinterpreted as XSS attacks or something.
Example
I own two domains, sweet-bro.com and hellajeff.net . They're hosted on the same account, such that people who go to sweet-bro.com see the files in ~/sweet-bro/html and people who go to hellajeff.net see the files in ~/hellajeff/html
There's a drupal 7 site at http://sweet-bro.com/drupal and I want visitors to see the same site if they go to http://hellajeff.net/ruse . So, first I make a symlink in the html directory:
ln -s ~/sweet-bro/html/drupal  ~/hellajeff/html/ruse

Then I make a symlink in the sites directory:
ln -s ~/sweet-bro/html/drupal/sites/default  ~/sweet-bro/html/drupal/sites/hellajeff.net.ruse

This is what I've done and it seems to be working. Is there any reason not to do it this way?
Answer: I don't think it's going to cause any problems, but it seems you just make things complicated for no reason. So, that would be a reason not do it that way :)
Just point both domaines to ~/sweet-bro/html and get rid of the symlink in /sites/.
Both domains will be showing the same site, as long as you don't use a .htaccess rule to redirect to one or the other.
Comment: It's true that this would work, but I'd prefer for hellajeff.net to be the main location for the site, and for that to be the domain the visitors see. In fact, I'm not interested in them visiting sweet-bro.com at all, it's just the main drupal install for a multisite setup. Sorry the question was misleading in that way -- I was trying to make it easier to explain.


What should I look for while considering a used keyboard?

Question: I used to learn piano when I was little and now I'm considering to start again as a complete beginner. I don't know how long this is going to stick so I'm going for a used instrument.
I found a not-so-local list for a used Korg SP-250 for about $250. I only have the photo of it avaliable to me right now, and it seems that it has suffered some cosmetic damages (dotty stains on speaker grille, scratch on far right keys and chips that I've not been able to identify from the photo but seller mentions it). The seller claims that everything functions okay.
A quick research says that Korg is a respected brand in keyboards and this model is quite old. (Amazon last sold one in 2015 and it was discontinued) In fact, the age does make me a bit anxious. I do not know much about keyboards and I don't have anywhere else to turn. This is from a private seller, so there will be no way out if things go south.
Since I don't know how to interpret the spec-sheet, what is this keyboard, and is it okay? What should I look for, test for, and which questions should I be asking the seller?
Comment: Asking specifics about this particular k'bd will get the question closed - but the title is in its favour.
Comment: The only way to decide whether you like it would be to play it. As that's out of the question, you're just going to have to make the call. No-one can help you on that. Caveat emptor… which is why I'd always buy from a music shop (in normal times)
Answer: You're right to be looking at something with weighted keys and 88 notes if learning piano is your ultimate goal.
Weighted keys enable you to achieve a range of volumes by responding to the force you apply to them. Some synthesiser/keyboards are not 'touch sensitive' at all. Others often only provide a much more limited sensitivity.
Weighted keys also mimic the feel of a traditional piano (to varying degrees of success).
A full-size piano has 88 notes. 88 notes provides a far greater tonal range than smaller keyboard formats, such as the popular 61 note styles. Many, many popular piano pieces require an 88 note keyboard to be played, and even if you are interested more in improvisation/composition, an 88 note keyboard provides a greater capacity for expressive potential.
You might also consider whether any keyboard you buy comes equipped with one or more expression pedals (Usually a damper/'soft' pedal and a sustain pedal, which 'holds' onto the note when depressed). These can be purchased separately, providing the keyboard has an appropriate input (most do, but it's worth checking).
As for buying second-hand from a seller who lives a long way away, simply as him or her to send a short video of every note being played in succession. This will identify important mechanical and/or tonal issues. If they are not willing to this simple task, look elsewhere.


Prove that a simple planar bipartite graph on $n$ nodes has at most $2n-4$ edges.

Question: By simple I mean no loops or double edges.
Comment: hmm...I got it out of Lovasz's Discrete Math text and have given it to my students for HW.  If you find a counter example, let me know.  Thanks.
Comment: @Ali:  Do you mean that the entire result is false or that it is false for some cases?
Comment: What do you mean by "no loops" in the case of a bipartite graph ?
Comment: Congratulations on putting in almost no effort into the question and still somehow getting 2 golden badges and half of the way to the "Good Question" Badge. I am positively surprised.
Answer: This is a very standard result in graph theory.
Theorem: If a connected planar graph with more than $3$ vertices has no cycles of length $3$, then $e \le 2v-4$.
Proof: From Euler's formula, we have $v-e+f=2$. Since there are no cycles of length $3$, every face has degree $4$ or greater. From the handshaking lemma, we then have
$$4f \le \sum_{f\in F}\deg(f) = 2e$$
Substituting, we have
$$2 = v-e+f \le v-e+\frac{e}{2}$$
which is the required result.
Comment: It's easily overlooked that the proof really makes use of $v\ge3$.
Comment: nic eexplanation sir


My pager code doesn't work

Question: I'm using the following code just to see if the paging works in Drupal 7, but I'm having trouble to set it to work.
<code>$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5);

$headers = array(t('node'), t('Title'));
$rows = array();
$result = $query->execute();

foreach ($result as $record) {
  $rows[] .= array($record->nid, $record->title);
}

$output = theme('table', $headers, $rows);
return $output . theme('pager');
</code>
I'm not so good with PHP, so can someone please tell me what am I doing wrong?
Answer: Your code is using the string concatenation operator with an array; you need the assignment operator.
<code>$rows[] = array($record->nid, $record->title);
</code>
<code>$headers = array(t('node'), t('Title'));
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

return theme('table', $headers, $rows) . theme('pager');
</code>
Depending from which function contains that code, it could also be re-written as follows:
<code>$page = array();
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

$page['table'] = array(
  '#rows' => $rows,
  '#header' => array(t('Node'), t('Title')),
  '#theme' => 'table',
  '#empty' => t('No content available.'),
);

$page['pager'] = array(
  '#theme' => 'pager',
);

return $page;
</code>

My pager code doesn't work


Composition of Linear Maps satisfying $ST\neq TS$

Question: Is the following proof Correct?
Theorem. Suppose $V$ is finite-dimensional with $\dim V \ge 2$. Prove that there exist
$S,T\in\mathcal{L}(V,V)$ such that $ST \neq TS$.
Proof. Since $V$ is finite-dimensional  and $\dim V = m\ge 2$ it follows that there exist a list of vectors $v_1,v_2,...,v_m$ basis for $V$, arguing from cases
Case-1$(m =2)$: Consider the linear transformations $S$ and $T$ defined as follows
$$Tv_1=v_1,\ Tv_2=0$$
$$Sv_1=v_2,\ Sv_2 = v_1$$
consequently
$$S(Tv_1)=Sv_1=v_2,\ S(Tv_2)=S(0) = 0$$
$$T(Sv_1)=Tv_2=v_1,\ T(Sv_2)=Tv_1 = v_1$$
evidently $ST\neq TS$.
Case-2$(m > 2)$: Consider now the linear transformations $S$ and $T$ defined by
$$Tv_{j}=v_{m-j+1}$$
$$Sv_{j}=v_{j\bmod m+1}$$
consequently
$$T(Sv_j) = v_{m-(j\bmod m+1)+1}$$
$$S(Tv_j) = v_{(m-j+1)\bmod m+1}$$
Assume now that there exists some $j\in\{1,2,...,m\}$ such that
$$m-(j\bmod m+1)+1=(m-j+1)\bmod m+1$$
but then
$$\implies m-(j\bmod m+1)=(m-j+1)\bmod m$$
$$\implies m-(j\bmod m)-1=(m-j+1)\bmod m$$
$$\implies m-1=(m-j+1)\bmod m+(j\bmod m)$$
$$\implies m-1=(m-j+1+j)\bmod m$$
$$\implies m-1=(m+1)\bmod m$$
$$\implies m-1=1$$
$$\implies m=2$$
resulting in a contradiction we may now conclude that
$$\forall j\in\{1,2,...,m\}(S(Tv_j)\neq T(Sv_j))$$
implying that $ST\neq TS$.
$\blacksquare$
Comment: I personally found nothing else wrong with the proof aside from the comment above.  What I find weird, though, is that I interpreted $TS \neq ST$ to mean that for some $v$, $TS(v) \neq ST(v)$.  You ended up proving something stronger than my intepretation: that $TS(v) \neq ST(v)$ for all $v$.
Comment: Minor mistake so far.  $T(S(v_{1})) = T(v_{2})  = 0$.  You have the last equality as $v_{1}$.
Comment: @layman Indeed!
Comment: Is this exercise from *Linear Algebra Done Right* by Sheldon Axler? If not what book is it from?
Comment: @layman, assuming $v\ne0,$  :P
Comment: @Scientifica Yes this is from Sheldon Axler Ch.3 Excercise A Question 14
Comment: @layman thanks for pointing that out !
Answer: Your proof looks correct besides the small mistake that layman spotted out. As layman said, it's impressing that you went as far as finding $T,S\in\mathcal{L}(V)$ with $TSv\neq STv$ for every $v$ when $\dim V>2$. I'd just like to point out two small things:
1- In your proof for the case $\dim V=2$, you didn't have to bother yourself calculating the images of $v_2$ by $ST$ and $TS$. Since $STv_1\neq TSv_1$ this shows that $ST\neq TS$.
2- You could use generalize your construction in the case of $\dim V=2$. Define $S$ and $T$ for $v_1$ and $v_2$ just as you did, and then for $v_3,\dots,v_n$ (if the dimension is larger than $2$) define their values in whatever way (say $Sv_i=Tv_i=v_i$ for $i\ge 3$, or $Sv_i=Tv_i=0$ for $i\ge 3$, or whatever). You will still have $TSv_1=0$ and $STv_1=v_2$, showing that $TS\neq ST$.


Spark Shuffle takes place because Spark needs to transmit data across Stages

Question: spark Document:
    In Spark, data is generally not distributed across partitions to be in the necessary place for a specific operation. During computations, a single task will operate on a single partition - thus, to organize all the data for a single reduceByKey reduce task to execute, Spark needs to perform an all-to-all operation. It must read from all partitions to find all the values for all keys, and then bring together values across partitions to compute the final result for each key - this is called the shuffle.
spark document:
"This typically involves copying data across executors and machines, making the shuffle a complex and costly operation."
my understanding is:"This typically involves copying data across "task", making the shuffle a complex and costly operation."
I think computing shuffle across tasks. Is this understanding correct?
Comment: Bad title it appears
Comment: Does this answer your question? [Spark: disk I/O on stage boundaries explanation](https://stackoverflow.com/questions/58699907/spark-disk-i-o-on-stage-boundaries-explanation)
Answer: Your understanding is somewhat accurate, although I think the docs were trying to emphasize the more expensive operation of sending data over the network, as opposed to staying on a single node, which can have multiple tasks, especially if it has multiple cores.
There are some nuances:
Quote from Cloudera doc: "A stage is a collection of tasks that run the same code, each on a different subset of the data." Generally, the shuffle data is the output of a stage (set of tasks) saved for the next (dependent) stage to be run afterwards.
Spark 2.x docs: "During a shuffle, the Spark executor first writes its own map outputs locally to disk, and then acts as the server for those files when other executors attempt to fetch them." This is the end part of a stage. Furthermore, the service providing shuffle data is "a long-running process that runs on each node of your cluster independently of your Spark applications and their executors". This means tasks, too.
As you mentioned, a shuffle can happen at the end of the stage, for example, if there is a reduceByKey involved. However, the output of the tasks is managed outside of the tasks themselves, so the tasks are not typically copying data amongst themselves directly. Rather, the data is saved somewhere on the node, and fetched later on-demand.
Comment: reduceByKey is in fact quite economical and thus a bad example, more like groupBy, etc.
Comment: Good point, but both operations would technically still result in a shuffle, so the OP is right.
Comment: You get my point I believe, different sort of shuffle to repartition


SmartGWT MenuItem show Checked on canSelect(false)

Question: i have a problem in my SmartGWT-Application.
I should display different Organisations in a Menu where the user can see them and can change his Organisation.
But the thing is, he should see the active Organisation, see that the specific Organisation is active, but he should't be able to click it.
Here is my code so far:
if(menuItemList[location].getAttribute("id").equals(USER_MANAGER.getUserOrganisation())){
    menuItemList[location].setChecked(true);
    menuItemList[location].setCanSelect(false);
}else{
    menuItemList[location].setChecked(false);
    menuItemList[location].setCanSelect(true);
}

The Problem is, that SmartGWT doesn't show the Checked-Icon (checkmark) if the MenuItem is "canSelect(false)".
Also there isn't a difference in the generated HTML code that let me see if the MenuItem is that with the active organisation.
Does anyone have a workaround or know what i did wrong?
Answer: I found the solution:
I've used the wrong Event-Handler for what i wanted to do.
Since i let the MenuItem's generate with DataSource and not Directly, those elements don't exist at the moment of the Code execution
previously i've used the DrawHandler() and the Element hasn't had the ID at this moment(at least i think that).
that's why my if(){}else{} won't do as i wanted it to.
But with the MembersChangedEvent, the code is executet after the Element gets it's id and therefore the Elements can check their ID with the one from my USER_MANAGER.
Hope this helps somebody with the same problem


NetworkError: 400 Bad Request

Question: Ao Enviar um post recebi pelo retrofit no log a mensagem NetworkError: 400 Bad Request.
No Ambiente de Desenvolvimento nenhum erro ocorre, os dados são sincronizados do dispositivo para o Servidor ( Tomcat ) de minha rede interna com sucesso.
Publiquei o sistema, no dispositivo eu configurei a URL, e ao tentar transmitir os dados recebo o erro NetworkError: 400 Bad Request
http://18.104.22.168:8080/nova/fw.rule?sys=TSE&usuario=teste&metodo=fw_addSessao&parametros=7b911e32-1432-45c3-8ee0-e316bad7a2f7|2|15/01/2017%2023:19:44|15/01/2017%2023:22:01|e8b5ed5c-d1bf-43c2-a7ad-cdb7699cc496|Outros|Teste%20|-7.99032|-34.8935

Os parametros são:
sys=TSE

usuario=teste

metodo=fw_addSessao

parametros=7b911e32-1432-45c3-8ee0-e316bad7a2f7|2|15/01/2017%2023:19:44|15/01/2017%2023:22:01|e8b5ed5c-d1bf-43c2-a7ad-cdb7699cc496|Outros|Teste%20|-7.99032|-34.8935

tudo é enviado em texto, o ultimo parâmetro tem concatenado varias informações como Id do registro, latitude, longitude e eu usei como delimitador o pipe "|" e pelo que eu estou notando o problema é ele, mais em minha rede interna não tem problema nenhum com o seu uso.
Comment: Você diz que no Amabiente de desenvolvimento não ocorre erros, isso quer dizer que quando disponibiliza para produção esse erro acontece? Você verificou se a URL está correta?
Comment: Sim a url esta correta, e uma vez que peguei ela do log do AE, fiz o seguinte onde tinha o "|" mudei para ";" ai o erro passou a ser o 500 que indica um erro no Servidor ou seja o POST chegou no servidor e como minha regra de negocio espera por um delimitador e chegou outro a rotina quebrou.
Comment: Tenta usar o URL ENCODE. Esse problema que está dando é requisição. Você não ta fazendo a requisição corretamente no server.
Comment: Veja: http://www.url-encode-decode.com/
Comment: Olá Ack Lay boa tarde, entendi bem seria para pegar o texto onde eu tenho varias informações concatenadas e fazer um encode nele? e no servidor um decode?
Comment: Exatamente. Tente fazer isso, talvez tenha alguns caracteres que estão entrando em conflito com caracteres padrões da URL e está dando problema na interpretação.
Answer: O erro 400 Bad Request ocorre quando servidor não pode compreender e processar a solicitação correspondente. Depois de ter conferir se a URL referente ao servidor esteja realmente correta, uma solução possível é codificar os parâmetros usando a classe URLEncoder, para que não tenha conflito com algum carácter reservado. Veja como ficaria:
String parametroCodificado = URLEncoder.encode("?sys=TSE&usuario=teste&metodo=fw_addSessao&parametros=7b911e32-1432-45c3-8ee0-e316bad7a2f7|2|15/01/2017%2023:19:44|15/01/2017%2023:22:01|e8b5ed5c-d1bf-43c2-a7ad-cdb7699cc496|Outros|Teste%20|-7.99032|-34.8935", "utf-8");
String url = "http://22.214.171.124:8080/nova/fw.rule" + parametroCodificado ;

Para mais detalhes sobre URLEncoder, veja na documentação.
Comment: Meu caro Ack Lay, vc estava absolutamente certo, muito obrigado cara, valeu mesmo, salvou o dia

NetworkError: 400 Bad Request


Intercept significant but not the variables in GLM

Question: I got these results from a GLM from R, but I am not sure what it means that the intercept is significant but none of my variables actually are. So is nothing really significant? Here are my results:
Groups Name        Variance   Std.Dev.  Corr
 Plot   (Intercept) 1.4842e+07 3852.4696
        Year        3.6783e+00    1.9179 -1.000
Number of obs: 121, groups: Plot, 50

Fixed effects:
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)        -3.90239    1.36721  -2.854  0.00431 **
Wald_ManagBUBAdi  -16.50851 9563.66009  -0.002  0.99862
Wald_ManagBUBAj     0.45015    2.31227   0.195  0.84564
Wald_ManagBUBAun    1.63915    1.46892   1.116  0.26447
Wald_ManagBUdi     -0.03527    2.25725  -0.016  0.98753
Wald_ManagBUplen    1.14402    1.52959   0.748  0.45450
Wald_ManagFIBA      2.92878    1.53228   1.911  0.05595 .

Comment: Could well be separation as @tiantianchen suggests: see [here](http://stats.stackexchange.com/questions/11109/how-to-deal-with-perfect-separation-in-logistic-regression/68917) for a discussion of ways to deal with it.
Comment: I kind of have the same thing: a significant intercept effect, but no significant effect of my factor. However, in my case it is interesting to know whether the data differs from 0. Am I allowed to do a post-hoc analysis testing the levels of my factor separately to check for an intercept effect?
Comment: Welcome to the site. This is not an answer to the question, so I am converting it to a comment.
Comment: I just posted a question which might have similar problem as this post: http://stats.stackexchange.com/questions/72824/a-categorical-variable-in-glm-shows-signifcance-from-analysis-of-deviance-but-e; maybe you could check your data to see whether all response are 0 or 1 when the variable is Wald_ManagBUBAdi
Answer: The intercept is the predicted value of the dependent variable when all the independent variables are 0. It is rarely of interest, unless the IVs are centered or standardized. Since you haven't told us what any of your variables are, there's no way to say more than that.
Answer: The standard error of this variable
Wald_ManagBUBAdi  -16.50851 9563.66009  -0.002  0.99862

is kind of alarming.  I would suggest trying to see if something went wrong with the data for that variable, or try excluding it from the model and see what happens to the significance levels of the variables left in the model.


convert java code to c# code (hexString To ByteArray)

Question: Hello I have a code in Java I want to make it to code in C # but I'm having a problem:
This code (func):
DatatypeConverter.parseHexBinary (temp);

I'm looking for a replacement in C#
On the other hand
I have the full code should do this in Java but also where I encountered a problem in this code:
public static byte [] hexStringToByteArray (String s)
{
    int len = s.Length;
    byte [] data = new byte [len / 2];
    for (int i = 0; i <len; i + = 2)
    {
        data [i / 2] = (byte) ((Character.digit (s.charAt (i), 16) << 4)
                                     + Character.digit (s.charAt (i + 1), 16));
    }
    return data;
}

The problem is that the compiler does not recognize the
Character.digit (s.charAt (i)

Any help is appreciated. Thanks!
Comment: Beer Sheva :) Thanks!
Comment: I think you used `Google translate` for that last line from hebrew. right? :P
Comment: genius!!!!!!!!!
Comment: I live in Modiin, btw. (I'm also trying to answer your question right now)
Comment: did you work it out?
Answer: To convert a hex string to a byte array, you can use:
public static byte[] HexStringToByteArray(string s)
{
    int len = s.Length;
    byte[] data = new byte[len/ 2];
    for (int i = 0; i < len; i += 2)
    {
        data[i / 2] = Convert.ToByte(s.Substring(i, 2), 16);
    }
    return data;
}


Sousaphone repair suggestions

Question: I've recently bought a cheap battered second (probably mode) hand sousaphone on a garage sale. It is in faily bad shape, but the valves look ok.
The instrument is made of a metallic grey alloy which shows through the cracked white paint. What could that alloy be? I need to make some repairs, and weld / solder some pieces together. What are the best options for this?
Answer: You can normally use silver solder on brass instruments. It may take a propane torch instead of a soldering iron. A lot of instruments are silver-plated brass.
Check for and seal leaks in the joints and around the valves and spit valves. They can cause resonance problems that  make it hard to hit certain notes.
Comment: Hey, nice answer. I have a friend's beater trombone, and one of the tube spacers has come unstuck. Problem is that it appears to be gold plated (or something that looks like gold). If I torch it and silver-solder braze it back together, the plating is going to come off, right? (the spacer is too heavy to use a soldering iron, I think). Is there any way to re-plate it after brazing, or is it just going to look ugly what ever happens?
Comment: It's possible to replate it after soldering it, but I don't know the details of how it's done. Local music stores that sell band instruments can usually do that.
Comment: probably a good idea to get a pro to do it, considering it's not my instrument. I might get an old beater and have a practice on that when it breaks :)

Sousaphone repair suggestions


Suppose $E=\cup_{n=1}^{\infty}A_n$ and the cardinal number of $E$ is $c$.

Question:
Suppose $E=\cup_{n=1}^{\infty}A_n$ and the cardinal number of $E$ is $c$ ($c$ represents the cardinal number of $(0,1)$). Prove that there exsits $n_0$ such that the cardinal number of $A_{n_0}$ is also $c$.

For now, I have proved if $E=A_1\cup A_2$ the conclusion holds. Then by induction the finite union case is also true. But I do not know how to prove the denumberable case stated above.
Appreciate any help or hint!
Comment: Hint: show that the union won't be countable at a certain index. As an uncountable union  does not produce a countable number.
Comment: Did you secrestly use the continuum hypothesis? Can you be more specific? I don't really follow.
Answer: Hint:
Are you aware that the cofinality of $\mathfrak{c}$ must be uncountable? This is a corollary of König's theorem.
Next, if you want to hit $\kappa$ by unioning stuff smaller than $\kappa$, you'll need to union at least $\text{cf}(\kappa)$ many things (do you see why?).
Putting these two facts together: if we try to union up countably many things of size $\lt \mathfrak{c}$, can we hit $\mathfrak{c}$?
As an aside, notice that we need choice in order to run this argument. It's consistent without choice that $\mathbb{R}$ is a countable union of countable sets!

I hope this helps ^_^
Comment: We can apply König's theorem right away: suppose on the contrary that each $A_n$ has smaller cardinality than $c$. Then $$|E|\le\sum_n|A_n|\ <\  c^\omega=(2^\omega)^\omega=2^\omega=c$$


Google Maps API: Change marker animation speed

Question: Google Maps API v3 currently supports two types of animation for markers: DROP and BOUNCE
Is there a way I can speed up the BOUNCE or slow down the DROP animation?
Answer: Google Maps API doesn't support animation properties or customization, just the ability to select "drop" or "bounce" as you said.
It should be possible to apply custom animations to marker elements through jQuery or other framework. Alternatively you could supply an animated GIF as a marker.


Add a form to the list output of a view

Question: Assume that I've created a view that outputs a list of cars. For each car, I display the name and the age of the car. This is all done with the Drupal UI. Now I'd like to add a simple button (Set as favorite) at the end of each line that when clicked saves the ID of the chosen car in a user's session variable. So my view table should look like the following:
Name Age Button
car1 23  'set as favorite'
car2 10  'set as favorite'

I am not asking about the session-variable part, but only how I can alter the view output to add a simple button to each row of the list output (I bet it'll be a form in each row).
I've done a lot of reading and I bet this could be done with hook_views_data_alter or some other hook_views_* but I'm not proceeding. I've already tried drop-buttons as suggested on Drupal 8 Add custom action buttons to a view, but that does not solve the things I need. I need the car's ID I want to save in a session variable, so basically I need a form functionality.
Answer: You probably can do this with just a Global custom text field and some hidden view fields.
E.g.:

Add car id to the view but exclude from view.
Move this to the top of the list.
Add a global custom text field for your Favorite button using the replacement values.  Could be something like:
Add as Favorite

Notes:
Classes are bootstrap specific.
Href is the code to set the favorite.
Destination string is Drupal way to circle back to view.

Add a form to the list output of a view


Practicing all possible three-note chords on guitar

Question: Ignoring octaves, every note in a on the guitar shows up in many different places.  I'd like to practice all the achievable three note chords on the guitar so that I can move my chord progressions up and down and across the neck better.
By "three note chords", I mean major, minor, dominant and aug/dim together with any color notes (7, 9, 11, 13).  The root can be implied and the chords can be in any voicing.
I'm interested in the three note chords because they give the richest tone while still playable at two chords per bar at 120bpm, which is where I usually live.
Three note chords also give me the ability to comprehend at performance tempo what I'm doing and where I can go.  If I play grips of more than three notes then I'm just playing grips and sequences of grips, which doesn't always work for the kind of improvisation I do with my band.
What I currently do is try to construct new voicings during practice time and then play the voicings as harmonized scales at one or more positions. But I need a systematic way to string the chord voicings and substitutions at a single position and all the possible positions along the guitar neck.
Are there any Spaced Repetition Systems or other automated tools out there that I could use for drilling on all the three note chords possible for particular chord progressions such as I-IV-V, ii-V, ii-I, etc.?
I'm already familiar with the Freddy Green system but I'd like to work on new grips.
Comment: @AmericanLuke - most definitions apply three or more notes to constitute a chord. Two notes make an interval.A 'power chord' is a 5th interval, and things like a jazz 3rd and 7th  together is an implied chord, usually with the missing note/s supplied by another player.Two note 'chords' are not easy to name, apart from the now ubiquitous 5th chord, known mainly to electric guitarists.
Comment: Are you confining this to major and minor triads? By definition, any combination of two or more notes is a chord.
Comment: Do you have an iOS device? If so, I highly recommend Guitar Toolkit for learning scales and chords. If not, please elaborate on what you mean by "automated tools."
Comment: Answerers: know that you can use [jTab's custom chord syntax](http://jtab.tardate.com/#notation).
Comment: What is "playing grips?"
Comment: Chord shapes you've played for so long they're in your muscle memory.
Comment: Your question is very confusing to me.  Why do you want to focus on 3 note chords only?  Why not get 4, 5, and 6 note voicings in your muscle memory?  I cannot understand what you are trying to accomplish in this regard.  Also, what significance does the speed 120 bpm have?  Are you playing quarter, eight, sixteenth, at that speed?
Comment: @ggcg paragraphs 2 and 3.
Answer: If you have an iOS device, I highly recommend the Guitar Toolkit app from Agile Partners. It can show you all common chords in all neck positions in any tuning. You can also "strum" or "pluck" the screen to hear what the notes are supposed to sound like. Working in reverse, you can tap frets on the screen to find out which chords they belong to.
The app has a similar feature for learning scales in different neck positions, or seeing how scales correspond to chords. Unfortunately, it does not appear to have three-note-per-string scale charts, although it's easy enough to figure them out by showing key notes over the entire fretboard.
Finally, the app also has a built-in tuner and metronome. It's a great reference and practice resource in general, not just a chord chart.
Answer: Get a hold of "George Van Eps Guitar Method" - buy it, find it on the interweb thing, check out triad exercises on ewetube. It is the ultimate foundation guide for triads that will open up the fretboard and unlock your hidden potential, the enabler to show music aficionados why you are on this planet.
Comment: Unfortunately, it's just in notation, not tab. I'd like both because I think about harmony in notation but I think tab when I perform.  Moreover, you don't really need all 12 keys tabbed for guitar, just a sufficiency that you slide around the neck.   Also Van Eps' notation of broken string sets is rather confusing.
Answer: Here are a few resources that might help with your quest, though I'm not sure it's the right quest to be on but that's your choice.

Chord Chemistry by Ted Greene

Mel Bay's Rhythm Method Guitar Chord System

Three-Note Voicings and Beyond by Randy Vincent

The last one might be more aligned with your question.  It covers many 3 note chord forms that fit into other larger chord structures and it is very "guitar-centric" with box diagrams etc.  Ted Greene's book is the most comprehensive out there, and it covers the idea of polychords, how larger chords are broken into sets of triads overlapped.  This knowledge helps in identifying simple patterns in progressions.
There are a ton of other great guitar method books that contain chord exercises in them.  Two that come to mind are Complete Guitar Method by Mike Christensen (Mel Bay series), and William Levitt's books vol 1, 2, and 3.  But these are not chord centric.  I hope that helps.


Visualization of complex roots for quadratics

Question: I read that if a parabola has no real roots, then its complex roots can be visualized by graphing the same parabola ($ax^2 + bx + c$) with $-a$ and then finding the roots of that, then using those roots as the diameter of a circle. Then, the "top" and "bottom" of the circle will be the complex roots of the parabola (in the complex plane).
I don't know if I explained that in [enough] detail, but I'm trying to prove this. I've been trying to generalize an equation for all the parabolas with no real roots, and I seem to be getting somewhere, but it seems like I'm over-complicating this.
How would you approach this? Any suggestions would be appreciated.
A proof of this construction would also be an acceptable answer. Thank you.
Answer: There is a statement along these lines, but it doesn't work to simply negate $a$ when the quadratic is in standard form.  You have to start by completing the square:
$$
ax^2 + bx + c \;=\; a(x-h)^2 + k.
$$
Then the roots of the quadratic
$$
-a(x-h)^2 + k
$$
will have the properties you describe.  In particular, if we write the roots of this quadratic as $h + r$ and $h - r$, then the roots of the original quadratic are $h + ri$ and $h - ri$.
By the way, observe that the auxiliary quadratic described above has the same vertex as the original quadratic, but its graph has been reflected across the horizontal line that goes through this point.  This gives a nice geometric way of "picturing" the complex roots of a quadratic by looking at the graph.
Answer: Either I'm misunderstanding what you wrote, I did a mistake below, or the construction does not work.
Assume that $a\gt 0$ (we may as well, since the roots of $ax^2+bx+c$ are the same as the roots of $-ax^2-bx^2-c$).
The roots of $-ax^2+bx+c$ are the same as the roots of $ax^2-bx-c$, and are given by
$$\frac{b+\sqrt{b^2+4ac}}{2a}\quad\text{and}\quad\frac{b-\sqrt{b^2+4ac}}{2a}.$$
If you are assuming that $ax^2+bx+c$ has no real roots (so that $b^2-4ac\lt 0$), then this has real roots, since $b^2-4ac\lt 0$ implies that $ac\gt 0$, so $b^2+4ac\gt 0$.
The circle whose diameter goes from the point $\left(\frac{b-\sqrt{b^2+4ac}}{2a},0\right)$ to $\left(\frac{b+\sqrt{b^2+4ac}}{2a}\right)$ has center at $\left(\frac{b}{2a},0\right)$, and radius $\frac{\sqrt{b^2+4ac}}{2a}$. So the coordinates of the "top" and "bottom" of that circle are
$$\left(\frac{b}{2a},\frac{\sqrt{b^2+4ac}}{2a}\right)\quad\text{and}\quad\left(\frac{b}{2a},-\frac{\sqrt{b^2+4ac}}{2a}\right).$$
That is, they correspond to the complex numbers
$$\frac{b}{2a} + \frac{\sqrt{b^2+4ac}}{2a}i\qquad\text{and}\qquad \frac{b}{2a}-\frac{\sqrt{b^2+4ac}}{2a}i.$$
These are the roots of $ax^2+bx+c=0$ if and only if they are the roots of $x^2+\frac{b}{a}x + \frac{c}{a}=0$, if and only if they add up to $-\frac{b}{a}$ and multiply to $\frac{c}{a}$. But they add up to $\frac{b}{a}$, not $-\frac{b}{a}$; and their product is
$$\left(\frac{b}{2a} + \frac{\sqrt{b^2+4ac}}{2a}i\right)\left(\frac{b}{2a}-\frac{\sqrt{b^2+4ac}}{2a}i\right) = \frac{b^2}{4a^2} + \frac{b^2+4ac}{4a^2} = \frac{b^2+2ac}{2a^2}\neq \frac{c}{a}.$$
For an explicitly example, take $x^2+x+1$, which has no real roots; the complex roots are $\frac{1}{2}+\frac{\sqrt{3}}{2}i$ and $\frac{1}{2}-\frac{\sqrt{3}}{2}i$. The construction you describe begins by considering instead $-x^2+x+1$, whose roots are $\frac{1}{2}+\frac{\sqrt{5}}{2}$ and $\frac{1}{2}-\frac{\sqrt{5}}{2}$. The circle whose diameter goes from $(\frac{1}{2}-\frac{\sqrt{5}}{2},0)$ to $(\frac{1}{2}+\frac{\sqrt{5}}{2},0)$ has center at $(\frac{1}{2},0)$ and radius $\frac{\sqrt{5}}{2}$, so the "top" and "bottom" of the circle will be $(\frac{1}{2},\frac{\sqrt{5}}{2})$ and $(\frac{1}{2},-\frac{\sqrt{5}}{2})$, which are not the complex roots of $x^2+x+1$.

The construction works if $b=0$: in that case, instead of graphing $ax^2+c$, with $\frac{c}{a}\gt 0$, we graph $-ax^2+c$; the zeros are $\pm\sqrt{\frac{c}{a}}$, so the circle in question will be centered at the origin and have radius $\sqrt{\frac{c}{a}}$, so the complex numbers corresponding to the "top" and "bottom" are exactly $i\sqrt{\frac{c}{a}}$ and $-i\sqrt{\frac{c}{a}}$, which are the roots of $ax^2+c$ when $\frac{c}{a}\gt 0$.
So this suggests that for the general case you should first complete the square and then change the sign of the entire squared factor. For my example, beginning with $x^2+x+1$, first complete the square:
$$x^2 + x + 1 = \left(x^2 + x + \frac{1}{4}\right) + \frac{3}{4} = \left(x + \frac{1}{2}\right)^2 + \frac{3}{4}.$$
Then graph $-(x+\frac{1}{2})^2 + \frac{3}{4} = -x^2 -x + \frac{1}{2}$ and proceed as you describe. This will work: it amounts to first doing a horizontal shift so that we are dealing with a quadratic of the form $Az^2 + C$ (where $z=x+k$ for some $k$), and then proceeding as above. But you'll note that the resulting equation is not obtained simply by changing the sign of $a$: the values of $b$ and $c$ are also changed.
You can check that this modified idea works by doing essentially what I did above, but showing it does work.
Answer: We give a construction of the complex roots, focusing on the geometry.
The general quadratic equation has the shape
$$ax^2+bx+c=0,$$
where $a \ne 0$.  But if we are only interested in the geometry of the roots, it does no harm to divide every coefficient by $a$, obtaining the simplified form
$$x^2+px+q=0.$$
Geometrically, this corresponds to a scaling in the $y$-direction.
Consider the parabola with equation $y=x^2+px+q$. Move the parabola sideways so that the vertex of the parabola lies on the $y$-axis. Then the equation of the shifted parabola assumes the simple shape
$$y=x^2+d^2,$$
where $d>0$.  We have written the constant term of the shifted parabola as $d^2$, since because the parabola does not cross the $x$-axis, the constant term must be positive.
The vertex of the parabola is at $(0,d^2)$.  Draw a horizontal line at distance $d^2$ above the vertex.  This line has equation $y=2d^2$, so it meets the parabola at the points with $x$-coordinates $x=\pm d$.
Draw a circle with center halfway between these two points, and passing through them. So the circle has radius $d$.  Lower this circle to make a new circle $C$ with center the origin.
The "top" and "bottom" of this new circle $C$ are at $(0,d)$ and $(0,-d)$.  If we use complex numbers to represent them, they are $0+di$ and $0-di$, the complex roots of $x^2+d^2=0$.
Now shift the parabola back to its original position, dragging everything we have constructed along.  Then the roots of $x^2+d^2=0$ are dragged along to become the roots of the original equation $x^2+px+q=0$.
The shifting was done to make the algebra simple.  But now we can give a geometric recipe for constructing the complex roots of a quadratic equation that has no real roots, say with positive coefficient for $x^2$.
(i) Draw the appropriate parabola.
(ii) Draw a line which is just as far above the vertex of the parabola as that vertex is above the $x$-axis.  Suppose that this line meets the parabola at points $P$ and $Q$.
(iii) Draw the circle with center midway between $P$ and $Q$ and passing through $P$ and $Q$.
(iv) Lower this circle so that it becomes a circle $C$ with center on the $x$-axis.
(iv) The complex roots of our equation are at the "top" and "bottom" of circle $C$.


How many ways are there to distribute eight different toys among four children if the first child gets at least two toys?

Question: My work:
$e_1 + e_2 + e_3 + e_4 = 8$
let $e_1\geq2$
with no constraint on the other $e_i$'s
we want to find coefficient of $\cfrac{x^8}{8!}$
with this I've found the exponential generating function to be
$g(x) = (\cfrac{x^2}{2!} + \cfrac{x^3}{3!}+...)(1 +x+\cfrac{x^2}{2!}+...)^3 = (e^{x}-1-x)(e^x)^3 = e^{4x}-e^{3x}-xe^{3x}$
so first series would be $ \sum_{r=0}^{\infty} 4^r\cfrac{x^r}{r!}$ for $e^{4x}$
Second series would be -$ \sum_{r=0}^{\infty} 3^r\cfrac{x^r}{r!}$ for $-e^{3x}$
But I get stuck here
What would the third series be for $-xe^{3x}$?
I need to figure this third series out to figure out the coefficient
Any help would be appreciated here.
Also is my logic and methodology right for this question?
If it helps, I just need help with the $-x$ in front of $-xe^{3x}$
It's really throwing me off as I'm not sure how it would turn into a series.
Comment: @lulu wouldn't that be if toys are identical?  Toys are different here I thought.  Instead, let us just look at the set of all such ways of distributing the toys and remove the "bad" results where no toys were given to the first child and where exactly one toy got given to the first child.
Comment: @JMoravitz Yes, my error.  I will delete my prior, unhelpful, comment now and this one soon.
Answer: kludginess says hello
I don't know enough about generating functions to specifically
examine your work.  However, I do know that there is a strong
relationship between generating functions and stars and bars
analysis.  Stars and bars is discussed at https://brilliant.org/wiki/integer-equations-star-and-bars/.
I also know that stars and bars analysis, at least in its
simplified form, is inappropriate here, specifically
because the toys are deemed to be different.
The problem is actually ambiguous, depending on whether the second, third,
and fourth child must each get at least one toy.
$\underline{\textbf{Interpretation 1: Some children may get no toys}}$
This is easy.
$$4^8 - \left(8 \times 3^7\right) - 3^8.$$
$\underline{\textbf{Interpretation 2: Each child gets at least 1 toy}}$
There may be an elegant approach here that I am unaware of.  My kludgy approach
is to identify all of the possible satisfying toy distribution patterns and then
enumerate each pattern.
Patterns:
P-1 : 5 - 1 - 1 - 1 : # ways $= S_1$.
P-2 : 4 - 2 - 1 - 1 : # ways $= S_2$.
P-3 : 3 - 3 - 1 - 1 : # ways $= S_3$.
P-4 : 3 - 2 - 2 - 1 : # ways $= S_4$.
P-5 : 2 - 2 - 2 - 2 : # ways $= S_5$.
The final tally will be $S_1 + S_2 + S_3 + S_4 + S_5.$
P-1
1st child gets 5 toys, other 3 toys are permuted.
$$S_1 = \binom{8}{5} \times 3!.$$
P-2
Three ways of selecting which other child gets more than one toy.
Then, you examine the # of ways that 1st child gets 4 toys, and other child gets 2 toys.
Then, you multiply by 2, since the first child can switch roles with the other child here.
$$S_2 = 2 \times 3 \times \binom{8}{4} \times \binom{4}{2} \times 2!.$$
P-3
Analysis very similar to analysis of P-2.
However, since the first child and the odd man out child
will each get 3 toys, you must not apply the factor of 2,
which would correspond to their switching places.
$$S_3 = 3 \times \binom{8}{3} \times \binom{5}{3} \times 2!.$$
P-4
If the first child is to get three toys, with one of the children the odd man out,
then the first tally is
$$ S_{4a} = 3 \times \binom{8}{3} \times 5 \times \binom{4}{2}.$$
If the first child is to get two toys, then there are 3! ways of deciding which
of the other children get 3 toys, 2 toys, 1 toy.
With this decided:
$$ S_{4b} = 3! \times \binom{8}{2} \times \binom{6}{3} \times 3.$$
$$ S_4 = S_{4a} + S_{4b}.$$
P-5
The # of ways of first giving 2 toys to 1st child, then giving 2 toys to 2nd child, ...
$$ S_5 = \binom{8}{2} \times \binom{6}{2} \times \binom{4}{2}.$$
Comment: @BadwaterBarry You must take this comment with a **large** grain of salt, since I am **totally ignorant** of the possible applications of generating functions.  My **very narrow** experience has been that generating functions are often a substitute for Stars and Bars analysis.  Since Stars and Bars is inappropriate here, this begs the question whether generating functions can be appropriately applied to interpretation 1 of this problem.  Note that the toys are deemed to be **different**.  It is almost as if you would have to *juggle* 8 variables: $x_1, x_2, \cdots, x_8.$
Comment: @user2661923 This is why we are using exponential generating functions rather than ordinary ones.
Comment: I'm 100% sure that the problem is interpretation one. While I do appreciate the effort and I did find the same answer as you. I wish to learn how to solve this via exponential generating functions as that's what I am currently studying. But thank you for your effort!
Comment: (By the way, if the second, third, and fourth child each need to get at least one toy, we'd be looking for the coefficient of $\frac{x^8}{8!}$ in $(e^x - 1 - x)(e^x - 1)^3$.)
Comment: @MishaLavrov Which *strongly suggests* that as the problem gets more complex, exponential generating functions **becomes** the superior approach.
Answer: To find the coefficient of $\frac{x^k}{k!}$ in $x e^{3x}$, I find it easier to find the coefficient of $x^k$ and then multiply by $k!$.
The coefficient of $x^k$ in $x e^{3x}$ is the coefficient of $x^{k-1}$ in $e^{3x}$, which is $\frac{3^{k-1}}{(k-1)!}$. So the coefficient of $\frac{x^k}{k!}$ is $k! \cdot \frac{3^{k-1}}{(k-1)!} = k 3^{k-1}$.
Therefore our final answer should be $4^k - 3^k - k 3^{k-1}$, where $k=8$ in your case. That's $4^8 - 3^8 - 8 \cdot 3^7 = 41\,479$, which I also checked by brute force:
<code>Length@Select[Tuples[Range[4], 8], Count[#, 1] >= 2 &]
</code>
gives $41\,479$ in Mathematica.


For Multiple Tabs Single Fragment not working getItem called twice

Question: Sir, I have to use single fragment for multiple tabs. I have implemented it using FragmentStatePagerAdapter but after debugging I have got that some of the tabs displays data but not correct. This is because getItem called twice please help me as early as possible.
I have passed arguments from getItem. it passes arguments two times as getItem calls twice. thus it overrides data of arguments. I have 6 tabs but only 1, 3 and 5 tab displays data but data is of 2, 4 and 6th tab and 2, 4 and 6th tab not showing anything on the screen.
not working any solution from previous questions.
ViewPager Code
<code>public class ViewPagerAdapter extends FragmentStatePagerAdapter {

int TAB_COUNT=5;
Context mContext;
public ViewPagerAdapter(FragmentManager fm,Context context) {
    super(fm);
    mContext=context;
}

@Override
public Fragment getItem(int position) {
    NewsFragment fragment = new NewsFragment();
    Bundle args = new Bundle();
    args.putString("title", String.valueOf(getPageTitle(position)));
    args.putString("data", "data");
    fragment.setArguments(args);
    return fragment;

}

@Override
public CharSequence getPageTitle(int position) {

    return  mContext.getResources().getStringArray(R.array.tabs)[position];
}

@Override
public int getCount() {
    return TAB_COUNT;
}
</code>
}
Listeners to change tab :
<code>@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onPageSelected(int position) {

    TabLayout.Tab tab = tabLayout.getTabAt(position);
    if (tab != null) {
        tab.select();
    }
}
</code>
Adapter setting
<code> private void setUpTab() {
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), this);
    for (int i = 0; i < viewPagerAdapter.getCount(); i++) {
        tabLayout.addTab(
                tabLayout.newTab()
                        .setText(viewPagerAdapter.getPageTitle(i)));
    }
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager.setAdapter(viewPagerAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    viewPager.addOnPageChangeListener(this);
    tabLayout.addOnTabSelectedListener(this);
}
</code>
Answer: getItem gets called every time the adapter creates a new page for the first time. The reason you see it being called twice is that the viewPager prepares the next page in advance, so if you enter page 1, page 2 is already being created too for faster paging when you swipe right.
To help you further please show us the code for NewsFragment.
Also, you might consider using FragmentPagerAdapter instead of FragmentStatePagerAdapter because you seem to have a fixed number of tabs (5 in your example) and according to the documentation that is the use case for FragmentPagerAdapter.
Documentation from the page I linked above:

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs.


Adding a different constant to numerator and denominator

Question: Suppose that $a$ is less than $b$ , $c$ is less than $d$.
What is the relation between $\dfrac{a}{b}$ and  $\dfrac{a+c}{b+d}$? Is  $\dfrac{a}{b}$ less than, greater than or equal to $\dfrac{a+c}{b+d}$?
Comment: Any possibility can occur. Take $a=1$ and $b=2$.  Then consider $c=1, d=2$ (equality); $c=1, d=3$ (greater than ); and $c=4,d=5$ (less than).
Answer: Note that if $b$ and $d$ have the same sign, then
$$
\frac{a}{b}-\frac{a+c}{b+d}=\frac{ad-bc}{b(b+d)}
$$
and
$$
\frac{a+c}{b+d}-\frac{c}{d}=\frac{ad-bc}{d(b+d)}
$$
also have the same sign.
Therefore, if $b$ and $d$ have the same sign, then $\dfrac{a+c}{b+d}$ is between $\dfrac{a}{b}$ and $\dfrac{c}{d}$.
Comment: As Srivatsan points out, if $b$ and $d$ are both positive,
$$
\frac{a}{b}\lesseqqgtr\frac{a+c}{b+d}\text{ if }\frac{a}{b}\lesseqqgtr\frac{c}{d}
$$
Comment: My impression is that the OP might be most interested in the case when all the numbers are positive. In that case, it will be nice to point out explicitly that $\frac{a+c}{b+d}$ will be larger than $\frac{a}{b}$ if and only if $\frac{c}{d} > \frac{a}{b}$.
Comment: @robjohn: Do you know if this operation has a name? Other than 'add the numerators and denominators of the fractions'.
Answer: One nice thing to notice is that
$$
\frac{a}{b}=\frac{c}{d} \Leftrightarrow \frac{a}{b}=\frac{a+c}{b+d}
$$
no matter the values of $a$, $b$, $c$ and $d$. The $(\Rightarrow)$ is because $c=xa, d=xb$ for some $x$, so $\frac{a+c}{b+d}=\frac{a+xa}{b+xb}=\frac{a(1+x)}{b(1+x)}=\frac{a}{b}$. The other direction is similar.
The above is pretty easy to remember, and with that intuition in mind it is not hard to imagine that
$$
\frac{a}{b}<\frac{c}{d} \Leftrightarrow \frac{a}{b}<\frac{a+c}{b+d}<\frac{c}{d}
$$
and similar results.
Comment: With a small caveat:$$\frac11=\frac{-1}{-1}\text{, but }\frac11\ne\frac00$$


Need to encrypt and decrypt using PEM key

Question: Is it possible to use C# to encode a string of text using a .PEM file and decode it using the same .PEM file?
Answer: If the PEM file contains the private key, the public key can be computed out of it so it is indeed possible to encrypt a text and then decrypt it again using that PEM file.
PEM is not supported by the c# framework, but third party libraries such as BouncyCastle can help you: http://www.bouncycastle.org/csharp/


When and why are IEMs used together with monitor speakers?

Question: Following up on the question about what monitors are:
When and why are in-ear monitors (IEMs) used together with monitor speakers?
Are there situations where using only one and not the other would be beneficial?
Answer: When and why are in-ear monitors (IEMs) used together with monitor speakers?
That hybrid monitoring configuration is becoming very common. The main why and when, according to Mix Magazine, is the preferences of the band members. One member can ask for in-ears, while another can ask for speakers.

In-ear monitors are not for everyone. Drummers and keyboard players love IEMs, while guitarists and (to a lesser degree) bass players tend to dislike them. Some singers need the intimacy of direct interaction with their audience, while others can't perform without the isolation provided by in-ear monitors. With the recent introduction of "ambient" in-ear systems that blend binaural mics at performers' ears with their monitor mix, we may have reached the Holy Grail that finally tips the balance in favor of IEMs. However, for the foreseeable future, many engineers will mix a hybrid monitor system.

Another reason is to have the monitor speakers as backup for the IEMs.
Are there situations where using only one and not the other would be beneficial?
It depends on your priorities, both have their caveats.
From a mixing point of view, IEMs are far superior. Feedback is taken out of the equation from the monitoring system, each performer can have a different monitoring mix, you can implement stereo IEMs and have two channels to work with, you can do stuff that you wouldn't do in monitor speakers, like metronome or communication. Here, using in-ears only would be beneficial. (at least technically, since the ultimate benefit is to deliver an outstanding performance, and a musician might perform better with speaker monitoring systems simply because s/he prefers them over in-ears)
From a healthy point of view, in-ear monitors, if correctly implemented, can be less damaging to your ears than monitor speaker systems. Less SPL is entering your ears, the sound doesn't mess with them as much. In this context, using in-ears exclusively is beneficial.
From the artist point of view it will be about preference. Using one and not the other would be beneficial depending on what the performer likes and is used to.


Setting up SSH Key securely for SCP/rsync to run without password

Question: This is how I am currently doing it:
# ssh-keygen -t dsa -b 1024 -f /root/localhost-rsnapshot-key

Enter passphrase (empty for no passphrase): [press enter here]
Enter same passphrase again: [press enter here]

# if [ ! -d ~/.ssh ]; then mkdir ~/.ssh ; chmod 700 ~/.ssh ; fi
# cd ~/.ssh/
# if [ ! -f config ]; then touch config ; chmod 600 config ; fi
# echo Host server2 >> config
# echo Hostname server2.domain.tld >> config
# echo IdentityFile /root/localhost-rsnapshot-key >> config

Now when I run rsnapshop like:
backup  firstname.lastname@example.com:/home/     localhost/server2/

I get the following:
rsnapshot hourly
reverse mapping checking getaddrinfo for server2-domain-tld.1-2-3-4 [220.127.116.11] failed - POSSIBLE BREAK-IN ATTEMPT!
email@example.com's password:

Is there a way to make this run without a password?
Answer: You can run the command ssh-copy-id firstname.lastname@example.com from server1 to copy your identity file to the remote system and allow pubkey authentication. You may also need to make sure key-based authentication is enabled in your sshd config.
Answer: On server2, you need to add the generated public key to /root/.ssh/authorized_keys
Answer: Assuming you want to authenticate into a shell account named 'server2' on a host named 'server2', you need to add the contents of localhost-rsnapshot-key.pub generated on server1 to the server2:/home/server2/.ssh/authorized_keys file.
Answer: First off, please consider using rsa keys instead of dsa although I know this is unsolicited advice, rsa is more secure than dsa, unless of course you have a compelling reason to do so.
Let me start by saying I will do this using standart unix command like scp, cat, chmod, chown and such instead of using more esoteric commands, likes of ssh-copy-id. So that you can use it on pretty much any Unix flavor, not only Linux.
Getting these out of the way after running the ssh-keygen command, you have two files in your .ssh directory:
id_dsa
id_dsa.pub

# on the local machine which will connect the remote server without a password

cd ${HOME}/.ssh
scp id_dsa.pub ${REMOTE_SERVER}:${REMOTE_USER_HOME}/.ssh
# if this errors out, you might need to create the .ssh on the remote server
#

# on the remote machine which will accept incoming ssh connection without a password
chown ${REMOTE_USER} ${REMOTE_USER_HOME}  # this should already be set like this
chown ${REMOTE_USER} ${REMOTE_USER_HOME}/.ssh # if this exists, it should be this way

chmod 700 ${REMOTE_USER_HOME}
chmod 700 ${REMOTE_USER_HOME}/.ssh

cd ${REMOTE_USER_HOME}/.ssh
cat id_dsa.pub >> ./authorized_keys
chown ${REMOTE_USER} ./authorized_keys
chmod 600 ./authorized_keys

Now, you should be able to connect to the remote machine without a password.
hope this helps.
Answer: Though it's already explained up in above few answers, but if you looking for more details, you can refer to this article.
Password-Less Login
Comment: Welcome to Server Fault! We really do prefer that answers contain content not pointers to content. Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Perform regex on an specific item in list in Python

Question: Need a hand on implementing the below:
I've the below line in my list.
item =  ['0', '58s', '8us', '11s', '13ms', '176us', '320ms', '89us']

I want to perform check on item[6]. The logic should check, if item[6] contains the string 'us' or 'ms' the logic should. If it has either 'us' or 'ms', it should print 'Good' else it should print the item[6].
Comment: You don't need a regexp. `if 'us' in item[6] or 'ms' in item[6]:`
Comment: You could also use `endswith`: `if item[6].endswith(('us', 'ms'))`
Comment: You need quotes around the list elements that aren't numbers.
Comment: endswith worked for my usecase. I'll accept this as answer.
Thanks!
Answer: You can use the inbuilt function any to literally check if any of the elements are contained in a interable, its also efficient as it does not go through the whole list as any works when the first Truth is found. Additionally you are able to add elements to find for if required.
item =  '0    158s    48us     11s    13ms   176us   320ms    89us'.split()
find_for = ['ms','us']

if any(x in item[6] for x in find_for):
    print('Good!')


Intuitive explanation for dividing by n-1 when calculating sample variance?

Question: I understand how to mathematically show that the sample variance (that involves dividing by n-1) is an unbiased estimator of the population variance (which divides by n), and the mathematics has been shown many times here on Math.SE.
I am wondering however if there is an intuitive way to understand this result that I can use to easily explain why this is done to layman.  So far I have seen many derivations but I haven't seen an elegant intuitve explanation for the result.
Comment: The most intuitive way I've seen standard deviation explained is as a minimization problem for the distance squared between data points and the mean. I think in that context, the $n-1$ factor comes out quite naturally. I can't quite recall the details (and I've likely messed them up a bit). It's been years since we talked about it in my stats class in high school.
Answer: At an elementary level it is possible to give a couple of "reasons" for dividing
by $n - 1$. (At higher levels there are rationales that involve
discussions about n-dimensional vector spaces, but let's not go there now.)
"Reason 1." Suppose you are finding the sample variance of observations 2, 3, 1, 6.
Then you computations might look like this:
<code>        x   x - 3  square
        -----------------
        2    -1     1
        3     0     0
        1    -2     4
        6     3     9
       ----------------
   Tot 12     0    15
 Mean 3          Var = 15/3
</code>
If somehow one of the four rows between dashed lines got smudged and was
unreadable, you would be able to reconstruct it from the rest of the
information. (2 + 3 + 'smudge' + 6 = 12; what is 'smudge'? Etc.) So in some sense, given the structure of the computation
you have only $n - 1 = 3$ rows that contain information. The jargon
for that is you have "degrees of freedom $DF = n - 1$."
"Reason 2." If you divide by $n - 1$ in the definition of the sample
variance $S^2$, then $E(S^2) = \sigma^2.$ In statistical terminology
this means "$S^2$ is an unbiased estimator of $\sigma^2.$" If you
divided by $n$ instead, then you would have an estimator of the population
variance that is too small.
Note: Dividing by $n - 1$ is pretty much agreed upon, but reputable
authors in statistics and probability have proposed $n$, $n + 1$, and even
$n + 2$ as divisors--each giving a rationale aimed at a particular objective.
None of these alternative denominators has received wide acceptance.
But these discussions confirm that it is not a stupid question to ask
why we use $n - 1.$
$Addendum$ (Jan 25, '16): I have just read a latter by Jeffrey S. Rosenthall (U. Toronto) in the December '15 issue of the IMS Bulletin, arguing that in elementary statistics
courses it is OK to use $n$ as the denominator of the sample
variance. Briefly, his view is based mainly on arguments involving
mean square error (MSE). For example, with normal data, MSE for estimating $\sigma^2$ is minimized by denominator $n + 1$ instead of $n - 1.$
(See his letter on page 9 for details.)
However, in more advanced courses: as in my Comment below, a penalty for changing from $n - 1$ would be minor
confusion in getting confidence intervals for $\sigma^2$ and doing tests for $\sigma^2$ based
on the sample variance---mainly because $\sum (X_i - \bar X)^2/\sigma^2
\sim Chisq(df = n - 1).$
Comment: As far as I know, the textbooks never explain **why** it's important for the sample variance to be an unbiased estimator of the population variance, although nobody seems to mind the fact that the sample standard deviation is a biased estimator of the population standard deviation. Isn't the standard deviation more important/useful than the variance, anyway?
Comment: @bof: The expected value of the SD (call it $S$) can be made unbiassed by multiplying by a constant, but that constant depends on $n$ and the population distribution. If you know $S$ from normal data then you can use the fact that $(n-1)S^2/\sigma ^2 \sim Chisq(n-1)$ to get  CIs for $\sigma^2$ and $\sigma.$ If $S^2$ were not defined with $n-1$ in its denominator, this distributional relationship would be a bit messier. "Its customary" may be the best, if less than satisfactory, answer to the original question.
Answer: The sample variance is computed using deviations from the sample mean $\bar x$ instead of the population mean $\mu$, and this is the source of the bias.
When the squared deviations are accumulated, there is a deficit of $\bar x-\mu$ every time, so that the computed variance is too small.

Hint:
$$(x_i-\mu)^2=((x_i-\bar x)+(\bar x-\mu))^2=(x_i-\bar x)^2+2(x_i-\bar x)(\bar x-\mu)+(\bar x-\mu)^2.$$
When averaging over $i$, the double product in the middle vanishes due to the factor $(\bar x-\bar x)$, and you get
$$\sigma^2=\overline{(x_i-\mu)^2}=\overline{(x_i-\bar x)^2}+\overline{(\bar x-\mu)^2}=s^2+\frac{\sigma^2}N.$$
Answer: The sample mean is defined as $\bar{X} = \frac{1}{n}\sum_{i=1}^{n} X_i$, which is quite intuitive. But the sample variance is $S^2 = \frac{1}{n-1}\sum_{i=1}^{n} (X_i - \bar{X})^2$. Where did the $n - 1$ come from ?
To answer this question, we must go back to the definition of an unbiased  estimator. An unbiased estimator is one whose expectation tends to the true expectation. The sample mean is an unbiased estimator. To see why:
$$ E[\bar{X}] = \frac{1}{n}\sum_{i=1}^{n} E[X_i]
= \frac{n}{n} \mu = \mu $$
Let us look at the expectation of the sample variance,
$$ S^2 = \frac{1}{n-1} \sum_{i=1}^{n} (X_i^2) - n\bar{X}^2 $$
$$ E[S^2] = \frac{1}{n-1} \left( n E[(X_i^2)] - nE[\bar{X}^2] \right). $$
Notice that $\bar{X}$ is a random variable and not a constant, so the expectation $E[\bar{X}^2] $ plays a role. This is the reason behind the $n-1$.
$$E[S^2] = \frac{1}{n-1} \left( n (\mu^2 + \sigma^2) - n(\mu^2 + Var(\bar{X})) \right). $$
$$Var(\bar{X}) = Var(\frac{1}{n}\sum_{i=1}^{n} X_i)
= \sum_{i=1}^{n} \frac{1}{n^2} Var(X_i)
= \frac{\sigma^2}{n} $$
$$E[S^2] = \frac{1}{n-1} \left( n (\mu^2 + \sigma^2) - n(\mu^2 + \sigma^2/n) \right). = \frac{(n-1)\sigma^2}{n-1} = \sigma^2 \\
$$
As you can see, if we had the denominator as $n$ instead of $n-1$, we would get a biased estimate for the variance! But with $n-1$ the estimator $S^2$ is an unbiased estimator.
Answer: It seems your question is related to the statistical concept of degrees of freedom.  The sum of deviations of n observations from their sample mean must be zero.  This means that if n-1 of the deviations are known, they completely determine the nth deviation.  It is the squared deviations from the mean that are used to construct the sample variance and hence we say that the sample variance has n-1 degrees of freedom.  Box, Hunter, and Hunter gives a more in depth explanation, and I'm sure many other statistics texts do as well.
Answer: I think of it that you lose a degree of freedom in estimation of the mean, since to calculate variance you also need to estimate the mean. This is essentially what Bruce is saying in his comment regarding a line being smudged.


Is $C([0,T] ; L^1(\mathbb{R}^{N}) \cap L^{\infty}(\mathbb{R}^{N}))$ a Complete Metric Space? (For Using Banach Fixed Point Theorem)

Question: Consider $$C([0,T] ; L^1(\mathbb{R}^{N}) \cap L^{\infty}(\mathbb{R}^{N})) := \{ u:(0,T) \rightarrow L^1(\mathbb{R}^{N}) \cap L^{\infty}(\mathbb{R}^{N}) \ | \ \text{u continuous on }[0,T]  \}$$ with $T>0$, $N \in \mathbb{N}$. I am reading a paper which uses the Banach Fixed Point Theorem for a contraction mapping $\phi$ on the closed subset
$$B := \{ u \in C([0,T] ; L^1(\mathbb{R}^{N}) \cap L^{\infty}(\mathbb{R}^{N})) \ | \ ||u|| \leq R \}$$ with $R \in \mathbb{R}$ being some constant. The norm $||u||$ is defined as follows:
$$||u|| := \sup_{0 < t < T} \left(||u(t)||_{L^{1}(\mathbb{R^{N}})} + ||u(t)||_{L^{\infty}(\mathbb{R^{N}})}\right)$$
Upon looking at the statement of the Banach Fixed Point Theorem, I noticed that the metric space in question must be complete. I have had a hard time showing that $C([0,T] ; L^1(\mathbb{R}^{N}) \cap L^{\infty}(\mathbb{R}^{N}))$ is complete under the norm $||\cdot||$, so I am wondering if it even is a complete space?
If not, are we allowed to use a closed (and thus cauchy) subset of a metric space for the purpose of the Banach Fixed Point Theorem?
Comment: Sure you can choose a closed subset. Every restriction of a metric space is again a metric space. Banach's FPT won't even know about which metric space you feed it.
Comment: @DavidHughes: It is true that all you really care about is whether $B$ is complete.  However, as in my answer below, it is probably just as easy to show that the whole space $C([0,T] ; L^1(\mathbb{R}^{N}) \cap L^{\infty}(\mathbb{R}^{N}))$ is complete, and then just note that $B$ is a closed subset of it.
Comment: @ComFreek Ah, I had mistakenly thought I needed the subset to be a vector space, i.e. closed under addition, etc. I see. That makes things very easy. Thank you!
Comment: @ComFreek: However, if the space were not complete, a closed subset of it would not necessarily be complete either.
Comment: @NateEldredge So I need only check if $B$ is complete, right?
Comment: @DavidHughes Yes. I don't have too much experience doing this, so can't suggest something here.
Answer: Yes, it is complete.
The first step would be to show that $L^1 \cap L^\infty$ is complete in the given norm.  To see this, note that if $\{f_n\}$ is Cauchy in this norm, then it is Cauchy in both the $L^1$ and $L^\infty$ norms.  Since $L^1$ and $L^\infty$ are each complete, this means that there are functions $f,g$ such that $f_n \to f$ in $L^1$ norm, and $f_n \to g$ in $L^\infty$.  Now verify that in fact $f = g$, and that $f_n \to f$ in the $\|\cdot\|_{L^1} + \|\cdot\|_{L^\infty}$ norm.
To finish, it is a fact that for any complete metric space $X$, the space $C([0,1],X)$ is complete in the uniform metric.  Just look back at the proof that $C([0,1], \mathbb{R})$ is complete, and note that it goes through (with the obvious changes) replacing $\mathbb{R}$ by $X$.