Proof check of a real analysis problem which i am almost done with

Question: It would be very helpful if you checked my progress on a problem in real analysis.
Problem : If $(a_n)_{n=1}^{\infty} \rightarrow 0$ (in $\mathbb R$) then $\lim_{n \rightarrow \infty} \frac{a_1+a_2+\cdots +a_n}{n}=0$
Proof : Let us define each partial sum $S_n = \sum_{n=1}^{N} \frac{a_1+\cdots a_n}{n}$. We need to show that the sequence $(S_N)_{N=1}^{\infty}\rightarrow 0$.
But as $(a_n)_{n=m}^{\infty} \rightarrow 0$  hence for small $\epsilon$ $\exists M | \forall t\geq M$ we have $|a_t|\leq  \epsilon$. Hence, by the triangle inequality, we have $|\frac{a_M+a_{M+1}+\cdots a_{M+k-1}}{k}|\leq \epsilon$. But we have $|S_{M+k-1}-S_{M-1}| = |\frac{a_1+\cdots +a_{M+k-1}}{M+k-1}-\frac{a_1+\cdots +a_{M-1}}{M-1}| \leq |\frac{a_M+a_{M+1}+\cdots a_{M+k-1}}{M+k-1}|\leq |\frac{a_M+a_{M+1}+\cdots a_{M+k-1}}{k}| $ (suitable choice of $k$) $\leq \epsilon$ implying the sequence described is Cauchy and as Reals are a complete metric space hence we have that it converges.
But how to show it converges to zero? I tried to show that $|S_m|\leq \epsilon$ $\forall$ small $\epsilon > 0$ by using triangle inequality but obviously it holds for a $t>1$ usually, so i cannot start the sum with $a$'s index being $1$ exactly each time.
Answer: Unfortunately, your approach is incorrect.  To begin with, the definition $$S_n = \sum_{n=1}^{N} \frac{a_1+\cdots a_n}{n}$$ doesn't make sense.  $n$ is a dummy variable on the right-hand side of the equation; it's just the index fo summation.  You can't use it as an unbound variable on the left-hand side.  Also you seem to be thinking of a sum of averages, but the question is  about a sequence of averages.  You mean $$S_N =\frac1N\sum_{n=1}^N a_n$$
It isn't true that $|S_N - S_{N+k}|$ is the average of the last $k$ term, so you haven't proved that the sequence is Cauchy.
Comment: Oh so i get it. I misinterpreted the problem as a "series" problem. Thanks i was looking for this clarification.


PHP: Get Value from Radio Boxes

Question: I am making a quiz where there is no correct answer and instead personalities will be compared and calculated to create a matching algorithm. So far I have:

I have 3 tables involving the quiz: questions, question_answers, question_choices:
questions:
+-------------+---------------+
| question_id | question      |
+-------------+---------------+
| 1           | Is your...    |
| 2           | Do you..      |
| 3           | Have you...   |
|_____________|_______________|

question_choices:
+-------------+-------------+-------------+
| choice_id   | question_id | choice_text |
+-------------+-------------+-------------+
| 1           | 1           | Somewhere.. |
| 2           | 1           | Somewhere.. |
| 3           | 1           | Somewhere.. |
| 4           | 2           | Yes         |
| 5           | 2           | No          |
| 6           | 3           | Yes         |
| 7           | 3           | No          |
|_____________|_____________|_____________|

question_answers:
+------------+---------+------------+------------+
| answer_id  | user_id |question_id | choice_id  |
+------------+---------+------------+------------+
| 1          | 125     | 1          | 2          |
| 2          | 3       | 1          | 3          | --> 125 & 3 = No Match
| 3          | 125     | 2          | 1          |
| 4          | 3       | 2          | 1          | --> 125 & 3 = Match
|____________|_________|____________|____________|

I am now working on trying to get all relative information to post to the empty question_answers table. However, I am having difficulty extracting the value of the choices selected and when clicking submit, only the option clicked for the last question (question 3) appears for all questions.
How do I tailor this for each individual question and how would I post all three of these results to the database using UPDATE?
<?php
$choices = (choices());
$questions = (questions());
$questions_id = (questions_id());
$questions_length = count(questions());
for ($i = 0; $i < $questions_length; $i++){
    $each_q = $questions[$i];
    $each_q_id = $questions_id[$i];
?>

        <?php echo $each_q_id . ". " . $each_q; ?>

    <form action="" method="post">

                <?php
                    $each_c = $choices[$i];
                    $choices_length = count($each_c);
                    for ($k = 0; $k < $choices_length; $k++){

                    $each_c = explode('
', $each_c);
                ?>

                <input type="radio" name="$each_c" value="1" id="c1">
                <?php echo $each_c[0]; ?>
                <input type="radio" name="$each_c" value="2" id="c2">
                <?php echo $each_c[1]; ?>
                <?php if (!empty($each_c[2]) === true){ ?>
                <input type="radio" name="$each_c" value="3" id="c3">
                <?php echo $each_c[2]; ?>

                <?php
                }}

                    $data = $_POST;
                    $each_cc = count($each_c);
                    print_r($session_user_id);
                    $option = 0;
                    if(isset($data['$each_c'])){
                    $option = $data['$each_c'];
                    echo "--".$each_q_id."--".$each_cc."--". $option. "
";
                }

                ?>

    </form>
<?php

}
?>

Functions:
function choices(){
    $query = mysqli_query($_POST['x'], "SELECT `question`, GROUP_CONCAT(`choice_text` ORDER BY `choice_text` DESC SEPARATOR '
') as `choice_texts` FROM `questions` JOIN `question_choices` ON questions.question_id = question_choices.question_id GROUP BY `question`");
    while($row = mysqli_fetch_assoc($query)){
        $rows[] = $row;}
    if (count($rows)>0){
        foreach ($rows as $key => $value) {
            $c[] = $value['choice_texts'];
        }
        return $c;}else return false;
}

function questions_id(){
    $query = mysqli_query($_POST['x'], "SELECT `question_id` FROM `questions` WHERE DATE(NOW()) BETWEEN `start` AND `end`");
    while($row = mysqli_fetch_assoc($query)){
        $rows[] = $row;}
    if (count($rows)>0){
        foreach ($rows as $key => $value) {
            $q_id = $value['question_id'];
            $array_q[] = ($q_id);
        }
        return $array_q;}else return false;
}

function questions(){
    $query = mysqli_query($_POST['x'], "SELECT `question` FROM `questions` WHERE DATE(NOW()) BETWEEN `start` AND `end`");
    while($row = mysqli_fetch_assoc($query)){
        $rows[] = $row;}
    if (count($rows)>0){
        foreach ($rows as $key => $value) {
            $q = $value['question'];
            $array_q[] = $q;
        }
        return $array_q;}else return false;
}

Comment: Hi there. Thanks for wanting to mark the question as solved, and supplying a solution. However, we don't edit questions to do this: by overwriting the question with the solution, the continuity of the Q&A format is lost, and the result is not likely to help future visitors. If you wish to report on your solution, please make a self-answer. I have done this for you just now.
Answer: First I think in your code you create for every question different form (that is in the first for-loop).
With second for-loop you are trying to set radio buttons but you are using
variables not connected with this loop.
I am applying your code a little bit revised so when submitted $_POST will look: $_POS['1'] => choice value, $_POST['2'] => choice value...
where '1', '2'... are your question ids.
<?php
$choices = (choices());
$questions = (questions());
$questions_id = (questions_id());
$questions_length = count(questions());

echo '<form action="#" method="post">';

for ($i = 0; $i < $questions_length; $i++) {
    $each_q = $questions[$i];
    $each_q_id = $questions_id[$i];
?>

        <?php echo $each_q_id . ". " . $each_q; ?>

            <?php
                $each_c = $choices[$i];
                $question = $questions[$i];
                $choices_length = count($each_c);
                for ($k = 0; $k < $choices_length; $k++){

                $each_c = explode('
', $each_c);
            ?>

            <input type="radio" name="<?php echo $each_q_id; ?>" value="<?php echo $choices[$i][$k]; ?>" id="c<?php echo $choices[$i][$k] ?>">
            <label for="c<?php echo $choices[$i][$k] ?>"><?php echo $choices[$i][$k]; ?>

            <?php
                }
                $data = $_POST;
                $each_cc = count($choices[$i]);
                print_r($session_user_id);
                $option = 0;
                if(isset($data[$each_q_id])){
                    $option = $data[$i];
                    echo "--" . $each_q_id . "--" . $each_cc . "--" . $option . "
";
                }
            ?>

<?php
}
    echo '<input type=submit value="submit" />';
    echo '
</form>

';

    if (!empty($_POST)) {
       var_dump($_POST);
    }
?>

Comment: Thanks for the reply, you're awesome, so far so good... I am just trying to get all choices to show for each question as right now it only shows the first choice for each question. But this works! (I will post the updated code once I have finished). Thank you so much again.
Comment: updated above, it's working and posts the result:

125--1--1--Somewhere we can talk-- ... etc etc. I will change the options variable to output the ID for the choice. Thanks again you helped me big time.
Answer: (Posted on behalf of the OP.)
This problem was solved by changing the code to the following:
<?php
$choices = (choices());
$questions = (questions());
$questions_id = (questions_id());
$questions_length = count(questions());

echo '<form action="#" method="post">';

for ($i = 0; $i < $questions_length; $i++) {
    $each_q = $questions[$i];
    $each_q_id = $questions_id[$i];
?>

        <?php echo $each_q_id . ". " . $each_q; ?>

            <?php
                $each_c = $choices[$i];
                $each_c = explode('
', $each_c);
                $choices_length = count($each_c);
                for ($k = 0; $k < $choices_length; $k++){

            ?>

            <input type="radio" name="<?php echo $each_q_id; ?>" value="<?php echo $each_c[$k]; ?>" id="<?php echo $each_c[$k] ?>">
            <label for="<?php echo $each_c[$k] ?>"><?php echo $each_c[$k]; ?>

            <?php
                }
                $data = $_POST;
                $each_cc = count($choices[$i]);
            //    print_r($session_user_id);
                $option = 0;
                if(isset($data[$each_q_id])){
                    $option = $data[$each_q_id];
                    echo $session_user_id . "--" . $each_q_id . "--" . $each_cc . "--" . $option . "--" . "
";
                }
            ?>

<?php
}
    echo '<input type=submit value="submit" />';
    echo '
</form>

';

    if (!empty($_POST)) {
       var_dump($_POST);
    }
?>

PHP: Get Value from Radio Boxes


In R CMD INSTALL as a response to package installing through console

Question: I tried to install a package I got from github to R through the console:
install.packages("location_of_local_package.zip", repos = NULL, type = "source")

And R responded with this:
In R CMD INSTALL

I also tried using the package manager and changing type to source/win.binary/binary
Comment: In my experience, a `.zip` file indicates a "binary" package and a `.tar.gz` file indicates a "source" package, so there shouldn't have been need to go with `"source"` (but good on you for confirming). Unfortunately, this is not reproducible without seeing more details about the zip files. Perhaps you could include the output from `unzip -v location_of_local_package.zip` to confirm that the package looks like what it should? (Even that's not deterministic, though.)
Comment: To confirm, though ... are you certain that the package did not install? In the same session, does `packageVersion("local_package")` (whatever its name is) produce an error? If so, then I suspect that `install.packages(...)` had more on the console than just those four words; if so, please include the full output, warnings, errors, and all.
Comment: @r2evans unfortunately, it did not install.
It had beenkind of mistakes and warnings when i tried win.binary or binary, but now only this output. Never seen it before
Comment: So you're saying that the console literally says just `In R CMD INSTALL` and promptly exits with nothing more said? Does it crash? If not, are you immediately interacting with the interpreter, so can enter commands once again? That isn't a programming mistake, that's a (not minor) [bug in R itself](https://www.r-project.org/bugs.html). In either case, this question is unfortunately not reproducible given what we know at the moment. If you want to `debugonce(install.packages)` and trace through where it fails, that would be incredibly useful, otherwise I think I cannot help much.
Comment: Yes, it doesn't crash and I can interact with console immediately.
The other person tried to install this package couldn't install it too, but I don't know what the error was, so maybe it is something wrong with the package.
I'm new to R so I could have made some stupid mistakes, that also could be the problem. Anyway, thank you a lot.
Comment: I didn't realize somebody else tried with the same results. That is (to me) "strong" indication that the package is corrupt or invalid. If you put the output from `unzip -v ...` in your question, it might be clearer whether it looks like a package or something a friend clumped together. Whether binary or source, for example, the archive should have a single directory (named for the package) with, among other things, a `DESCRIPTION` file in that directory. If it doesn't look like that, then it is definitely not a proper package archive. Include the output and I might be able to help.
Comment: I don't know if the error the other person got is the same is mine.
I found the reason: this package came out two years ago and not available for R version 3.5.1
Thank you for help!
Answer: That package was not compatible with the latest available version of R (3.5.1 currently).
Downgrade to R 3.3 solved the problem.


lvs output : Data% column

Question: Following is a example of standard lvs output:
LV    VG     Attr       LSize   Pool  Origin Data%  Meta%  Move Log Cpy%Sync Convert
POOL  VG     twi-aotz-- 399.80g              28.12  14.75

The
Data%

field specifies the percentage of data the pool or volume is filled as a percentage of it's total size.
Could you please let me know which column name it's corresponds to.
I checked man lvs and looked at the columns:
Column  names include: chunk_size, convert_lv, copy_percent, data_lv, devices, discards, lv_attr, lv_host, lv_kernel_major, lv_kernel_minor, lv_kernel_read_ahead, lv_major, lv_minor, lv_name,
          lv_path, lv_profile, lv_read_ahead, lv_size, lv_tags, lv_time, lv_uuid, metadata_lv, mirror_log,  modules,  move_pv,  origin,  origin_size,  pool_lv,  raid_max_recovery_rate,  raid_min_recov‐
          ery_rate,  raid_mismatch_count,  raid_sync_action,  raid_write_behind,  region_size, segtype, seg_count, seg_pe_ranges, seg_size, seg_size_pe, seg_start, seg_start_pe, seg_tags, snap_percent,
          stripes, stripe_size, sync_percent, thin_count, transaction_id, zero.

Could not find anything which maps to Data%.
It would be also good to have the value as exact value and not percentage.
The way to dump specific columns in lvs is:
lvs -othin_id,lv_name,origin,lv_size

I am looking for what should I append at the end of the columns which are being dumped.
Thanks
Answer: lvs -o data_percent
lvs -o help (more info).

sorry I'm not speak english well...
I'm not rude. :)
Comment: I confirm this works for me.

lvs output : Data% column


Como ordernar uma busca no MySQL com data no formato d-m-Y?

Question: A data no meu banco está salva da seguinte maneira dia-mês-ano. Gostaria de saber como posso ordenar por data utilizando esse formato de data.
Comment: Esse campo é do tipo `date` ?
Answer: Se os dados estão armazenados em string (campo char ou varchar), talvez não haja necessidade de conversões apenas para ordenação, então você pode simplesmente usar substrings, que são rápidas de se processar:
Se tiver separador na data (dd-mm-aaaa), pode ser assim:
SELECT * FROM basededados
   ORDER BY
      SUBSTR( campoComAData, 7, 4),
      SUBSTR( campoComAData, 4, 2),
      SUBSTR( campoComAData, 1, 2)

Se for sem separadores (ddmmaaaa), basta ajustar os índices:
SELECT * FROM basededados
   ORDER BY
      SUBSTR( campoComAData, 5, 4),
      SUBSTR( campoComAData, 3, 2),
      SUBSTR( campoComAData, 1, 2)

Basicamente, estamos dizendo via ORDER BY: "ordene por Ano, depois pelo Mês, e por fim pelo Dia".

SUBSTR( string, inicio, qtd) extrai o pedaço da string começando por "inicio" e pegando "qtd" caracteres.
Comment: @Miguel Angelo Tá vendo, não é só com você que acontece.
Answer: Se a data está armazenada como texto, você pode usar a função STR_TO_DATE do MySQL:
SELECT data
FROM tabela
ORDER BY STR_TO_DATE(data, '%d-%m-%Y');

Answer: Basta apenas adicionar o formato com date_format() na lista de campos e depois ordernar:
SELECT date_format(data, '%d/%m/%Y') FROM datas ORDER BY data DESC

Answer: SELECT * FROM `mensagens` order by date(concat(ano,'-', mes,'-',dia)) asc

Assim, adeque ao seu modelo


Can we get two run outs in one ball?

Question: Suppose player1 is got runout and player2 is also out of the line then can we get player2's wicket too by hitting the stumps?
Comment: https://www.youtube.com/watch?v=sd6yFyfrE2M
Comment: @Jon Mark Were both of them got out?
Comment: i thought so, i didn't know the ball is dead once a wicket is taken.
Comment: @JonMarkPerry please provide evidence they were both out.
Comment: @PhilipKendall; that's all i could find - i think i have seen 2 outs in one ball somewhere before, but i can't find it.
Comment: @PhilipKendall; the case i find amusing is if the non-receiving batsman dislodges his own wicket - are they out? in which case the receiving batsman could be bowled, the non-receiving batsman could dislodge his wicket...
Comment: Nope, because once again the ball would be dead as soon as the first batsman is out.
Answer: No. As soon as a batsman is out, the ball is dead so there is no way to get two run outs in one ball. The only exception is to get a "regular" run out on a ball, and then to run out the non-striker backing up ("Mankading") before the next ball is delivered.
Comment: https://www.youtube.com/watch?v=sd6yFyfrE2M see video
Comment: I see the video, but I'm not sure what point you're trying to make - the comments on the video (if you ignore the usual YouTube spam) agree precisely with my answer.

Can we get two run outs in one ball?


Structural Equation Modelling

Question: Consider the following model :
$$\begin{aligned}
Crime &= α_0 + γ_1Police + α_1Unemp + α_2Income + α_3Gini + u_1 &(1) \\
Police &= β_0 + γ_2Crime + β_1Income + β_2Pub + u_2 &(2)
\end{aligned}$$
where for suburb i, Crime is the crime rate (criminal cases per thousand residents),Police is the size of the police force, Unemp is the unemployment rate, Income is
the median income of households, Gini is the Gini coefficient (a measure of inequality),
and Pub is the number of pubs. Assume that all parameters are significantly
different from zero. Only Crime and Police are jointly determined by this system.
I have to estimate these equations using SEM.
1)Can anyone help me in determining which equation here is identified and why?
2)Am I right to say that crime and police are both endogenous?
Any help here would be highly appreciated.
Thank you very much.
Comment: Can anyone please help me out at least in giving me some idea as to how I approach this problem?
Answer: I think both these equations are identified (Either exactly or over). The intuition to say that these equations are identified is that in both equations there exists a variable which can be used as an instrumental variable i.e, there exists in both equations a variable which is not present in the other equation. The explanation is very layman and not very sound theoretically so I'll advice you to go through a textbook to exactly get the intuition behind identification.
Secondly, Yes both crime and police are endogenous because the value of both these variables are determined within the system. So a change is some specifics in the system you've modeled will have an impact on these variables so these variables are defined as endogenous.
Hope it helps.

Structural Equation Modelling


How to embed a view in a specific node?

Question: I try to embed a view in a specific node. I found tutorials for doing this with Drupal 7 and PHP-Templates:
<?php print views_embed_view('view_name'); ?>

But I look for a way in Drupal 8 with twig-Templates. I tried to call the views_embed_view() function in the hook_node_view() and assign it to the node so that I can print it out in the twig-Template. But it seems that this hook never gets called.
Any hints/solutions how to do this in the Drupal 8 way?
Answer: Twig Views Embed

This module allows to embed views with a twig function.
{{ views_embed_view('view_name', 'view_id') }}

The above module was depreciated in favour of
Twig Tweak

Twig Tweak module provides a Twig extension with some useful functions
and filters that can improve developer experience.

Ex:    {{ drupal_view('view_name', 'view_machine_name') }}
You can find the view_machine_name over here
Comment: @VishalKumarSahu since my answer was posted, Mar 18 '16. I think the module still works, it's just that it's no longer being maintained or being developed any further.
Comment: @TiMESPLiNTER just giving you a heads up.
Comment: Since when? Version?
Comment: Perfectly perfect. It works great and I am having good experience with it. Thanks
Comment: Twig Tweak ! Good Module
Comment: I was always using the code mentioned in question in drupal7 inside blocks in order to print more than one view in a block but it doesn't work in drupal8. how does it work inside blocks?
Comment: @shekoufeh can you provide link to that code? or create a new question about your issue.
Comment: i created a new question here: https://drupal.stackexchange.com/questions/281314/print-views-inside-a-block-in-drupal-8
Answer: This is the way it worked for me in Drupal 8 beta 12 sub-theme of Classy.
In the your_theme.info.theme file
function stjameskidsclub_preprocess_node(&$variables){
  $stuff  = views_embed_view('policy_documents', 'embed_1', 28);
  $variables["my_view"] = \Drupal::service('renderer')->renderRoot($stuff);
}

I copied the node.html.twig and surrounded the article tags (or the area you wish to replace) with a twig block. I placed this in the /template/content folder.
{% block replace_area %}

    ...

{% endblock replace_area %}

Then I created a node--2.html.twig (replace 2 with desired node) in the /template/content folder with the following code.
{% extends "node.html.twig" %}

{% block replace_page %}
  {{ my_view }}
{% endblock %}

Comment: Worth to say this will work inside your module as well
Answer: The first problem you're fighting with is that rendered entities like nodes are now cached by default, so hook_node_view() is only called once after a cache clear/saving that node.
However, this is fairly easy to disable, see settings.local.php.
Then, putting the output of a view in $build is fairly easy and more or less works like in 7.x. Instead of using the embed function, consider using $views = Views::getView() and then $views->buildRenderable()
Two tips:

Make the key you use for $build available as an extra field in hook_entity_extra_field_info(), then check the display if the component is enabled (see how user_user_view() does that. That allows you to configure the weight/placement of the view in the UI and also hide it on certain view modes.
If your view has a page, then it is a bit more complicated, as the node output is cached. You need to make the cache key aware of the pager then, see comment_entity_build_defaults_alter() for an example (not a view, but that is the closest example that core has).
Comment: There is a snippet in settings.php that you need to uncomment (at the end). to make sure that settings.local.php is loaded, add invalid PHP that results in a fatal error. if your site doesn't fail, the file doesn't get loaded.
Comment: First of all thx for this great answer. Well I "enabled" the `settings.local.php` and cleared all caches. But my hook `themename_node_view()` in `themename.theme` still gets not called. Have you any idea why this could be the case?
Answer: As Berdir alluded to View->buildRenderable is what you're looking for, but to give some more context in a module you'll need to do the following.
//use core libraries
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

//use views class
use \Drupal\views\Views;

function hook_node_view(&$build, $node, $display, $view_mode){

 $thisView = Views::getView('view_name');

 $build['arbitrary_render_array_key_here'] = $thisView->buildRenderable('block_1',array($your_arguments));

}

Then in your page template you can access it with
{{ page.content.theme_name_content }}

Comment: All of this was a single liner in Drupal 7. Interesting.
Answer: Within views, you can create a block with your relevant data.
After block creation, you can assign the block to appear in your desired content area (footer/header/content/etc). Assign it, and then click "configure". You should be able to "Show block on specific pages". Selecting "Only the listed pages" and adding /node/your-node-number to the page specification should limit that view/block to appearing only with your desired node.
Cheers!
Comment: Thx for your answer :-). But then I have to create a content area for each case then. So if I like to have first text, then the view and then again text. Or if I like to have first text and then the view or first the view and then text. Then I have to create 3 different content areas which I render in the specific node temapltes. But the `views_embed_view()` approach is much easier and cleaner I guess.
Answer: I know you mention you'd like to use twig templates but you could use the Views Reference Field module to avoid having to dig around in templates. Also gives the advantage of being able to add it to any fieldable entity so that content editors can configure the view / output.

How to embed a view in a specific node?


Boundaries of a triple integral between $x^2+y^2=2z$ and $x+y=z$

Question: I am calculating the integral $\iiint_V z\,dV$ between $x^2+y^2=2z$ and $x+y=z$, but I am not sure how to find boundaries for this case. I tried with cylindrical coordinates, but I was unable to solve the problem.
I would also like to know if there is any general procedure to solve this kind of problem.
Answer: In cylindrical coordinates, those conditions become $r^2=2z$ and $r(\cos\theta+\sin\theta)=z$. But then $\frac12r^2=r(\cos\theta+\sin\theta)$ and therefore $r=2(\cos\theta+\sin\theta)$. So, $\cos\theta+\sin\theta\geqslant0$, and therefore $-\frac\pi4\leqslant\theta\leqslant\frac{3\pi}4$. For each such $\theta$, the possible values of $r$ go from $0$ to $2\sqrt{1+\sin(2\theta)}$ (taken at $\bigl(2\cos^2(\theta)+\sin(2\theta),2\sin^2(\theta)+\sin(2\theta),2+2\sin(2\theta)\bigr)$). So, since we are interested in the region above the paraboloid $z=\frac12(x^2+y^2)$ and below the plane $x+y=z$, take$$\int_{-\pi/4}^{3\pi/4}\int_0^{2\sqrt{1+\sin(2\theta)}}\int_{r^2/2}^{r(\cos\theta+\sin\theta)}rz\,\mathrm dz\,\mathrm dr\,\mathrm d\theta.\tag1$$Then\begin{align}(1)&=\int_{-\pi/4}^{3\pi/4}\int_0^{2\sqrt{1+\sin(2\theta)}}-\frac{r^5}8+\frac{r^3}2\sin(2\theta)+\frac{r^3}2\,\mathrm dr\,\mathrm d\theta\\&=\int_{-\pi/4}^{3\pi/4}\frac23\bigl(\sin(\theta)+\cos(\theta)\bigr)^6\,\mathrm d\theta\\&=\frac{5\pi}3.\end{align}
Comment: I think I see two problems with this argument. (1) Because $V$ is, as you say, above the paraboloid and below the plane, the limits of integration for $z$ are in the wrong order. (2) We have $(x, y, z) \in V$ only if $(x - 1)^2 + (y - 1)^2 \leqslant 2.$ This implies that for each value of $\theta \in (-\pi/4, 3\pi/4),$ the range of values of $r$ for which $(r\cos\theta, r\sin\theta, z) \in V$ for some $z$ is $(0, \cos\theta + \sin\theta + \sqrt{1 + \sin{2\theta}}],$ not $(0, 2\sqrt2]$ (except when $\theta = \pi/4$), so the limits of integration for $r$ are wrong, too.
Comment: @CalumGilhooley Thank you. Yes, of course that I've put the plane and the paraboloid in the wrong order. But it cannot be just that. I will delete my answer and try to repair it.
Comment: @CalumGilhooley Done! I got the same result as you. This proves that the answer is correct. $\ddot\smile$
Comment: The integral looks right to me now (although only after I cheated, by putting $\phi = \theta + \pi/4,$ and guiltily looking up $\int_0^{\pi/2}\sin^6\phi\,d\phi=\frac{5\pi}{32}$ in an old book), and I haven't found any further errors in my own answer, so I'm almost starting to have confidence in the result.
Answer: Here I present a way to solve the integral. Maybe there's an easier way to integrate, because now you get some troubling terms in the last integral.
Since we have a function of $z$, we would like to integrate over $z$ first. The boundaries of $z$ evaluates to
$$\frac{x^2 + y^2}2 \le z \le x + y$$
since that's the only bounded volume. Therefore we get
$$\int_V z \ dV = \int_{\pi(V)} \left[\int_{\frac{x^2 + y^2}2}^{x + y} z \ dz \right] dA = \int_{\pi(V)} f(x, y) \ dA,$$
where $\pi(V)$ is the projection of $V$ on the $xy$-plane. The boundaries for $\pi(V)$ is where $\frac{x^2 + y^2}2 = x + y$. Solving for $x$ we get $x = 1 \pm \sqrt{1 + 2 y - y^2}$. Therefore $x$ in $\pi(V)$ is therefore contained by
$$1 - \sqrt{1 + 2 y - y^2} \le x \le 1 + \sqrt{1 + 2 y - y^2}.$$
and we get
$$\int_{\pi(V)} f(x, y) \ dA = \int_{Y} \left[\int_{1 - \sqrt{1 + 2 y - y^2}}^{1 + \sqrt{1 + 2 y - y^2}}  f(x, y) \ dx\right]dy$$
where $Y$ is the projection of $\pi(V)$ on the $y$-axis. Now the last step is to solve where $Y$ is located. Well, solve where $1 - \sqrt{1 + 2 y - y^2} = 1 + \sqrt{1 + 2 y - y^2}$. Here $y$ is bounded by
$$1 - \sqrt2 \le y \le 1 + \sqrt2,$$
so $Y = [1 - \sqrt2, 1 + \sqrt2]$.
Answer: Caution: I have very little experience of solving this kind of problem, so the way I have evaluated the integral is probably not to be recommended! However, it only involves integration of polynomials of low degree, and in any case, the question was not how to evaluate the integral, but how to describe the region over which one must integrate, so perhaps these remarks will be of some use, even though I cannot suggest a general method for approaching such problems.
The paraboloid $x^2 + y^2 = 2z$ is the common boundary of two regions of $\mathbb{R}^3,$ and the plane $x + y = z$ is the common boundary of another two regions of $\mathbb{R}^3.$ The easiest way I find to visualise the way in which these four regions intersect, partitioning $\mathbb{R}^3$ into four regions, is to consider the coordinate system in the $(x, y)$ plane with basis vectors $\left(\frac1{\sqrt2}, \frac1{\sqrt2}\right)$ and $\left(-\frac1{\sqrt2}, \frac1{\sqrt2}\right)$:
$$
(u, v) = \left(\frac{x + y}{\sqrt2}, \frac{y - x}{\sqrt2} \right).
$$
In the plane $v = 0,$ the paraboloid $x^2 + y^2 = 2z$ projects onto the parabola $z = \frac12u^2,$ and the plane $x + y = z$ projects onto the line $z = \sqrt2u.$ It is clear from this projection that the only one of the four regions of intersection that is bounded is:
$$
\left\{ (x, y, z) \colon \frac{x^2 + y^2}2 \leqslant z \leqslant x + y \right\}.
$$
In terms of $(u, v)$ rather than $(x, y),$ this is:
$$
\left\{ (u, v, z) \colon \frac{u^2 + v^2}2 \leqslant z \leqslant \sqrt2u \right\}.
$$
The region of integration projects onto a circle of radius $\sqrt2$ in the $(u, v)$ plane:
$$
\{ (u, v) \colon u^2 - 2\sqrt2u + v^2 \leqslant 0 \} =
\{ (u, v) \colon (u - \sqrt2)^2 + v^2 \leqslant 2 \}.
$$
Let us therefore transform coordinates again, by translating $(u, v)$ to $(t, v)$ where $t = u - \sqrt2.$
After some simplification, the region of integration becomes:
$$
\left\{ (t, v, z) \colon 1 + \sqrt2t + \frac{t^2 + v^2}2 \leqslant z \leqslant 2 + \sqrt2t \right\}.
$$
One final transformation: $(t, v) = (r\cos\theta, r\sin\theta),$ where $0 \leqslant r \leqslant \sqrt2$ and $-\pi < \theta \leqslant \pi.$ (I hope it doesn't matter that I haven't expressed this very precisely.) The Jacobian is (if I remember the notation for this sort of thing correctly! - please bear with me, I've got about half a century's worth of rust to get through):
$$
\frac{\partial(t, v)}{\partial(r, \theta)} =
\begin{pmatrix}
\cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta
\end{pmatrix},
$$
with determinant $r,$ so we are finally interested in:
$$
I = \iiint_Ezr\,dE,
$$
where:
$$
E = \left\{ (r, \theta, z) \colon 1 + \sqrt2r\cos\theta + \frac{r^2}2 \leqslant z \leqslant 2 + \sqrt2r\cos\theta \right\}.
$$
Evaluating:
\begin{align*}
I & = \int_0^\sqrt2\int_{-\pi}^\pi\int_{1 + \sqrt2r\cos\theta + \frac{r^2}2}^{2 + \sqrt2r\cos\theta}zr\,dz\,d\theta\,dr \\
& = \int_0^\sqrt2r\int_{-\pi}^\pi\left[\frac{z^2}2\right]_{1 + \sqrt2r\cos\theta + \frac{r^2}2}^{2 + \sqrt2r\cos\theta}\,d\theta\,dr \\
& = \int_0^\sqrt2r\int_{-\pi}^\pi\frac12\left(1 - \frac{r^2}2\right)\left(3 + 2\sqrt2r\cos\theta + \frac{r^2}2\right)\,d\theta\,dr \\
& = \frac12\int_0^\sqrt2r\left(1 - \frac{r^2}2\right)\left[3\theta + 2\sqrt2r\sin\theta + \frac{r^2\theta}2\right]_{-\pi}^{\pi}\,dr \\
& = \pi\int_0^\sqrt2r\left(1 - \frac{r^2}2\right)\left(3 + \frac{r^2}2\right)\,dr \\
& = \pi\int_0^\sqrt2\left(3r - r^3 - \frac{r^5}4\right)\,dr \\
& = \pi\left[\frac{3r^2}2 - \frac{r^4}4 - \frac{r^6}{24}\right]_0^{\sqrt2} \\
& = \pi\left(3 - 1 - \frac13\right) \\
& = \frac{5\pi}3.
\end{align*}
Comment: I can't visualise it clearly yet, but this region of integration $V$ provides a curious illustration of [Cavalieri's principle](https://en.wikipedia.org/wiki/Cavalieri%27s_principle), because its "height" $1 - r^2/2$ is a function only of the distance $r$ from the origin of the $(t, v)$ plane, so $V$ is a kind of vertically sheared version of the radially symmetric region between the *same* paraboloid $x^2 + y^2 = 2z$ and the *horizontal* plane $z = 1.$ The volume of either region is $\pi.$


Ajax Async: true, preciso de um exemplo

Question: Olá, quero apenas um exemplo para fins de estudo. Quero que a página fica atualizando automaticamente, para futuramente fazer chat, a página atualizar de forma assincrona e também para página atualizar em tempo real, onde outra pessoas do computador possa ver os dados ao mesmo tempo. Todo com bastante dúvida em Ajax com JQuery, por isso estou fazendo a pergunta. A minha dúvida é relacionado a função...
eu tenho o arquivo teste.php

<!DOCTYPE html>

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

Tenho o arquivo ajax.php

$(function(){
$.ajax({
    url: "ajax.php", // substitua por qualquer URL real
    async: true
}).done(function () {
    a = true;
});

});

Desculpe mas não sei muito bem utilizar essa função, preciso de apenas uma função simples para está atualizando os dados sem que usuário perceba. Pode ser qualquer uma, Porém entendo de JQuery mas tem poucos matérias que ensina sobre ajax.
Atualização pode ser a cada 2 segundos...
Comment: Por curiosidade, você já leu a [documentação](http://api.jquery.com/jquery.ajax/) da função? Se sim, pode editar a pergunta e adicionar quais são as reais dúvidas?
Comment: `async: true` é o valor inicial mesmo que não o indiques. E `async: false` foi removido do jQuery porque era uma má ideia. Também não percebo a pergunta, podes explicar melhor?
Comment: Primeiramente @Alan o código do arquivo`ajax.php` não será executado, pois você está tentando executar `javascript` dentro de um arquivo `.php`.
Answer: Um exemplo simples seria criar uma função para chamar o Ajax e retornar os dados:

Ajax Async: true, preciso de um exemplo


How to get field value having stdClass from views?

Question: I am attempting to retrieve a value in a Fivestar rating field using views PHP. So far nothing I have attempted has been successful.
Here is the output from print_r($data):
PHP: stdClass Object ( [entityform_created] => 1448480841 [entityform_id] => 2 [field_data_field_rating_entityform_entity_type] => entityform [_field_data] => Array ( [entityform_id] => Array ( [entity_type] => entityform [entity] => Entityform Object ( [uid] => 1 [entityType:protected] => entityform [entityInfo:protected] => Array ( [label] => Entityform Submission [entity class] => Entityform [controller class] => EntityformController [base table] => entityform [fieldable] => 1 [entity keys] => Array ( [id] => entityform_id [bundle] => type [revision] => ) [bundles] => Array ( [current_feelings_about_job] => Array ( [label] => current feelings about job [admin] => Array ( [path] => admin/structure/entityform_types/manage/%entityform_type [real path] => admin/structure/entityform_types/manage/current_feelings_about_job [bundle argument] => 4 [access arguments] => Array ( [0] => administer entityform types ) ) [rdf_mapping] => Array ( ) ) [job_test] => Array ( [label] => job test [admin] => Array ( [path] => admin/structure/entityform_types/manage/%entityform_type [real path] => admin/structure/entityform_types/manage/job_test [bundle argument] => 4 [access arguments] => Array ( [0] => administer entityform types ) ) [rdf_mapping] => Array ( ) ) ) [bundle keys] => Array ( [bundle] => type ) [view modes] => Array ( [full] => Array ( [label] => Full content [custom settings] => ) [email] => Array ( [label] => Email [custom settings] => ) [confirmation] => Array ( [label] => Confirmation [custom settings] => ) [download] => Array ( [label] => Downloads [custom settings] => ) [table] => Array ( [label] => Submissions Table [custom settings] => ) [review] => Array ( [label] => Review [custom settings] => ) [token] => Array ( [label] => Tokens [custom settings] => ) ) [label callback] => entity_class_label [uri callback] => entityform_uri [creation callback] => entityform_create [access callback] => entityform_access [module] => entityform [admin ui] => Array ( [path] => admin/structure/entityforms/list [front path] => entityform [file] => entityform.admin.inc [controller class] => EntityformUIController [menu wildcard] => %entityform ) [metadata controller class] => EntityformMetadataController [metatags] => [static cache] => 1 [field cache] => 1 [load hook] => entityform_load [translation] => Array ( ) [base table field types] => Array ( [entityform_id] => serial [type] => varchar [language] => varchar [created] => int [changed] => int [data] => blob [uid] => int [draft] => int ) [schema_fields_sql] => Array ( [base table] => Array ( [0] => entityform_id [1] => type [2] => language [3] => created [4] => changed [5] => data [6] => uid [7] => draft ) ) [token type] => entityform [configuration] => ) [idKey:protected] => entityform_id [nameKey:protected] => entityform_id [statusKey:protected] => status [defaultLabel:protected] => [wrapper:protected] => [entityform_id] => 2 [type] => current_feelings_about_job [language] => [created] => 1448480841 [changed] => 1448480841 [data] => [draft] => 0 [field_rating] => Array ( [und] => Array ( [0] => Array ( [rating] => 100 [target] => ) ) ) [field_please_tell_us_why_optiona] => Array ( [und] => Array ( [0] => Array ( [value] => good day at work [format] => [safe_value] => good day at work ) ) ) [field_job_your_industry] => Array ( [und] => Array ( [0] => Array ( [tid] => 5 ) ) ) [field_job_title] => Array ( [und] => Array ( [0] => Array ( [value] => sales [format] => [safe_value] => sales ) ) ) [rdf_mapping] => Array ( ) ) ) ) [field_field_rating] => Array ( [0] => Array ( [rendered] => Array ( [#attributes] => Array ( [class] => Array ( [0] => clearfix ) ) [#theme_wrappers] => Array ( [0] => container ) [user] => Array ( [#theme] => fivestar_formatter_percentage [#instance_settings] => Array ( [stars] => 7 [allow_clear] => 1 [allow_revote] => 1 [allow_ownvote] => 0 [target] => none [user_register_form] => ) [#display_settings] => Array ( [widget] => Array ( [fivestar_widget] => default ) [expose] => 1 [style] => user [text] => average ) [#item] => Array ( [count] => 1 [user] => 100 [average] => 100 ) ) [#access] => 1 ) [raw] => Array ( [count] => 1 [user] => 100 [average] => 100 ) ) ) )

The field I am attempting to retrieve data from is field_rating. Any ideas on how to accomplish this?
Answer: Since $data is a stdClass object which seems to contain your entityform (based on your entityform_x values), you can load it as a metadata wrapper and then get the value of it via value() method, e.g.:
$wrapper = entity_metadata_wrapper('entityform', $data->entityform_id);
$rating = $wrapper->field_rating->value();

See: Entity metadata wrappers.


Using IHttpClientFactory to immediately close connections

Question: I'm connecting to an API, whos' owner doesn't allow more than 1 request per connection. This is very unfortunate, but I have to work with this.
I could create a new HttpClient for each request, but this would leave me vulnerable for socket exhaustion. As such, I'm setting for my HttpClient:
DefaultRequestHeaders.ConnectionClose = true;

And getting it from IHttpClientFactory via
_httpClientFactory.CreateClient();

Now this mostly works fine, but there is one issue. If I send subsequent calls in a loop, like so:
        for (int i = 0; i < 10; i++)
        {
            var request = _requestBuilder.BuildRequest();
            var httpClient = _httpClientFactory.CreateClient();
            var response = await httpClient.SendAsync(request);
        }

Then this will sometimes fail trying to reuse the old connection before it's closed. So my first question is: why is IHttpClientFactory reusing the old connection if I send the request with a Connection: close header?
What's more, I've been looking at netstat and while, unsuprisingly, after creating a new HttpClient for each call I get a bunch of connections in TIME_WAIT status. But for the above ,if it doesn't fail, I get a single connection in CLOSE_WAIT. If I query netstat during runtime of these requests I can see the port is being changed for the current connection, but if a new connection is opened the old one is closed immediately and it doesn't hang in any status. So how is the IHttpClientFactory actually managing this? I couldn't get to close the connection immediately by calling dispose on either HttpClient or HttpResponseMessage
Answer:
I could create a new HttpClient for each request, but this would leave me vulnerable for socket exhaustion.

I recommend you use an HttpClient for each request. If the server honors ConnectionClose (which it seems to be doing), then you won't be in any more danger of socket exhaustion than you would be using IHttpClientFactory.
For modern HTTP servers (ones that allow multiple requests, like was added in HTTP 1.1... in 1997), there's a danger of socket exhaustion because the clients normally close their sockets, which enter TIME_WAIT state. So IHttpClientFactory avoids the socket exhaustion by reusing the sockets. But in your case, the server won't allow socket reuse, so IHttpClientFactory is just going to add complexity without providing any benefit.

DefaultRequestHeaders.ConnectionClose = true;

Setting this for HTTP connections means that the server closes the socket connection, which means that your local socket enters CLOSE_WAIT rather than TIME_WAIT. Here's the diagram if this isn't clear; it's from Stevens' TCP/IP Illustrated:

Then this will sometimes fail trying to reuse the old connection before it's closed. So my first question is: why is IHttpClientFactory reusing the old connection if I send the request with a Connection: close header?

The whole point of IHttpClientFactory is to reuse connections. AFAIK the factory does not have any special handling around ConnectionClose, so it assumes the socket is still viable so it keeps it around. Then it tries to use that socket again.
The "sometimes" part of the failure could be due to a race condition: I suspect the factory is doing something like checking whether the socket is closed, and if it is, creating a new one; and if not, returning a socket (in the CLOSE_WAIT state), which will then fail.

But for the above ,if it doesn't fail, I get a single connection in CLOSE_WAIT.

I would expect the factory to keep its socket connection around, since it's not aware of ConnectionClose.

If I query netstat during runtime of these requests I can see the port is being changed for the current connection, but if a new connection is opened the old one is closed immediately and it doesn't hang in any status.

Connections cannot change ports. I expect the old connection is kept around until it is closed by the factory when it determines the connection isn't viable, and then the factory immediately creates a new one.

I couldn't get to close the connection immediately by calling dispose on either HttpClient or HttpResponseMessage

Technically, the thing that the factory reuses is not HttpClient, but the last HttpMessageHandler in the chain of handlers wrapped by the HttpClient. And for factory-created clients, this isn't disposed when you dispose HttpClient.
Comment: Thanks. If I know that every connection is finished after 1 request, can I set my application / HttpClient to send the FIN message back to the server after I receive one from them? Or is it not feasible?
Btw. I was thinking that's what happens to these connections "being switched" with the IHttpClientFactory that I described as "changing ports" - apologies for wrong technical term on that. I assume they would be shown by the netstat if kept around, right?
Comment: The TCP layer will handle the FIN packets for you. It's just that server-initiated closes are not common, so that's why the factory doesn't think to detect them.
Comment: I see. If the server in the response would send a header Connection: close, would the tcp layer send FIN back to the server to close this connection immediately?
Comment: No. The TCP layer doesn't interpret HTTP headers.


Output all instances of a repeating field together

Question: I have Paragraphs installed and am creating a content-type which has nested Paragraphs - so there is a Paragraph with a Title Field, a Body Field - this is then nested in a another Paragraph, so that I can have several boxes across the page. So far so good - what I want to learn is to output the fields so I can put them in jQuery UI tabs.
In my template I currently have:
{{ content.field_tab_title }}
{{ content.field_body }}

Which outputs:
Title Body Title Body Title Body etc.
What I need is:
Title Title Title Body Body Body
So that I can put all the titles in li's for jQuery UI. I've tried putting
{% for item in items %} {{ content.field_tab_title }} {% endfor %}

But then nothing comes out at all.
UPDATE
Following Kevin's Suggestions, I've started again with my templates and have now got;
in paragraph--tab.html.twig:

{{ content.field_tab_title }}

{{ content.field_body }}

and in field--paragraph--tab.html.twig:
{% for item in items %}

{{ item.content }}

{% endfor %}

but this is still outputting:

Tab Title - 1

Body Copy 1

Tab Title - 2

Body Copy 2

But what I need is:

Tab Title - 1

Tab Title - 2

Body Copy 1

Body Copy 2

Answer: This is going to be tricky, but you will need to think through the rendering layers via twig and work inside out.
Example, if you need all field tab titles in li's, the twig for field tab title (field--field-tab-title.html.twig) should look something like this:
{% for item for items %}

{{ item }}

{% endfor %}

In your Paragraph field twig, you would put the wrappers as needed, like:

  {{ content.field_tab_title }}
  {{ content.field_tab_body }}

The same applies to Body:
{% for item for items %}

{{ item }}

{% endfor %}

Here is a similar example perhaps you can follow. This isn't tabbed content, but it is accordion based, so it is similar. Still paragraphs.
Main container (paragraph--component):

  {% block content %}
    {{ content }}
  {% endblock %}

Main accordion paragraph twig, extends the main container (paragraph--component is a custom twig suggestion I made for easier theming):
{% extends 'paragraph--component.html.twig' %}

{% set attributes = attributes.addClass('c-accordion') %}

{% block content %}
  {{ content }}
{% endblock %}

The accordion item itself, containing a title and other fields:

  <input type="checkbox" class="c-accordion__trigger visuallyhidden" id="step-{{ paragraph.id() }}" />

    {% if paragraph.field_accordion_step_title is not empty %}

{{ content.field_accordion_step_title }}

    {% endif %}

{{ content.field_accordion_title }}

{{ content.field_accordion_body }}

When this renders, all X accordion items are rendered the same way into one container. Granted, in my example, the markup container for fields live outside of the field twig and in this twig here, because I chose to have 0 field markup in that project. You can go either way you want.
Comment: Thanks Kevin, I'll give that a go (no don't need both in one li) - fingers crossed.
Comment: I added a real world example maybe that will clarify paragraph theming.
Comment: Can't work out what I'm doing wrong - if I wrap `{% for item in items %} {% endfor %}` around a `` they stop outputting, I just get an empty `` . Think I'm going to delete all my Paragraph twig templates and start again, follow through your process above and see how it goes - thanks for all the detail Kevin.


Applying Zorn's lemma in the proof of $|X|\leq |Y|\lor |Y|\leq |X|$

Question: I'm trying to understand this math.SE answer by Captain Lama. The question is about how to prove that always either $|X| \leq |Y|$ or $|Y|\leq|X|$ for arbitrary sets.
Captain Lama firstly remarks that—due to the axiom of choice—the problem reduces to showing that if there is no surjective map $X\twoheadrightarrow Y$, then there is however an injection $X\rightarrowtail Y$. Now he defines a partial order $(A, f)\leq(B, g)\iff(A\subseteq B\land g|_A = f)$ on the set $E:=\{(A, f) : A\subseteq X, f : A \to Y\text{ injective}\}$. I guess he does this to apply Zorn's lemma, because as a next step he says:

Clearly this order is inductive (just take the union in a chain to get a supremum), so there is a maximal element $(A,f)$.

I don't know what "inductive" means in this context but I think he means that each chain has an upper bound (why does he speaks about "supremum"?). So my question is: How to prove that each chain $T\subseteq E$ has an upper bound? Does one need totality ($\forall x, y\in T: x\leq y\lor y\leq x$) in the proof? Captain Lama says that one should take the union. So the domain of $(A, f)$ is going to be $A = \bigcup_{t\in T}\pi_1(t)$, I guess, but what can we take as function $f?$
Comment: Related: http://math.stackexchange.com/questions/421638/proving-a-le-b-vee-b-le-a-for-sets-a-and-b
Answer: "Inductive" here (I believe) means that every chain has a supremum (EDIT: but see Daniel Fischer's comment), that is a least upper bound; of course this is stronger than what we need to apply Zorn, but it's worth noting.
As to what the supremum is, exactly, you have to take the union of both coordinates of elements of the chain - that is, $$\left(\bigcup_{t\in T}\pi_1(t), \bigcup_{t\in T}\pi_2(t)\right)$$ where the union of a family $\{f_i: i\in I\}$ of functions is the set $\{(x, y): \exists i(f_i(x)=y)\}$. Note that this is only a function if the $f_i$s "agree" with each other; but they do in this case, since $T$ is a chain (so in particular, yes, one does need totality in the proof to guarantee that the union of the functions is a function).
It will follow immediately that this is an upper bound of $T$, and it's not hard to show that it is in fact the least upper bound of $T$.
Comment: Thanks for your fast answer. Before accepting it, let me think about it a bit. I'm wondering: why do you use the notation $\{f_i : i\in I\}$ for a *family*? Concerning to the notation I've learned, a family is denoted $(f_i)_{i\in I}$ or $(f_i : i\in I)$, whereas your notation $\{f_i : i\in I\}$ with curly brackets denotes a *set* (note that if we have a family, we can construct the image of it, but a family contains more information than the image set).
Comment: @user419308 Often the notation "$\{f_i: i\in I\}$" is used to denote "$(f_i)_{i\in I}$". But in this case, I only need the set, not the map from indices to functions - the point is that any two functions in the set need to not disagree with each other.
Comment: Mhm? If you have for each $i\in I$ a function $f_i$ this indicates that you have a function $i\mapsto f_i$ rather than a set. Or what do you mean?
Comment: Ahhh, thanks for clarification. I haven't heard of this kind of abuse of notation.
Comment: [Bourbaki also defines an inductive set to be a partially ordered set that satisfies the hypothesis of Zorn's lemma when nonempty.](https://en.wikipedia.org/wiki/Inductive_set) In German, an "induktiv geordnete Menge" is precisely one that (when nonempty) satisfies the hypotheses of Zorn's lemma, so every chain has an upper bound, not necessarily a supremum.
Comment: @user419308 I literally just mean the set of $f_i$s. I mean exactly what I wrote.
Comment: @DanielFischer Ah, I was unaware of that usage - I've seen "inductive" used to denote what I described above, in English, although I've only seen it so used once or twice.
Comment: @DanielFischer: Why "when nonempty"? In the hypotheses of Zorn's lemma one does not have to require that something is nonempty.
Comment: @user419308 You are right. The empty poset (if you consider it a poset) *fails* the condition of Zorn's Lemma - the chain $\{\}$ doesn't have an upper bound, since there are no elements to bound it! But the empty poset also doesn't have any maximal elements, so it fails the conclusion of Zorn's lemma too; so no exception needs to be made.
Comment: @user419308 I was misled by the wikipedia article that explicitly said "when nonempty", I wasn't quick enough to think of the empty chain guaranteeing nonemptiness of an inductively ordered set before posting the comment.


Adding vertical space after header in LilyPond score

Question: I have prepared a \header and I would like to increase the vertical space before my first stave, which also includes chords.
Is that also possible with LilyPond?
Answer: The simplest approach would be to include a \markup \vspace #1 command before your score block. You can change the #1 to any value, including values with decimals.
\version "2.18.2"

\header {
  title = "This"
}

\markup \vspace #1 % change this value accordingly

sample = \relative c'' {
  c4
}

\score {
  \new Staff \sample
  \layout { }
}


Determining the velocity is terms of displacement given acceleration. (terminology)

Question: So I  need to determine the velocity in terms of displacement. It was given the acceleration of the particle is $a(x) = 49x - 14$
I know that $a =  \frac{d}{dx}(\frac{1}{2}v^2)$; which is $49x-14\:=\:\frac{d}{dx}\left(\frac{1}{2}v^2\right)$
This is where I got bamboozled, my textbook went straight to $\frac{1}{2}v^2=\int \:49x-14\:dx$. How?
I get that you need to times $dx$ by both sides. But Where did the $"d"$ go? So when you integrate both sides, the $"d"$ and the integral sign cancel out?
Like so:
$\int \:\frac{1}{2}v^2\:\:\:d=\int \:49x-14\:dx$
and $"d"$ cancels out?
$\:\frac{1}{2}v^2\:=\int \:49x-14\:dx$
Comment: Think of it as integrating both sides rather than as "times $dx$ by both sides"
Answer: In general we have that by definition:
$$\frac {dF(x)}{dx}=f(x) \iff F(x)= \int_0^x f(u) du$$
with $F(x)=\frac12 v^2$ and $f(x)=49x-14$ in your case.
We don't cancel out "d" which is just used as a symbol to indicate the derivative or the integrating variable.
Answer: Note that
$$\frac{d}{dx}\left(\frac{1}{2}v^2\right) =49x-14 $$
leads to
$$d\left(\frac{1}{2}v^2\right) =(49x-14)dx $$
Then, integrate both sides
$$\int d\left(\frac{1}{2}v^2\right)= \frac{1}{2}v^2 =\int (49x-14)dx $$


Triple integral boundaries

Question: If $W\subset \mathbb{R}^3$ is bounded by the planes $y+z=2, 2x=y, x=0, z=0$, what are the boundaries of $\int\int\int_W x dV$?
How can I find the boundaries if I take $dV$ as $dydxdz$, $dxdzdy$ and $dzdydx$?
Answer: A picture can help. $W$ is the tetrahedron with the grey plane as its base.

The three sets of boundaries:
$$\int_{y=0}^{2} \int_{x=0}^{y/2} \int_{z=0}^{2-y} {x\;dy\;dx\;dz} \\
\int_{x=0}^{1} \int_{z=0}^{2-2x} \int_{y=2x}^{2-z} {x\;dx\;dz\;dy} \\
\int_{z=0}^{2} \int_{y=0}^{2-z} \int_{x=0}^{y/2} {x\;dz\;dy\;dx}.$$
The reasoning for the first one, for example:
\begin{eqnarray*}
y &:& \text{over the whole region, $y$ has a min of $0$ and max of $2$} \\
x &:& \text{given $y$, then $x$ has a min of $0$ and max of $y/2$} \\
z &:& \text{given $y,x$, then $z$ has a min of $0$ and max of $2-y$ (regardless of $x$).} \\
\end{eqnarray*}

Triple integral boundaries


Java library : Gate Creole ResourceInstantiationException

Question: I am using GATE library and am getting the error
gate.creole.ResourceInstantiationException: Couldn't get resource data for com.jpetrak.gate.stringannotation.extendedgazetteer2.ExtendedGazetteer2.

You may need first to load the plugin that contains your resource.
For example, to create a gate.creole.tokeniser.DefaultTokeniser
you need first to load the ANNIE plugin.

Go to the menu File->Manage CREOLE plugins or use the method
Gate.getCreoleRegister().registerDirectories(pluginDirectoryURL).

I am initialised my plugins folder and also have added the following line
Gate.getCreoleRegister().registerDirectories(new URL("file:///home/latest/plugins/ANNIE"));

and folder ANNIE contains the file cerole.xml
as told here
why am I still getting the error?
Thank you
Answer: You have to register any plugin you are using.
The class

com.jpetrak.gate.stringannotation.extendedgazetteer2.ExtendedGazetteer2

is a GATE processing resource from a very old version of gateplugin-stringannotation .
So except ANNIE, you have to register the directory of this plugin as well.


Inner_join() adding rows together instead of unique rows

Question: I'm concerned that something is wrong with my R/Rstudio. I'm trying to do an inner_join() to get the intersection of male and female baby names from the babynames package, but am seeing that my inner_join() is greater than my subset for male names with the following code:
library(babynames)
library(dplyr)

malenames <- babynames %>%
  filter(sex=="M")
girlnames <- babynames %>%
  filter(sex=="F")

names <- inner_join(girlnames, malenames, by ="name")

To clarify, I'm seeing rows for 786372 rows for malenames and 1138293 rows for girlnames. What could be going wrong? Thank you in advanced for your guidance.
Comment: "unique rows" plus "do an inner_join() to get the intersection of male and female baby names" plus not "my inner_join() is greater than my subset for male names" does not clearly explain what you want your query to return. Please in code questions give a [mcve]--cut & paste & runnable code & desired output & clear specification & explanation. That includes the least code you can give that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.) When describing a result: Say enough that someone could go away & come back with a solution.
Answer: You need to join on both name and year, otherwise each (year, name) pair in girlnames gets matched with every row with a matching name in malenames:
names <- inner_join(girlnames, malenames, by = c("name", "year"))

Comment: Great, thank you.
I also was playing around and noticed that piping %>% group_by(name) to the malenames and girlnames dataframes resolves this issue as well. I appreciate the help


"Invalid algorithm specified" when signing with JwtSecurityTokenHandler.CreateToken

Question: I've been signing JWT tokens for a couple of years with no problems. I recently upgraded to Windows 10 and when I try to sign a JWT token I get a CryptographicException of "Invalid algorithm specified".
I'm passing an X509Certificate2 into this method and I'm not doing anything else really.
System.IdentityModel.Tokens.JwtSecurityTokenHandler.CreateToken()

The signing certificate was previously created using SHA-1, so I even created a new signing certificate using SHA-256 RSA, but still no joy.
I read several SO questions that suggested I needed to enable the "Microsoft Enhanced RSA and AES Cryptographic Provider" or at least create my signing certificate using it. Many SO Qu's suggested adding this line, but still no luck.
CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

I also checked that this algorithm is in registry and found it in the Provider list and Provider type list. Unfortunately I don't have control of what algorithm the Jwt signing code uses as its all hidden within the System.Identity libraries.
Strangely, when I stepped into the code and looked at the Signature it mentioned it had an RSA Provider of "Microsoft Strong Cryptographic Provider", rather than the "Enhanced" one mentioned earlier, although from the MSDN documentation they appear to be pretty much the same.
I presume its complaining it can't find the Algorithm used to sign the actual token, rather than the algorithm to read or intepret the signing certificate?
What other checks can I do with the limited flexibility of the JwtSecurityTokenHandler code?
The full stack trace is:
at      System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
   at System.IdentityModel.Tokens.AsymmetricSignatureProvider.Sign(Byte[] input)
   at System.IdentityModel.Tokens.JwtSecurityTokenHandler.CreateSignature(String inputString, SecurityKey key, String algorithm, SignatureProvider signatureProvider)
   at System.IdentityModel.Tokens.JwtSecurityTokenHandler.CreateToken(String issuer, String audience, ClaimsIdentity subject, Lifetime lifetime, SigningCredentials signingCredentials, SignatureProvider signatureProvider)
   at System.IdentityModel.Tokens.JwtSecurityTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor)

Comment: Not a duplicate, but appears to be the same underlying issue as this: http://stackoverflow.com/questions/7444586/how-can-i-sign-a-file-using-rsa-and-sha256-with-net
Answer: I recently had to tackle the exact same issue.
TL;DR; You need to use "Microsoft Enhanced RSA and AES Cryptographic Provider", as opposed to what I suspect you are using which is "Microsoft Enhanced Cryptographic Provider v1.0".
You can find a full explanatory [ReadME][2], and source code at Karama.Jwt.Public. I happen to be using a different library for generating my JWT, namely JOSE, but I think that this is incidental.
Please let me know how you get on.
Comment: Yes, this is true. I had to upgrade all of my certificates in my application to use SHA2 (i.e. SHA256), rather than using a combination of SHA1 and SHA2 certificates.


Match 1st value before comma of each line from first file with second file line by line

Question: My 1st file -
#cat 123
tom,123
jack,222
rock
google,908
mohan,323
ram,789

My 2nd file -
#cat www
vicky,tom,home
google,monk,uber
dhoom,monk,uber
ram,monk,uber
rock,monk,uber
jack,monk,uber

Desired output -
#cat  match_output.txt
tom,123,vicky,tom,home
rock,rock,monk,uber
jack,222,jack,monk,uber
google,908,google,monk,uber
ram,789,ram,monk,uber

For now, I'm getting only this -
#cat match_output.txt
rock,monk,uber

My Script -
#!/bin/bash

# because File2 is bigger, it gets the main loop.
# read each line of File2
>/var/lib/jenkins/Jack/match_output.txt
while IFS=, read -r string; do
    # read each line of File1.txt
    while IFS=, read -r string2; do
    # check match, and write if needed.
    if [[ $string == *"$string2"* ]]; then
        echo $string >> match_output.txt
        echo "wrote "$string" to match_output.txt..."
    fi
    done < /var/lib/jenkins/Jack/123
done < /var/lib/jenkins/Jack/www

Not able to read 1st value of 1st file before the comma of each line and match with 2nd file line by line and print the output in a new file....
Comment: Is the desired input in your question complete? Why does your desired output not contain "google,908,google,monk,uber"?
Comment: why doesn't `ram,789,ram,monk,uber` show up in the expected output?
Comment: By storing the first file in an associative array you'll greatly speed up the processing. bash >= 4 has it, but if your stuck to bash 3 then you can use a standard tool like `awk`. No, even your bash have associative arrays, you should go with `awk` ;-)
Comment: turn on debugging (`set -xv`) and re-run your script; I'm guessing you'll find `string` and `string2` do not contain what you think they contain; also, the only thing you're writing to the output file is `$string`, ie, nowhere does the code attempt to write `$string2` to the output file
Comment: I've updated my Desired output....Sorry missed some entries earlier. @markp-fuso
Answer: To get the first value before the comma, you can use the cut command.
With the following code
    if [[ $string == *"$string2"* ]]; then
        echo $string >> match_output.txt
        echo "wrote "$string" to match_output.txt..."
    fi

you compare the complete lines. If you want to compare $string with only the first value (before the comma) of $string2, you need to adjust this comparison.
    string2FirstValue=`echo "$string2" |cut -d',' -f1`
    if [[ $string == *"$string2FirstValue"* ]]; then
        echo $string2,$string >> match_output.txt
    fi

Answer: Safer and more efficient way is to use awk:
awk '
BEGIN {FS=OFS=","}
FNR == NR {
   map[$1] = $0
   next
}
{
   for (i=1; i<=NF; ++i)
      if ($i in map) {
         print map[$i], $0
         next
      }
}' 123 www

tom,123,vicky,tom,home
google,908,google,monk,uber
ram,789,ram,monk,uber
rock,rock,monk,uber
jack,222,jack,monk,uber


Loading a large and dynamically changing data set into a table

Question: I have a large set of data that occasionally might be updated in the background. As a self teaching experiment I do not wish to rely on any framework. Right now I am trying to find the right place with the MVC/MVVC patterns within a DDD/CQRS context.
In order to populate a table I do a query of a large data set and limit the results to twice the number of displayed rows. Once the user scrolls past half of the query, I query for the next batch of results.
I am loading all results into an array as the user scrolls, just a progressive load without throwing away non displayed rows.
Who is responsible for building the array of results converted to domain objects? The model of the MVC or the data repository?
Ideally I would like to reuse my MVC model without being always concerned about limiting the query results.
If data is updated in the background, a system event is created. However in the cases where a new row was created, I want my application to animate the background insertion of a new row, not just discard the query and reload the table. In such case I guess that a background process must load a copy of the current query and compare it with the existing one. It should create a "New Rows System Event" with the positions of the new rows.
Which component should compare current query results with previous ones in order to calculate insertion and deletion points? A system service? The MVC model?
My final concern is that loading a set of rows with multiple limited queries, might be inconsistent if the data is updated in the background. How/Where should I enforce this consistency?
Comment: The data displayed are always stale in some extent. Why not just let the user refresh or make the system do it periodically.
Comment: Considering a CQRS architecture, if a user request a new row, the command and the query are asynchronous events. I think that in such case, if you want to render as soon as possible the new empty row, it can only be the system and not the user, who decides when to reload a query based on when the database is updated, not when the user clicks the button for a new row.
Comment: I think the client is responsible for detect the data change(by scanning periodically), otherwise the server needs to broadcast a dataUpdatedEvent(which I think a waste of network) or keep a client memo to decide which client is interested in the update(which I think adds a lot of complexity). Hmm...How is the comment notification feature implemented on StackOverflow?
Comment: For me when to update a query is irrelevant. I already have an Event object when the database is updated.  My question is about (1) in which patterns/components I should build up partial query results and (2) compare differences from previous queries to animate insertions or deletions.
Comment: Take a look at SignalR so you can push data to the client when it changes.
Comment: I already have data pushed to my client. I just need to know which DDD layer (application? domain?) and pattern/component (model? service? repository?) should hold my results and calculate insertion points. A quick lick to SignalR does not seem to show a domain driven architecture
Answer: CQRS and DDD = one Domain model and at least one Query model. Now, it's for your own good to not think of DDD as of something with many rules which broken will make you the DDD public enemy no1.
Let's think a bit: Once a Domain object is updated and a domain event is published, you'll have an event handler which will update the query model. Which query model is exactly the one you need for the UI (the view models).
The client UI should request updates (passing the current model datetime stamp) at an interval. Which updates are also part of the query model. In order to detect what changed, the update should have a datetime stamp which will get compared with the one currently shown. If it's a web app, then I strongly suggest to use a js framework like angularjs.org
Now, The MVC Model in this scenario is the query repository. When insert/edit a row, the Model will be a service (or a command handler) which will update the Domain. Everything related to Domain changes and query model generation is outside the UI, as a part of a Services/Application (call it whatever you wish) layer.
Comment: Nice! So in MVC the model should be a service between the Application and Domain layer, right? I use NoSQL database which sends me a message whenever a mapreduce function is triggered, therefore I do not need to request updates. Whenever my repos return a sequence of root objects, I return a custom Array class that provides me with some lazy loading. I am thinking now about expanding that class with a timestamp, maybe even an UID set during creation inside my repo...but that does not look like something I have seen before. Would that be too crazy? Then repos should manage the age of queries :/
Comment: The MVC model represetns the bits of other layers usable by the UI. MVC exists ONLY inside the UI. The UI should ask for updates, regardless of the db used. Also, the concept of lazy loading (LL) has no place here or in the Repository pattern. LL is an ORM workaround, leave it there. The query repo should return whatever the UI needs as a DTO. The updating of query model is done outside UI or db. The db just persists the changes, but another component manages the process. Once again, don't worry much about how the layer is called. I prefer to call it Services, but that's my opinion only
Comment: Thanks! I realized after my comment that my CustomArray should not have UID or timestamp, since that is needed only for certain models. However you make me think about "query repo returning whatever the UI needs as a DTO". Before CQRS my repos returned root entities only (List), but since the Query part of CQRS can be separated from the entities of the domain, I added List. Oh well, that is a whole different question and I must review my knowledge about CQRS
Comment: OMG! I've just realized on my own code that in the past, I used my CustomArray to simulate LL outise a repo for large query results by caching internally calls to a Repo.FindByID(). Now with your answer I will get some neurons working, but I will have to evaluate the tricks of having a "revision" of the DTO on screen/Application Layer different to the "revision" of the Entity on Domain Layer, thanks @MikeSW


How does a DI box work together with guitar?

Question: Basically I'm in need of a DI box and I'm not really sure what to get.
I have a performance in January where I'm using Ableton Live 9 alongside a guitarist. The guitar will be DI'd straight into Live for live processing. I'm not a guitarist myself and the only experience I have had with DI'ing, the DI box has already been there and ready to use.
I'm not sure what and passive means for DI boxes, so breakdown of the different types of DI boxes and their use would be beneficial.
Answer: The most important difference between passive and active DIs is that the latter have a much higher input impedance: usually something like 200 kΩ, whereas a passive DI "inherits" the low impedance of the mic input you're feeding (around 2kΩ), or transforms it up a bit to something in the 20 kΩ range. That makes hardly a difference for instruments with low output impedance (e.g. keyboards, acoustic guitars with build-in preamp): if the output impedance, e.g. 300 Ω, is much lower then the input impedance, you're in "voltage saturation mode", then it makes no difference whether the input impedance is ten times as high or a thousand times as high. So for "powered" instruments you'll always be pretty ok with a passive DI.
The story is very different for instruments that are themselves passive. In particular, guitar pickups have a resistance up to some 10 kΩ even in DC, and the inductive impedance is much higher. So if you plug an electric guitar into a passive DI, the transmission becomes current-saturated. In this mode, the pickups operate completely different from voltage-saturation, the resonance almost vanishes and the volume pot becomes very quiet much quicker. So if you're DI-ing a guitar and don't want to alter the sound even before processing, you must use an active DI, whose input impedance is close to that of an electric-guitar amp (those range between 50 kΩ and 500 kΩ).
It's even more drastic for acoustic guitars with passive piëzo pickups: those have a high capacitive impedance. If you connect them to a low ohmic impedance, you're building a high-pass filter, cutting away all bass frequencies (often in fact everything below 1 kHz). That's why acoustic instruments, unlike electric guitars, almost always have dedicated preamps with input impedance > 1 MΩ: because even standard active DIs have too low impedance to get an even frequency response.

I should add a bit more detail on impedance matching in a passive DI. As I said, passive DIs can also increase the input impedance: by transforming down, i.e. using a transformer with more windings on the primary side than the secondary. The cost is that the output voltage is reduced. Not all DIs do this, for some models I've used I'm sure the output was actually in the same range as the input. (Strangely, it isn't usually specified on a passive DI what winding ratio is used.) But Wikipedia quotes ratios between 10:1 and 20:1 as typical, which is definitely more than I would have reckoned. With such high ratios, voltage loss becomes an issue, but good mic preamps should have enough SNR so this should still be ok; after all, dynamic microphones also offer rather poor voltage. At any rate however, even if you transform a 2 kΩ input up to 40 kΩ, this is still rather on the low end for electric guitar, so my point stands: the main issue with passive DIs is low input impedance.
Now, it would certainly be possible to design a passive DI with transformer ratio as high as perhaps 100:1. Then the input impedance would be high enough to connect guitars, perhaps even a piëzo – but the output voltage really wouldn't be satisfying anymore, no matter what instrument you connect. So I think the current situation is pretty fine for practical purposes:

Active DIs can easily offer enough input impedance for most instruments, without sacrificing gain (though they normally offer a switch to do that on purpose, if your inputs are overloaded). If you need high impedance, use an active DI.
Passive DIs don't aim at very high input impedance, so as not to sacrifice too much gain either – and that's ok, because for active instruments impedance is not really an issue. Hence, for those instruments a passive DI is a cheap, simple, reliable alternative. Also, you may use them to deliberately dampen a guitar's pickup resonance; perhaps that's worthwhile sometimes. (A few guitar effects pedals have low input impedance, best known the Fuzz Face, and the thus changed guitar response makes up a good part of many fuzz sounds you can hear on old records.)
Comment: Thanks for this. You might want to contribute to the Wikipedia article on DI Units, which is missing this information. I think my answer doesn't deserve all its upvotes, because of this omission, but I don't want to plagiarise yours, nor remove my post altogether because I think it has other useful info -- so I'm leaving it as it is. @Perceptic I would encourage you to accept this answer instead.
Comment: I think I've got my head around that haha thanks for the extensive answer. I've ordered a passive DI for now, if I don't like the sound I'll go ahead and get an active DI as well. Can't have too much equipment ha. Very useful information though thankyou
Answer: A DI ("Direct Input") box converts a signal on an unbalanced lead into a signal on a balanced lead (that is, usually a lead with XLR connectors).
The advantage of a balanced lead, of course, is that you can run it for long distances without hearing interference.
With a passive DI, the signal on the XLR lead is at the same level as the input signal. So, if you plug a guitar into it, whatever's at the other end needs to be able to handle instrument-level input (which is similar to mic-level; most mixers and sound interfaces will be OK with this).
An active DI contains a pre-amp, which you would normally use to bring the output signal up to line level. That's a big difference, and brings with it a lot of factors. It needs a knob to control the gain. It needs power -- from battery or phantom power. The quality of the amplifier is a factor. You need an active DI if your signal source is instrument-level, but the receiving end requires line-level.
It's more common for active DIs to have extra features such as passthrough, than for passive DIs.
If you are running the XLR lead a very long way, it may be beneficial to have a line-level signal on it. Even though balanced lines compensate for interference, a stronger signal relative to interference can only be helpful.
If you're not running the signal a long way, perhaps you don't need a DI box at all. From what you've described, I imagine you and your guitarist standing next to each other on stage, with your computer and audio interface in front of you. If that's the case, just plug his guitar lead directly into your audio interface. People use the term "DI" for any situation in which an instrument that's traditionally played through an amp and mic'd, is instead connected electrically to whatever's doing the mix. There doesn't have to be a DI box or an XLR plug involved.
Comment: I guess I was being a bit harsh – this answer does, of course, still make some correct points, it just doesn't get to the gist IMO. In particular, the preamps in active DIs generally don't boost the signal voltage at all ("bring the output signal up to line level" – in fact they rather bring the signal _down_ to mic level!), though they do in a sense boost the _current_. That, in turn, actually means that the signal is more immune to interference, though when the original source was low-impedance then the balanced connection after a passive DI is plenty stable for any realistic XLR connection.
Comment: Thanks for the reply. I was thinking I wouldn't have to use a DI, as yes, he will be playing probably no more than 4ft from the computer. I had a practice session and I was getting huge amounts of hum. I understand that this could be the pickups picking up interferance from somewhere. As we cant practice at the venue until the day, I figured it would be best to try and prevent it in any way possible, so I'm going to get one just to be sure. The interface will be a Scarlett, which accepts instrument level input, so would you reccomend a passive DI?
Comment: I'd go passive if money is an issue. Or borrow whatever you can. However hum sounds more like a ground loop or a dodgy lead (or a fault in the guitar's electrics). You wouldn't expect "massive amounts of hum" from a 10ft guitar lead.
Comment: Okay thanks for the info. I'll go ahead and get one. It may not solve it if it is an issue with something else but at least I'll have one for the future. Thanks again!
Comment: Sorry, but that's _totally_ not the crucial difference between a passive and active DI.


If n isn't mth power of any natural number then prove $n^{\frac{1}{m}}$ is irrational

Question: :I just asked another question in here
If $(a,b)=1$ and $(\frac{a}{b})^m=n$ then show $b=1$
Which we can get If $(a,b)=1$ and $(\frac{a}{b})^m=n$ then $b=1 or -1$
Here is another question:
If n isn't mth power of any natural number then prove $n^{\frac{1}{m}}$ is irrational.
So we use contradiction and assume :$\sqrt[m]{n}=\frac{a}{b} ,(a,b)=1$ so we want to show there is no a and b that (a,b)=1
But according to the previous question of mine we know b is 1 or -1
So (a,b) would be actually 1
And it shouldn't be to $n^{\frac{1}{m}}$ to be irrational
Am I misunderstanding something here?
Comment: Do you mean "is irrational" instead of "is rational"?
Comment: @RobertIsrael yeah sorry
Answer: If $b=\pm 1$, then $n=(\pm a)^m$ and hence a $m$-th power. Contradiction
Comment: thank you so much for your answer but can you tell me what's the flaw in my deduction?
Comment: There is no flaw in your deduction; you've simply stopped too soon. The contradiction you are looking for is not that there exist no $a,b$ with $(alb)=1$ such that $\sqrt[m]{n}=\frac ab$. The contradiction is that this would lead to $b=\pm 1$ and, hence, $n$ would be a $m$-th power, yet we assumed that $n$ is no $m-$th power. Contradiction!
Comment: thank you so much

If n isn’t mth power of any natural number then prove $n^{\frac{1}{m}}$ is irrational


Adding Contextual Links to Ctools Custom Content Type Plugin

Question: Ctools custom content type called Custom Panes shows contextual links when you have access permission and you hover over the pane (much like a block shows the contextual links) which allows you to easily configure the content of the pane.  After creating my own plugin that is similar to Custom Panes content type (with a few custom fields), I noticed that I do not have contextual links when I hover over my custom panes. I'm wondering if I can set that in the $plugin definition to show contextual links or what the work around would be.  I found the template function the panels uses to template_preprocess_panels_pane(&$vars) which actually looks for $vars['content']->content['#contextual_links'].  I'm wondering if there is a way to add contextual links to custom ctools content type plugins?
Any advice would be great!
Answer: You don't need to do that, what you can do is you can implement a hook_menu_alter and do this.
function YOUR-MODULE_menu_alter(&$items) {
  $items['YOUR-PLUGIN-PATH/%ctools_export_ui/edit']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

and then add your contextual link to your object. If it a block you can add below code in to your hook_block_view.
$block['content']['#contextual_links'] = array(
  'YOUR-CUSTOM-PLUGIN' => array('YOUR-PLUGIN-PATH', array($delta, 'edit'))
);

Answer: Inside the render callback of your custom CTools Content Type include file you can provide admin_links.
Here is an example pane that has a companion edit page at URL admin/config/custom/my_custom_pane_settings
<?php

$plugin = array(
  'title' => t('Custom Pane'),
  'single' => TRUE,
  'render callback' => 'my_custom_pane_render',
  'defaults' => array(),
  'category' => t('Page elements'),
  'edit form' => 'my_custom_pane_edit_form',
);

function my_custom_pane_edit_form($form, &$form_state) {
  return $form;
}

function my_custom_pane_render($subtype, $conf, $args, $context) {

  // Output.
  $block = new stdClass();

  // Define pane title & content.
  $block->title = 'Default pane title';
  $block->content = 'My custom pane content';

  // Add custom contextual links.
  $block->admin_links = array(
    'my_custom_pane' => array(
      'title' => t('Edit my custom pane'),
      'href' => 'admin/config/custom/my_custom_pane_settings',
      'query' => array(
        'destination' => current_path(),
      ),
    ),
  );

  return $block;
}


Expand existing RAID1 zpool into RAID10 zpool

Question: I'd like to expand/convert my existing RAID1 (2x 3TB mirror) zpool to RAID10 zpool by adding 2 more 3TB HDDs without losing (or moving) data stored on my existing pool.
The final result will look like 2x3TB (existing mirror) + 2x3TB (new mirror) combined into RAID0 zpool
Is it possible?
Answer: Yes, it's possible. The incantation you are looking for is:
zpool add poolname mirror newdisk1 newdisk2


Getting errors while creating trigger function from .sql file in postgres

Question: I'm trying to inject .sql file like xyz.sql in that I have created some triggers and in another file I'm implementing this function but I'm getting these errors in.
Maybe I am missing syntax, because the same is running in PostgreSQL editor but I have to write in .sql file, please check this combined image
Comment: Show us the Java code that runs those scripts - **[Edit]** your question - do **not** post code or additional information in comments.
Comment: Okay I will not write next time,
Answer: On the create trigger section, the ending semi-colon is missing.
PS: in the future, please copy-paste the code and error, not a screenshot of it
Comment: Even though after adding semicolon it is showing same error.


Does marginal likelihood have closed-form solution for hyperparameters in Bayesian linear regression?

Question: We know that marginal likelihood has the following form in Bayesian linear regression,
$$
\mathbf{K} = \sigma_w^2XX^T + \sigma_n^2I\\
p(\mathbf{y}|X) \sim \mathcal{N}(0, K)\\
\log p(\mathbf{y}|X) =
  -\frac{1}{2} \mathbf{y}^{T}
                K^{-1}
               \mathbf{y}
  - \frac{1}{2}\log|K|
  - \frac{n}{2}\log (2 \pi)
$$
Can we estimate $\sigma_n$ and $\sigma_w$ in closed form by maximizing log marginal likelihood or with any other way (other than numerical methods such as gradient descent)? I am also interested to know if this is possible for Gaussian process regression where $K$ could be RBF or Matern or any other kernel?
Answer: That is the exact procedure used in GP. Kernel parameters obtained by maximizing log marginal likelihood. You can use any numerical opt. method you want to obtain kernel parameters, they all have their advantages and disadvantages. I dont think there is closed form solution for parameters though.
Comment: I see. Thanks for your answer. I could relate it to GP that way but intuitively thought that linear regression being the simplest model may have some trick.
Answer: This blog post gives the answer I was looking for. There is a method to estimate $\sigma_w$ and $\sigma_n$ parameters for linear regression that is computationally far better than fitting a GP with linear kernel.


Caractere inválido em arquivo .bat

Question: Senhores !
Tenho um arquivo .bat que utilizo para iniciar o Apache Tomcat da minha aplicação em modo de debug. Porém ao executar este arquivo no CMD, a primeiro coisa exibida é a seguinte mensagem:
'´╗┐' não é reconhecido como um comando interno
ou externo, um programa operável ou um arquivo em lotes.
Ressalto que após isto, o script funciona normalmente, porém gostaria de saber se alguém já passou por algo semelhante ou conhece alguma solução. Eu havia tentado refazer o mesmo, porém o erro persiste.
Segue abaixo o conteúdo do arquivo:
@echo off

echo.

rd /s /q C:\tomcat\work\
rd /s /q C:\tomcat\conf\Catalina\
del /s /q C:\tomcat\logs\*
del /s /q C:\tomcat\temp\*
del /s /q C:\tomcat\webapps\sa\WEB-INF\web.xml.template
del /s /q C:\tomcat\webapps\sa\META-INF\context.xml.template

echo.

set CATALINA_HOME=C:\tomcat
set CATALINA_BASE=C:\tomcat
set JAVA_HOME=C:\java\jdk7
set INSTANCE=C:\instance

set CATALINA_OPTS=-Xms256m -Xmx512m -XX:MaxPermSize=256m

set CATALINA_OPTS=%CATALINA_OPTS% -Dfile.encoding=UTF-8
set CATALINA_OPTS=%CATALINA_OPTS% -Djava.awt.headless=false
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote.port=9014
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote.ssl=false
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote.authenticate=false
set CATALINA_OPTS=%CATALINA_OPTS% -Dorg.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false
set CATALINA_OPTS=%CATALINA_OPTS% -Duser.timezone=America/Sao_Paulo
set CATALINA_OPTS=%CATALINA_OPTS% -Duser.language=pt
set CATALINA_OPTS=%CATALINA_OPTS% -Duser.region=BR
set CATALINA_OPTS=%CATALINA_OPTS% -Dsun.java2d.noddraw=true
set CATALINA_OPTS=%CATALINA_OPTS% -Dsun.java2d.d3d=false
set CATALINA_OPTS=%CATALINA_OPTS% -Xdebug
set CATALINA_OPTS=%CATALINA_OPTS% -Xrunjdwp:transport=dt_socket,address=8990,server=y,suspend=n

%CATALINA_HOME%\bin\startup.bat

Comment: Tem certeza que é esse bat e não o startup.bat? Se você copiar o conteúdo desse bat tal como esta aqui e salvar em outro arquivo bat  e executa-lo o erro também ocorre?
Comment: Oi Reginaldo ! O problema está neste .bat provavelmente, pois o erro é exibido na tela antes da primeira ação do script e a chamada do startup é o último passo. Ressalto que sim, tentei recriar o .bat conforme tua sugestão e o erro persistiu. Obrigado !
Comment: Salvar o arquivo com padrão ANSI, e teste.
Answer: O seu arquivo possivelmente foi salvo com UTF-8 COM BOM (BOM sendo a abreviação de BYTE ORDER MARK) no bloco de notas, ou seja no topo do documento .bat ou qualquer tipo de documento, quando é salvo com UTF-8 BOM é adicionado um caractere chamado byte-order mark, que já foi citado em algumas perguntas aqui no site, mais detalhes sobre o BOM em utf-8 e outros como utf-32 em:

https://pt.wikipedia.org/wiki/Marca_de_ordem_de_byte

Basicamente o seu .bat pensa que esse caractere chamado byte-order mark é um comando, no caso o caractere unicode U+FEFF é imprimido como ´╗┐, o .bat procura então um programa com tal nome, o que provavelmente não existe, ocasionando assim o erro de comando ou programa não reconhecido.
Criei um exemplo salvando em UTF-8 via Bloco de Notas do Windows:
@echo off

echo Oi

pause

No caso deixei uma linha antes do @echo off e logo ao executar ocorreu o mesmo erro:

Veja que é o mesmo caractere ´╗┐

Se deseja usar UTF-8 você deve salvar com UTF-8 sem BOM ou usar ANSI (ou qualquer formato compatível), vai depender da necessidade.
Se desejar ainda sim usar UTF-8 você deverá fazer uso de um programa mais avançado, como notepad++ que pode ser baixado em:

https://notepad-plus-plus.org

Abra o seu .bat nele e salve assim:

Se utf-8 não for necessário para ti no proprio bloco de notas do windows selecione Salvar como... e selecione ANSI:
Answer:
Possivelmente seu problema não esteja no batch, mas na página de caractere usada no sistema na pela interface do prompt/cli, sugiro dar uma verificada nas configurações das chaves:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
OEMCP="850"

Verifique se figura algo diferente de 850 ou 1252, caso esteja outro valor, é só mudar 850, ou 1252
Para verificar na linha de comando, use:
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage" | findstr "OEMCP"

rem :: o comando retorna a saída assim :: OEMCP    REG_SZ    850

Para alterar usando a linha de comando você pode usar o comando abaixo, observando que necessário executar como administrado:
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage" /v OEMCP /t reg_sz /d 850 /f

Já tive problemas quando precisava da exibição de um caractere que figurava no chcp 65001, após eu mudar o valor na chave, retornando para o padrão chcp 850, meus batchs pararam de exibir essa mesma mensagem com estes caracteres..
tem post que me ajudaram:
esse foi 1
esse foi outro

Caractere inválido em arquivo .bat


Any technical reason to install "real" windows to run a hyper-v only server?

Question: Please ignore licensing questions here.
Is there any technical reason not to "only" use Hyper-V Server (the free version) to run a Hyper-V cluster? From a pure feature comparison it looks like the Hyper-V-Server is as capable as the other servers (while the pre r2 version had missing features) for a pure hyper-v role.
Answer: From a capability standpoint, Hyper-V Server R2 is essentially the same as the Hyper-V role on a Windows Server 2008 R2 installation.
From a "technical limitations" standpoint, going with Hyper-V server is actually better than going with Windows Server 2008 R2 Standard. Hyper-V Server R2 supports up to 1TB of memory and 8 (multi-core) CPUs. Windows Server 2008 Standard supports up to 32GB of memory and 4 (multi-core) CPUs.
If you compare memory/CPUs to Windows Server 2008 Enterprise or Datacenter, then Hyper-V starts to fall a little short. Enterprise supports 2TB memory and 8 CPUs, Datacenter supports 2TB and 64 CPUs.
I know you said to ignore licensing - but the other big factor is the included free guest licenses on Windows 2008 Server. Hyper-V Server includes none. Standard includes 1 free guest OS license, Enterprise includes 4, and Datacenter allows unlimited. You need to do the comparison between purchasing guest OS licenses or purchasing the "upgraded" host OS and using the included licenses.
Comment: Well at least the answer will serve as good info for google users who are finding this question, who most likely won't have SPLA licensing. :)
Comment: Actually licenses are to be ignored because you can always install hyper-v server and "assign" an enterprise license to the server - so there is no difference here. I work in an environment where the server is licensed under SPLA anyway, so licensing can change every month - and want to keep freedom. Hyper-v server allows me to relicense the server "free" should only linux run on it in a given month. So, licensing is  non-issue for the selection - actually I will mostly pay for datacenter.
Comment: @TomTom: are you sure that is true? Based on the Hyper-V FAQ "What sorts of upgrades are permitted?..." I would say it is not. http://www.microsoft.com/hyper-v-server/en/us/faq.aspx
Comment: It is nto an upgrade, and rules under SPLA are different. Basically I RUN physical hyper-v server, PAY (monthly) physical Datacenter Edition and use the datacenter virtualization rights. This is not an upgrade. Actually in THIS case, the whole EULA is void - relevant for me are the SPUR (Service Provider Usage Rights), a separate 2xx page document for everything licensed under SPLA.
Comment: I am mostly concerned "falling short" in technical capabilities. But yes, looks like unless I go more than 8 sockets (which I do not) it is identical to datacenter in all the rest. So, I will use it ;)
Answer: As Sam Cogan mentioned, it will be a core install. Make sure all of your drivers, network card utilities, backup solutions, etc will work just fine on Core before going ahead.
Also be aware that managing Hyper-V Server outside of a domain (aka workgroup) requires a lot of extra configuration (I believe this is the same for Server 2008 Core but only have experience with H-V Core).
Answer: If all you want to do is run Hyper-V then I do not believe that there is any reason not to just use Hyper-V Server. Bear in mind that is a core install, so no GUI just cmd line. Obviously most of the work you do on it will be from the Hyper-V mmc, so that's not too much of an issue.
Comment: Actually the other servers would be enterprise upward core installs also - so that is a total non-difference (who installs full servers in larger scenarios?). I am mostly concerned about things like memory limits etc. coming back and biting me in half a year.
Answer: technical reason not to "only" use Hyper-V Server (the free version) to run a Hyper-V cluster? From a pure feature comparison it looks like the Hyper-V-Server is as capable as the other servers (while the pre r2 version had missing features) for a pure hyper-v role.
Comment: Does this actually answer the question? Feels more like just a comment. Can you add some more details to make this more?