How can I transform my coordinate's values?

Question: Quick question:
I have a given value of a Point(x,y) with respect to one coordinate system, how can I solve the value of the same Point(x,y) but with respect to a second coordinate system?
I will be getting X within [0 -> 1000] range, I need to find its correct value within [-100 -> 100] range.
Example Point(750,SomeY):
Comment: What is the relationship between the 2 coordinate systems? If there is a transformation that maps from the first to the second, then apply that transformation to your points. If there is not such a transformation, then I'm not sure we can answer the question.
Comment: scott, my question IS to find the relationship(equation) that I need to apply on my `Point` in order to then transform it. To answer your question then no I don't have a relationship between both systems, yet. **Expected value is 50**.
Comment: Your figure is the answer! The unknown $x$ is $?=50$.
Comment: @EmilioNovati, this is an example that I know about. What if I have a million different points and I want the generic formula. Now this is different right?
Answer: If you're just focusing on $x$, it seems like a very simple transformation. You're taking $x \in [0, 1000]$ and you're trying to map it to $[-100, 100]$. If you send $0 \rightarrow -100$ and $1000 \rightarrow 100$, you can make a simple function
$f: [0, 1000] \rightarrow [-100, 100]$ where $f(x)=x/5-100$.
So $f(0) = -100$ and $f(1000)=100$.
Comment: This is it. Thank you very much :). Yes I am focusing on X but I am using the same scales for Y so it should work as it is too.


Drum Programming and Tempo/BPM

Question: I have a song that I am making in 88 bpm. I want to add the bass to sound like a heartbeat at 44bpm to simulate a slow, meditative feel. However, I am having trouble deciding where I should place the bass at.
So in a song of 88bpm where the bass will fall for a double beat (like heartbeat, quick succession), where should I place that at?
I would like you to help me with the math rather than just giving an answer. I want to understand how to do this math on my own.
Answer: First of all, tempo is the same for all your instrument. BPMs is the speed of tempo. If your drum kit is in 4/4 time signature (that means you have 4 hits, usually count with hi hat, in every meter) and you want half of those notes on your bass, that mean you have 2/4 on you bass. This is very simple thing to do, you have to imagine that you split up at half every bass note (always at your 2/4 TS). Now you have count your hi hats, two hits on each bass note, and you similarly can place the other components of the kit.
Now, in your 'where' question. Always in 4/4 time signature meters you have two strong and two weak hits. The first one and 3rd one (like Tim said) are strong ones, the other two are weak. We always put kick and snare on strong for emphasis, but you can always extend kicks and snare to weak parts too.
However, in other time signatures meter we have different strong and weak hits, for example in 3/4 we have 1 strong (at hit one) and two weak).
So, now you have to figure out how your rhythm going on, if you want heart beat kind of rhythm you have two notes on 1 and 2 on your beat and pauses (nothing, silence) on 3 and 4. Don't forget that you bass can play either 1/4 value notes either 2/4 value notes, just remember that if you are going with 2/4 TS means that 1 and 2 beats are a single bass note and same for 3 and 4. You just need to experiment with those and find out, I think heart is beating 60 times per second, so if you want to simulate this you may want to change bpm at 60 (at 4/4) or even 120, if you want your drums a bit faster.
Conclusion: same bpm, same time signature but adapt the way you count it in every instrument (depend on rhythm), figure out rhythm and ready to go.
Sorry for my bad english, I hope I helped you, enjoy writing music.
Answer: On beats 1 and 3               !
Comment: "I would like you to help me with the math rather than just giving an answer." (Sorry, Tim; someone flagged it.)
Comment: You're right, I realized that today. Duh. Half of 88 is 44 so just 1 & 3. Thank you
Comment: @Richard - it was probably automatically flagged - we may never know! But the maths is extremely fundamental, I think.

Drum Programming and Tempo/BPM


Is it legal to use a trick involving another player to pass the ball to the keeper without kicking it?

Question: It says in Law 12, under "Cautions for unsporting behaviour", that:

A player must be cautioned for unsporting behaviour including if a
  player: [...] uses a deliberate trick to pass the ball (including from
  a free kick) to the goalkeeper with the head, chest, knee etc. to
  circumvent the Law, whether or not the goalkeeper touches the ball
  with the hands.

I was wondering if a deliberate high pass from one defender to another, who then heads it back to his keeper, is considered to be a trick.
Comment: The second paragraph of [this answer on a relevant question](https://sports.stackexchange.com/a/2362/12991) suggests that this is not illegal as the law always refers to one player.
Answer: What you have described it not a trick, nor is it illegal.
The first player has simply played an aerial pass to another defender. This is not a deliberate trick to circumvent the Law.
The second player has simply headed an aerial ball back to the goalkeeper, at a height that a player would be reasonably expected to head the ball. This is not a deliberate trick to circumvent the Law.
A deliberate trick to circumvent the Law would, for example, include, but not be limited to:

a player flicking the ball up to their head or knee and then playing it back to the keeper with the head or knee, or
heading or knee sliding the ball from off the ground back to their goalkeeper, that is, a position where playing it with the knee or head would be abnormal.

Any team that attempts the scenario outlined in your question this puts themselves at a considerable disadvantage. A poorly-skilled team would possibly fail to make a high pass at the right height, or the header would be difficult for the keeper to get to. This could see a loss of possession in their defending third.
At the highest levels of the game, even if the high pass was made perfectly and the header was directly to the keeper's hands, a defending striker would have a good chance of intercepting the high pass (since they generally move slower) or the header back to the goalkeeper. Either way, the defender making the header would be under significant pressure.
Deliberate trickery to circumvent the Law is rare enough that it is obvious when it occurs. Referees should not go hunting for it.


Drush error when attempting Drupal update: unable to copy/move

Question: I have a Drupal site running on localhost (Windows) that I'm trying to update from 8.6.7 to 8.6.15.
When using Drush to perform the update (drush up drupal -y), I encounter the following error:
Unable to copy C:\Users\USERNA~2\AppData\Local\Temp/drush_tmp_1556533742_5cc6d1ee1cacf/drupal-8.6.15 to
W:\htdocs\site-name\www/drupal-8.6.15.
Unable to move C:\Users\USERNA~2\AppData\Local\Temp/drush_tmp_1556533742_5cc6d1ee1cacf/drupal-8.6.15 to
W:\htdocs\site-name\www/drupal-8.6.15.
Updating project drupal failed. Attempting to roll back to previously installed version.
Backups were restored successfully.

I've tried:

clearing Drush's cache (drush cc drush)
updating Drush (via composer) (now running Drush 8.2.3)
clearing Drupal's caches

But the problem remains.
This problem does NOT occur when updating modules. Only Drupal itself.
I checked the C:\Users\USERNA~2\AppData\Local\Temp folder while drush was working, and I was able to confirm that the drush_tmp_1556533742_5cc6d1ee1cacf subfolder was indeed present for a time (containing the Drupal .tar.gz and its upacked folder). So there's no issue in writing in this folder.
Any idea what causes this and how to solve it?
Thanks in advance.
Answer: We can only guess at an answer. A likely scenario might be disk space, permissions, or some other conflict with Drush & filesystem, but that's speculation.
Run the same command with the --debug flag (drush up drupal -y --debug) to see a verbose dump of what Drush is doing and look for errors/warnings that occur as Drush is attempting a core update. Once you know the underlying filesystem issue you'll be able to resolve it.
Comment: Thanks for the `--debug` tip. I've upgraded my sites manually for now, so I can't try it at the moment, but I'll keep that in mind for the next update. (No disk space issue (18GB free), and as stated drush is able to create the "temp" subfolder, unpack the D8 files and then delete everything, so I don't think it's a permission issue.)
Answer: Please upgrade to Drush 9 and try again. See Drush's Drupal Compatibility.

And then maybe use grasmash/composerize-drupal to composerize your Drupal installation because:
Comment: Thanks for the info, but I also have some D7 sites that I need to manage, so I'd rather stay with Drush 8. The pace at which everything changes around Drupal nowadays is a bit discouraging at times... :/
Comment: @s427 – That shouldn't be the reason to stick to Drush 8. See https://drupal.stackexchange.com/questions/267511/having-multiple-drush-instances-for-different-core-versions on how to have multiple Drush versions. Apart from that in the composerized Drupal you'll use the local Drush. `$ cd /my/drupalproject/web && ../vendor/bin/drush cr` and not the globally installed Drush.


Remove an item from $form_state in an ajax callback

Question: I'm using this form api example: AjaxAddMore. I want to add a "remove button" for each indiviaul element, in order to remove an item but not the latest. Thouse are my changes:
...
  $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('People coming to picnic'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#attributes' => array('class'=>array('container-inline')),
    ];

    for ($i = 0; $i < $num_names; $i++) {

      $form['names_fieldset']['fields'][$i] = [
        '#type' => 'fieldset',
        '#name' => 'id_'.$i
      ];

      $form['names_fieldset']['fields'][$i]['ids'] = [
        '#type' => 'textfield',
        '#title' => $this->t('ID'),
        '#default_value' => $i,
        '#name' => 'id_'.$i
      ];

      $form['names_fieldset']['fields'][$i]['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name')
      ];

      $form['names_fieldset']['fields'][$i]['remove'] = [
        '#type' => 'submit',
        '#name' => 'remove_'.$i,
        '#value' => $this->t('Remove this'),
        '#submit' => ['::removethisCallback'],
        '#ajax' => [
          'callback' => '::addmoreCallback',
          'wrapper' => 'names-fieldset-wrapper',
        ],
      ];
    }
....

It works good and I can add several records. But I can't remove an item other than the latest one. This is my callback function where I've tried to unset the item I want to remove:
public function removethisCallback(array &$form, FormStateInterface $form_state) {
    $button_clicked = $form_state->getTriggeringElement()['#name'];
    $id = substr($button_clicked,7);
    $values = $form_state->getValue(['names_fieldset']);
    unset($values[$id]);
    $form_state->setValues(['names_fieldset'], array_values($values));

    $name_field = $form_state->get('num_names');
    if ($name_field > 1) {
        $remove_button = $name_field - 1;
        $form_state->set('num_names', $remove_button);
    }
    $form_state->setRebuild();
}

But It doesn't work. How could I remove or update an item from $form_state?
Comment: `unset($values[$id]);` should be `unset($values[$ids])` because your `$form['names_fieldset']['fields'][$i]['ids']` has an "s".
Comment: Thanks for your answer, but I don't think so, because $id is a variable that hold the item index to delete. It isn't the field 'ids'. I get the item index to delete using $form_state->getTriggerElement, and then I get #name.
Comment: Ok then you don't need to `unset`, you just set a new value and that will override it.
Comment: Yes. That's what I want. But I don't find a way to do it. All changes I do over $form_state are lost.
Comment: try adding a `&` to `$form_state` in your function `removethisCallback(array &$form, FormStateInterface &$form_state) {` or try commenting out `$form_state->setRebuild();` I don't think you need this.
Comment: I need $form_state->setRebuild() in order to delete the input elements. If I comment out this line, the form doesn't change.
Comment: I think that explains why all changes to `$form_state` are lost.
Comment: I don't think so. When buildForm is called, I don't loose input values. They remain with values I put. What I was wondering is if I can alter $form_state in a callback function or I should alter $form. But I've tried both without success.
Comment: It is doable. Keep it simple, for testing purposes, build a form with 1 text field. In the validate function, alter the `$form_state` there. Once you get this simple scenario working add AJAX to it. Once you get that working on an ajax callback, now try it on your real world complex scenario.
Comment: I've tried it. I tried to update input value in a callback funtion, but, again, without success.
Answer:
$form_state->setValues(['names_fieldset'], array_values($values));

setValues(array $values) only has 1 parameter
For 2 params, you need to use setValue($key, $value) without the "s"
$form_state->setValue('name', array_values($values));

Alternatively, you could do
$values = $form_state->getValues();
$values['name'] = array_values($values);
$form_state->setValues($values);

Answer: I have same problem, and I think I have a working solution (D9).
public function buildForm(array $form, FormStateInterface $form_state): array {
  // $form_state contains all values. Add a new item for init.
  $values = $form_state->getValues();

  if (!isset($values['persons'])) {
    $values['persons'][] = [
      'name' => '',
      'birthdate' => '',
      'btn_text' => 'remove person',
    ];
  }
}

An example from the $form build:
foreach ($values['persons'] as $k => $v) {
  $form['persons'][$k]['name'] = [
    '#type' => 'textfield',
    '#title' => 'Person name',
  ];
}

Remove btn. #indx is the person id param.
$form['persons'][$k]['remove_person'] = [
  '#type' => 'submit',
  '#value' => 'remove person',
  '#submit' => ['::removePerson'],
  '#name' => 'reove_person_' . $k,
  '#indx' => 'indx' . $k,
  '#ajax' => [
    'callback' => '::personCallback',
    'wrapper' => 'persons',
  ],
  '#suffix' => '
',
];

Remove person callback get the person index (#indx), remove the item, and rebuild the $form_state:
public function removePerson(array &$form, FormStateInterface $form_state): void {
  $values = $form_state->getValues();
  $element = $form_state->getTriggeringElement();

  if (!isset($element['#indx'])) {
    return;
  }

  $i = preg_replace('~\D~', '', $element['#indx']);

  if (isset($values['persons'][$i])) {
    unset($values['persons'][$i]);
  }

  $form_state->setValues($values);
  $form_state->setRebuild();
}

person callback rebuild the form:
public function personCallback(array &$form, FormStateInterface $form_state): array {
  return $form['persons'];
}


Find the unique value of K for which the system has infinitely many solutions

Question: So I've been working through this linear algebra problem.
Find the unique value of k for which the following system has infinitely many solutions
\begin{align}
2x_1 + 2x_2 - x_3 + x_4 &= 10 \\
3x_1 + x_2 + x_3 - 2x_4 &= 1 \\
x_1 + 4x_2 - x_3 + 9x_4 &= 13 \\
x_1 + x_2 + x_3 + kx_4 &= -1
\end{align}
\begin{bmatrix}
2 & 2 & -1 & 1 & 10\\
3 & 1 & 1 & -2 & 1\\
1 & 4 & -1 & 9 & 13\\
1 & 1 & 1 & k & -1
\end{bmatrix}
So, I've reduced this to
\begin{bmatrix}
1 & 0 & 0 & -2 & 1\\
0 & 1 & 0 & 3 & 2\\
0 & 0 & 1 & 1 & -4\\
0 & 0 & 0 & k-2 & 0
\end{bmatrix}
which I think the value of $k$ should be $2$. But then this makes $x_4$ equal to $0$ which implies that there is a unique solution to the system? Can anyone help?
*edit - I've been consulting tutor who told me that k = 3 as this would make that entry 1 which gives an infinite solution. Thanks for all your help!
Comment: $k=2$ is precisely the value which does *not* make $x_4$ equal to $0$!
Comment: A (questionable) shortcut is compute the determinant of the original matrix, as a function of $~k~$ and then determine, which values of $~k~$ cause the determinant to equal $~0.~$ I refer to this shortcut as questionable, because it may actually require more time/effort than the approach taken in the posted question.
Comment: Try to plug in $k=2$ into your last reduced matrix. Recall that this matrix corresponds to the coefficients.
Answer: We can use the Rouché–Capelli theorem that can be more readable in this form:
Given the linear system $Ax = B$ and the augmented matrix (A|B).

If rank(A) = rank(A|B) = the number of rows in x, then the system
has a unique solution.

If rank(A) = rank(A|B) < the number of rows in x, then the system
has Infinitely number of solutions.

If rank(A) < rank(A|B), then the system is inconsistent.

To prove that the system at hand has Infinitely number of solutions, try to show that there is at least one row that looks like this in the agumented matrix.
$$\begin{pmatrix}0&0&0&0&| 0\end{pmatrix}$$
We can reach this result by transforming the augmented matrix to row-echelon form to get:
$$\begin{pmatrix}2&2&-1&1&10\\ 0&-2&2.5&-3.5&-14\\ 0&0&3.25&3.35&-13\\ 0&0&0&k-2&0\end{pmatrix}$$
In this transformed version, when $k=2$ the system will have infinite number of solutions because the fourth variable (say, $x_4$) can assume any possible number without constraints, for each of those values, we can computer the corresponding value of the other variables.
Note that you must use the augmented matrix not just the coefficient matrix for this solution.
A second approach would be using this fact:

A nxn homogeneous system of linear equations has a unique solution
(the trivial solution) if and only if its determinant is non-zero. If
this determinant is zero, then the system has an infinite number of
solutions.

In your case the determinant's value is $k-2$. When $k=2$, there would be an infinite number of solutions.
Note that you don't need to use the augmented matrix to find the determinant.
References: U of Oregon Education - Linear Systems and University of Pennsylvania - Course material.
Answer: For infinitely many solutions to exist, you should be able to write eqn (4) as a linear combination of the first 3, i.e.
$\text{eqn}(4) = a \times \text{eqn}(1) + b \times \text{eqn}(2) + c \times \text{eqn}(3)$
Plugging in the numbers:
$2a + 3b + c = -1$
$2a + b + 4c = -1$
$-a + b -c = -1$
$a - 2b + 9c = -k$
From the first two equations,
$2b-3c = 0$, i.e. $b = 3c/2$
From the first and third equations,
$5b-c = -3$, i.e. $15c/2-c = -3$, i.e. $c=-6/13$, $b = -9/13$
From the third equation, $a = b-c + 1 = 10/13$
Finally, $k = -a + 2b -9c = -10/13 -18/13 + 54/13 = 26/13 = 2$


get parameter from url and after submitting form append this parameter with action

Question: /*  current page url*/
/AddProduct.jsp?categoryId=1/
<code> <script type="text/javascript">
     function abc(){

    var hashes = window.location.href.slice(window.location.href.indexOf('?')+1).split('&');
    window.location="addproduct.action?"+hashes;
    return false;
    }

        </script>
</head>

<body>

  <s:form method="post" enctype="multipart/form-data">
        <s:textfield  label="Name" name="productBean.name" id="productBean.name"/>
        <s:textfield  label="Price" name="productBean.price" id="productBean.prsice"/>
        <s:textfield  label="Description" name="productBean.description" id="productBean.description"/>
        <s:label name="upload" value="Image"></s:label>
        <s:file name="upload"> </s:file>
        <s:submit onclick='abc()' value="Add Product" ></s:submit>
     </s:form>
</code>
I want to get parameters from url and when form is submitted, the url parameter will append to a new action (addaction)
PROBLEM
get "categoryId=1" and when submit button is pressed append "categoryId=1" with an action
Answer: What I understand from your code you want to resend catgoryId with product's form data and categoryId is available is in URL. I thought  don't need to use window.location and use the following code for your problem solution
<code> </head>

 <body>

  <s:form method="post" enctype="multipart/form-data" action="addproduct.action">
    <s:textfield  label="Name" name="productBean.name" id="productBean.name"/>
    <s:textfield  label="Price" name="productBean.price" id="productBean.prsice"/>
    <s:textfield  label="Description" name="productBean.description" id="productBean.description"/>
    <s:label name="upload" value="Image"></s:label>
    <s:file name="upload"> </s:file>
    <input type="hidden" value="${param.categoryId}">
    <s:submit  value="Add Product" ></s:submit>
 </s:form>
</code>


How did we move from using syllables (ut, re, etc) to refer to intervals to using syllables to refer to notes?

Question: My understanding of syllables used in solmization is when Guido d'Arezzo created syllables ut, re, mi, fa, sol, la, it was a mean to refer to intervals in any hexachord built on :2:2:1:2:2: intervals found in the natural hexachord.
From The Cambridge History of Western Music Theory:

The six notes of any hexachord, regardless of its location, are sung to the syllables ut, re, mi, fa, sol, la, which act as vocables for solmization, or as the medievals called them, voces (singular: vox), and also embody the intervallic relationships of each note to the others.

Syllables weren't a mean to identify the pitch, but to help remember intervals and sing them. It wasn't a reference to notes C D E F G A, re could represent the interval C-D as well as F-G or G/Γ-A.
The system was spread in several countries, including mine, where today C major scale is just spelled do ré mi fa sol la si in place of C D E F G A B elsewhere. Today old ut, now do, definitely means C in these countries.
Assuming I am correct, how did we move from Guido d'Arezzo concept of using syllables to refer to intervals to the concept of using syllables to refer to notes?
Comment: @Tim _ti_ a.k.a. _si_ was invented roughly 500 years after Guido.  Before Guido, none of the syllables existed.  So Guido invented a system with six syllables, _ut, re, mi, fa, sol,_ and _la,_ that are all separated by a whole step except for _mi-fa._
Comment: Since the "natural" hexachord corresponds to the familiar solfege assignments, I wonder if the "notewise" solfege either arose fram that being the most commonly occurring arrangement or from that perhaps being the principal hexachord during the transition into major/minor tonality.
Comment: @Tim that was my reaction at first, too, but then keep in mind that the point of Guido's theoretical innovations was to make it easier to learn where the half steps are: between _mi_ and _fa_.  All other steps are whole steps.  This purpose is shared by modern movable _do_ solfège.  And in Guido's system, notes were _not_ named by syllables but by letters and syllables both, for example _A la mi re_ or _C fa ut._
Comment: With movable do solfege, do(/ut) is any pitch, and mi is two tones higher.
Comment: Intervals are useful when singing, but actual note names are more useful for instruments.
Comment: @Aaron solmization requires the use of multiple hexachords within a single piece.  The idea of a "most commonly occurring" or "principal" hexachord makes little sense.
Comment: Ut, re, mi etc., I don't think ever meant *intervals* - they were (and still basically are) *note names*. The intervals between them were just a natural occurrence. So is the question asked under false pretences?
Comment: @phoog - I thought the semi. intervals came after solfege names ending in 'i'. (mi>fa,  ti or si>do/ut) Not difficult to learn, unless one is a very thick budding muso!
Comment: If they were movable surely any monk with perfect pitch would cover his ears and squeal, "That's not an Ut! That's not an Ut!" :-)
Comment: @phoog - I thought he 'borrowed' the sounds from an earlier Gregorian chant, and the tune itself was maybe from an earlier existing one, adapted. So 'invented' may be a little generous.
Comment: @Tim some believe that Guido composed that chant for his purpose, so it's unclear.  I think it's clear that he didn't compose the text, but still, deciding to take the first syllable of each line from a hymn to denote the pitch on which that tune starts counts in my book as "inventing a system" even if he didn't make up the syllables out of thin air.
Answer: I did some research. This summary of the facts I found can be re-used in an improved answer from someone more knowledgeable who can better contextualize them and perhaps fix omissions or errors.
Guido's used note letters for music theory
Guido invented today's syllables (except si) to teach intervals to singers but always used letters and signs for music theory, like ancient Greeks. The key factor in switching from letters to syllables to refer to pitch classes is the adoption of the fixed ut, which likely first occurred among French musicians.
Fixed ut/do early popularity among French musicians
French started looking for alternatives to the moving hexachords on 17th century. The hexachord was turned into an heptachord by adding si, the idea of extending hexachords to a full octave was proposed earlier by Bartolomé Ramos de Pareja (1482).
Jean Rousseau described major/minor modes as well as the link between heptachord syllables and major/minor modes. Syllables are definitely linked to notes:

(Source).
The first column contains usual notes letters. The third column contains syllables associated with letters in the natural mode (no flats -- b quarre is ♮, and ſi/ſol are actually si/sol).
The growing complexity of hexachord mutation in the new music landscape was favorable to a fixed ut. Another Rousseau, philosopher and musician Jean-Jacques, developed a detailed argument against fixed "ut", namely the loss of functional properties but, end of 18th, the newly created French music academy taught music theory using syllables and the fixed ut method.
From six syllables to fixed do
From Guido's hexachord (1032) until c. 1800, music evolved a lot, from voice to instrumental, from modal to tonal. During this period modulation and transposition gained popularity:

Hexachord mutation, i.e. switching from an hexachord to another one to accommodate the ambitus, became increasingly complex with transposition and altered notes.
Using keyboards introduced the tuning problems. Perfect hexachords weren't practical with temperaments.
Modal theory inherited from old modes also progressively lost momentum, while tonal theory became attractive. This pushed forward the octave interval, and the need for a degree after la to create the tritone.

Guido's system continued to be a reference until 1800, but there was a large number of proposals for improvement, creating confusion.
The fixed ut method with 6 syllables seems to have been enjoyed in France starting c. 1600. In 1798, the Conservatoire de musique simplified it, retaining 7 syllables and no semitone variants. It was used to teach music, theory and singing.
It inspired music teachers abroad, at least for solmization purposes. Other countries chose to keep using a moving scale, more suitable to learn intervals, but with an additional syllable for B, and often variants for semitones.
Proposals to improve the hexachord system

Use 8 syllables psal li tur per vo ces is tas: Bartolomé Ramos de Pareja in Musica Practica (1482).
Change mutation from re to ut: Loys Bourgeois (1550).
Drop one of the three hexachords and use additional mutations: Adrian Petit Coclico (1552), Gioseffo Zarlino (1573), Thomas Morley (1597), Marin Mersenne (1636).
Drop ut and re: Thomas Morley (1597). This gave the fasola system where la-fa are used for the semitone.
Add syllables for B and B♭: Adriano Banchieri (1614). With these two additional syllables, syllables corresponded to pitch classes and mutation was not required.
Use se for B: Joachim Burmeister (1599)
French start to use fixed ut syllables where ut is C (c. 1600)
Rename ut into do: Giovanni Battista Doni (1640)
Use 8 syllables do re mi fa sol la ni do with variants for semitones: Otto Gigelius (1659)
Use a double scale based on two hexachords, with an additional si: Guillaume Gabriel Nivers (1666).
Integrate heptachordal solmization with major-minor system: Jean Rousseau in Méthode claire et facile pour apprendre à chanter (1683). This document first describes the two modes which can replace the old modes, and also proposes to map the seven syllables on the modes.
Stop using fixed ut, stay focused on intervals: Jean-Jacques Rousseau in Dissertation sur la musique moderne (1743).

French Conservatoire of Music: Fixed do
In the aftermath of French Revolution, the Convention creates the Conservatoire de musique, a national body to teach music (1795). Continuing on the same trend of using a fixed ut and with si added c. 1650, the school imposes a single scale with fixed do. It's against Jean-Jacques Rousseau's earlier advice but the situation has changed, modulation is developping making moving do inspired by Guido hexachords too difficult to use.
The simplification encompasses dropping the double scale used earlier and the syllables specific to semitones. As sometimes read, it drop voces (degree functions) and only expresses claves (pitches) within an octave.

Sources (some only in Fr):

L'Enseignement de la Lecture à Vue Depuis les Temps Médiévaux jusqu'au XXe Siècle (online)

Do Fixe Ou Do Mobile?: Un Débat Historique (online)

Syllable Systems. Kodaly's Choices (online)

The French Path: Early Major-Minor Theory (online)

Wikipedia's article on solmization.
Comment: Given the constant implication in this website that movable do solfege is just as worthy as fixed do solfege, your claim that "However most movable *do* methods seem to be effective only for simple solmization and beginners, most advanced uses require using letters to refer to pitches" seems to give movable do solfege short shrift.
Comment: @Dekkadeci: This is the position of Wikipedia ("*La méthode du do mobile devient quasiment impraticable pour chanter des musiques atonales lorsque la tonalité n'est pas forcément affirmée*"), but I'll edit my post to not start a useless Apple vs PC war.
Comment: The position of Wikipedia is, for the benefit of those who do not read French, "Movable _do_ becomes virtually impractical for singing atonal music when the tonality isn't firmly established."  This statement, even if it were true, does not support the statement to which @Dekkadeci takes exception.  The vast majority of music is neither simple nor atonal, so it can be solmized using movable do.


Easiest way to migrate complete dns

Question: I've been struggling with this problem for awhile now and don't know the best way to proceed safely.
Our team recently acquired a smaller company's site design service and we are in the process of migrating all their sites/services into our server cluster.  The problem I am having is that they originally had their own nameservers registered at GoDaddy to serve DNS for their clients from one central BIND instance.  All of the domains for their clients were configured at their registrars to use this DNS server, whether the names were registered by the company or the client.
Obviously, we do not have access to the login credentials for many of these domain names, so changing their DNS records is not really a feasible option.  I was thinking I could move the ns1 and ns2 records that the acquired company has associated with their domain name to a new BIND server, but the the registrar will not allow me to change these records since it knows they are responsible for the DNS of other domains.  I would be apt to leave the configuration as is and just make the server currently handling dns forward to a new host, but part of the business arrangement is that the machine at that address will be shutdown soon.
What would be the best way to move the address of the nameserver without having to access all of the clients' registrar domain managers.  Thanks.
Comment: There is no way to do this without changing the glue at the registrar, they are pointing to a static IP address, since you are going to shut down that box there will be no DNS for that domain.
Comment: @Flash Oh man I was worried someone would say that.  Want the rep?  Pop that in an answer ;)
Answer: There is no way to do this without changing the glue at the registrar, they are pointing to a static IP address, since you are going to shut down that box there will be no DNS for that domain.

Easiest way to migrate complete dns


Noise coming from dunlop gcb95 original crybaby

Question: I'm using a dunlop gcb95 original crybaby. It's powered by a zoom ad16 9v adapter. The problem is, there's no noise if I use any clean preset in my fender mustang II amp, but using metal 2000 or any high gain preset introduces an unbearable buzz even if the wah is turned off, and there're no other pedals in the chain. FYI, this pedal is not modded, hence no true bypass.
My question is, is this a common issue with gcb95, because I've used another psu also, and the noise was still there? Depending on the cause, I may have to buy a power supply or a new wah unit, as it's driving me crazy. I've checked my other pedals also, and I'm sure they are not causing this noise.
Comment: Checked with just a battery? [& as a complete aside, how does Dunlop get to claim it's an 'original' CryBaby? My CryBaby, late 60s/early 70s possibly, says "made in Italy by Jen" on the base.
Comment: Yup, same thing with battery.
Answer: The original CryBabys hum.  It's usually quiet but as you've heard, certain effects can exacerbate the problem.  And there's no true bypass.  I suggest you get a different model of wah and test it in the store with your set up.  I personally use a 535Q Cry Baby Multi-Wah but YMMV.


Difference between KDE, MLE and EM for density estimation

Question: I'm reviewing kernel density estimation (KDE), maximum likelihood estimation (MLE) and expectation maximization (EM) algorithm for density estimation and struggling to differentiate what each algorithm's merits are compared to it's predecessor.
I'm aware that if data has two or more peaks, i.e., it came from two or more unknown distributions, parametric density estimation doesn't work, so we need to go for KDE.

But, why do we have to go for MLE when we have KDE to solve for multiple peaks? What does MLE solve that KDE doesn't? I went through this lecture: Stat Lecture - Washington Univ but couldn't understand the reasoning.

I do understand the framing of MLE for density estimation:
$$
\log[Pr(x_i; \text{dist}, \text{dist params})]
$$

Does above formulation still work in cases where data comes from two unknown distributions?

If '2' doesn't work, is EM algorithm the solution where there are multiple peaks in data?
3.b) If EM is solution for data with multiple peaks, then why do we even need MLE for density estimation?

What is intuition behind E-Step and using MLE in M-step of EM algorithm?

Any pointers, explanations are high appreciated!
Comment: I think you are confused about a couple of things
1. There is nothing uni-modal about parametric density estimation. For instance, the beta can be bimodal, and you can still fit the parametric beta.
2. You are specifically referring to mixtures models, which are multimodal, but not all multimodal distirbutions are mixture models.
3.  The EM algorithm is just an algorithm for obtaining MLEs that works well with mixture models. However, you could do mixtures without EM.
Answer: KDE is a non-parametric method: it can be used without specifying any assumptions regarding the density your are trying to estimate. To put it bluntly, if you have a set of $N$ observations $\{x_i\}_{1 \leq i \leq N}$ and absolutely no idea about what their ground-truth distribution $p(x)$ might be, then KDE gives you an estimate $\hat{p}(x)$. The price to pay for this flexibility is a high sensitivity to hyperparameters (i.e. the type of kernel and its bandwidth), since different hyperparameters will lead to greatly different results.
Maximum Likelihood Estimation (MLE, which I guess is what you are referring to with "Max LLE") refers to a family of methods for performing parametric density estimation. Let us assume that you know that your observations $\{x_i\}_{1 \leq i \leq N}$ have been generated from a Gaussian distribution, but that you don't know the parameters $\theta$ (e.g. the mean $\mu$ and variance $\sigma^2$) of this distribution. MLE gives you an estimate $\hat{\theta}$ of these parameters as the value that maximizes the likelihood of your observations:
$$
\hat{\theta} = \underset{\theta}{\arg\max} \log p(\mathbf{x}|\theta)
$$
i.e.  if you already have assumptions about the shape of the density, but need to infer its exact parameters, then MLE should be used instead of KDE.
EM is a  special way to perform MLE for when your observations were generated from hidden variables, for instance when your model is a Hidden Markov Model or a mixture of distributions.

I'm aware that if data has two or more peaks, i.e., it came from two
or more unknown distributions, parametric density estimations doesn't
work , so we need to go for KDE.

That is not right: the number of modes in the ground-truth distribution has nothing to do with the estimation method to be chosen. If you have no idea (no assumption) about the density you want to estimate, use KDE. If you know the family of the density but want to estimate its parameters (for instance if you know that the density is a mixture of Gaussians but you don't know its weights, means and variances), then use a MLE method such as EM.
Andrew Ng's lecture notes on EM should further clarify this.
ADDENDUM: the above only focuses on density estimation (i.e. fitting a density on observations). If the model includes hidden variables (e.g. is a HMM or a mixture of densities), inferring these hidden variables from observations is a separate problem commonly called filtering. Filtering is a field of research in its own right, and many different methods can be used to infer hidden variables, see for instance Review 1 or Review 2. For instance, if the model is a HMM or a mixture of distributions, once the parameters $\theta$ have been estimated (using e.g. the EM algorithm) then the hidden variables can be inferred using the Viterbi algorithm.
KDE does not assume any underlying structure for your data, and especially does not assume the presence of hidden variables or of different distributions. However, if KDE yields a multimodal distribution (with several peaks), then it would make sense to assume that data were generated from a mixture of distributions and to use EM (to infer $\theta$) and Viterbi (to infer the hidden variables).
Comment: Thanks much for detailed explanation ! This clarifies a lot of confusions I had.

Small follow up, when using KDE, if points came from multiple distributions, I'm assuming that it has to do something similar to Max LLE or EM : Probablistically identify which point belongs to which distribution and then identify densities ?

I guess I just want to know, does KDE separate which points came from which distribution somehow, and then identify their densities separately ?
Comment: I edited my answer to provide more details on filtering.
Comment: Would kernel density be completely non-parametrized? Could one not estimate kernel density via max likelihood, by assuming that the probability distribution is not a simple family but some complex mixture?
Comment: @Cryo I guess by definition, Max LLE is **PARAMETERIZED** , as you'd already make assumptions about what distribution data came from, but just don't know params of it. KDE is by definitions **NON-PARAMETERIZED** , so ya , don't think you need Max LEE to implement KDE, KDE will find out the right distribution and right parameters without explicit assumptions.
Comment: Except the assumptions for the optimizer, and assumptions about the appropriate kernel specification. You don't need ML for KDE, but you are not free from assumptions in either of them. So declaring one parametrized, in bold, and another one non-parametrized is probably a bit of an over-kill.
Comment: BTW lack of explicit assumptions is not a definite benefit. You may want to know exactly what you are assuming


What is the preferred symbol to indicate the least positive number to start a sequence?

Question: I need a least positive number and I am considering $\delta$, $\epsilon$ and $\theta$.  Which one would be best to start a sequence? Are there any others I should also consider?
Edit:
$a(0)\text{:=}\theta$
$a(n)\text{:=}\left \lceil \left(x=a(n-1)\right)+x^{\frac{1}{2}}\right\rceil$
The starting number can be anything $0<\theta<1$
Comment: To start a sequence of what?
Comment: I think there is no answer to this question, but at minimum you should give a lot more information. What are you doing with this sequence? What is it a sequence of? What does the phrase "the least positive number to start a sequence" *mean*?
Answer: A fairly commonly used name for the starting point, at least for arithmetic and geometric sequences, is $a$.  Another possibility is $c$, for a generic constant.
Or else in your case, depending on the indexing, you could use $a(0)$, or $a(1)$. Using Greek letters in this type of context is less traditional.  But there is nothing wrong in doing so.
Answer: $\delta$ and $\epsilon$ have particular common uses which seem not the same as yours, so given those choices I would use $\theta$. But I'd have to know more about your use to say for sure.


Code First Migration relacionamento e Insert?

Question: Estou utilizando UserManager para gerenciar os usuários, estou utilizando migration e estou tendo problema com relacionamento.
Acontece que eu tenho a entidade Cliente:
public class Cliente : IdentityUser
{
    [NotMapped]
    public string Senha { get; set; }

    [Required]
    public string NomeCompleto { get; set; }

    public virtual ICollection<Pedido> Pedidos { get; set; }

    // Telefone
    [Required]
    public virtual TelefoneCliente Telefone { get; set; }

    // Documento
    [Required]
    public virtual DocumentoCliente Documento { get; set; }

    // Endereço
    [Required]

    public virtual EnderecoCliente Endereco { get; set; }
}

A qual possui relacionamento 1=1 com EnderecoCliente:
public class EnderecoCliente
{
    [Key, ForeignKey("Id")]
    public virtual Cliente Cliente { get; set; }

    public string Id { get; set; }
    [Required]
    public Estado Estado { get; set; }
    [Required]
    public Cidade Cidade { get; set; }
    [Required]
    public string CEP { get; set; }
    [Required]
    public string Bairro { get; set; }
    [Required]
    public string Rua { get; set; }
    [Required]
    public string Numero { get; set; }

    public string Complemento { get; set; }
}

E a EndereçoCliente possui relação com Estado e Cidade que são dados fixos na tabela.
Quando envio a model com essa estrutura a model e seus relacionamentos estão ok, porém ele tenta incluir e efetuar um insert na tabela Cidade e Estado e obviamente gera erro pois esse registro já existe, o que precisa ser feito é apenas adicionar a referencia do id na tabela EnderecoCliente.
Codigo para inserir o cliente
var result = await UserManager.CreateAsync(model, model.Senha);

Estado:
public class Estado
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string NomeEstado { get; set; }
}

Cidade:
public class Cidade
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string NomeCidade { get; set; }

    public Estado Estado { get; set; }
}

Alguém consegue me ajudar??
@@Edit
Segue me DBContext
public class EfDbContext : IdentityDbContext<Cliente>
{
    public EfDbContext() : base ("EFDbContext")
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Produto> Produtos { get; set; }
    public DbSet<Administrador> Administradores { get; set; }
    public DbSet<Cliente> Cliente { get; set; }

    public static EfDbContext Create()
    {
        return new EfDbContext();
    }

    public DbSet<Categoria> Categorias { get; set; }
    public DbSet<MarcaVitrine> MarcaVitrine { get; set; }
    public DbSet<ClubesNacionais> ClubesNacionais { get; set; }
    public DbSet<ClubesInternacionais> ClubesInternacionais { get; set; }
    public DbSet<FaixaEtaria> FaixasEtarias { get; set; }
    public DbSet<Genero> Generos { get; set; }
    public DbSet<Grupo> Grupos { get; set; }
    public DbSet<Marca> Marcas { get; set; }
    public DbSet<Modalidade> Modalidades { get; set; }
    public DbSet<SubGrupo> SubGrupos { get; set; }
    public DbSet<ProdutoVitrine> ProdutoVitrine { get; set; }
    public DbSet<QuironProduto> QuironProdutos { get; set; }
    public DbSet<Cor> Cores { get; set; }
    public DbSet<Tamanho> Tamanhos { get; set; }
    public DbSet<Estoque> Estoque { get; set; }
    public DbSet<ProdutoModelo> ProdutoModelo { get; set; }
    public DbSet<Cidade> Cidade { get; set; }
    public DbSet<Estado> Estado { get; set; }
    public DbSet<Pedido> Pedidos { get; set; }
    public DbSet<ProdutoPedido> ProdutosPedidos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Produto>().ToTable("Produtos");
        modelBuilder.Entity<Administrador>().ToTable("Administradores");

        base.OnModelCreating(modelBuilder);
    }

}

Answer: Acredito que o problema seja porque as entidades de cidade e estado estejam detachadas do seu contexto, tente fazer o seguinte antes de chamar o UserManager.CreateAsync(model, model.Senha):
if (UserManager.Entry(model.Cidade).State == EntityState.Detached)
    UserManager.Cidades.Atach(model.Cidade);

if (UserManager.Entry(model.Estado).State == EntityState.Detached)
    UserManager.Estados.Atach(model.Estado);

Não sei se isso irá resolver seu problema, pois não sei o código que você esta utilizando no seu DbContext (UserManager).
Comment: Obrigado por responder, não existe a opção Entry e também não visualizo a entidade em UserManager, nem referencias a serem adicionadas para que funcione.
Comment: UserManager nao é o DbContext e sim UserManager do asp.net.identity por isso nao tem essas opcoes


derivative of $\arcsin \frac{e^{2x}-1}{e^{2x}+1}$

Question: Question
Please help me find the derivative of $\arcsin \dfrac{(e^{2x}-1)}{(e^{2x}+1)}$
Answer
Using the chain rule this can be written as:
$$\dfrac{1}{\sqrt{1- \left( \dfrac{e^{2x}-1}{e^{2x}+1}\right)^2}} \times \dfrac{2e^{2x}(e^{2x}-1)-2e^{2x}(e^{2x}+1)}{(e^{2x} + 1)^2}$$
This can be simplified to:
$$\dfrac{1}{\sqrt{1- \left( \dfrac{e^{2x}-1}{e^{2x}+1}\right)^2}} \times \dfrac{-4e^{2x}}{(e^{2x} + 1)^2}$$
The correct answer should be
$$\dfrac{2e^{x}}{e^{2x}+1}$$
I can't really see how they get there...
Comment: Along with the below answers, your quotient rule is backwards, derivative of the numerator comes first, this just makes your expression positive
Answer: Do your computations in blocks; first consider
$$
1-\left(\frac{e^{2x}-1}{e^{2x}+1}\right)^2=
\frac{(e^{2x}+1)^2-(e^{2x}-1)^2}{(e^{2x}+1)^2}=
\frac{4e^{2x}}{(e^{2x}+1)^2}
$$
so
$$
\frac{1}{\sqrt{1-\left(\dfrac{e^{2x}-1}{e^{2x}+1}\right)^2}}=
\frac{e^{2x}+1}{2e^x}
$$
Now the derivative of the fraction
\begin{align}
\left(\frac{e^{2x}-1}{e^{2x}+1}\right)'
&=
\frac{(e^{2x}-1)'\cdot(e^{2x}+1)-(e^{2x}-1)\cdot(e^{2x}+1)'}
{(e^{2x}+1)^2}
\\[6px]
&=
\frac{2e^{2x}(e^{2x}+1)-2e^{2x}(e^{2x}-1)}{(e^{2x}+1)^2}
\\[6px]
&=
\frac{4e^{2x}}{(e^{2x}+1)^2}
\end{align}

There is a slicker way: by definition,
$$
\frac{e^{2x}-1}{e^{2x}+1}=
\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}=
\frac{\sinh x}{\cosh x}=\tanh x
$$
and the derivative of $\tanh x$ is
$$
\frac{1}{\cosh^2x}=1-\tanh^2x
$$
so your derivative is
$$
\frac{1}{\sqrt{1-\tanh^2x}}(1-\tanh^2x)=\sqrt{1-\tanh^2x}
=
\frac{1}{\cosh x}=\frac{2}{e^x+e^{-x}}=\frac{2e^x}{e^{2x}+1}
$$
Comment: Thank you for your answer, much appreciated!
Answer: Are you familiarized with hyperbolic functions? Note that $$\frac{e^{2 x}-1}{e^{2 x}+1}=\tanh (x)$$
We know that for the circular function $$
\frac{\mathrm{d}}{\mathrm{d}x} \tan(x) = [\sec(x)]^2.$$
I won't go into details, but circular relations hold in the hyperbolic case.
So we have:
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x} \arcsin\left(\tanh(x) \right)
&= \frac{\mathrm{d}}{\mathrm{d}x} \arcsin\left(x \right)\big|_{x=\tanh(x)} \times \frac{\mathrm{d}}{\mathrm{d}x} \tanh\left(x \right) \\
&= \frac{1}{\sqrt{[\tanh(x)]^2+1}} \times [\mathrm{sech(x)}]^2 \\
&= \frac{1}{\sqrt{[\mathrm{sech(x)}]^2}} \times [\mathrm{sech(x)}]^2 \\
&= \sqrt{[\mathrm{sech(x)}]^2} \\
&= \sqrt{\frac{4}{\left(e^{x}+e^{-x}\right)^2}} \text{, assuming } x \in \mathbb{R},\\
&= \frac{2}{e^{x}+e^{-x}}
\end{align}
Comment: Thank you for your answer!
Answer: $$\sqrt{1-\left(\frac{e^{2x}-1}{e^{2x}+1}\right)^2}=\sqrt{\frac{(e^{2x}+1)^2-(e^{2x}-1)^2}{(e^{2x}+1)^2}}=\sqrt{\frac{4e^{2x}}{(e^{2x}+1)^2}}=\frac{2e^x}{e^{2x}+1}$$
Can you continue?
Answer: Could it probably help working with hyperbolic functions?
$$\tanh x=\frac{\sinh x}{\cosh x}=\frac{\frac{e^x-e^{-x}}2}{\frac{e^x+e^{-x}}2}=\frac{e^{2x}-1}{e^{2x}+1}\implies$$
$$\left(\arcsin\frac{e^{2x}-1}{e^{2x}+1}\right)'=\left(\arcsin\tanh x\right)'=\frac1{\sqrt{1-\tanh^2x}}\cdot\text{sech}^2x=\frac1{\cosh x}=\text{sech}\,x$$
I think you can leave it that way or instead also write
$$\text{sech}\,x=\frac1{\cosh x}=\frac2{e^x+e^{-x}}=\frac{2e^x}{e^{2x}+1}$$


Understanding React-hook-form Controller

Question: I am working on a website that has been build before me and it uses a method of the Controller part of react-hook-form that I have not seen before.
This is an example of the code:
const CheckboxController = (props: CheckboxProps) => {
  return (
    <Wrapper>
      <Controller as={CheckboxInput} {...props} />
    </Wrapper>
  );
};

With CheckboxInput being a simple material-ui checkbox.
I understand the traditional method of using something like:
const CheckboxController = (props: CheckboxProps) => {
  return(
    <Controller
    name={props.name}
    control={props.control}
    render={({ field }) => (

          <Checkbox
            onChange={(e) => field.onChange(e.target.checked)}
            checked={props.checked}
            disabled={props.isDisabled}
            />
            {props.label}

      )}
    />
  );
};

But unfortunately the entire site is build upon the <Controller as={}> setup. I cant seem to find any info online about it to figure out how it works. Does anyone know about this method or can point me in the right direction? Thank you.
Comment: Is it related to. - https://react-hook-form.com/api/usecontroller/controller/ ?
Answer: Barkley.
It seems the project is using a lagacy version of react-hook-form, whose version is v5.
You can find the api doc here:
https://react-hook-form.com/v5/api
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: @Frank3en, thank you so much. I imagined this was the issue but got lost somewhere along the line. Thank you for your help!


Cox proportional hazard regression in SPSS using reference group

Question: I am running cox proportional hazard regression in SPSS to see the association of 'predictor' with risk of a disease in a 10 years follow-up. I have another variable 'age_quartiles' with values 1,2,3,4 and want to use '1' as reference to get HRs for 2,3, and 4 relative to '1'. When I put this variable in Strata I still get one 'HR' as follows ('S_URAT_07' is the predictor with continuous values);

Question: How do I get HRs for the predictor for the event based on 'age_quartiles' 2,3 and 4 and keeping 1 as reference group? 'age_quartile' is not a predictor here. Am I suppose to choose a specific method?
Answer: The model you're fitting involves only the one parameter for changes in hazard as S_URAT_07 varies (e.g., the B is the change in log hazard for a single unit increase in S_URAT_07), regardless of the level of age_quartiles. What differs by age_quartiles is the baseline hazard function when it's used as a strata or stratification variable, and the hazards are then no longer proportional.
If you specify age_quartiles as a factor (called a categorical covariate in COXREG) rather than a strata variable, you'll again get a single coefficient for S_URAT_07, but also a set of three coefficients that reflect proportionally differing baselines for each level of age_quartiles. You can specify simple contrasts on the factor with the first level as the reference category to reflect comparisons with that category.
If you specify age_quartiles as a factor and also include the interaction bewteen it and S_URAT_07, then you get separate proportional baseline hazard functions, but also allow the impact of S_URAT_07 to differ depending on the age_quartiles level.


What would be the SwiftUI (iOS native) equivalent implementation of an aria-live region announcing a "reminder" on web (ARIA)?

Question: I have a web app that announces a "reminder" to screen readers every minute. I implement it with standard WAI-ARIA live regions:

setInterval(function() {

  var targetDiv = document.getElementById("reminder");
  targetDiv.innerHTML = "
This reminder is announced.
";

}, 60000);

If ARIA is web only, how is a similar implementation/outcome achieved if I were to implement this in a native iOS app using SwiftUI?
I haven't tried anything yet because I don't know SwiftUI.
Answer: Generally speaking you are looking for UIAccessibility.post to announce anything you want at any point in time:
struct MyView: View {

    static let timer = Timer.publish(every: 60, on: .main, in: .common).autoconnect()

    @State var reminder: String = "This reminder is announced."

    var body: some View {
        VStack {
            Text(reminder)
                .onReceive(MyView.timer) { _ in
                    UIAccessibility.post(notification: .announcement, argument: reminder)
                }
        }
    }
}

But really depends on your use case. If you don't want to repeat the same announcement for example, but only want to read out when it changes, you can use .accessibilityAddTraits(.updatesFrequently) modifier (good example here):
...
Text(reminder)
    .onReceive(MyView.timer) { _ in
        reminder = "Read this value now"
    }
    .accessibilityAddTraits(.updatesFrequently)
...

Comment: Is there any resource that maps ARIA roles and attributes to UIaccessibility? Or something else that can help me transition from web to swiftUI in terms of a11y apis?
Comment: I haven't heard of any. But Apple does a good job providing a11y to the elements automatically, so most of the time you can just rely on default behavior. I.e. in example above `Text` will be read out properly without me providing any other clues to the system. Only in few cases - such as changing content, grouping of the elements (to read them out as one), or changing the nature of the element (e.g. reading out image as button) you need some manual adjustments. So my recommendation would be: develop SwiftUI (without any custom code), then test, and adjust only things that require adjustments.


react native how to link official libraries (like CameraRoll)?

Question: I've tryed to install camera roll with the official documentation.
But i couldn't find the name of the library in npm
I've tryed :
npm install RCTCameraRoll --save

but i get
npm ERR! code E404

what is the proper way to do it ?
NOTE: i don't want to install a third party plugin i want to use facebook CameraRoll
Answer: Inorder to use CameraRoll in ios you need to:

Drag the node_modules/react-native/Libraries/CameraRoll/RCTCameraRoll.xcodeproj file in your Libraries folder in Xcode
in Xcode Build Phases -> Link Binary With Libraries -> then press + sign and add the libRCTCameraRoll.a
Recompile your app
Comment: on react 61.5 you dont need to do this.
Answer: Its part of the react-native api as mentionned in the docs so you dont need to save it as dependency from NPM.
So you just do :
import React, { CameraRoll } from 'react-native'

Take a look at the example from the docs, it's quite complete.
Comment: That was it thanks. But why do they say "Before using this you must link the RCTCameraRoll library. You can refer to Linking for help" ?
Comment: Ha ok ! Didn't understand it that way thanks a lot :)
Comment: Because when you use libraries that requires native modules like (CameraRoll) You need to link them and make them available for calling inside javascript. Certain NPM packages also require you to do this in order for them to work. I won't go into details, but essentially they are implemented in native code and need to be made available to your javascript via the RCT Bridge.
Comment: My pleasure :) Feel free to contact me if you have any questions on react or react-native.
Comment: @WilomGfx do you know if the CameraRoll is working on Android ?  I tried to use the exmaple from docs, but it's not working...
Comment: define not working ? as far as i know it works on android.


What is the name of the scale containing A, Bb, C#, D, E, F?

Question: I found that there are six notes that sound curious and inspiring to my ears, namely A, Bb, C#, D, E, F. But I am not aware of any named scales that have these six particular notes. So my question is:if there exists a named scale that contain these six notes, what is it?
Comment: @Richard, haha I am not sure about that; don't forget he is majorly recognized as a tasteful pentatonic player :).
Comment: Not sure if it helps you: according to [this page ("All named scales in txt format, but with nearly every…")](http://www.muzuu.org/new_life/pics/simpleblog/scales/allnamedscales.html), this is known as Raga Malahari in Indian music. You can find videos on Youtube with Raga Malahari, e.g. [this (singing)](https://www.youtube.com/watch?v=bHfdXHDBEmE), or [this (Carnatic guitar)](https://www.youtube.com/watch?v=in7NynBPeD0) or [this (flute+)](https://youtu.be/ZxlAaN_HqwY?t=13) or [this (violin)](https://www.youtube.com/watch?v=o3f8Ac96-YY) or [this](https://www.youtube.com/watch?v=RZcSOrZkKb4).
Comment: You should know this, Eric Clapton! ;-)
Comment: My full answer is below, but just as a bit of advice, whenever you see a flat immediately followed by a sharp, you should think of the harmonic minor scale.
Comment: @BraddSzonye - trouble is, a beginner may well not spell the notes with the accepted letter names...
Comment: @Tim, thank you for raising a concern. No worries about me in this case. :) It is that I am not an English native speaker; so my use of music terms would seem fishy :).
Answer: That looks like a mode of the D harmonic minor scale. D natural minor is D, E, F, G, A, B-flat, C, D. The harmonic minor has a raised seventh degree, so D, E, F, G, A, B-flat, C-sharp, D. If you specifically want the fifth mode of D harmonic minor (starting on A), that is usually called the Phrygian dominant scale, spelled A, B-flat, C-sharp, D, E, F, G.
Comment: Related: https://music.stackexchange.com/q/46114/6556
Answer: Awkwardly, more than one scale starts with A-Bb-C#-D-E-F (let alone contains those notes in that order). A scale starting with these notes that I haven't seen here so far is the A double harmonic scale, which is A-Bb-C#-D-E-F-G#(-A).
Answer: There are so many ways of defining scales but IMHO this is the most logical but neither jazz nor classical musicians seem to totally use it for name calling. Divide any scale into 2 tetrachords (a tetrachord always has 2 notes a perfect 4th apart, with 2 other notes in-between them, and never with 3 semitones together — there are only 4 possibilities: Major, Minor, Upper-Minor and Harmonic).
We're using A as tonic here so there is already an A harmonic tetrachord on the bottom, i.e. tonic, semitone, minor 3rd, semitone. On the top we start from the octave and work down. There is a note missing. It can only be G or G#. (F# breaks the 3 semitone rule with no symmetric logic).
Adding G# creates a harmonic tetrachord in the upper half and thus a double harmonic scale. (ala Allan Holdsworth, and a mode of Gypsy minor). Double harmonic does break the 3 semitone rule but each half is a mirror of the other and can be used in a very logical way.
G works and doesn't break the 3 semitone rule. Upper minor tetra in the upper half, tonic, semitone, tone, tone. To me this scale should be called Upper-Minor/Harmonic. Harmonic minor scale is called that because it has a harmonic tetra in the top half and minor tetra in the lower half. Harmonic Major is called using the same logic. Calling the upper half 1st and lower half 2nd. To me that is so logical and memorable.
All who commented here have a deep understanding of harmony and insight into scales and modes. Well done guys. I see confusion amongst a lot of students and feel that scales could be more easily mastered using the 2 tetrachords approach to scale naming IMHO.
Answer: When a G note is in the sequence, it's the scale and key of D harmonic minor.
Answer:
So my question is:if there exists a named scale that contain these six notes,  what is it?

Here are the common scales that fit your notes. As you can see, both the Harmonic Minor and Double Harmonic fit.
Harmonic Minor

Phrygian Dominant: A Bb C# D E F G
Aeolian Harmonic/Lydian sharp 2: Bb C# D E F G A
Ultralocrian: C# D E F G A Bb
Harmonic Minor: D E F G A Bb C#
Locrian natural 6: E F G A Bb C# D
Ionian Augmented: F G A Bb C# D E

Double Harmonic

Double Harmonic: A Bb C# D E F G#
Lydian Sharp 2 Sharp 6: Bb C# D E F G# A
Ultraphrygian: C# D E F G# A Bb
Double Harmonic Minor: D E F G# A Bb C#
Asian/Oriental: E F G# A Bb C# D
Ionian Augmented Sharp 2: F G# A Bb C# D E


SQL Query to Update One Table if Value Matches in Another

Question: I am having trouble writing an SQL query which I am trying to do using an Update and Join. I have already checked online here and there are numerous similar examples but I haven't been able to get them to work as yet.
I am trying to do a join between Table A and Table B (on a unique id linking them) and then update a value in Table A, if two of the values found in Table B match what what I am expecting (which I am inputting manually in the statement):
UPDATE TableA
INNER JOIN TableB ON TableA.UniqueId = TableB.UniqueId
SET TableA.email = 'emailaddress'
WHERE upper(TableA.user) = upper('user') AND TableB.Account = 'accountnumber'
      AND TableB.userType = 'usertype';

I may be over complicating this. Thanks.
Comment: Please tag your question with the database you are using.  Your syntax is not supported by most databases.  And please explain what the issue is with your query.  It does not look overly complicated given what you want to do.
Answer: You can use merge
MERGE INTO TableA e
USING (SELECT * FROM TableB) h
ON (e.UniqueId = h.UniqueId)
WHEN MATCHED THEN
  UPDATE
     SET e.email = 'emailaddress'
   WHERE upper(e.user) = upper('user')
     AND h.Account = 'accountnumber'
     AND h.userType = 'usertype';

Answer: Try this one:
UPDATE TableA
SET TableA.email='emailaddress'
FROM TableA INNER JOIN TableB
ON TableA.UniqueId = TableB.UniqueId
WHERE upper(TableA.user) = upper('user')
AND TableB.Account = 'accountnumber'
AND TableB.userType = 'usertype';

Comment: That's non-standard SQL. You should add for which DBMS this works
Comment: Apologies, this is using an Oracle Database
Comment: sorry i didn't get you, do u need a query that runs on oracle database or what?


UPS Shipment JSON documentation

Question: Where can I find a guide for complete UPS Shipment JSON developer guide for shipment?
I know that they have a pdf guide for shipment, but I think not all fields are present on their JSON Developer pdf guide. Like the field number of package is missing. And is there a field where you can put the package value like 100 USD.
And It's not well explained. :(
Answer: UPS uses the same query structure everywhere.
The description of all fields is in the "Shipping Package Web Service Developer Guide.pdf". To use JSON, you just need to send a request to the URL specified in the "Shipping Package JSON Developer Guide.pdf".
Comment: Where can I find the "Shipping Package Web Service Developer Guide.pdf"?
Comment: can you give an example of the request you need to make?
Comment: if you download the archive from here https://www.ups.com/upsdeveloperkit -> Shipping, you can find examples of requests and responses

UPS Shipment JSON documentation


C# Pointer in a HTML file

Question: The objective:

Create a marker in a HTML file for the "end" of the file in C#

I am iterating through a file in C# and taking the table values and storing them in a database. The file grows and grows everyday, the results being added in are just being appended to the report.
In C# I have a StreamReader that iterates through each file and places values in a list for insert into a SQL database.
string file_path = @"C:\This\Is\The\Way";
string[] files = Directory.GetFiles(file_path, "*.html", SearchOption.TopDirectoryOnly);
List<string> file_contents = new List<string>();
int* file_pointer; // Create my pointer
foreach(string file in files)
{
    using (StreamReader reader = new StreamReader(file))
    {
        string line = string.Empty;
        while ((line = reader.ReadLine()) != null)
        {
            // Remove  and
            line = line.Substring(4);
            line = line.Remove(4);
            // store in a list
            file_contents.Add(line);

            // Would I leave a pointer here ? then just keep moving it after every line until the end?
            // The thought for line.Contains("	") is that the last line,
            //  will just be moved to the end and the pointer wont show new rows.
            // this way it goes to last
            if(line.Contains("	")
                file_pointer += 1;
         }
    }
    foreach (string item in file_contents)
        // SQL insert, not implemented yet
    file_contents.Clear();
}

"Test" Data

Test Unique to File
Data Point A Unique to Test
Data Point B Unique to Test
Time Taken
Pass/Fail

Test A Run
Data Point A
Data Point B
213 seconds
Pass

Test B Run
Data Point A
Data Point B
3333 seconds
Fail

Test C Run
Data Point A
Data Point B
12 seconds
Pass

The goal is for once the html report is parsed & inserted into the database, a position is marked in that html file.
Then say tomorrow, another 6 rows are added. Instead of iterating through the whole file and just verifying that everything about to be inserted isn't a duplicate, we can just pick up where we left off.
I'm not sure the best way to go about this and would appreciate some guidance.
Question: Would creating a pointer at the end of every  be the best bet?
Comment: @Travis if you can't get into the html file generation process, it means you can't be sure it won't override your line marker, if you save it in the same file. You should save it somewhere else. Proposition: save current line marker in {filename}.llm. llm stands for Last Line Marker. In your code, when loading a {filename}.html file, try read {filename}.llm. If you find it, convert content to int and skip same amount of lines from {filename}.html.
Comment: This code won't compile. You are confusing "memory" pointers (int* pointer) with line pointers (or indexers, int currentLine). Memory pointers will work only in unsafe context and pointer arithmetics is extremely dangerous. You'll probably want to go for int pointer (without asterisc).
Comment: I think I would recommend always parsing the entire file, and comparing the data to the database and only adding new rows. This would re-process data repeatedly but would handle resets and unexpected re-orderings without issue.
Comment: it would help if you provide an example of table row, maybe there is some better approach to do that
Comment: This is a very strange and inefficient storage system.  Why are you appending HTML to the same file repeatedly instead of storing them as separate files?
Comment: also maybe you don't need a pointer? i mean, if you have some identifier from db in report, you could just get latest key from db, and read your file backwards, until you find your key. this way you don't need pointer at all
Comment: @Amy I cant get into the process that makes the HTML file and change it to go straight to the database. The HTML file also I think is able to be appended incase of network crashing
Comment: @pwrigshihanomoronimo I can make a sample set of a data, will edit once done.
Comment: @ClaudioValerio not sure what im doing for pointers :) never used one so just flying by the seat of my pants here
Comment: I will look into the Last Line Marker, thanks for the idea @ClaudioValerio
Comment: I would use Python (or similar and regex) for this.  Regardless, look into [StreamReader and seeking](https://stackoverflow.com/a/5404324/70317)
Comment: Does this answer your question? [StreamReader and seeking](https://stackoverflow.com/questions/5404267/streamreader-and-seeking)
Comment: Looks interesting for sure @TheofanisPantelides . I'll create a test right now and see if it does!
Comment: This sounds like a bad idea - surely the HTML file must reset at some point or it would grow to fill the hard drive?
Comment: @NetMage I'm not sure how the file resets. Have not been here long enough & the guys to ask are OOO
Comment: Why not just save the "where I'm up to" in the database?
Answer: Unless you want to create your html parser (that is a pain in the a**, believe me), I think this could be a solution, that doesn't need line markers.
I'm using HtmlAgilityPack nuget package:
Install-Package HtmlAgilityPack

Then my code would look like this:
private static void Run(string[] files)
{
    var sql = $@"
        MERGE TestsResults AS target
        USING (SELECT @TestId, @DataPointA, @DataPointB, @Duration, @Result) AS source (TestID, DataPointA, DataPointB, Duration, Result)
        ON (target.TestID = source.TestID)
        WHEN MATCHED THEN
            UPDATE SET DataPointA = source.DataPointA, DataPointB = source.DataPointB, Duration = source.Duration, Result = source.Result
        WHEN NOT MATCHED THEN
            INSERT (TestID, DataPointA, DataPointB, Duration, Result)
            VALUES (source.TestID, source.DataPointA, source.DataPointB, source.Duration, source.Result);";
    // Get database connection
    var dbConnection = GetDbConnection();
    // Create base command from sql
    var cmd = dbConnection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = sql;
    var paramsNames = new[] { "@TestId", "@DataPointA", "@DataPointB", "@Duration", "@Result" };

    foreach (var file in files)
    {
        // Using HtmlAgilityPack to load the document
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(file);
        // Getting all TR from document, skipping first with header
        var rowsCollection = doc.DocumentNode.SelectNodes("//tr").Skip(1);
        foreach (var row in rowsCollection)
        {
            // Getting all TDs in current row and converting contents to string[]
            var values = row.SelectNodes("td").Select(el => el.InnerText).ToArray();

            // insert or update in database: each row is a new DbParameter set for our DbCommand
            cmd.Parameters.Clear();
            for (int i = 0; i < paramsNames.Length; i++)
            {
                var param = cmd.CreateParameter();
                param.ParameterName = paramsNames[i];
                param.DbType = DbType.String;
                param.Value = values[i];
                cmd.Parameters.Add(param);
            }
            // Run the command, will update existing tests and adding new ones
            cmd.ExecuteNonQuery();
        }
    }
}

I'm using the power of MERGE statement for SQL Server: https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql.
Basically the MERGE statement will update matching records and inserting new ones.
Please note you could need to do some additional cleaning on the data (e.g. Duration can be converted to int, pass/fail to boolean, ...).
If you are super sure that file generator will always append rows (and will not remove or modify any of the previous worked rows), and don't want to go through already parsed lines, this is the solution:
private static void Run(string[] files)
{
    var sql = $@"
        MERGE TestsResults AS target
        USING (SELECT @TestId, @DataPointA, @DataPointB, @Duration, @Result) AS source (TestID, DataPointA, DataPointB, Duration, Result)
        ON (target.TestID = source.TestID)
        WHEN MATCHED THEN
            UPDATE SET DataPointA = source.DataPointA, DataPointB = source.DataPointB, Duration = source.Duration, Result = source.Result
        WHEN NOT MATCHED THEN
            INSERT (TestID, DataPointA, DataPointB, Duration, Result)
            VALUES (source.TestID, source.DataPointA, source.DataPointB, source.Duration, source.Result);";
    // Get database connection
    var dbConnection = GetDbConnection();
    // Create base command from sql
    var cmd = dbConnection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = sql;
    var paramsNames = new[] { "@TestId", "@DataPointA", "@DataPointB", "@Duration", "@Result" };

    foreach (var file in files)
    {
        // Using HtmlAgilityPack to load the document
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(file);
        int skipLines = 1;

        // Try to load last line marker file
        var lastLineMarkerPath = Path.ChangeExtension(file, ".llm");
        int lastWorkedLine = 0;
        if (File.Exists(lastLineMarkerPath))
        {
            var text = File.ReadAllText(lastLineMarkerPath);
            if (int.TryParse(text, out lastWorkedLine))
            {
                // if file exists and content is convertible to int, add found value to the numer of line to skip
                skipLines += lastWorkedLine;
            }
        }
        // Getting all TR from document, skipping first with header
        var rowsCollection = doc.DocumentNode.SelectNodes("//tr").Skip(skipLines);
        foreach (var row in rowsCollection)
        {
            // Getting all TDs in current row and converting contents to string[]
            var values = row.SelectNodes("td").Select(el => el.InnerText).ToArray();

            // insert or update in database: each row is a new DbParameter set for our DbCommand
            cmd.Parameters.Clear();
            for (int i = 0; i < paramsNames.Length; i++)
            {
                var param = cmd.CreateParameter();
                param.ParameterName = paramsNames[i];
                param.DbType = DbType.String;
                param.Value = values[i];
                cmd.Parameters.Add(param);
            }
            // Run the command, will update existing tests and adding new ones
            cmd.ExecuteNonQuery();
        }

        // write total row count to last line marker file
        File.WriteAllText(lastLineMarkerPath, (rowsCollection.Count() + lastWorkedLine).ToString());
    }
}

Although I would recommend you work always the whole file.
Comment: So in the first example, my table name would be `MERGE my_table AS target`, then leave source as it is?
Comment: yes, substitute "TestsResults" with your actual table name. Fix other possible naming differences accordingly to your situation.

C# Pointer in a HTML file


Any tool to benchmark web server performance

Question: What I wanted to know is if there is any easy tool for me to run in Centos linux to know how good the box is.
Disk IO, CPU, Memory ...not only the data but their performance under high usage, high traffic, high IO operations...
You can tell me tools towards the websites as well. I think that can also test to know if the server as web server is good or bad
Comment: This isn't an answer, just a comment that the very good answers here should specify whether they'll work on shared hosting (in which people often lack root access to install the programs mentioned, even if they have SSH access). Many people searching for this answer, and perhaps the OP, will be on shared hosting, or want to compare it as an option. I'd have added this as a comment on the OP but couldn't, so alas it'll appear after all the other answers, rather than before where it might help someone in this position. Oh well!
Answer: You can use Apache Bench (ab) to test webserver performance
You can analyze sar reports (e.g. sarcheck) to identify system bottlenecks.
Answer: Try installing and running HardInfo. I use Ubuntu, so my package manager is APT, but on CentOS the relevant command might be something like
yum install hardinfo

Also, take a look at this how-to.
Answer: Have a look at Apache JMeter; you can use it to simulate high load on the web server, and it will give you useful stats.  You can customize web hits so it's not just a high-load spider crawl of the web server, but can perform exact actions such as click here, enter text, submit, etc.
Answer: Try httperf:
http://www.hpl.hp.com/research/linux/httperf/
Combine it with Ganglia:
http://ganglia.sourceforge.net/
Answer: If you are working with a very large infrastructure/IT department, Traverse is pretty neat -- http://www.zyrion.com/products/
It does dashboards, generates reports, and many other things. It even has an API for setting up your own tests.
Answer: You can use 'ab' (apache benchmark) to flood your webserver with requests.
Answer: This might be a very simple option, but if you use Google Chrome as your browser, click view, developer tools. There is a nice tab in here for checking latency for elements and how fast they load, I've found this to be one of the best tools to see what part of a page is being delivered slowly.
As for server level monitoring, I've used Zenoss Core to monitor both the host and the application (IIS via WMI and Apache via the Nagios plug-in).
Answer: I've used Pylot off and on, I like it being as you can program user behavior into it via simple XML.
http://www.pylot.org/


Change Visibilty of imageviews in alertdialog-Android

Question: I'm trying to build an custom alertdialog in which there are 3 ImageViews .I want to hide and show these ImageViews dynamically.Here is my showroute() in HomeActivity class in which i'm creating the custom dialog.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(HomeActivity.this);
    alertDialog.setView(getLayoutInflater().inflate(R.layout.routedialog, null));
    alertDialog.setTitle("Home Activity");
    alertDialog.setIcon(R.drawable.logo);
    alertDialog.setMessage(Html.fromHtml("Route Details"));
    ImageView iv1,iv2,iv3;
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View convertView = (LinearLayout) inflater.inflate(R.layout.routedialog, null);
    iv1=(ImageView) convertView.findViewById(R.id.iv1);
    iv2=(ImageView) convertView.findViewById(R.id.iv2);
    iv3=(ImageView) convertView.findViewById(R.id.iv3);

    iv1.setVisibility(View.GONE);
    iv2.setVisibility(View.GONE);
    iv3.setVisibility(View.GONE);

    convertView.findViewById(R.id.ll).invalidate();

and here is my routedialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
 <ImageView
            android:id="@+id/iv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/ivred" />
  <ImageView
            android:id="@+id/iv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/ivblue" />
  <ImageView
            android:id="@+id/iv3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/ivgreen" />
</LinearLayout>

I want these ImageViews to be hidden when the dialog manager pops up and has to be made visible dynamically after checking certain conditions.Please Help.
Answer: You are inflating the layout again
 LayoutInflater inflater = getLayoutInflater();
 View convertView = (LinearLayout) inflater.inflate(R.layout.routedialog, null);
 alertDialog.setView(convertView);

Now initialize views and set the visibility for the views. Also check whether you want GONE or INVISIBLE @ http://developer.android.com/reference/android/view/View.html#attr_android:visibility depending on your need
Also i do not see anywhere iv4,iv5,iv6,iv7,iv8 in your custom dialog layout.
This
   iv4=(ImageView) convertView.findViewById(R.id.iv4);
   iv5=(ImageView) convertView.findViewById(R.id.iv5);
   iv6=(ImageView) convertView.findViewById(R.id.iv6);
   iv7=(ImageView) convertView.findViewById(R.id.iv7);
   iv8=(ImageView) convertView.findViewById(R.id.iv8);

will give NullPointerException.
Edit :
AlertDialog.Builder alertDialog = new AlertDialog.Builder(HomeActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.routedialog, null);
        alertDialog.setView(convertView);
        alertDialog.setTitle("Home Activity");
        alertDialog.setIcon(R.drawable.ic_launcher);
        alertDialog.setMessage(Html.fromHtml("Route Details"));
        ImageView iv1,iv2,iv3;
        iv1=(ImageView) convertView.findViewById(R.id.iv1);
        iv2=(ImageView) convertView.findViewById(R.id.iv2);
        iv3=(ImageView) convertView.findViewById(R.id.iv3);
        iv1.setVisibility(View.GONE); // GONE oR INVISIBLE according to what you want
        iv2.setVisibility(View.GONE);
        iv3.setVisibility(View.GONE);
        alertDialog.show();

Snap when imageview is visible
Comment: Thanks for ur answer..But i want the image views to be invisible when the dialog window pops up and should be made visible after checknig some condition..
Comment: @Lal set the visibility to `INVISIBLE`. or in xml for the views `andorid:visibility="INVISIBLE"`. Then on condition make it visible


How to deal with deployments to a single host with multiple application servers using Fabric?

Question: I have many application servers running on the same host. Every application server is installed in a different directory.
How should I tackle deployments on the servers, using Fabric? I would like to be able to perform deployments on each server separately, and on subsets of servers. Clearly the env.hosts parameter has no use here, since all servers are on the same host. Same goes for the env.roledefs parameter. These come in handy when every server is installed on a different host.
How should I deal with grouping of the servers, and setting separate environment parameters for each one of them which the fab tool can read and apply.
Answer: It's just python so do what you need to do to keep them seperate. You can define the dir differences in a dictionary or some yaml file that's read into the script. There isn't anything made in fabric to make you do it one way nor provide any specific way to do this.
But essentially just keep in mind that it's not a DSL, it's a full python file, and you'll stumble onto what works best for you and your environment.
Comment: Thanks Morgan.
I already do define the different target folders in a configuration file, which the fabfile then retrieves. However it's quite inconvenient, since they belong to the same host and I can't use lots of the "goodies" that Fabric provides out of the box, since it seems to make the assumption that every host runs one single server. The question was whether there is some built-in functionality in Fabric that provides  what i'm looking for.


Redirect specific IP address to a another site/page/IP using IPTABLES

Question: Currently, I am using IPTABLES to ban people from accessing my site. Using this format in IPTABLES:
<code>  iptables -I INPUT -s 96.266.184.52 -j DROP -m comment --comment "whatever I have to say"
</code>
I would like to instead have it setup where iptables will redirect that specific person (IP 96.266.184.52 in this case) to a webpage where it says they are banned, and the steps involved to get unbanned. Rather I do this using apache, another IP, redirecting them to a specific port, whatever the case may be I would like to not access anything of mine except that one webpage telling them how to be unbanned.
Answer: To do this with iptables you could setup a virtual server in apache listening on an alternate port with the docroot set to the instructions for how to be un-banned.
<code>iptables -t nat -I PREROUTING -p tcp --dport 80 -s 96.266.184.52 -j DNAT --to-destination $server_ip_address:$alternate_apache_port
</code>
Comment: This is what I was looking for. Thanks. Now if I can only perfect the damn Vhosts.


Difference between pre-lattice and complete posets?

Question: As they are defined, they seem to be the same thing to me, other than that a pre-lattice involves finite subsets... Is there another important difference?
These are the definitions in the text:
We say that a partially ordered set $( S, \leq)$ has the largest-lower-
bound property if $\inf E$ exists for every subset $E \subseteq S$ which is nonempty and
bounded below.
Dually, we say that $S$ has the least-upper-bound property if $\sup E$ exists
for subset $E \subseteq S$ which is nonempty and bounded above.
Partially ordered sets with the largest-lower-bound property are said to be
inf-complete, and those with the least-upper-bound property are said to
be sup-complete.
A partially ordered set $( S, \leq)$ is called a pre-lattice if every
nonempty finite subset $E \subseteq S$ has supremum and infimum.
Comment: It's a good idea to include context in your post, so we can know how to help! Could you add your definitions of pre-lattice and complete posets so that we know exactly your problem?
Comment: Your definition of pre-lattice seems to coincide with the usual definition of lattice. Also, you don't define complete posets. Are they the posets which are both inf-complete and sup-complete?
Answer: If you take e.g. $\mathcal P(\{a,b\})\smallsetminus\{\emptyset\}$ with respect to $\subseteq$, by your definition it is not a pre-lattice because $\{\{a\},\{b\}\}$ does not have $\inf$. But it is $\inf$-complete because you don't ask for $\{\{a\},\{b\}\}$ to have $\inf$ since it is not bounded from below.
Also if you take $\mathcal F$ to be the family of finite and co-finite subsets of $\mathbb N$ with respect to $\subseteq$, all finite sets have $\inf$ and $\sup$, but not all bounded from below sets have $\inf$ and bounded from above have $\sup$. E.g. $\{\{2n\}\mid n\in\mathbb N\}$ doesn't have $\sup$ in $\mathcal F$.


Newly created node type is always disabled

Question: I have created a new node type using a custom module on Drupal 7. However when I check the content type under the structure menu item it isn't listed. Looking in the node_type table, I see that it is listed as disabled. My question is how do I get the content type to be enabled?
Here is my content type creation function located in mymodule.install file:
// define the node type
  $type = array(
    'type' => $machine_name,
    'name' => $t($parameters['name']),
    'base' => 'room_reservations',
    'module' => 'room_reservations',
    'description' => $t($parameters['description']),
    'has_title' => TRUE,
    'title_label' => $t($parameters['title_label']),
    'custom' => FALSE,
    'locked' => TRUE,
    'disabled' => FALSE,
  );

// set other node defaults not declared above
  $content_type = node_type_set_defaults($type);

// add the body field
  node_add_body_field($content_type, $t($parameters['body_label']));

// save the content type
  node_type_save($content_type);

I believe this is correct but it obviously doesn't work. Any ideas
Answer: Drupal base install uses this configuration to create the basic page content type. Try to modify the custom value just like the example underneath:
$type = array(
    'type' => 'page',
    'name' => st('Basic page'),
    'base' => 'node_content',
    'description' => st("Use basic pages for your static content, such as an 'About us' page."),
    'custom' => true,
    'locked' => true,
    'modified' => true,
    'disabled' => false,
);

Edit
I've just checked the code of some Drupal core modules how they manage the creation of content types within code.
The Blog module defines the content type within the HOOK_node_info (just like you did). This to notify Drupal about the new type. The HOOK_install only add fields to the content type. The module also implement the HOOK_form for the content creation form and HOOK_view for the rendering.
// blog.install
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

// blog.module
function blog_node_info() {
  return array(
    'blog' => array(
      'name' => t('Blog entry'),
      'base' => 'blog',
      'description' => t('Use for multi-user blogs. Every user gets a personal blog.'),
    )
  );
}

}
Comment: The custom value indicates whether the content type was create by a module or by a user. In my case, setting it to false is the correct thing to do.
Comment: If you are still interested, I've updated my answer with the correct implementation for custom content types in code.
Answer: A possible answer to my own question. I believe that along with using hook_install() you must also use hook_node_info() as well. I was under the impression from reading the documentation that when adding fields to your node type, all you needed to do was use hook_install() as shown in the original question. That didn't work for me. It did work when I included hook_node_info() and that seemed to make the node types enabled. Am I correct that you have to use both these hooks in order to get custom node types to display?


Existence of a homeomorphism on $\mathbb{R}$ with certain properties

Question:
Let $p,q \in \mathbb{R}$ with $p \neq q$. Then there exists a homeomorphism $h: \mathbb{R} \to \mathbb{R}$ with $h(p) = q$ which is the identity mapping on $\mathbb{R}$ except a bounded set containing $p$ and $q$.

First of all, $h(q) \neq q$ since $h$ should be a homeomorphism. But somehow, I do not get the right idea by dwaing some graphs. Any hint?
Answer: HINT: An example with $p>q$; in this case the bounded interval is $[0,c]$.
Comment: Ah I see. I was dealing with the case $q > p$ but I think it goes the same way as your solution, I might put $c$ between $p$ and $q$, right? Thanks.
Comment: @TheGeekGreek: If $q>p$ you'll still have $c$ to the right of both $p$ and $q$, but the bump will be above the diagonal instead of below it.
Comment: That was dumb, sorry.
Comment: @satish: I could take a quick look now.
Comment: The solution is posted as http://math.stackexchange.com/questions/1585651/find-the-distribution-of-the-sum-z-x-1x-2-x-n/1586801#1586801.  I gave a different solution than what the book's author has given.  Was not quite sure if it is right, seems correct for me.  Hopefully you can tell me
Comment: @satish: I'll take another look after I get some sleep, but at the moment I don't follow some of your reasoning. Also, your last two displayed formulas are inconsistent: it can't be true that $P(Z)=1$ *and* $P(Z)=\frac1{2-p}$ unless $p=1$.
Comment: Thanks, Dr Scott I would correct that now and you can take a look tomorrow whenever you have time


Cancelling 3-handles in Kirby diagrams

Question: Recently been trying to understand the proofs of Gompf and Akbulut that certain 4-manifolds are $S^4$ (these 2 papers: Gompfs paper in Topology Vol. 30 Issue. 1, Akbulut). In which they use a clever 2 and 3 handle cancelling pair to reduce the Kirby diagrams associated to these manifolds.
The part of the proof that I don't quite understand is the way the 2 handle is added.
In an unpublished book on Akbulut's web page Book.pdf he states (on p.14/15),
"Notice that since 3-handles are attached uniquely, introducing a canceling 2- and 3- handle pair is much simpler operation. We just draw the 2-handle as 0-framed unknot, which is $S^2 × B^2$, and then declare that there is a canceling 3-handle on top of it. In a handle picture of 4-manifold, no other handles should go through this 0-framed unknot to be able to cancel it with a 3-handle."
A similar definition for cancelling a 2-3 handle pair is given on p.146 of 4 Manifolds and Kirby Calculus by Gompf and Stipsicz.
My problem is that in both the papers above they add in a 2-3 handle pair but the 2 handle is drawn in such a way that is goes through a 1 handle, which seems to contradict the above cancelling criteria. If anyone could explain this to me it would be greatly appreciated.
Comment: Could you please specify which figure of Akbulut's Book.pdf, and in the paper, seems wrong? Book Fig 1.12 is a 1-2 cancellation, and I don't see a figure of 2-3 cancellation, only the statement that nothing should be linked with the 2-handle so that a 3-handle actually can be put on top of it.
Comment: Unfortunately there isn't a diagram in his book but in the paper it is attached in figure. 4 along the curve $\alpha$ specified in figure. 3. In the book by Gompf and Stipsicz the diagram is as simple as a circle with framing 0.
Comment: In Figs 3-4, it looks like he's claiming that the black knot is the unknot, so the resulting manifold of a 1-framing on it is $S^3$, and therefore $\alpha$ and $\beta$ are isotopic, and also unlinked from the knot, so there's nothing passing through them; then apparently there's also an isotopy between them which increases $m$? I don't see either of these things easily, you'll probably have to play around with it, but it looks like that's what's going on.
Comment: So I'm thinking that I can look at it as follows, since the knot is the unknot we can add in out 0 framed unknot somewhere in the diagram and can then move it until it coincides with the curve $\alpha$ after doing this we reverse all the surgery do get back the original manifold with an extra 2 handle where the curve $\alpha$ was. Is this the right way to think about it?
Answer: Continued from the comments, this response was too long to fit there.
Something like that. If you believe that the knot is the unknot, then you may attach a 2-handle and immediately cancel it with a 3-handle to either $\alpha$ or to $\beta$, and get the diffeomorphism indicated on the 6th-to-last line of page 2. Then the claim is that if you attach the 2-handle to $\beta$, and then do a handle slide, you untwist one of the $m$-twists and wind up with $\alpha$ with a 2-handle, which can then be cancelled by the previous statement, and therefore $\Sigma_m\simeq\Sigma_{m-1}$. You might need to go digging through the references to see why some of those claims are true (the ones I'd want to verify are that that thing is the unknot, and the handleslide untwisting $m$).
Comment: I certainly agree with you that those points both need checking and are not obvious from the figures but I really wanted to understand how the extra handle was attached along a curve which has a one handle going through it but as I said above I assume the point is you attach and then slide then reverse surgery and the 2 handle becomes attached to this one handle. Thank you.
Comment: Sure. Sorry I couldn't give an answer more definite than "looks like they claim it works out if you play with it."
Answer: See LNM 722, Springer
Pag 16- 30
Proceedings  of Low Dimensional Manifolds
A  Link  Calculus for 4 Manifolds

Cancelling 3-handles in Kirby diagrams