Ajuda com erro foreach

Question: estou desenvolvendo um sistema que precisa subir 2 tipos de img uma pequena e uma grande para o banco de dados porem quando mando subir 3 img pequenas e 3 img grandes de teste meu foreach não sobe todas as img pequenas ou seja as suas respectivas ele sobe somente as 3 img grande ele ate sobe as 3 imgpequena porem ele repete a primeira 3 vezes alguém pode me ajudar?
Codigo:
require"conexao.php";

    if(isset($_POST['port'])){
    //dados que serão incluidos
    $nome = $_POST['galeria'];

foreach($_FILES['imgp']['tmp_name'] as $key => $name_temp){
        $name = $_FILES['imgp']['name'] [$key];
        $tmpnm = $_FILES['imgp']['tmp_name'][$key];
        $type = $_FILES['imgp']['type'][$key];
        $size = $_FILES['imgp']['size'][$key];

        $dir = "../images/small/portfolio/".$name;
        $mover = move_uploaded_file($tmpnm , $dir);

        foreach($_FILES['imgb']['tmp_name'] as $k => $n){
                $nomev = $_FILES['imgb']['name'] [$k];
                $t = $_FILES['imgb'] ['tmp_name'] [$k];
                $tipo = $_FILES['imgb']['type'][$k];
                $tam = $_FILES['imgb']['size'][$k];

        $dire = "../images/big/portfolio/".$nomev;
        $move = move_uploaded_file($t , $dire);

    if($mover&&$move){
             $sql = mysqli_query($mysqli, "INSERT INTO portfolio(nome, img, type, size, img_big, tipo, tam)
                values('$nome', '$name', '$type', '$size', '$nomev', '$tipo', '$tam')") or die (mysqli_error());
            if($sql){
                echo "foi";
            }
            else{
                echo "erro database";
            }
        }else{
            echo"
Ocorreu um erro.
";
        }
      }
   }
}

Comment: O problema seria que as fotos grandes estão repetindo?
Comment: as pequenas estao repetindo as grande tao indo certo
Comment: se eu subo 3 pequenas e 3 grandes ele vai pegar a 1 pequena q subi e vai repetir ela 3x. mas a grande ele vai subir normal
Comment: provavelmente o seu problema seja o foreach das imagens grandes dentro do foreach das imagens pequenas, ele deveria repetir todas imagens grandes para cada imagem pequena.Não consigo ver a imagem pequena sendo repetida daqui, talvez se você fizer mais alguns testes e postar mais informações talvez fique mais fácil de te ajudarem.
Comment: ta certo o que voce disse eu ja usei o `var_dump()` para ver os resultados do primeiro `foreach` ele nao passa por todos ele sempre para na primeira `img` ja o segundo pega tudo normal. o que eu devo fazer para eles funcionarem do modo que ele suba todas as `img` pequena e todas as `img` grande?
Comment: Coloquei uma resposta com um código que deve ser aproximado do que você precisa, teste ele e informe o resultado depois.
Answer: Nesse caso está sendo utilizado um foreach das imagens grandes dentro das imagens pequenas, tente utilizar um foreach apenas.
O exemplo abaixo pode não funcionar 100%, pois considera que as imagens grandes tenham os mesmos índices das pequenas

if(isset($_POST['port'])){
//dados que serão incluidos
    $nome = $_POST['galeria'];

    foreach($_FILES['imgp']['tmp_name'] as $key => $name_temp){
        $name = $_FILES['imgp']['name'] [$key];
        $tmpnm = $_FILES['imgp']['tmp_name'][$key];
        $type = $_FILES['imgp']['type'][$key];
        $size = $_FILES['imgp']['size'][$key];

        $dir = "../images/small/portfolio/".$name;
        $mover = move_uploaded_file($tmpnm , $dir);

        $nomev = $_FILES['imgb']['name'] [$key];
        $t = $_FILES['imgb'] ['tmp_name'] [$key];
        $tipo = $_FILES['imgb']['type'][$key];
        $tam = $_FILES['imgb']['size'][$key];

        $dire = "../images/big/portfolio/".$nomev;
        $move = move_uploaded_file($t , $dire);

        if($mover&&$move){
            $sql = mysqli_query($mysqli, "INSERT INTO portfolio(nome, img, type, size, img_big, tipo, tam)
values('$nome', '$name', '$type', '$size', '$nomev', '$tipo', '$tam')") or die (mysqli_error());
            if($sql){
                echo "foi";
            }
            else{
                echo "erro database";
            }
        }else{
            echo"
Ocorreu um erro.
";
        }
    }
}

Comment: tudo se resolvia com um `foreach` intao eu tentei fazer mas eu tinha feito diferente acho que por isso deu erro eu passei os 2 `move_uploaded_file` no final do `foreach` acho q por isso que deu errado
Comment: Se os `move_uploaded_file` estivessem depois da condição do sql provavel que daria erro, fora isso não vejo nada "fora do comum".Outro detalhe é que mesmo esse código que te passei não está 100% a prova de erros, mas não é nada que mais uns testes de verificação e tratamento de exceção não resolvam.

Ajuda com erro foreach


Add HTML to pdfCell in iTextSharp

Question: I wanted to render a HTML string in a page with header and footer. I tried by PdfPageEventHelper to add header/footer and then load the HTML. It does work. However the HTML loads in the page without margins. I tried adding margin to body element in HTML, which didn't work. Then I tried to add a table to body and then load the HTML inside the Table using HTMLWorker.ParseToList and cell.AddElement. It resulted in an empty table without the HTML elements.
pdfDoc.Open();

iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc);
    StyleSheet styles = new StyleSheet();
    // hw.Parse(new StringReader(invoiceHTML));

    PdfPTable bodyTable = new PdfPTable(1);
    PdfPCell bodyCell = new PdfPCell();
    bodyTable.AddCell(bodyCell);
    pdfDoc.Add(bodyTable);
    var htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(invoiceHTML), styles);
    for (int k = 0; k < htmlarraylist.Count; k++)
    {
    var   ele = (IElement)htmlarraylist[k];

        bodyCell.AddElement(ele);
    }
pdfDoc.Close();

Comment: `HTMLWorker` has been abandoned in favor of [XML Worker](http://itextpdf.com/sandbox/xmlworker). `HTMLWorker` is no longer supported. You should not expect an answer to this question unless you switch to using XML Worker.
Answer: You are creating a table, creating a cell, adding the cell to the table and then adding that table to the document. At this point these objects are done and you should treat them as read-only variables (at best). However, after those steps is when you start adding actual content to the cell and that's why you aren't seeing anything. You need to move your adding the cell to the table and your table to the document after the loop:
var bodyTable = new PdfPTable(1);
var bodyCell = new PdfPCell();

var htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(invoiceHTML), styles);
for (int k = 0; k < htmlarraylist.Count; k++) {
    var ele = (IElement)htmlarraylist[k];
    bodyCell.AddElement(ele);
}

bodyTable.AddCell(bodyCell);
pdfDoc.Add(bodyTable);

Add HTML to pdfCell in iTextSharp


Changing the position of graphs that are stacked, using ggplot

Question: I am trying to plot 4 graphs on top of each other using ggplot's function facet_wrap. The plot positioning goes from top to bottom in this order: Central, Eastern, Northern, Western. However, I would like the order to be: Eastern, Central, Northern, Western. My code looks like this...
region_plot = ggplot(region_data, aes(fill = Disease, x = Year, y = region_data$Average_rate)) +
  ylab("Average Rate") +
  geom_bar(position="stack", stat="identity") +
  scale_fill_manual("legend", values = c("Lyme Disease - Confirmed" = "red", "Lyme Disease - Probable" = "grey")) +
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) +
  ylim(0, 260) +
  facet_wrap(vars(Zone)) +
 facet_grid(Zone ~ ., scales = "free_y")
region_plot

Is there a way to change the order of plots when stacking plots?
Comment: Whenever I see a question with `ggplot2` and *"order of facets/labels/..."*, invariably the answer has to do with `factor`s. I can't show you anything with your data, but create a `factor` and facet on that.
Comment: I agree with @r2evans .  Check this tutorial, it might be useful for your purpose.  https://trinkerrstuff.wordpress.com/2013/08/14/how-do-i-re-arrange-ordering-a-plot-revisited/
Comment: That helps, didn't know the right terminology so I was finding it difficult to come up with a solution.
Answer: Turn your Zone into a factor.
Some fake data:
set.seed(42)
dat <- data.frame(dir=sample(c("North", "East", "West", "South"), size=100, replace=TRUE), x=runif(100), y=runif(100))

The plots:
library(ggplot2)
ggplot(dat, aes(x, y)) + geom_point() + facet_grid(dir ~ .) + labs(title="Order: alphabetic")

dat$dirfctr <- factor(dat$dir, levels=c("North", "South", "East", "West"))
ggplot(dat, aes(x, y)) + geom_point() + facet_grid(dirfctr ~ .) + labs(title="Order: factor")

Two notes:

I generated a second variable and used that; other SO answers (or off-site tutorials) might just replace the original variable with the factor ... but I like keeping the original as a character because during dev, I often play around with various things that deal with the two separately (but it is just a preference); and
I tend to prefer generating the levels= parameter programmatically if there is any chance that some other level will pop up in the data; otherwise, you'll find NAs in your factors. An alternative might be that you always want something first and the others don't matter, in which case levels=c("North", setdiff(c("North"), unique(dat$dir))) is a way. There are several utilities/functions/packages that can help with managing your factors/levels.


How to display the weekly view in manage availability in rooms_availability?

Question: I installed the Rooms module, and enabled all dependencies. Now when I edit a bookable unit and when I click in "manage availability", I can edit availability per month.
But I do not want a monthly view, I want weekly view. And I want to select the availability per hours/days.
Is that possible? And is there any other way to do this? Or is there another change in the code?
Comment: Any feedback about my answer?
Answer: I'm not aware of a way to display a weekly view. But as per your "... is there another change in the code ...", it seems like it should be pretty forward to transform the 3 months view to a single month view via rooms_three_month_calendar.tpl.php.
To actually do so, remove line 2 (with class="month1") and line 4 (with class="month3") from this part of that tpl file:

After doing so, it should look like so:

Still not exactly a weekly view, but at least you already got rid of 2/3 of the days you don't want to see, right? And hence leaves 3 times as much space for the current month view.
Note: By not removing the backward / current / forward links in that tpl file, you should still be able to easily navigate to another month.


Exposed date filter that uses "Is between" doesn't include end date

Question: SITUATION:

Create a view of transactions (a custom entity in my case, but I don't think this is relevant)
Filter against Authored on (which includes both the date and time of creation)
Expose the filter
Choose Operator: Is between
Display the view with 10/01/2020 and 10/31/2020 as start and end dates for October
Note: I'm using the Date Popup module for date entry, which accepts mm/dd/yyyy

Transactions on 10/31/2020 are omitted. How can I include end-date transactions, short of telling users to put 11/01/2020 instead of 10/31/2020 (which is what seems natural to them)?
Answer: It's a core bug, as @prkos mentioned, end time is assumed 00:00:00 when it needs to be 23:59:59
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (!empty($form['created']['max'])) {
    // use array_unshift() so custom submit runs before the default submit.
    array_unshift($form['#submit'], '_fix_max_date_submit_function');
  }
}

function _fix_max_date_submit_function($form, FormStateInterface $form_state) {
  $date_filter = $form_state->getValue('created');
  if ($date_filter['max']) {
    $date_filter['max'] = $date_filter['max'] . ' 23:59:59';
    $form_state->setValue('created', $date_filter);
  }
}

Alternative solution
You might have to use this solution if you don't like the default Y-m-d formatting and rather have a m/d/Y input for example. Below I use Y-m-d, but you can always change it.
It's a core bug, as @prkos mentioned, end time is assumed 12:00:00 AM when it needs to be 11:59:59 PM
If you enable Views sql query at /admin/structure/views/settings
you'll see the query is like:

So all you have to do is swap the last timestamp with the corrected timestamp that takes 11:59:59 PM into account.
You can do that with hook_views_query_alter, but hold your horses, this hook can only run inside of mymodule.views_execution.inc file, so create that file and then you can do
<?php

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter($view, $query) {
  if (!empty($query->where[1]['conditions'])) {
    foreach ($query->where[1]['conditions'] as $con_key => $con_val) {
      $has_created_date_condition = strpos($con_val['field'], 'node_field_data.created') !== FALSE;
      if (($has_created_date_condition)) {
        // timezone set in /admin/config/regional/settings, will get "Users may set their own time zone" if checked.
        $timezone = date_default_timezone_get();

        $min_date = $view->exposed_data['created']['min'];
        $min_date_obj = DrupalDateTime::createFromFormat('Y-m-d', $min_date, $timezone);
        $min_date_timestamp = $min_date_obj->getTimestamp();

        $max_date = $view->exposed_data['created']['max'];
        $fixed_max_date_obj = DrupalDateTime::createFromFormat('Y-m-d h:i:s A', $max_date . ' 11:59:59 PM', $timezone);
        $fixed_max_date_timestamp = $fixed_max_date_obj->getTimestamp();

        $query->where[1]['conditions'][$con_key]['field'] = 'node_field_data.created';
        $query->where[1]['conditions'][$con_key]['value'][0] = $min_date_timestamp;
        $query->where[1]['conditions'][$con_key]['value'][1] = $fixed_max_date_timestamp;
        $query->where[1]['conditions'][$con_key]['operator'] = 'BETWEEN';
      }
    }
  }
}

Comment: You're absolutely correct @No Sssweat. I failed to use `array_unshift`, so my custom submit was running after the default submit. That's what was keeping it from working. I agree with you that the submit approach is more straightforward than intercepting the views query. I'm using it with the Date Popup module and it seems to work fine, even though user input is mm/dd/yyyy, Again, thank you.
Comment: Thanks (again) @No Sssweat. You seem to be saving me all the time. This solution works perfectly.
Comment: For the benefit of others who may see this, mymodule.views_execution.inc goes in your modules/custom/mymodule directory. Also, because I'm using a custom entity of type transaction, 'node_field_data' is in my case 'transaction_field_data'. Finally, the Filter id for the Authored on filter must be 'created' for this code to work.
Comment: A curiosity question @No Sssweat if you have time: Any idea why modifying the form state in a custom submit function as I explain in my UPDATE above doesn't work? In addition to tacking on the time, I tried simply replacing 2020-10-31 with 2020-11-01 in the submit function as a test. That didn't work either.
Comment: @MarshallMorrise I took your word for it, I guess you must of done something wrong as when I tried, it worked. Perhaps you didn't do `array_unshift` part. I had used `views_query_alter` with D7 to solve this exact same problem, so I decided to stick to that known to work approach, but `form_later` with custom submit sure looks to be a quicker & smarter solution. *[Updated my answer](https://drupal.stackexchange.com/a/298099/27710)*
Answer: I agree this implementation lacks some UX polishing.
The reason why that day is omitted in your case is because you're not including the time, so a time of 00:00:00 is assumed, which is the beginning of the day and most of that day's time will be excluded. The first day also assumes it, but because it's the beginning of the range it includes the whole day.
The solution is to use the time along with the date, and give clues to users to orientate them with using Placeholder example values and the Filter field Description:
Empty form:

After filling in:

You can come up with better UX Label and Description, I'm just demonstrating a good starting point.
Comment: Thanks for this insight, @prkos. I'm using the Date Popup module, which "provides a HTML 5 date popup for all views filters", so dates are entered in mm/dd/yyyy format, with mm, dd, and yyyy each being a separate field. There doesn't appear to be a way to control which date filter fields a popup is applied to; seems to be all or nothing. I'll try some sleuthing to see if I can intercept the second date to tack on 23:59:59 before it gets used by the view. Otherwise, I'll either live with the off-by-a-day problem or ditch the Data Popup module (though I really like it).
Comment: Yes, I like Date Popup too, it provides some nice usability, although it clearly fails in this case with the time missing. But you can try other similar modules that have the time picker option and see if they work for you. Here are some you might try: [Datetime Range Popup](https://www.drupal.org/project/datetime_range_popup), [Date Popup](https://www.drupal.org/project/date_popup), [Bootstrap Materialize DateTime Picker](https://www.drupal.org/project/materialize_datetime_picker), [Date Popup Timepicker](https://www.drupal.org/project/date_popup_timepicker).
Comment: Again, thank you @prkos. Given your explanation, I thought I would add a custom submit function to the views filter to tack on the time, but as I explain in my UPDATE above, it doesn't have any effect.
Answer: This issue is also solved by the patch provided in https://www.drupal.org/node/2982968


How to paginate a list of objects which contains a list of object

Question: I have an Object called Person which has the following attributes:
private String firstname;
private String lastname;
private List<UserDetails> userList;

Now I have to display a list of persons and it requires to have pagination.
I am thinking to use a display tag. However I'm not able to find out how to display a list inside a list of object using display tag as I am a newbie to display tag.
Answer: <display:table name="test" id="person">
   <c:set var="userListVar" value="test.item[${parent_rowNum -1}].userList" />

  <display:column title="Related address">

    <display:table name="${userListVar}" id="child${parent_rowNum}" class="simple sublist">
        <display:column property="name" />

    </display:table>
  </display:column>
</display:table>

for your refference
http://demo.displaytag.org/displaytag-examples-1.1/example-nestedtables.jsp
Comment: the special character which is used here $..it is displaytag specific?
Comment: this is ${} EL expression in JSP


Rank theorem of linear algebra

Question: Let $U$ be an orthogonal matrix consisting of eigenvectors of $AA^{T}$, and $V$ be an orthogonal matrix consisting of eigenvectors of $A^{T}A$. Here $A$ is an $m\times n$ matrix which has rank $r$.
I want to show that $\operatorname{rank}(AA^{T})=\operatorname{rank}(A^{T}A)$. It says that since $\dim(N(AA^{T}))=m-r$, we can find independent $u_1,\ldots,u_m$ from $N(AA^{T})$ such that $U=[u_1 \ldots u_m]$ is orthogonal.
But I can't understand why $\dim(N(AA^{T}))=m-r$ guarantees there exist $m$ independent column vectors and that the matrix $U$ is orthogonal.
I studied rank theorem before but a little confused in here.
Answer: Another way to approach.
Assume $A\in M_{m\times n}(\mathbb{R})$, $\operatorname{rank}(A)=r$.
Step 1: $$\operatorname{rank}(AA^T)=\operatorname{rank}(A).$$
Obviously, $\operatorname{rank}(AA^T)\leq\operatorname{rank}(A)$.
For $\operatorname{rank}(A)=r$, so we can find a subdeterminant
$\begin{vmatrix}
a_{i_1j_1} &\dots  & a_{i_1j_r}\\
\vdots &  & \vdots\\
a_{i_rj_1} &\dots  &a_{i_rj_r}
\end{vmatrix}\not=0.$
By Binet-Cauchy Formula:
$$AA^T\bigl(\begin{smallmatrix}
i_1 &i_2  &\cdots  &i_r \\
i_1 & i_2 &\cdots  &i_r
\end{smallmatrix}\bigr)=\sum_{1\leq v_1<v_2<\cdots<v_r\leq n}A\bigl(\begin{smallmatrix}
i_1 &i_2  &\cdots  &i_r \\
v_1 & v_2 &\cdots  &v_r
\end{smallmatrix}\bigr)A^T\bigl(\begin{smallmatrix}
v_1 &v_2  &\cdots  &v_r \\
i_1 & i_2 &\cdots  &i_r
\end{smallmatrix}\bigr)=\sum_{1\leq v_1<v_2<\cdots<v_r\leq n}\left[A\bigl(\begin{smallmatrix}
i_1 &i_2  &\cdots  &i_r \\
v_1 & v_2 &\cdots  &v_r
\end{smallmatrix}\bigr)\right]^2>0$$
because at least one term of the above sum $\not=0$. (We have found above the subdeterminant of $A$ of order $r$.)
So we have proved $\operatorname{rank}(AA^T) \geq r=\operatorname{rank}(A)$.
Then we get the conclusion: $\operatorname{rank}(AA^T)=\operatorname{rank}(A)$.
Step 2:
$$\operatorname{rank}(AA^T)=\operatorname{rank}(A)=\operatorname{rank}(A^T)=\operatorname{rank}(A^TA).$$
Answer: Probably there is some mistake in the question. There can't be, in any case, $m$ independent columns in the matrix $AA^T$. Because, its rank is $r$ which means there should be only $r$ independent columns. But, the first $r$ columns of $U$ (which you have defined) will be a basis for the columns for $AA^T$ and rest of the $m-r$ columns will be a basis for $N(AA^T)$.
Let $B_1=AA^T$. Now according to rank-nullity theorem, $rank(B_1)+nullity(B_1)=number~of~columns~in~B_1$. Number of columns in $B_1$ is $m$. Rank of $B_1$ is $r$ (rank of A), so from that equation above, $nullity(B_1)=m-r$.
Comment: Yes, exactly. The proof's result is what you say above. I'm just wondering how can we say that the matrix U is orthogonal from that result.
Comment: It doesn't say it's columns are orthogonal. It just says that there is a orthogonal basis for the columns of $AA^T$. The thing is that the eigenvectors of $AA^T$ (which is $U$ as you defined) will form a orthogonal matrix. The last $m-r$ columns will give a orthogonal basis for $N(AA^T)$.
Comment: Please question if you don't get it. By the way, are you familiar with SVD? Because then, explaining all this is very easy.
Comment: Actually, it's a part of SVD. But, in SVD, matrix U is an orthogonal matrix and I can't get the meaning of "It doesn't say it's columns are orthogonal". Since U is an orthogonal matrix I think all of its columns should be orthogonal...
Comment: What I meant is there can't be $m$ independent columns as you have stated in your question. There will only be $r\leq m$ independent columns. $U$ will be a orthogonal matrix and its last $m-r$ columns will be a basis for its null space

Rank theorem of linear algebra


Trills in Clementi Op. 36 No. 1 2nd movement

Question: This is related to this discussion: How to play these trills from Clementi's Sonatina in C Major on piano?

My question: is the FG at the end of AGAGFG part of the trill, or is it the one explicitly shown in the original score (blue circle) right after the trill note G? The image I'm attaching seems to have discrepancy. In Measure 3, that FG (orange cicle) seems to be the one in the original score (blue circle), which is consistent with Neil Meyer's first image in the previous discussion linked above. However, in Measure 25, there is no FG in the original score following the trill note G, but the trill is suggested to be played as before, AGAGFG (red circle). If the FG belonged to the trill of the G note, then one would play FG twice in Meausure 3: AGAGFG FG.
Could someone please clarify? (My Willard Palmer edition shows the same as the above from sheetmusic2print)
Comment: Although Clementi printed the "FG" in the [first edition](https://s9.imslp.org/files/imglnks/usimg/f/fd/IMSLP801193-PMLP6617-clementi_g.132.-4.-_Six_Progressive_Sonatinas_for_the_Piano-Forte_Op.36.pdf), it doesn't have to be significant that it's omitted in the next-to-last measure; he might expected it to be understood.
Comment: I'll let others answer at more length, but I hope they'll include and explain the word _nachschlag_.
Comment: So which way is more stardard/common? When I see a similar trill elsewhere in future, should i always play that FG part in case it's not printed? or it depends on the context?
Answer: The ornament is played the same way in both cases — the FG occurs only once in each — it just happens to be scored differently.
The FG are a nachschlag, which is

the auxiliary closing note or notes usually played at the end of a trill
(Merriam-Webster)


Responsive design: Do I have to make a media query for each mobile width?

Question: I am trying to practice responsive design but the problem is I have imgs in a container and they don't scale with the container after each dimension.  How do I get my images to change in size according to the change in mobile device I select in the "inspect element" tool?  Hopefully this makes sense.
Answer: Try setting your img width: 100%; and height: auto;
that should make the img fit into your container.
Comment: ok, so I added it to the original coding and it is too small.  how do I make it bigger while still getting it to adjust in conjunction with the page mobile screen sizes.
Comment: by changing the dimensions of your container
Comment: Can I just send you my coding?  I can't figure this out.


conditional validation in webform

Question: I have webform 7.x-3.18+3-dev and webform presav e 7.x.1.1 installed
how can I make one field be obligatory depending on another field.
Eg if someone selects phone as best form of contact they must fill out the phone field. If they choose email they must fill out the email field.
Answer: Take a look at https://www.drupal.org/project/webform_conditional
Just make both e-mail & phone mandatory, but only show the relevant field, based on what was chosen in 'best form of contact'.
The module takes into account the 'state' of the form. It doesn't force mandatory, even if the field is set to be mandatory, but is hidden due to a certain select option ( in your case, the 'best form of contact' ).
Answer: i think field permissions module will help you
Answer: I had to make a custom module to do it without hiding the fields .  Followed the instructions here https://www.drupal.org/node/908600

conditional validation in webform


Glmnet: How to select Lambda and Alpha

Question: I'd like to pick the optimal lambda and alpha using the Glmnet package.  I'm open to all models (Ridge, Lasso, Elastic).  I'm assuming some out of sample error/cross validation is the best model selection criteria.
Macro <- read.csv("P:/Earnest/Old/R/Input.csv")
x <- Macro[1:13,3:21]
x <- as.matrix(x)

y <- Macro[1:13,2:2]
y <- as.matrix(y)

t <- Macro[14:14,3:21]
t <- as.matrix(t)

Right now, I'm using the following code.  The below code presupposes alpha = .5 (elastic), and that lambda.min is the ideal lambda.
fit <-glmnet(x, y, alpha = .5, lambda = NULL)
cv.fit=cv.glmnet(x,y, alpha = .5, lambda = NULL)
min <- cv.fit$lambda.min
predict(fit ,t, s = min)

Questions: How do I know what is the ideal alpha and lambda?  What code can I use to test various lambda/alpha combinations, to find the best out of sample error.  Is this the right approach and utilization of Glmnet?  What questions am I not considering that should be?
The data:
Comment: You can use the mean square error to select the tuning parameter lambda
Comment: The manual published with `glmnet` in `R` explains rather clearly how to do this, so reading it would be a good place to begin.
Answer: It appears that the default in glmnet is to select lambda from a range of values from min.lambda to max.lambda, then the optimal is selected based on cross validation. The range of values chosen by default is just a linear range (on the log scale) from a the minimum value (like 0, or some value for which we set no features to zero) to the maximum value, (which they set to the smallest value for which the model would set all features to zero).
From the glmnet documentation:

lambda can be provided, but is typically not and the program constructs a sequence. When automatically generated, the λ sequence is determined by lambda.max and lambda.min.ratio. The latter is the ratio of smallest value of the generated λ sequence (say lambda.min) to lambda.max. The program then generates nlambda values linear on the log scale from lambda.max down to lambda.min. lambda.max is not given, but easily computed from the input x and y; it is the smallest value for lambda such that all the coefficients are zero. For alpha=0(ridge) lambda.max would be ∞; hence for this case we pick a value corresponding to a small value for alpha close to zero.)

Glmnet: How to select Lambda and Alpha


How to achieve the use exposure filter of views, head Title Update?

Question: I use the exposed filter on a Drupal 7 website. I want to achieve that when the user clicks on the filter, the head of the title will also output the filtering term.
Any suggestions?
Answer: 1) Add Taxonomy term: Name as a field

Check Exclude from display
Uncheck Link this field to its taxonomy term page

2) Click on Title: and put [name]

How to achieve the use exposure filter of views, head Title Update？


Solving an Equation by going to the 3rd dervative

Question: Given the equation $y'=5x^2+2y^2-7$, where $y(0)=-2$, find $y'(0), y''(0), y'''(0)$
using the above, I have to find $y'''(0)$, which is what I'm having trouble with.  I solved $y'(0)=1$, and then differentiated to get that $y''(0)=10x+4y(x)y'(x)=10(0)+4(y(0))(y'(0))=4(1)(-2)=-8$
I am having difficulties solving for y'''(0), as I have trouble diffentiating $4(y(x))(y'(x))$.  Thanks!
Comment: Isn't the following true? $(y'y)'=y''y+y'y'$
Comment: I think so by the product rule eh?
Answer: Basically: $$y'''=(10x+4yy')'$$ which leads you to: $$=10+4(yy')'$$Now you do basic product rule to get your final answer: $$y'''=10+4(y''y+y'y')$$


Fragmentation and packet size,using tcpdump

Question: i am trying to understand concept of fragmentation:
i have two virtual machines with public ip connected to a switch.
tracepath shows packet not going through gateway
from vm1:
   Trying to send icmp with 65507 bytes to vm2.
ping -M want -s 65507 vm2

but in tcpdump output on vm2: its showing
tcpdump -evvv icmp
12:48:44.635551 42:43:30:b4:89:0c (oui Unknown) > b6:7a:6b:7d:54:32 (oui Unknown), ethertype IPv4 (0x0800), length 1514: (tos 0x0, ttl 64, id 10843, offset 1480, flags [+], proto ICMP (1), length 1500)
VM1 > VM2: icmp
12:48:44.635568 42:43:30:b4:89:0c (oui Unknown) > b6:7a:6b:7d:54:32 (oui Unknown), ethertype IPv4 (0x0800), length 1514: (tos 0x0, ttl 64, id 10843, offset 2960, flags [+], proto ICMP (1), length 1500)
VM1 > Vm2: icmp
12:48:44.635572 42:43:30:b4:89:0c (oui Unknown) > b6:7a:6b:7d:54:32 (oui Unknown), ethertype IPv4 (0x0800), length 1514: (tos 0x0, ttl 64, id 10843, offset 4440, flags [+], proto ICMP (1), length 1500)
VM1>VM2 icmp
12:48:44.635575 42:43:30:b4:89:0c (oui Unknown) > b6:7a:6b:7d:54:32 (oui Unknown), ethertype IPv4 (0x0800), length 1514: (tos 0x0, ttl 64, id 10843, offset 5920, flags [+], proto ICMP (1), length 1500)
VM1>VM2: icmp
12:48:44.635578 42:43:30:b4:89:0c (oui Unknown) > b6:7a:6b:7d:54:32 (oui Unknown), ethertype IPv4 (0x0800), length 1514: (tos 0x0, ttl 64, id 10843, offset 7400, flags [+], proto ICMP (1), length 1500)
**Vm1 > VM2**: icmp
12:48:44.635581 42:43:30:b4:89:0c (oui Unknown) > b6:7a:6b:7d:54:32 (oui Unknown), ethertype IPv4 (0x0800), length 1514: (tos 0x0, ttl 64, id 10843, offset 8880, flags [+], proto ICMP (1), length 1500)

This is repeated 31 times until is received fully. full paste: http://pastebin.com/cnQhn8dK
So why it looks like total data received is 1500*31=46500 bytes and what happened to 65507-46500=19007 bytes.
Can some one please clarify this.
Comment: Please post more output of tcpdump, about 5 to 10 packets.
Comment: @Gnouc now can you please check.
Comment: What are parameters of tcpdump command you have used?
Comment: tcpdump -evvv icmp
Comment: Try: `tcpdump -s 1514 -evvv` and check result.
Comment: can u tell me what this "-s" will do?.With -s its showing a longer dump.
Comment: It changes the capture size of packets, you can `man tcpdump` for more details. What is your result?
Comment: http://pastebin.com/gXvfaVjg Now its showing 44 packets.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8810/discussion-between-kevin-parker-and-gnouc)
Answer: Yes, using tcpdump with -s option, the result is now right. As your result, we count 45 packet. 44 packets with 1500 bytes, 1 packet 415 bytes.

44*1500 + 415 = 66415
66415 - 65507 = 908
908 / 45 = 20 plus 8

You can see, each packet add 20 byte for ip header + 8 byte icmp header for the first packet.
Answer: Just to add on Gnouc's answer.
You are sending 65507 bytes of data.
This doesn't include the ICMP headers which are 8 bytes.
The most common MTU size is 1500 . This size accounts for Layer 3 size that's why you see ethertype IPv4 (0x0800), length 1514: which means that the total frame size is actually 1514 bytes.
These 14 bytes account for the Ethernet header. 12 bytes per mac address  + 2 for the type.
The minimum and very common size for an IP Header is its minumum size 20 bytes (Maximum is 60 bytes).
So we have
1514 bytes - Ethernet header = 1500 bytes
1500 - IP header = 1480 bytes
1480 - ICMP header = 1472 bytes

You can send at most 1472 bytes without fragmentation.
BUT the way that IP fragments the packets it doesn't require to send the header for every packet but only for the first packet.
WITH fragmentation the maximum amount of bytes that you can send  given an MTU of 1500 is 1480 bytes.
We know the total size of your data and what's the maximum you can send.
So it's going to take at least 65507 / 1480 ~= 44.2 packets . I.e. 44 packets of 1514 and then a final packet of less than half the size.
What happened to the rest of the packets?
But why 31 packets? Well it's all in the buffer size that you are capturing.
At the end of your tcpdump you should be seeing
31 packets captured
57 packets received by filter
14 packets dropped by kernel

If you add the packets captured + the packets dropped by kernel you will get to the right answer and that's what -s it alters the snap length.
From the tcpdump manual

-s Snarf snaplen bytes of data from each packet rather than the default of 65535 bytes. Packets truncated because of a limited
  snapshot are indicated in the output with ``[|proto]'', where proto is
  the name of the protocol level at which the truncation has occurred.
  Note that taking larger snapshots both increases the amount of time it
  takes to process packets and, effectively, decreases the amount of
  packet buffering. This may cause packets to be lost. You should limit
  snaplen to the smallest number that will capture the protocol
  information you're interested in. Setting snaplen to 0 sets it to the
  default of 65535, for backwards compatibility with recent older
  versions of tcpdump.

Why did the kernel drop the packets in the first place?
Again from the tcpdump manpage

packets dropped by kernel (this is the number of packets that were
  dropped, due to a lack of buffer space, by the packet capture
  mechanism in the OS on which tcpdump is running, if the OS reports
  that information to applications; if not, it will be reported as 0).
Comment: ICMP header for the `last packet` or `the first`?
Comment: @Gnouc you are right, fixed. The headers always go on the first packet.
Comment: you are right,with out s there are lots of dropped packets and filtered packets.So that means fragmented packets are reaching destination,but tcpdump can not show it due to low buffer space.Can you tell me who fragments these large icmp packet,since i am using L2 switch.
Comment: The linux kernel does. And any other known OS as well.


Dúvida - View de sistema MVC

Question: Estou desenvolvendo um sistema para uma contabilidade em PHP, MySQL, jQuery e css, o sistema é divido em setores, e cada setor possui uma aba de gráficos (plugin highcharts), que são gerados dinamicamente de acordo com os parâmetros passados.
Funciona da seguinte forma:
indexView() -> renderIndex() -> chama menu e opções ( suponhamos aqui que nós entramos no setor fiscal):
fiscalControll -> fiscalView() -> renderFiscal() -> chama as opções do fiscal e exibe a dashboard (agora suponhamos que clicamos na aba 'Gráficos'):
O sistema chama:
fiscalControll-> fiscalModel() -> get_charts_data_json_from_mysql($chart).
na sequencia o controll pega os dados do fiscalModel() e passa para o fiscalView() rederizar de alguma forma, ai está meu 'problema'.
Dúvida:

Devo renderizar os gráficos diretamente pela função php, ou em uma pagina html separada com os locais dos gráficos?
Obs: As duas formas funcionam, quase com o mesmo tempo de resposta, mas
  qual seria o mais correto?
Answer: Apenas parafraseando o conceito da View:

View: responsável por todo o processamento necessário para a exibição, incluindo o processamento e renderização de objetos.

O MVC tem como foco principal a View. Logo, todas as demais camadas (MC) trabalham quase que exclusivamente para a View. Entretanto, o processamento/renderização é uma responsabilidade exclusiva da View.
Se algum tratamento de objetos é realizado por qualquer outra camada, com objetivo exclusivo de renderização, mova essa lógica para a View.
Os únicos contrapontos que posso adicionar, é quando o objeto é complexo demais e a View só utilizaria uma pequena parte dele. Nesse caso, o objeto pode ser tratado anteriormente. Entretanto, normalmente algum padrão, como Proxy/LazyLoad, faz esse trabalho por ti.
Como leitura complementar, sugiro os seguintes links:
https://forum.imasters.com.br/topic/536201-mvc-p%C3%A1ginas-din%C3%A2micas/#comment-2141430
https://forum.imasters.com.br/topic/557523-d%C3%BAvida-sobre-mvc-view/?do=findComment&comment=2224178

Dúvida - View de sistema MVC


Cloudberry Backup Inherit Backup State

Question: Is there a way to "inherit" an existing backup state on a new computer? Use case is that a computer is reinstalled, and data is backed up and restored using a local USB drive. Can a previous backup location be inherited so that the entire backup process doesn't need to be restarted?
Answer: For sure that is possible.
Please, add your previous storage account, go to it's settings->advanced settings and change your prefix to the previous one (it's a machine name). After that, the sync would commence and you will be able to backup from the point you've stopped previously.

Cloudberry Backup Inherit Backup State


Flutter does not work custom enum for swtich statement

Question: abstract class Enum<T> {
  final T value;

  const Enum(this.value);
}

class FlightScheduleStatus<int> extends Enum<int> {
  const FlightScheduleStatus(int val) : super(val);
  static const None = const FlightScheduleStatus(0);
  static const OnTime = const FlightScheduleStatus(1);
  static const Delayed = const FlightScheduleStatus(2);
}

Widget getFlightStates(LiveStatus liveStatus) {
switch (liveStatus.flightScheduleStatus) {
      case FlightScheduleStatus.Delayed:
        return Row(
          children: <Widget>[
            Text('Delayed'),
            SizedBox(
              width: 3,
            ),
            Chip(
              label: Text('${liveStatus.delayedTime}'),
              backgroundColor: Colors.red,
            ),
          ],
        );
        break;
      case FlightScheduleStatus.OnTime:
        return Text('On Time');
        break;
      case FlightScheduleStatus.None:
        return Text('N/A');
        break;
    }
}

here I have created custom enum with custom class. but when we use switch statement does not go through any of the case here. please help me on this issue. I want to work this code as it is if it is a enum class.
even I use liveStatus.flightScheduleStatus.value its not working.
Comment: can you add liveStatus.flightScheduleStatus and liveStatus.flightScheduleStatus.value ?
Comment: I created a sample based on your code and its working fine. Have a look at [this dartpad](https://dartpad.dev/25b511e8c606a34211330f5dc4a65f96).
Answer: I guess the issue is your FlightScheduleStatus class actually allow you to create multiple object instances with the same internal value. Since you have a public constructor for FlightScheduleStatus I am guessing you are using that elsewhere in you code to convert a int into a FlightScheduleStatus. If that is the case, you really need to use a factory constructor like the following example:
abstract class Enum<T> {
  final T value;

  const Enum(this.value);
}

class FlightScheduleStatus extends Enum<int> {
  const FlightScheduleStatus._(int val) : super(val);

  factory FlightScheduleStatus(int val) {
    if (val == None.value) {
      return None;
    } else if (val == OnTime.value) {
      return OnTime;
    } else if (val == Delayed.value) {
      return Delayed;
    }
    throw Exception('$val is not a valid value for FlightScheduleStatus.');
  }

  static const None = const FlightScheduleStatus._(0);
  static const OnTime = const FlightScheduleStatus._(1);
  static const Delayed = const FlightScheduleStatus._(2);
}

void main() {
  var test = FlightScheduleStatus(0);

  switch (test) {
    case FlightScheduleStatus.None:
      print('None'); // <-- this is the one executed
      break;
    case FlightScheduleStatus.OnTime:
      print('OnTime');
      break;
    case FlightScheduleStatus.Delayed:
      print('Delayed');
      break;
  }
}

In the example I have made the normal constructor for FlightScheduleStatus private so it is only used by FlightScheduleStatus itself. The factory contructor allow us to return objects which have already be created instead of creating new objects.


JAVASCRIPT AJAX - Prevent redirect?

Question: <code>$.ajax({url:"URL",success:function(result){
</code>
I have a webpage that accesses a certain URL and then extract certain elements of the webpage. However, in order to access that URL you have to be redirected to what is similar to a log in page (requires form submission) and then you have access to that link.
I want to prevent the redirection upon loading the URL. Is that possible?
If not, am I able to manually do the form submission using JAVASCRIPT? Via AJAX or any other resource.
EDIT: By manually saving the .html to my directory and accessing the page from my root folder, it works fluently.
Thank you!
Comment: That's not possible. Where the request is redirected to is entirely determined by the receiving server. You haven't given us enough information to help with your latter request.
Comment: Is the webpage on a server you don't control?
Comment: Yes it's on a server I don't control.
Comment: Looks like you are accessing  an API, (e.g. Facebook)  please make sure if you need to implement oAuth REST API call. the reason you are redirected is the redirectionURL requirement of the API to return back to your site after your app or your user was authenthicated.
Comment: @agentpx It has to do with APIs but no, the URL I am requesting is not related to the API. I'm unsure if I may post the link I am trying to access to so you have an idea what I mean. Tell me if I'm allowed to and I'll post it.
Comment: @tempt yes it is allowed
Comment: www.addmesnaps.com/snapchat_online.php

Clicking the link should redirect you to the index page of the website.
Comment: Not possible it is a normal website not an API
Answer: Yes, it is possible. You need to stop the form submission and add your AJAX call. Like this:
<code>$("form").submit(function(){
    $.ajax({url:"URL",
        success:function(result){
        }
    });
    return false;
});
</code>
More information here.
Comment: @gibsonman507 please don't play games of deleting a comment and wonder why people make comments about it
Comment: @gibsonman507 you stated the `return false` isn't accessible, when it is.
Comment: This doesn't prevent the server side redireection
Comment: This isn't what the OP asked.
Comment: $("button").click(function(){
     $.ajax({url:"URL",success:function(result){

To be precise, my code is as above ^^, I click on a button and it calls ajax with the URL I have in, however when the URL is called it automatically redirects to a different webpage that serves a different purpose than what I want. Does return false do the trick?
Answer: If I understand your question, what you need to do is log the user into the external website programmatically beforehand. This is possible if the other site supports OAuth or something similar, but the specifics will depend on their API and what exactly you're trying to do. I can't tell you more than that without more information.
This assumes you're trying to include the other web page in an iFrame, or link directly to a page there, or something like that. If, on the other hand, you're trying to log in to the foreign website as the user, pull out some content, and mix it in with your own, then I suggest you change your approach. You'll probably run afoul of all kinds of anti-XSS security policies, either on the foreign website or in the browser depending on what you try to do. Or you'll have to ask your users to give you their password on another site, and they'll have to really trust you for that.
Generally speaking, if you want to interact with another website, the user's client should connect, log in, and receive content directly from the other server without you acting as an intermediary. I think perhaps you're asking the wrong question: Instead of "how can I do this without the user logging in," ask "how can I let the user connect and log in to another website without having to leave my page?"
Comment: The website does not require me to log in. All it asks me to do is write a valid username (could be anything) and press "Add Me" and I will have access to the URL. I don't know how to approach that.
Comment: Do they have an API? You said "it is a normal website not an API," but that doesn't mean they don't have an API *also.*
Comment: I'm unsure. www.addmesnaps.com/snapchat_online.php

JAVASCRIPT AJAX - Prevent redirect?


Lilypond: How to Change the Vertical Position of Raised Suffixes in Chord Names?

Question: The Problem
In Lilypond, the raised suffixes in chord names – such as the "sus4" in "Csus4" – don't seem to be proportionally changed with chord name font size changes. For example:
\score {
  \new ChordNames {
    \chordmode {
      c:sus4
      \override ChordName.font-size = #-3
      c:sus4
      \override ChordName.font-size = #10
      c:sus4
    }
  }
}

As can be seen, irrespective of the font size, the baseline of the suffix always has the same vertical position.
My Question
How can I correct the vertical position of suffixes in chord names when changing the font size?
I use the latest stable version of Lilypond (v2.18.2).
What I've tried
I have already looked at the chordRootNamer and chordNoteNamer properties but neither of them affects the suffixes in chord names: chordRootNamer only affects the "C" in "Csus4" while chordNoteNamer only affects the "F" in "Csus4/F".
I guess I could override the chordNameFunction but then it seems that I would have to entirely format the chord names myself. Ideally I would be able to only partly override the existing chordNameFunction (which seems to be ignatzek-chord-names) or to only decrease the raising amount it applies to suffixes. Any ideas how that could work?
Answer: I had the same problem and found a "non-definitive" solution taking into account that I was not using 7+ chords. First I moved all 7 chords to 7+ chords and then defined how I wanted 7+ chords to appear. I know that this is not the best solution, but it worked for me.
You can do that from a terminal as follows:
sed -i 's/:7/:7+/g' *.ly
sed -i 's/\\italianChords/\\italianChords \\set majorSevenSymbol = \\markup{\\raise #-1.0 7}/g' *.ly
Comment: Thanks, this is an interesting hack. Unfortunately it only works for at most one type of chord with a raised suffix. I have chord types with different suffixes in my score, like `c:sus2`, `c:sus4`, `c:6` or`c:7`.


Dungeons and Dragons: Ability Score combinations

Question: I am trying to figure out how likely it is to roll a certain combination of 6 ability scores in Dungeons and Dragons.
edit:
Dungeons and Dragons is a tabletop role-playing game. You create a character in a fantasy world which has 6 main statistics, Strength, Dexterity, Constitution, Intelligence, Wisdom, and Charisma. Those ability scores determine the powers that a certain character can use and how strong they are.
The ability scores are rolled using 4 6-sided dice (4d6) and then using the 3 highest scores, giving you values $\in [3, 18]$ for the possible values.
My goal is to compute the likelihood of getting a combination like (8, 8, 8, 8, 8, 8) or (15, 14, 13, 12, 10, 8).
/edit
I already worked out the probabilities for rolling a single stat and a question on here confirmed that I did the math right:
3: $\frac{1}{1296}$, 4: $\frac{4}{1296}$, 5: $\frac{10}{1296}$, 6: $\frac{21}{1296}$, 7: $\frac{38}{1296}$, 8: $\frac{62}{1296}$, 9: $\frac{91}{1296}$, 10: $\frac{122}{1296}$, 11: $\frac{148}{1296}$, 12: $\frac{167}{1296}$, 13: $\frac{172}{1296}$, 14: $\frac{160}{1296}$, 15: $\frac{131}{1296}$, 16: $\frac{94}{1296}$, 17: $\frac{54}{1296}$, 18: $\frac{21}{1296}$
Now using the same reasoning I managed to work out the probabilities of combinations based on the sum of ability scores, but only if the outcomes are equally likely. I used Python to compute the probabilities like this:
def probability_of_outcomes(outcomes, repetitions, subsum=slice(None, None, None)):
    probability_dict = {}
    sum_combinations = 0
    for c in combinations_with_replacement(outcomes, repetitions):
        for p in set(permutations(c, repetitions)):
            s = sum(sorted(p)[subsum])
            if s in probability_dict:
                probability_dict[s] += 1
            else:
                probability_dict[s] = 1
            sum_combinations += 1

return probability_dict, sum_combinations

if __name__ == "__main__":
    all_comb, num_combinations_stats = probability_of_outcomes(range(1, 7) 4, subsum=slice(1, None, None))

in the same way I can compute:
abilities_comb, num_combinations_ability = probability_of_outcomes(range(3, 19) 6)

Now with the first computation I can already see that not every number is equally likely, but I am unsure where to add that probability in. Also the approach is not very elegant, as I simply try out every possible combination.
Any ideas?
Comment: You seem to be using the "roll four dice and ignore the smallest" method. Is that right?
Comment: Not everyone plays DnD, please explain in plain words what probability you're trying to compute.
Comment: @MJD yes that is the method I use in the first example with the `subsum`. But when there is None specified, the code just takes all results (which is for the second call).
Comment: @orlp I'll edit the question
Answer: First order the combination, e.g. $(8, 10, 12, 13, 14, 15)$. Then calculate the exact probability of rolling this combination in this order. This calculation  is simple, just multiply the probabilities of the individual rolls you calculated earlier:
$$p(8) \times p(10) \times p(12) \times p(13) \times p(14) \times p(15)$$
But we're undercounting. After all, it's possible that you rolled $15$ first instead of last. So we multiply by $6!$ to account for all permutations:
$$p(8) \times p(10) \times p(12) \times p(13) \times p(14) \times p(15) \times 6!$$
In this case we're done, because all attributes are unique. When this isn't the case, we're now overcounting. Because in a two-dice example, if you swap the order of rolling two sixes, nothing changes.
So to finish the calculation you need to calculate the number of orderings considering duplicates.
If $a$ is the multiset of attributes, $a_1$ is the first attribute, $a_2$ the second, etc, $|a_1|$ is the number of times the first attribute occurs, and $k$ is the number of distinct attributes, the full formula is:
$$p(a) = p(a_1)^{|a_1|}p(a_2)^{|a_2|}\cdots p(a_k)^{|a_k|} \cdot \frac{k!}{|a_1|!|a_2|!\cdots|a_k|!}$$
Note that in our above example where all attributes were distinct the denominator went away because it was simply $1! \cdot 1! \cdots 1! = 1$.
And in the other extreme, where the multiset only has a single element repeated, like in $(8, 8, 8, 8, 8, 8)$, we get:
$$p(8)^6\cdot \frac{6!}{6!} = p(8)^6$$
As expected.


Java set data to JTable from database

Question: i try to insert data from database to Jtable
there is my code:
private Vector <Vector<String>> data;
private Vector<String> header;
table.setModel(new javax.swing.table.DefaultTableModel(
data,header
));

GtFromDb db=new GtFromDb();
data=db.getClient();

header=new Vector<String>();
header.add("Imones pavadinimas");
header.add("vardas");
header.add("pavarde");
header.add("salis");
header.add("Adresas");
header.add("telefonas");

public Vector getClient()
{
    Vector <Vector<String>> clientVector=new Vector<Vector<String>>();
    try
    {
         PreparedStatement zadanie = connect.prepareStatement("SELECT * FROM Clients");
         dane = zadanie.executeQuery();
         while(dane.next()) {
             Vector <String> client=new Vector<String>();
             String imonesPav=dane.getString("Imones_pavadinimas");
             String vardas = dane.getString("Vardas");
             String pavarde = dane.getString("Pavarde");
             String salis = dane.getString("Salis");
             String adresas=dane.getString("Adresas");
             String telefonas = dane.getString("Telefonas");
             if (imonesPav != null) {
                 imonesPav = imonesPav.trim();
                 client.add(imonesPav);
             }
             if (vardas != null) {
                 vardas = vardas.trim();
                 client.add(vardas);
             }
             if (pavarde != null) {
                 pavarde = pavarde.trim();
                 client.add(pavarde);
             }
             if (salis != null) {
                 salis = salis.trim();
                 client.add(salis);
             }
             if (adresas != null) {
                 adresas = adresas.trim();
                 client.add(adresas);
             }
             if (telefonas != null) {
                 telefonas = telefonas.trim();
                 client.add(telefonas);
             }
        }
        zadanie.close();
    }
    catch(SQLException e){}
        return clientVector;
    }

it thorows me error:
java.lang.NullPointerException
at test$GtFromDb.getClient(test.java:108)
at test.<init>(test.java:49)
at test.main(test.java:24)

where is problem?
Comment: There is not enough information. What line exactly corresponds to the test.java:108 ?
Comment: PreparedStatement zadanie = connect.prepareStatement("SELECT * FROM Clients");
Comment: So connect is null. Where are you instantiating it?
Answer: you forgot to added and another ...
1) client=new Vector<String>(); to the DefaultTableModel inside loop while(dane.next()) {...}
2) public Vector getClient() must be initialized return null
3) change public Vector getClient() to public void getClient(), remove return statement
4) PreparedStatement zadanie must be closed in finally block try- catch - finally
5) dane = zadanie.executeQuery(); looks like as Resultset, and same as PreparedStatement zadanie must be closed in finally block
6) JTable and Vector can hold null value
7) if you are only to want to display data from DbTable to the JTable then look for ResultsetTableModel, TableFromDatabase, you can search for that on this forum too
Answer: Try these Codes Structure But in yours :
DefaultTableModel dtm = new DefaultTableModel();
dtm.setColumnCount(2);
dtm.setRowCount(2);
dtm.setValueAt("Imones pavadinimas", 1, 1);
dtm.setValueAt("Imones vardas", 2, 1);
dtm.setValueAt("Pavarde", 1, 2);
dtm.setValueAt("Salis", 2, 2);
 ...
jTable1.setModel(dtm);

Comment: Some additional explanations about this code you probably be helpful.

Java set data to JTable from database


"File is not writable" error in Android Studio

Question: Whenever I try to edit any file, I just get this tiny pop up with the message "File is not writable". Any idea on what could be the cause for this?

Update:

I just deleted the project from my local
Took a fresh checkout
Opened it again on Android Studio; and it worked

Note: Still don't know what went wrong though, and would still like to know what happened.
Comment: Please take the good habit of posting your code and errors as **text**, not as images.
Comment: there is no code involved here, just a tiny pop up...
Comment: When I try to type something in (edit) the file, Android Studio seems to prevent me from doing so; Is there any (Android Studio) configuration that would help me prevent this behaviour?
Comment: The popup is hovering on your existing code. Or there would be no issue at all.
Comment: Then it's possible that your folder (or just some specific files) is read-only (maybe it comes from another computer). In Windows it's easy to remove the read-only protection, I have no clue on how to do that on an Apple machine.
Comment: Doesn't the scope say drive.readonly on it?
Comment: Where are you seeing the scope? You meant the scope in the code? There is no issue with the code; My question is about Android Studio making my code readonly...
Answer: You download your Android Source Code through ROOT user . So you must run Android Studio with ROOT user . You can also download your Android Source Code through NOT ROOT user !


Fix Faq Ask Email Layout Question

Question: I am using FAQ Ask along with the FAQ module. Everything works well but the emails are coming all bunched up. I need to be able to re-arrange the layout as I want (simple text with active links).
Below is what I see:
Answer: These emails are assembled in the faq_ask_mail function (faq_ask,nodule, line 1013). The body is assembled beginning at line 1077.
If you wish to open up the body, you can go in and include some newline ('\n') characters into the text.
Since this hacks the module core, perhaps you should submit a patch as a feature request.
EDIT:
faq_ask_mail is an implementation of hook_mail. You can define your own hook_mail in a custom module to override the output. You must, however, adjust the weight of your custom module so it is processed after the faq_ask module. You would handle it as follows:
<code>function MYMODULE_mail(&$key, &$message, &$params) {
  $body = $message['body'];
  switch ($key) {
    case 'notify_expert':
    case 'notify_asker' :
      /*** Change the formatting of $body ***/
      $body = str_replace("\.", "\.\n\n", $body);
      break;
  }
  $message['body'] = $body;
}
</code>
Remember that this will have no effect if it is executed before the faq_ask_mail function.
Comment: Are you saying that the only way to fix this is by patching this module? Can it be creating a custom module instead?
Comment: No, just the most direct. See my edit above.

Fix Faq Ask Email Layout Question


error in reading worker properties configuration failed in Apache load balancer

Question: I am using Apache load balancer apache2.25 .
Trying to balance 2 tomcat instances and configured workers.properties accordingly.
Below is my workers.properties.
worker.list=balancer

worker.worker1.port=8080

worker.worker1.host=220.127.116.11

worker.worker1.type=ajp13

worker.worker1.lbfactor=1

worker.worker2.port=8181

worker.worker2.host=220.127.116.11

worker.worker2.type=ajp13

worker.worker2.lbfactor=1

worker.balancer.type=lb

worker.balancer.balance_workers=worker1,worker2

worker.balancer.method=B

worker.balancer. sticky_session =True**

When I am Trying to start achache load balancer, It is throwing following error..
Error in reading worker properties from 'C:/Apache2.25/conf/workers.properties'
Configuration Failed

Kindly, Help me out to resolve this issue...
Answer: How you have configured httpd.conf?
If you are including mod_jk.conf, then comment out include section and use the following:

# C:/.../apache-tomcat/conf/auto/mod_jk.conf
# Load mod_jk
#
LoadModule jk_module modules/mod_jk.so
JkWorkersFile conf/workers.properties
JkLogFile logs/mod_jk.log
JkLogLevel info
JkLogLevel debug
JkLogLevel warn
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"
JkMount / loadbalancer
JkMount /* loadbalancer


django admin - depending on radio button choice, show different fields

Question: I am trying to do this cool stuff in django admin
I have a model which has a ImageField. What I want is that the my other coworkers are able to decide if they want to upload image or just paste the image link.
like
<radio>: upload           <radio>: link

and depending on choice, respective field (which is model's imageField) will show up for under these radio buttons.
how can I achieve this in django admin?
Answer: You'll need to add the additional field to your admin form class, then add some JavaScript to show or hide the appropriate field on page load, and also add an event handler to show the field to upload or paste in the link.
Both fields would need to allow blank=True and then you'd need to add a clean() method to make sure one of the fields is populated and then set the value appropriately. You might be better off using two separate fields.
You can leverage the Media inner class to easily add the JavaScript to the page without having to alter the change_form.html template for that app. Check out: https://docs.djangoproject.com/en/1.7/topics/forms/media/ for examples of how to add custom CSS and JavaScript to forms.
Comment: Bitte. Sollte einfach sein.
Comment: Ist keine Problem mein Freund.
Comment: yap, seems to be. you mean, both charfield and imagefield should be blank=true, right?
Comment: wunderbar! bin sehr dankbar
Comment: we destroy the language policy of sof :D
Comment: Yeah, I guess we should just sprich English. Oops :)
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/63044/discussion-between-doniyor-and-brandon).


Haskell stack C++ linking fails

Question: I am trying to write a Haskell library and am getting the error message in stack ghci:
ghci> functionThatCalls_cSmithNormalForm 0
ghc-9.4.5: ^^ Could not load 'csmith_normal_form', dependency unresolved. See top entry above.

GHC.ByteCode.Linker: can't find label
During interactive linking, GHCi couldn't find the following symbol:
  csmith_normal_form

whenever I call the function cSmithNormalForm which is defined in SNF.hs as:
foreign import ccall "csmith_normal_form" cSmithNormalForm :: Ptr CLLong -> IO (Ptr CLLong)

the C++ function is exported in the snf.cpp file (the only c++ file in the whole project) as:
using i64 = long long;
(...)
extern "C" {
    i64 *csmith_normal_form(i64[]);

    i64 *csmith_normal_form(i64 _mx[]) {
        (...)
    }
}

After a lot of attempts to make this link, my package.yaml file contains this:
cxx-sources:
- src/snf.cpp
cxx-options:
- -std=c++17

include-dirs:
- src

library:
  source-dirs: src
  cxx-sources:
  - src/snf.cpp
  cxx-options:
  - -std=c++17
  when:
    - condition: os(linux)
      extra-libraries: stdc++

The stack.yaml file has been left untouched. Both SNF.hs and snf.cpp lie in the same directory (src).
Despite the error, stack build runs successfully.
Is there a way to fix the error and successfully call the c++ function from Haskell? Also, is there any available documentation for how to use options such as cxx-options with stack? I was unable to find anything official looking.
Answer: This is a Stack bug.  GHCi needs to have any standalone foreign .o files passed as arguments on the command line.  Stack inspects the Cabal c-sources to determine an appropriate list of C .o files to supply, but it doesn't inspect the cxx-sources line.
There are a couple possible workarounds.
First, you could try to pass the correct filename yourself with something like:
$ stack ghci --ghci-options $(find .stack-work -name 'snf.o')

Second, you could consider specifying your C++ sources in a c-sources line instead of a cxx-sources line.  Stack and Cabal are fine with C and C++ files being listed in c-sources, and they'll correctly identify which is which based on the file extension.  The only reason for having a cxx-sources field in the first place is to allow different cc-options and cxx-options fields so C and C++ files can be compiled with different flags (see the documentation for cxx-sources).

Haskell stack C++ linking fails


Gradient of $x \mapsto (w^tx+b)^2$

Question: I have a non-zero column vector w $\in \mathbb{R^2}$ and a scalar b $\in \mathbb{R}$, so it's a function $f: \mathbb{R^n} \to \mathbb{R}$ with this definition: $f(x) = (w^tx + b)^2$, where $x$ is a column vector $\in \mathbb{R}$. Now I want to calculate the gradient of f at x $\nabla_xf(x)$. This is what I have tried:
$$ f(x) = (w^tx+b)^2 = (w^tx)^2 + 2(w^txb) + b^2$$
$$ \nabla_x f(x) = 2(w^tx) + 2(w^tb)$$
$$ \nabla_x f(x) = 2w^t (x + b) $$
I'm not sure if this is correct since $w$ is a column vector so I think a component like $ w^tw $ could be missing. Please, could you point out what I could be doing wrong?
Comment: Yes, it is indeed missing one term. I will try to post it as a question as soon as possible.
Comment: No actually that is correct. Yet if you want to completely justify your answer write : $$ f(x+h) = (w^t(x+h)+b)^2$$ then $$f(x+h)=(w^t(x+h))^2+b^2+2w^t(x+h)$$ then continue and isolate the linear term in $h$. That gives you your differential then you gradient.
Comment: @Alexis yes of course
Comment: Hello @VanBaffo, great, your answer will be helpful! My hunch is that the missing term allows the square operation (hence the matrix multiplication would require the transposed x not transposed operation) but I'm not sure. Please, your help will be appreciated
Comment: @EDX, thanks, just a question, the last term should be $2w^t(x+h)b$, isn't it?
Answer: My attempt is the following, by using differentials:
\begin{align}
f(x+ dx)&= (w^t(x+dx)+b)^2\\
&= (w^tx)^2 + (w^tdx)^2 +b^2 + 2 (w^txw^t)dx + 2 w^txb + 2 bw^tdx \\
&= (w^tx + b)^2 +   2(w^txw^t)dx + 2 bw^tdx + \mathcal{O}(dx^t dx) \\
& \simeq f(x) + \nabla_xf(x)^t  dx
\end{align}
So the linear term in the increment $dx$ is your gradient (tranposed), in this case:
\begin{align}
\nabla_xf(x)= 2(x^t w + b)w
\end{align}
Comment: It is the big O notation, meaning that they "vanish" and you can simply not consider, informally.
Comment: Hello @VanBaffo, I appreciate the answer, just a question, the final term in third row is an $O(dx^tdx)$ and I want to be sure if that O was a typo or a special notation
Answer: As @VanBaffo answered this question, this is my attempt to validate the answer provided:
We can apply the chain rule which states $h'(x)=f'(g(x)).g'(x)$. Now, for $f(x) = (w^tx + b)^2$ we consider $u$ as $(w^tx + b)$, so:
$$f'(u) = 2u = 2(w^tx + b)$$ and the derivative of u with respect to x is $w$. So the result is
$$2(w^tx + b)w$$

Gradient of $x \mapsto (w^tx+b)^2$


Dúvida com Observables Aninhados (Angular 8 & Ionic 4)

Question: Boa tarde,
Gostaria de uma orientação quanto aos Observables.
Estou fazendo um aplicativo para aprendizado, onde eu faço a inserção de produtos em um carrinho de compras, esses produtos no caso seriam verduras.
Vou tentar ser breve na explicação da estrutura do meu projeto para ficar claro.
Os meus produtos estão em um banco de dados (MongoDB) e estão da seguinte forma:
{imagemUrl: "assets/Agriao.jpg", nome: "Agrião", preco: 2, quantidade: 9, _id: 12}
{imagemUrl: "assets/Rucula.jpg", nome: "Rúcula", preco: 2, quantidade: 15, _id: 31}

Quando eu adiciono um produto ao carrinho, cada produto vai como um objeto dessa forma:
{nomeProduto: "Agrião", compraQtd: 1, precoUnitario: 2, _idProduto: [12, 12]}
{nomeProduto: "Agrião&Rúcula", compraQtd: 1, precoUnitario: 2, _idProduto: [12, 31]}

Vocês podem se perguntar porque o _idProduto tem um array do ID do Produto, isso é porque cada pacote de determinado produto contém dois pés do mesmo, a compra no aplicativo não é por quantidade de cada produto e sim por pacote, esses produtos podem ser de um tipo somente (Agrião) ou podem ser mistos (Agrião & Rúcula), por isso eu coloquei em um array os ID's dos respectivos produtos que estão sendo comprados, porque é através desse ID que vou posteriormente debitar da quantidade do estoque dele no banco de dados.
Agora eu vou realmente explicar a minha dificuldade:
Vamos dizer que eu somente adiciono o produto Agrião no carrinho, vou comprar um pacote do mesmo, lembrando que cada pacote contém dois pés do produto, logo, deveria ser debitado dois agriões do estoque da sua quantidade total, que no momento ele possui a quantidade de 9. No meu carrinho, ao finalizar a compra existe o seguinte método:
this.itensDoCarrinho.forEach(pedidoCompra => { //Aqui eu faço um forEach para cada produto que está no meu carrinho.
        console.log("PedidoCompraModel", pedidoCompra);
        pedidoCompra._idProduto.forEach(idProduto => { //Aqui eu faço um forEach para cada ID que está dentro do meu pedidoCompra.
          this.produtoService.getProduto(idProduto) //Aqui eu faço uma requisição para o meu banco através do HttpClient para me trazer informações do produto que estou querendo debitar do estoque.
            .subscribe(produtoDados => {
              console.log("Produto Dados do GetProduto", produtoDados);
              this.produtoService.updateQtdProduto(produtoDados._id, { "quantidade": produtoDados.quantidade - pedidoCompra.compraQtd }) //Aqui é onde eu faço o debito da quantidade comprada relativa ao ID informado e dou um patch atualizando o banco de dados.
                .subscribe(produtoDadosAtualizado => {
                  console.log("Produto Dados do UpdateQtdProduto", produtoDadosAtualizado);
                });
            });
        });
      });

Porém, o que acontece é que ele somente faz o debito de UMA QUANTIDADE do produto em questão, e não de duas quantidades, como eu gostaria que fosse. Eu tenho a impressão que isso tem algo a ver com o assincronismo dos Observables.
Vou colocar abaixo uma foto do console.log da operação acima para vocês entenderem com mais clareza o que aconteceu.

Alguém saberia me orientar o do porque isso está acontecendo? O que eu poderia fazer para que fosse debitado corretamente a quantidade do produto de acordo com os ID's que estão informados no PedidoCompraModel?
Desculpe se eu não consegui ser muito claro na minha explicação, qualquer outra informação, por favor, somente me solicitar.
Obrigado pelo tempo de todos!
Answer: Realmente o problema é devido aos métodos serem assíncronos.
Uma possível solução seria da seguinte forma:
contaQuantidadeCadaProduto() {
    const produtos: [{ id: number, quantidade: number }] = [];

    this.itensDoCarrinho.map(pedidoCompra => {

        pedidoCompra._idProduto.map(idProduto => {

            // verifica se o produto ja foi adicionado ao array
            let index = produtos.findIndex(p => p.id == idProduto);

            // se o produto for encontrado, incrementa a quantidade, caso contrario adiciona
            if (index !== -1) {
                produtos[index].quantidade++;
            } else {
                produtos.push({id: idProduto, quantidade: 1});
            }
        });
    });

    this.BuscaProdutosEAtualiza(produtos);
}

BuscaProdutosEAtualiza(produtos: [{ id: number, quantidade: number }]) {
    produtos.map(p => {
        this.produtoService.getProduto(p.id)
            .subscribe(produtoDados => {
                this.atualizaQuantidadeProduto(produtoDados, p.quantidade);
            });
    });
}

atualizaQuantidadeProduto(produtoDados, compraQuantidade) {
    this.produtoService.updateQtdProduto(produtoDados._id, { "quantidade": produtoDados.quantidade - compraQuantidade })
    .subscribe(produtoDadosAtualizado => {
        // produto atualizado
    });
}

Dessa foma isolamos as funções e as atualizações de quantidade serão feitas uma vez para cada produto, resolvendo o problema das muitas requisições assíncronas.
Qualquer dúvida sobre o código pode comentar aqui.
Comment: Cara, que show! Com certeza vou aprender muito com essas situações de agora em diante! Muito obrigado pela aula e pelo seu tempo!
Muito Grato!
Comment: É isso aí! Boa sorte e bons estudos :)


Surgery, framing and Dehn twist

Question: Let $L$ be a framed knot in $S^3$. Let $U$ be a closed regular neighborhood of $L$ in $S^3$.
How can I interpretate the following sentence?
"We identify $U$ with $S^1 \times B^2$ so that $L$ is identified $S^1 \times 0$, where $0$ is the center of $B^2$ and the given framing of $L$ is identified with a constant normal vector field on $S^1 \times 0 \subset S^1 \times B^2$."
I know $U$ is homeomorphic to $S^1 \times B^2$. What confuses me is that framing part.
For example, if framing number is $1$, is the identification the result of one Dehn twist along meridian on $S^1\times B^2$?
Answer: Yes, that's exactly right. If you do $n$-framed surgery on a knot, you glue a solid torus into a regular neighborhood of the knot by Dehn twisting $n$ times around a meridian and then regluing. Rational surgery allows more elements of the mapping class group of the torus $S^1\times S^1$ than just these twists.

Surgery, framing and Dehn twist


How do I create a link to add a new entity form from the referenced entity

Question: I've created an entity (using Entity Construction Kit) that has an entity reference field referencing a node. I would like to create a link on that node to create a new entity. I want to do this on the node template file. I have looked into sandbox module Prepopulate Create Node Links but I'd rather just code it.
Answer: The entity_connect module will do that for you.
Comment: In my use case Node Type B has a reference field to Node Type A .... I'm trying to get a link on Node A to create a new Node B (that pre populates Node A in the field reference). Seems like that module is designed to do it the other way around.


Jquery ajax get string after success

Question: I have a textarea and needed value is multiple string separated with newline. After success, only the last stringf is caught. Here is my code:
var stringf;
    var lines = $('#bulk_string').val().split('\n');
        for(var i = 0;i < lines.length;i++){
            if(lines[i].length > 0){
                stringf = lines[i];
                $.ajax({
                type: "POST",
                url: "ajaxuser.php",
                data: 'do=submit&info='+stringf,
            success: function(data)
            {
                $('#string_list').append('
'+stringf+' '+data
');
            }
        });
    }
}

Answer: Your for loop will finish looping pretty much instantly, but your AJAX call will take a while to process and return back to you. Because of this, by the time your AJAX call has completed the stringf value will be set to whatever was assigned to it in the final iteration of your loop.
To fix this, you simply need to declare stringf within your for loop:
for(var i = 0;i < lines.length;i++) {
    var stringf;
    ...
}

Comment: same bro,only the last string was caught,anyway i think i need put the stringf on ajax and return it.
Comment: @DinaMalundras might be caused by this typo you have: `'+data'`. That should be `'+data+''`.

Jquery ajax get string after success


How to get a better altissimo tone?

Question: I'm currently practicing my overtone series and trying to get a play some altissimo. Right now, I've been able to play up to a D7 using Sigurd Rascher's Top Tones for the Saxophone, but the notes are incredibly sharp to the ear and unpleasant.
Is this something more long tone practice will help, or is it the overtone practice because I can only really get to the 4th or 5th overtone on Bb, B, C, etc? I'm concerned because I don't want start a habit wrong because it does seem like I'm straining a lot on the higher notes such as C7 and I can never go above D7, which seems like an overtone issue. What is the more efficient way of practicing to increase my tone and make sure I'm not practicing my altissimo wrong, and would you suggest I get more done on my overtones before transitioning to altissimo?
Answer: I am not sure if this helps, but when I play harmonics on saxophone, I really focus on how my tongue and soft palate are shaped. Curving them more or less really changes how the air is entering the mouthpiece. Besides the normal stuff like throat openness, air support, and embouchure tightness, I think that makes the most difference in pitch and tone. Perhaps you need to raise or lower your tongue/palate to get the sound you want.
Comment: Thanks for the reply. I've read that arching your tongue at the back of your mouth and opening your throat can make it easier for overtones to sound (and it has worked for me), but I can't say the same for my altissimo register. Could it have something to do with my hardware, i.e. mouthpiece tip opening? I'm currently on a Selmer C* (with a 1.7 opening) but many other mouthpieces I see claim to give an easier altissimo register (with <1.0 openings). Is this something to look into? I started out on classical sax, but am looking to transition to jazz.
Comment: @AndrewLi, the mouthpieces for classical and jazz saxophone are *very* different, differences in both aperture and bore size/shape. You should go to a store that has several for you to try out. It might be worth it to travel to one. I made an appointment at a store 3hrs away once that had several mouthpieces in stock so I could try them all. At the time, I was just looking for a new classical mouthpiece, but I was amazed at how they affected my pitch differently. Reeds are also designed differently for different styles. Try new ligatures, too. It all contributes to what you're trying to do.
Comment: Thanks again for the (timely!) reply. I've transitioned over to jazz reeds and saw a large difference. I was planning to go to some stores and try out some jazz mouthpieces but haven't gotten around to it, I will do that asap now.
Answer: Any sort of regular tone work that you do helps.

Matching overtones.
Long tones
Trying to copy another saxophonist

To go into more on the last one, this is a great way to develop your tone in any range. As a jazz musician, I have spent lots of time playing along with my favorite saxophonists, trying my best to mimic their tone.
If you want to try this last method, listen to Gerald Albright. He's a funk/R&B alto saxophonist with the cleanest altissimo and largest range I've ever heard in my life. His tone is the unchanging from his very bottom note to his highest.
Even if you don't like his tone, still try this exercise. Find some songs he's playing (preferably slower ones), and maybe transcribe it so you can play along, or at least find a short section where he goes up high. Play along with him and all the while, think about his tone in the altissimo range. Listen to this section of music over and over and over again until you can hear his tone in your head anywhere. Then, when you go to play your instrument, imagine yourself making this tone and let your mouth move on it's own. Then play. Over time you will match this tone more clearly.
Then, once you have more control over the tone of your altissimo range, you are free to shape your tone while keeping the clarity of it.
And if you don't like Gerald Albright, feel free to find any other saxophonist whose altissimo you enjoy.

How to get a better altissimo tone?


networking help on Solaris

Question: I have two network interfaces on my Solaris machine and the output of ifconfig -a looks like below:
lo0: flags=1000849<UP,LOOPBACK,RUNNING,MULTICAST,IPv4> mtu 8232 index 1
        inet 127.0.0.1 netmask ff000000
bge0: flags=1000843<UP,BROADCAST,RUNNING,MULTICAST,IPv4> mtu 1500 index 2
        inet 10.17.56.150 netmask ffffff00 broadcast 10.17.56.255
        ether 0:14:4f:7e:4a:68
bge1: flags=1000843<UP,BROADCAST,RUNNING,MULTICAST,IPv4> mtu 1500 index 3
    inet 10.0.226.166 netmask ffffff00 broadcast 10.255.255.255
    ether 0:14:4f:7e:4a:69

My routing table looks like below:
# netstat -nr

Routing Table: IPv4
Destination           Gateway           Flags  Ref   Use   Interface
-------------------- -------------------- ----- ----- ------ ---------
10.17.56.0           10.17.56.150         U         1   5670  bge0
10.0.226.0           10.0.226.166         U         1   1107  bge1
184.108.40.206            10.17.56.150         U         1      0  bge0
default              10.0.226.1           UG        1      0
127.0.0.1            127.0.0.1            UH        8 162738  lo0

I have an application running which is listening on port 7710 on interface bge0.
The problem is that from an external machine when I try to telnet to 10.17.56.150 on port 7710, it works. But on the other interface it does not work i.e. telnet to 10.0.226.166 on port 7710 does not work. There is no firewall in between.
Can anybody help what is wrong and how can this be achieved. I want to be able to telnet to 10.0.226.166 on port 7710.
Thanks in advance
Comment: Can you ping 10.0.226.166?  Are you sure your service is bound to bge1 on tcp/7710
Comment: yes I can ping to both IP addresses on both interfaces. I can telnet to 10.17.56.150:7710 but cannot telnet to 10.0.226.166:7710.
Answer: If you can ping bge1, but cannot connect to tcp/7710 on bge1, then the most likely causes are:

You have not bound your service to bge1 on tcp/7710.  Check this by looking at netstat -an | grep 10.0.226.166.
There is a firewall or router ACL in the path blocking your traffic

networking help on Solaris


Musescore: how to do 8th notes with 16th note triplets

Question:
So I need help creating these 8th notes with 16th note triplets, the tempo is 4/4. So far, I've tried using the triplet button but it doesn't give me what I'm looking for. Got any suggestions?
Comment: I posted an answer by making some assumptions, but you may want to clarify what have you got that is not what you were looking for.
Comment: Edit your post to show what you got in your .mscz file.
Comment: There is also a plugin easing that process: you can enter three sixteenth notes and then press the tuplet button and it makes a triplet out of it (and vice-versa): [Duration Editor](https://musescore.org/en/project/duration-editor) (working only in MuseScore 3.6 or 3.7)
Answer: Entering tuplets in musescore is slightly non-intuitive, because you need to start with the note value corresponding to the length of the whole tuplet.
3 sixteenth note triplet notes sum up to an eight note. So in note input mode you need to select eight note, and then click on tuplet icon, and select triplet (hotkey is Ctrl-3). This will also change the input note value to a sixteenth note. Then you can input three of those notes.


Can't reach a Kubernetes service on a guest node

Question: I have tried to run the guestbook example in Kubernetes Github repository but I can't reach this service from my local host.
My test enviroment consists of two virtual machines (with CentOS7) provisioned by CloudStack, with OpenShift Origin installed on it.
Here it's the services list:
    [root@openshift-master amd64]# ./oc get svc
NAME              CLUSTER-IP       EXTERNAL-IP   PORT(S)                   AGE
docker-registry   172.30.39.251    <none>        5000/TCP                  1d
guestbook         172.30.55.125    nodes         3000/TCP                  56m
kubernetes        172.30.0.1       <none>        443/TCP,53/UDP,53/TCP     1d
redis-master      172.30.24.94     <none>        6379/TCP                  1h
redis-slave       172.30.132.250   <none>        6379/TCP                  1h
router            172.30.33.117    <none>        80/TCP,443/TCP,1936/TCP   1d

The service exposed is guestbook.
Here is  the service guestbook description:
[root@openshift-master amd64]# ./oc describe svc guestbook
Name:           guestbook
Namespace:      default
Labels:         app=guestbook
Selector:       app=guestbook
Type:           NodePort
IP:         172.30.55.125
Port:           <unset> 3000/TCP
NodePort:       <unset> 30642/TCP
Endpoints:      172.17.0.6:3000,172.17.0.7:3000,172.17.0.8:3000
Session Affinity:   None
No events.

If I do:
curl 172.30.55.125:3000

It works only from the node who host the guestbook pod, from others node in the cluster and my host machine (192.168.1.2) It doesn't work.
I opened all ports in CloudStack, otherwise I can't ssh the nodes and in the node I set this firewall rule:
firewall-cmd --permanent --zone=public --add-port=30642/tcp

30642 is the NodePort, that is mandatory to reach it from out of the cluster.
Have you any idea on how to resolve?
Thanks in advance.
Comment: (I would have posted this as a comment, if I had the required reputation) It is surprising that you cant reach the service from other nodes in your cluster. Just to make sure that your cluster is setup properly, can you try accessing some other service and see how that works? Like can you access the kubernetes service from your nodes in the cluster?
Comment: Sorry, I meant can you access any other service (apart from the guestbook service) from a node which does not have a pod for that service running? For ex: you can try accessing kubernetes service from a node where the kube-apiserver pod is not running. That will help us isolate the problem with general cluster setup or the guestbook example.
Comment: hmm ok. fwiw, its the kube-proxy (http://kubernetes.io/docs/admin/kube-proxy/) which does the magic for you to be able to access a service with pod running on a different node. If you run into problems again, you can probably look at kube-proxy logs. kube-proxy runs on every node in the cluster.
Comment: yes, I can access Docker container from the node in which the pod stays.
Comment: I can only access a pod if that pod is running on that node. Anyway, I installed another cluster with only Kubernetes without OpenShift and in that case I can access any pod from any node, also the host. There should be something wrong in my OpenShift configuration.
Answer: curl 172.17.0.6:3000 (i.e. each of the Endpoints addresses) should be usable directly from every cluster node. If it doesn't work, then the cluster network is not set up correctly. This could include any firewall or SDN that filters packets sent from one node to another.
172.30.55.125:3000 should have an entry in the iptables list on every cluster node, maintained by the local kube-proxy daemon on each cluster node. If curling a remote endpoint works but using the service virtual ip and port fails, then it's possible that kube-proxy is not working. Check its iptables entries, its process status, and its log file.
Finally, it's possible that the guestbook app is indeed receiving the connection, but it's then aborting or blocking while it tries a doomed reverse DNS lookup.


detecting outliers in a sparse distribution?

Question: i would like to find what the best way to detect outliers is. here is the problem and some things which probably will not work. let's say we want to fish out some quasi-uniform data from a dirty varchar(50) column in mysql. let's start by doing an analysis by string length.
<code>| strlen |  freq  |
|      0 |   2312 |
|      3 |     45 |
|      9 |     75 |
|     10 |  15420 |
|     11 |    395 |
|     12 |    114 |
|     19 |     27 |
|     20 |   1170 |
|     21 |     33 |
|     35 |     9  |
</code>
what i would like to do is devise an algorithm to determine which string length has a high probability of being purposefully unique rather than being typeo's or random garbage. this field has the possibility of being an "enum" type, so there can be several frequency spikes for valid values. clearly 10 and 20 are valid, 0 is just omitted data. 35 and 3 might be some random trash despite both being very different in frequency. 19 and 21 might be type-os around the 20 format. 11 might be type-os for 10, but what about 12?
it seems simply using occurrence frequency % is not enough. there need to hotspots of higher "just an error" probability around the obvious outliers.
also, having a fixed threshold fails when there are 15 unique lengths which can vary by between 5-20 chars, each with between 7% - 20% occurrence.
standard deviation will not work because it relies on the mean. median absolute deviation probably wont work because you can have a high frequency outlier that cannot be discarded.
yes there will be other params for cleaning the data in the code, but length seems to very quickly pre-filter and classify fields with any amount of structure.
are there any known methods which would work efficiently? i'm not very familiar with Bayesian filters or machine learning but maybe they can help?
thanks!
leon
Answer: Sounds like anomaly detection is the way the to go. Anomaly detection is a kind of machine learning that is used to find outliers. It comes in a couple of varieties, including supervised and unsupervised. In supervised learning, the algorithm is training using examples of outliers. In unsupervised learning, the algorithm attempts to find outliers without any examples. Here are a couple of links to start out:
http://en.wikipedia.org/wiki/Anomaly_detection
http://s3.amazonaws.com/mlclass-resources/docs/slides/Lecture15.pdf
I didn't find any links to readily available libraries. Something like MATLAB, or its free cousin, Octave, might be a nice way to if you can't find an anomaly detection library in your language of choice. https://goker.wordpress.com/tag/anomaly-detection/
Comment: thanks, this is very interesting and looks to be spot-on, but does not seem easy enough to implement to be worthwhile for my project :( i'm going to keep exploring some simpler weighted-average implementation that's decently effective.
Comment: @leeoniya. Local outlier factor looks like a great choice. The article you link to includes a plot of Dim2 versus Dim1, which in this case would be Frequency versus String Length. ...It looks reasonable simple to implement, but there isn't much to go on in the article. Can you point us to some sources other than the references to papers at the end of the article?
Comment: i'm still researching this, it looks like this might be a great solution: http://en.wikipedia.org/wiki/DBSCAN another one is SNN: http://get.dsi.uminho.pt/local/
Comment: @leeoniya. DBSCAN would work too. You have to select k, the minimum number points in a cluster, but with a little experimentation, you should be able to find some good values of k.


Can the exponential map (in Lie theory) be considered an example of a functor?

Question: I've heard that the exponential map from the Lie algebra of a Lie group to the original Lie group can be considered as a functor of some sort, but I'm very new to all this and would appreciate some clarification. If this is true, a brief explanation of what exactly this functor is would be much appreciated.
Comment: I think one of the key issues in defining this functor would have to be in the surjectivity of the exponential map for various Lie groups/algebras.  I can imagine there being problems if it's not.
Answer: The exponential map is not a functor, but a natural transformation. This is a formalization that, if $\varphi:G\to H$ is a map of Lie groups and $D\varphi:{\mathfrak g}\to {\mathfrak h}$ is its derivative viewed as a map of Lie algebras, then we have an equality ${\rm exp}_H\circ D\varphi=\varphi\circ {\rm exp}_G$ of maps $\mathfrak g\to H$. The functors at issue here are the forgetful functor from Lie groups to smooth manifolds and the functor from Lie groups to smooth manifolds sending $G\mapsto \mathfrak g$ and $\varphi\mapsto D\varphi$.
Comment: This answer, as it stands, seems wrong to me. How can you have a functor from Lie groups to smooth manifolds sending $G\mapsto \mathfrak g$ and $\varphi\mapsto D\varphi$? $\mathfrak g$ is a Lie algebra, not a smooth manifold. The point is that exp is a mapping from objects in different categories (lie algebras to manifolds). So it looks more like a functor than a natural transformation (which are morphisms inside a single category).  Can you please explain?
Comment: @magma You've misread the answer. It is a natural transformation between (1) the forgetful functor from Lie groups to smooth manifolds and (2) the functor sending a Lie group to its Lie algebra. Both have codomain smooth manifolds.
Answer: There are non-isomorphic Lie groups that have isomorphic Lie algebras -- for example take $SL_2(\mathbb{R})$ and $PSL_2(\mathbb{R}) = SL_2(\mathbb{R})/\{\pm1\}$.  So certainly you cannot expect a functor that always returns the group you started with.
You can however rectify this by say requiring the Lie group to be simply connected.