How can one prove that the resulting projection onto a "canvas" of a conic is still a conic?

Question: In one of my recent exams from an analytical geometry course, we were asked to prove that the resulting image of the projection from a point onto a plane of an ellipse, is still an ellipse. I had no problem understanding a given proof that used analytical geometry arguments.
I was wondering, however, how one could prove that (or a more general) result using only arguments from pure/synthetic geometry, i.e., that the resulting image of the projection from a point onto a plane of a conic, is still a conic.
To be precise, I'm considering the projection from a point $\overrightarrow{P_0}$ onto a plane ($\alpha$) of a point ($\overrightarrow{P}$) in space as the point obtained when intersecting the line $\overrightarrow{P_0}+t(\overrightarrow{P_0}−\overrightarrow{P_0}$) and the plane $\alpha$.
Thanks in advance!
Answer: I think the best approach would be to use the properties of an ellipse in terms of directrix and foci and eccentricity, and demonstrate that those properties remain the same or proportional.  For example, it should not be hard to show that a line projects onto a line, and a point projects onto a point.  So you could make an image of the directrix $D$, and an image of the focus $F$, and for an arbitrary point on the curve $Q$ show that its image $Q'$ shares the same ratio of distances $QF/QD$ as the original.  That would prove that the image is an ellipse, and the proof should generalize to all conic sections.
Comment: Thank you for your input, that is definitely one way to go about it. Hopefully, I`ll get somewhere with this approach.
Answer: In the synthetic approach of Apollonios of Perga's Conics, a conic section is generated by cutting a conic surface with a plane, as in the figure below.
Thus it seems any conic section, such as ellipse $EFG$, can be  projected from the cone's vertex at $P$ either onto the plane of the cone's base to produce circle $ABC$, or onto a plane parallel to $PA$ to produce a parabola $DJK$, or onto any other plane intersecting the conic surface, to produce any other possible sections of the given cone.
Comment: Good to see a reference to the Greeks. Mine refers to a late (19th century) treatment.
Answer: I advise you to have a look here more precisely in the section "Two theorems" and the figure therein. It is based on the understanding of the so called "Dandelin spheres".
They allow a rather simple geometrical proof of the fact that the image of a circle on a certain base plane becomes an ellipse on a slant plane by using the characterization of an ellipse as the set of points such that the sum of distances to its foci is constant.
One can also, by similar means, obtain hyperbolas or parabolas.
Comment: Thank you, for your answer. I understood how we may obtain these curves by means of intersecting a plane with a cone. I also see how one of those theorems proves that a particular case of an ellipse is taken to another ellipse when projected through a point onto a plane. However, I would like to see that conic sections are taken to other conic sections under the same transformation.


High jumping tactile target or bell

Question: I have a kid that plays basketball and he's always running around the house jumping to see what he can reach and to improve his jump height.
Does a "thing" exist that has targets that he can jump for that vary in height that have an audible noise and/or tactile feel?
I could, for example, buy a bunch of small bells and hang them from strings on a pole. Each of the strings having varying lengths from long on one end to short on the other and then attach that pole to a door frame or arch in the house. However I feel that this isn't an original idea and that someone must have come up with a better solution than I've just described. (Or perhaps there's a product and my Google Foo is failing me?)
Comment: Are you seeking this to help him develop his capability, or to provide an alternative outlet for slapping/smacking your doorframes/ceilings/chandeliers/very tall uncle's forehead?
Comment: In the NFL combine - they use something [like this](https://www.amazon.com/Tandem-Vertical-Challenger-Stand-Alone-Measurement/dp/B001BL52MI) (amazon link) for measuring a player's vertical jump height - the idea being you try and hit the "veins" to measure how high you have jumped. Although, having a quick look about, they seem _veeery_ expensive for what is essentially a metal pole and some rotating bits of acrylic :D
Comment: @Nij both. I don't mind him jumping and hitting all those things (his uncle gets annoyed) I just wanted to have something that's more fun for him and his friends to jump at that would at the same time encourage his jumping practice.
Comment: @ImClarky I had completely forgotten about those poles and I don't think that I've ever seen one in person and perhaps just a picture once. Having something like that would be amazing. I'm wondering if an indoor version of that could be created that could be hung off a frame or ceiling that functioned in a similar manner...
Comment: I'll leave this open as seeking equipment for training in a particular sport.
Answer: In the end I bought some dog bells online and fashioned a 2x1 as in the image and hung 2 bells per string at varying lengths for him to jump and hit. A very amateur solution but it seems to be working so far and he seems to be enjoying it. It achieves the sport objective of helping him (1) practice jumping and (2) measure improvement over time as he moves to higher ones.
Slo-mo of the contraption in action

High jumping tactile target or bell


Rsync / Sqlite database

Question: Does anyone have ever tried rsync'ing sqlite database?
Is it possible to access the data while it gets syncronised?
Answer: I would consider this dangerous.
The SQLite database also has journal files that need to be preserved.
If you

rsync the database without the journal files in the middle of a transaction
copy the database file
access the copy

It is highly likely that you will experience corruption.
Use the  SQLite Online Backup API  instead.
Answer: Assuming you'd like to do this via shell commands, you could do something along the lines of:
ssh user@host 'sqlite3 "/path/to/db.sqlite" ".backup /path/to/dbbackup.sqlite"'
rsync user@host:"/path/to/dbbackup.sqlite" "db.sqlite"

Which first, safely creates a backup of the existing database, and then copies it to "db.sqlite" on your own machine.
Answer: As Noah have pointed, it is dangerous. Your database will get corrupted.
You can use the litereplica library instead.
It does all the work behind the scenes respecting the normal SQLite transaction. And incrementally (only the changed pages are transferred).
Or the rqlite library.
This last one requires the installation of the Go language.
Answer:
While no transaction is open, rsync of the database will be OK.
While a transaction is open, rsync of the database will result in corruption.  Reason: you'll be getting the database and its accompanying journal file at a slightly different point in time, breaking the consistency that would allow SQLite to reconcile the journal with the database.  If SQLite cannot reconcile the journal with the database, then the database will be left in an inconsistent state with no way to tell what was part of a partially applied transaction.

In order to be able to rsync an SQLite database, you will need to either:

Use SQLite's own CLI commands for creating a backup copy of the database file.  This will wait to gain a write lock, and copy the file, then release the write lock, thus ensuring no transactions are partially applied.  Then, rsync the copy.
.backup ?DB? file

Or, shut down all processes using the SQLite database while you are doing the rsync.
Answer: For those looking for a more safer solution, to replicate and backup SQLite in realtime, without interrupting its operations, checkout Litestream - Litestream is a tool that runs in a separate process and continuously replicates a SQLite database to Amazon S3.
Answer: No, sqlite databases aren't constantly coherent by default.  However, a search on "sqlite copy file" has found a page on doing online backups with SQLite, which I suspect will cover all the issues you may have.
Answer: The previous answers are correct.
But if you make 100% sure there is only read activity on your database you can safely take any kind copy of the database file. I've done this in a production application for ages without issues (cp, tar, rsync, scp, sftp). The database file is set read only at os level (chmod a-w) and database write attempts give an error
Error: attempt to write a readonly database

while all selects work normally.
Then, of course, this approach may or may not be feasible regarding you application. The same approach can be used to prevent unauthorized writes like SQL injection on a web application.

Rsync / Sqlite database


Fixar thead ao rolar a tabela

Question: Possuo a table abaixo gostaria de fazer um scroll nela e fixar a thead ao rolar para baixo.

Código HTML até agora:

                        Cnpj
                        Cliente
                        QtDiasUltMovimento
                        Titulos vencidos não pagos
                        Valor do Frete do Mes Anterior
                        Valor do Frete do Mes Atual

                    //foreach

                    //end foreach

                        Total:

Código CSS:
.TableCSS table {
    font-size:12px;
    color:#ffffff;
    width:100%;
    border-width: 1px;
    border-color: #a9a9a9;
    border-collapse: collapse;
    zoom: 100%;
    text-align:left;
}
.TableCSS th {
    white-space: nowrap!important;
    font-size:12px;
    background-color:#ffffff;
    border-width: 1px;
    padding: 3px;
    border-style: solid;
    border-color: #a9a9a9;
    text-align:left;
    padding-bottom: 0px;
    padding-top: 0px;
    font-style: italic;

}
.TableCSS tr {
    background-color:#ffffff;
    padding-bottom: 0px;
    padding-top: 0px;
    text-align:center;
}
.TableCSS td {
    font-size: 12px;
    border-width: 1px;
    padding: 3px;
    border-style: solid;
    border-color: #a9a9a9;
    text-align:left;
    background-color: #ffffff;
    padding-bottom: 0px;
    padding-top: 0px;
    color: black;
}

Comment: Possível duplicata de [Fixar primeira linha tabela](https://pt.stackoverflow.com/questions/44546/fixar-primeira-linha-tabela)
Comment: As duas theads?
Comment: Uma somente, mas se tiver como fixar a de baixo na parte inferior também.
Comment: E por quê exatamente existem duas `thead` na tabela?
Comment: Erro meu, editei a pergunta vê se da para entender melhor.
Answer: Você pode usar jQuery para fazer a linha do thead acompanhar o scroll da janela alterando o top de forma dinâmica. É necessário que o elemento tenha position: relative, por isso coloquei no CSS:
*{
    position: relative;
}

Se você usa algum framework que já seta position: relative aos elementos, não precisar colocar o CSS acima.
Veja o exemplo:

$(window).on("scroll load", function(){

   var tabela_top = $(".TableCSS table").offset().top;
   var window_top = $(this).scrollTop();

   $(".TableCSS table thead th").css({
      'top': tabela_top-window_top <= 0 ? window_top-tabela_top+'px' : '0',
      'z-index':'9',
      'padding':'10px 0'
   });
});
*{
   position: relative;
}
      .TableCSS table {
    font-size:12px;
    color:#000;
    width:100%;
    border-width: 1px;
    border-color: #a9a9a9;
    border-collapse: collapse;
    zoom: 100%;
    text-align:left;
}
.TableCSS th {
    white-space: nowrap!important;
    font-size:12px;
    background-color:#ffffff;
    border-width: 1px;
    padding: 3px;
    border-style: solid;
    border-color: #a9a9a9;
    text-align:left;
    padding-bottom: 0px;
    padding-top: 0px;
    font-style: italic;

}
.TableCSS tr {
    background-color:#ffffff;
    padding-bottom: 0px;
    padding-top: 0px;
    text-align:center;
}
.TableCSS td {
    font-size: 12px;
    border-width: 1px;
    padding: 3px;
    border-style: solid;
    border-color: #a9a9a9;
    text-align:left;
    background-color: #ffffff;
    padding-bottom: 0px;
    padding-top: 0px;
    color: black;
}

Tabela

                  Cnpj
                  Cliente
                  QtDiasUltMovimento
                  Titulos vencidos não pagos
                  Valor do Frete do Mes Anterior
                  Valor do Frete do Mes Atual

                  a
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  1
                  1
                  1
                  1
                  1
                  1

                  Total:

Comment: @Kevin.F Segue um exemplo no JSFiddle: https://jsfiddle.net/fLxd0fL7/
Comment: Ficou legal porém, não tem como deixar a `thead`com mais `heigth` quando ela desce ? Pois ela não fica do mesmo tamanho quando está fixa la em cima.
Comment: @Kevin.F Sim. Adicionei padding à thead de `10px 0`. Assim ele fica mais alta. Atualizei na resposta.
Comment: Agora ta bom, outra dúvida vamos supor que eu tenho uma `div` com scroll, dentro desta `div` tem a `table`  a página em si não rola somente a `div`, tem como eu deixar a `thead` no topo da `div` e não da pagina ?
Comment: @Kevin.F Tem sim.

Fixar thead ao rolar a tabela


Popular select de paises e estados com php mysql ajax

Question: Tenho 2 selects: #pais e #estado.
Quero que ao selecionar o país, ele popule o estado apenas com os estados desse país, que estão gravados numa tabela mysql:
tabela_paises
id|pais
 1|brasil

tabela_estados
id|idpais|estado
 1|  1   |São Paulo

o select do país já traz por uma query, os valores da tabela_paises
$db =& JFactory::getDBO();
$db->setQuery("SELECT pais FROM tabela_paises ORDER BY pais ASC");
$results = $db->loadObjectList();
$items[] = "- Nenhum -";
foreach ($results as $res){
$items[] = $res->pais;
}
return implode("\n",$items);

Mas para o estado não sei como fazer para pegar o id do pais como filtro, pensei em algo como abaixo, mas nesse caso o id está fixo, ele precisa ser dinamico
$db =& JFactory::getDBO();
$db->setQuery("SELECT estado FROM tabela_estados WHERE idpais = 1 ORDER BY estado ASC");
$results = $db->loadObjectList();
$items[] = "-  Nenhum -";
foreach ($results as $res){
$items[] = $res->estado;
}
return implode("\n",$items);

Comment: Como você está fazendo para enviar a informação para o servidor?
A página é toda carregada ou por ajax? Você precisa definir como deve chegar o id do estado por parâmetro na requisição.
Answer: Quando selecionar um país, tu precisa fazer uma consulta com ajax no arquivo que tu faz o select no banco para listar os estados.
Nesse arquivo deixei o id do pais como $_POST['pais'], mas aí tu adapta pro jeito que tu tá definindo o tipo de requisição. Então tu retorna esses resultados para o ajax através do json_encode.
Por último tu percorre esses dados com um for e adiciona eles dentro do select de estados.
PHP
$db =& JFactory::getDBO();
$db->setQuery("SELECT estado FROM tabela_estados WHERE idpais = $_POST['pais'] ORDER BY estado ASC");
$results = $db->loadObjectList();

foreach ($results as $res) {
    $estados[] = array(
      'id'  => $res->id,
      'nome' => $res->estado,
  );
}

return json_encode($estados);

JAVASCRIPT
$(document).ready(function() {
  $('#pais').on('change', function() {
      var pais = $(this).val();

      $.ajax({
        url: 'estados.php,
        type: 'POST',
        data: { pais : pais },
        dataType: 'json',
        success: function(data) {
          var options = '<option value=""></option>';

          for (var i = 0; i < data.length; i++) {
            options += '<option value="' +
              data[i].id + '">' +
              data[i].nome + '</option>';
          }

          $('#estados').html(options);
        }
    });
  });
});


OG how to contrain a group to a maximum number of users

Question: I would like to restrict groups to a certain amount of members. Is there any ways to do so?
Answer: Organic Groups join limit
This module allows to set a join limit on a specific group.
Comment: What's the solution for Drupal 7?
Comment: https://drupal.org/node/1347870 - looks like owner of this module doesn't support it yet. Anyway, I assume it can be accessed via Rules module...


Use the Sandwich Theorem to evaluate the limit $\lim_{x\to \infty} \frac{\lfloor x\rfloor}{x}$

Question: Where $⌊x⌋$ is the largest integer not exceeding $x$, use the sandwich theorem to evaluate  $\lim_{x\to \infty} \frac{⌊x⌋}{x}$ and  $\lim_{x\to -\infty} \frac{⌊x⌋}{x}$
I am unsure what functions to sandwich this between in order to prove the limit?
Answer: Hint:
For $x\in\mathbb{R}$,
$$x-1 < \lfloor x\rfloor \leq x.$$
Answer: Note that $x-1<\lfloor x\rfloor\leq x$.
Hence, $\frac{x-1}{x}<\frac{\lfloor x\rfloor}{x}\leq \frac{x}{x}=1$.
It follows that we can take limits to form a sandwich, $\lim_{x\rightarrow a}\frac{x-1}{x}<\lim_{x\rightarrow a}\frac{\lfloor x\rfloor}{x}\leq \lim_{x\rightarrow a}1$.
Taking $a\rightarrow\pm\infty$ would result in a limit of 1.


How to add a field to menus?

Question: I am trying to add an extra text field to the menu entity. My field is showing up and saving input but the input saves for all menus not just the one I entered the data for.
This is how it is now:
function myModule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'menu_edit_form') {
    $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
    $my_field = $config->get('my_field');
    $form['my_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $my_field,
    '#weight' => '0',
    '#required' => FALSE,
    );

    $form['actions']['submit']['#submit'][] = 'myModule_menu_edit_submit';
  }
}

function myModule_menu_edit_submit($form, $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set('my_field', $form_state->getValue('my_field'))->save();
}

I need to save different data for each form, so I was trying to do change the submit function to:
function myModule_menu_edit_submit($form, $form_state) {
  $key = $form_state->getformObject()->getEntity()->id();
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set($key, $form_state->getValue('my_field'))->save();
}

If I do this though, when I enter the data in the field and save, it says updated successfully but the field is blank. Not sure what I'm doing wrong.
Comment: There is a module for that(TM)  - https://www.drupal.org/project/menu_item_extras
Comment: Did you install the module or re-install if already installed? By the way, using the field is not so easy because the menu link entity is behind a menu link plugin which has methods only for the standard fields. See https://drupal.stackexchange.com/questions/235754/get-menu-link-item-from-menulinktreeelement
Comment: @Hudri So I want to add the field to the actual menu where you add/edit the actual menu, not the menu links. Does that module work for my situation as well?

@4k4 I haven't tried reinstalling the module. Do you think making a ```hook_update_N``` and putting my code in that and then doing a ```drush updb``` would work?
Comment: The module is for menu links (this individual items below a menu). The menu itself is not a fieldable content entity, you can't add content fields there. A menu is a configuration entity, you only can add 3rd party config settings there.
Comment: Example for menu 3rd party setting: https://git.drupalcode.org/project/menu_trail_by_path/-/blob/8.x-1.x/menu_trail_by_path.module
Comment: @Hudri So I tried with hook_form_FORM_ID_alter before trying this method and the field did show up but I had no idea how to get the data input for the field to save/load.
Comment: @Hudri I updated my question. I got it working somewhat but not exactly as I need it. Any suggestions?
Answer: I figured out how to add a field to the menus (not menu links, the actual menus). I use the machine name of the menu's title as a key and store the value with the key I use in the $form variable.
Here is my code:
function myModule_form_menu_edit_form_alter(&$form, $form_state, $form_id) {
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $my_field = $config->get(str_replace('-', '_', $form_state->getformObject()->getEntity()->id()));

  $form['my_field'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => $my_field,
  '#weight' => '0',
  '#required' => FALSE,
  );

  $form['actions']['submit']['#submit'][] = 'myModule_custom_submit';
}

function myModule_custom_submit($form, $form_state) {
  $key = str_replace('-', '_', $form_state->getformObject()->getEntity()->id());
  $config = \Drupal::service('config.factory')->getEditable('myModule.settings');
  $config->set($key, $form_state->getValue('my_field'))->save();
}

How to add a field to menus?


Can I calculate the correlation coefficient from the beta of fixed effects in a linear mixed model?

Question: I would like to determine a partial correlation from fixed effects in my linear mixed models.
If i would run a model for example  $Aij = \beta_0 + \beta_1X + \beta_2Y + \beta_2Z + ui$ + ϵij
Can I calculate a partial correlation coefficient for the $\beta_1$ to $A$ using the formula
$r= \beta_1 *(var(\beta_1) / \text{sd}(A))$ ?
Comment: What information do you have available for calculating?  Because the units of your proposed formula for $r$ are incorrect, it cannot possibly be right.  (The units of $\beta_1$ are in units of $A$ per unit of $X$, so the units for your $r$ are units of $A$ per squared unit of $X,$ rather than being unitless as required of any correlation coefficient.)
Comment: This formula is the rescaling formula between the correlation coefficient and regression coeficient (see this post [link](https://stats.stackexchange.com/questions/32464/how-does-the-correlation-coefficient-differ-from-regression-slope) . This is valid for a simple linear regression but is I am wondering if its valid to use in a more complex models as presented here
Comment: You haven't quoted the formula correctly.  What your readers will understand by "$\operatorname{sd}(\beta_1)$" (which makes no sense when read literally because $\beta_1$ is a *number*) is that it is the *sampling variance of the least squares estimate of $\beta_1.$*
Comment: Thank, indeed I mean the _se_ of the estimate for the ___β1___.  I will change it.
Comment: The units still are nonsensical.
Comment: How would you suggest writing it down? Might be my ignorance.
Comment: I would suggest reviewing the formulas you can [find here on CV](https://stats.stackexchange.com/search?q=partial+correlation+formula+is%3Aanswer).
Answer: One solution you can consider is the partR2 package in R (Stoffel et al., 2019). This allows you to derive a partial effect size for each fixed effects predictor. It is technically devised of two coefficients. The first is $part R^2$, defined below as:
$$
R^2_{x^*} = \frac{Y_X-Y_\tilde{X}}{Y_X+Y_{RE}+Y_R} = \frac{Y_X-Y_\tilde{X}}{Y_{Total}}
$$
where ${X}$ is the variance explained by fixed effects in a full model versus $\tilde{X}$, which is the variance in fixed effects from a reduced model. The denominator $Y_X + Y_{RE} + Y_R$ is essentially the total variance in the model (fixed effects + random effects + residuals). This effectively allows one to tease apart to a degree how much variance changes when the model is reduced down to remove the effect of other predictors. The second coefficient is $inclusive$ $R^2$, which is defined below:
$$
IR^2_{x*} = SC^2 * R^2_{x^*}
$$
where $SC^2$ is the squared correlation between a predictor of interest and a linear predictor times its $part R^2$. This coefficient quantifies the total proportion of variance explained in the model, both uniquely and jointly with other predictors.
Citation
Stoffel, M. A., Nakagawa, S., & Schielzeth, H. (2021). partR2: Partitioning R2 in generalized linear mixed models. PeerJ, 9, e11414. https://doi.org/10.7717/peerj.11414


Confusion. about the precise definition on $\infty$ in complex analysis

Question: In the complex analysis, we define a point $\infty$ on the complex plane. Then the textbook claims that (a) None of the semi-plane (all the points on one side of a fixed line) contains the $\infty$
(b) every line goes through the $\infty$. But (b) implies that $\infty  \in l$, $\forall$ line $l$. And we can now pick a line contained in the semi-plane by letting the line be parallel to the boundary of the semi-plane. Then $\infty$ is a member of the semi-plane, contradicts what (a) said. But what is wrong in the above argument? And what's the precise definition of $\infty  \in S$, $S$ a subset of $C\cup \{\infty\}$?
Comment: In another context, plane projective geometry, there is a whole line "at infinity", not a single point.
Answer: (a) and (b) are really definitions, though they may not be phrased that way. The textbook is saying that when they use the word "line" in discussing a subset of $\mathbb{C} \cup \{\infty\}$, it will include $\infty$ (i.e., it will include an ordinary line in $\mathbb{C}$ together with $\infty$), while when they use the word "semi-plane" it will not include $\infty$ (it will include just the ordinary semi-plane in $\mathbb{C}$).
If you want a precise description of how $\infty$ is included in the complex plane, look up "stereographic projection" of the sphere to the plane. But that doesn't really change the fact that (a) and (b) are just definitions of how we use the words "line" and "semi-plane" in the context of $\mathbb{C} \cup \{ \infty \}$.
For a justification for why this is a reasonable definition, you can think that since a line includes $\infty$, then a semi-plane is one component of the complement of the line, so the semi-plane will not include $\infty$. This does have the consequence that a line (extended to $\mathbb{C} \cup \{ \infty \}$) parallel to the boundary of a semi-plane, will no longer be contained in the semi-plane (which is really what your argument shows), which may seem weird, but there is no logical contradiction.
Comment: Thanks. If you do not mind my further further bothering, I am reading Ahlfors recently. And I raised this question since the book defined simply connected space by saying that its complement wrt $\mathbb{C}\cup\{\infty\}$ is connected. So how to define a connected set on $\mathbb{C}\cup\{\infty\}$? And this may have something to do with the definition of the open set on $\mathbb{C}\cup\{\infty\}$.
Comment: Topologically, $\mathbb{C} \cup \{ \infty \}$ should be regarded as a sphere, and $\mathbb{C}$ embedded in the sphere by stereographic projection.
Comment: Thanks. So I think that a point set $A\subset \mathbb{C}\cup\{\infty\}$ with $\infty$ a member is connected if for any point $x\in A-\{\infty\}$ there is a continuous curve $\Omega\subset A$ such that it starts from $x$ and there is a point sequence $\{x_n\}$ such that $x_n\rightarrow\infty$ as $n\rightarrow \infty$, so that on the sphere, any point in $A$ is connected to the north pole with a continuous curve contained in $A$, and then any two point in $A$ can be connected using a continuous curve in $A$. Is this definition reasonable?
Answer: The Riemann sphere is the one-point campactification of the complex plane (or $\Bbb R^2$).
It's well known that the standard $2$-sphere $S^2$ minus a point is homeomorphic, indeed diffeomorphic, to $\Bbb R^2$.
Anyway $\infty $ can be thought of as the added (or subtracted)  point.


Finding the limit of the integral of some uniformly convergant sequence of functions

Question: Let $\{f_n\}_{n\in \mathbb N}$ be a sequence of uniformly convergent functions on the interval [0,1]. Find the limit of the following integral: $$\lim_{n\to \infty} \int_0^1nf_n(t)e^{-nt}\,dt$$
Here is my thought process so far. In isolation l'hospital's rule would indicate that  $\lim_{n\to \infty} \frac{n}{e^{nt}}$ would tend to zero, and so I expect that this exponential term will be more dominating.
Normally Lebesgue's Dominated convergence theorem (or at the very least his monotone convergence theorem) would allow us to say that this uniformly convergent sequence of functions would converge to f...however I am guessing the surrounding terms sufficiently mess this up to the point where we no longer have convergence. My guess is the point of this question is to prove that this is the case.
We know that  $\lim_{n\to \infty}\{f_n\}_{n\in \mathbb N}$ is measurable, but If I can show that
$g_n= \frac{n}{e^{nt}}$ is not measurable for $t\in[0,1]$ (because it tends to zero), then can I say this limit does not exist? I'm pretty confused, as is abundantly clear hahahaha.
Comment: Note that $\int_0^1 ne^{-nt} f(t) \, dt = \int_0^\infty e^{-u} f(u/n) \mathbf{1}_{[0,n]} \, du \to f(0)$ by the DCT for continuous $f$.  What other conditions on $f_n$ might you have?
Comment: If the $f_n$ are continuous, then so is $f$ and $f_n(u/n) \to f(0)$ -- when there is uniform convergence.
Comment: That is a very clever thing to notice! However, I don't think it lines up with what I am supposed to be learning from this question. I'll update my attempt soon, but I'm working more with the Lebesgue definition of the integral and some basic convergence theorems...
Comment: This can be the Lebesgue integral.  Just with $f$ instead of $f_n$ the limit may not exist if $ \lim_{z \to 0+} f(z)$ does not exist.  So I'm wondering if you are missing some assumptions. Why only the very strong assumption of uniform convergence?
Comment: they are continuous! I'm sure your answer is correct, but I wonder if there is a way that follows more from the definitions and does not rely on a transform...just to help me understand it in terms of the fundamentals. I also think, part of it is to show the limitations behind EVEN uniform convergence...maybe(?)
Comment: Just also show $\int_0^1 ne^{-nx}[f_n(x)-f(x)]\, dx \to 0$.
Comment: The expanded version in the link really helps me follow what you did, thanks!
Comment: You're welcome.  I tied it together for you in the answer below.
Answer: Let $(f_n)$ be a sequence of continuous functions that converges uniformly to $f$ on $[0,1]$.  By the triangle inequality, we have
$$\left|\int_0^1 n e^{-nt} f_n(t) \, dt - f(0) \right|\leqslant \left|\int_0^1 n e^{-nt} (f_n(t) - f(t)) \, dt \right|+ \left|\int_0^1 n e^{-nt} f(t) \, dt - f(0) \right|$$
For the first term on the RHS, we have
$$\left|\int_0^1 n e^{-nt} (f_n(t) - f(t)) \, dt \right| \leqslant \int_0^1 n e^{-nt}|f_n(t) - f(t)|\, dt$$
As $f_n \to f$ uniformly, for any $\epsilon > 0$ there exists $N_1 \in \mathbb{N}$ such that if $n > N_1$, then $|f_n(t) - f(t)| < \frac{\epsilon}{2}$ for all $t \in [0,1]$, and
$$\left|\int_0^1 n e^{-nt} (f_n(t) - f(t)) \, dt \right| \leqslant \frac{\epsilon}{2} \int_0^1ne^{-nt} \, dt = \frac{\epsilon}{2} (1 - e^{-n}) < \frac{\epsilon}{2} $$
Thus, for all $n > N_1$,
$$\left|\int_0^1 n e^{-nt} f_n(t) \, dt - f(0) \right|\leqslant \frac{\epsilon}{2}+ \left|\int_0^1 n e^{-nt} f(t) \, dt - f(0) \right|$$
Since $f$ is the uniform limit of a sequence of continuous functions it is continuous, and the proof given here shows there exists $N_2$ such that if $n > N_2$
$$\left|\int_0^1 n e^{-nt} f(t) \, dt - f(0) \right| < \frac{\epsilon}{2}$$
Altogether this proves that
$$\lim_{n \to \infty}\int_0^1 n e^{-nt} f_n(t) \, dt = f(0)$$


$\lim_{x \to 1} \frac{\ln(x^3)}{x^2-1}$

Question: My first idea was to use the definition of derivative (but it's giving me the wrong answer).
$\displaystyle \lim_{x \to 1}\frac{\ln(x^3)}{x^2-1} =\lim_{t \to 1}\frac{\ln(t^{3/2})}{t-1} = \frac{3}{2}\lim_{t\to 0}\frac{\ln(t+1)}{t} =\frac{3}{2}\lim_{t\to 0}\frac{\ln(t+1)-\ln(1)}{t} = \frac{d}{dx}\ln(x)\bigg|_{x=1} = 0.$
But using L'hopital's rule I get $\displaystyle \lim_{x \to 1}\frac{\ln(x^3)}{x^2-1} =\frac{3\frac{d}{dx}\ln(x)}{\frac{d}{dx}(x^2-1)} = \frac{3}{2}\lim_{x \to 1}\frac{1}{x^2} = \frac{3}{2}.$
So where have I messed up in the first approach?
Comment: You have forgotten $\frac{3}{2}$ and do $x=1$ !!!after!!! derivating.
Comment: Wow! Simply shows that I need to spend more time on questions before posting them in here.
Answer: Your error is that
$$\frac{d}{dx} \ln x \big|_{x = 1} = \frac 1 x \big|_{x = 1} = 1$$

Here's a slightly different way that doesn't involve making a substitution before applying the definition of the derivative:
\begin{align*}
\lim_{x \to 1} \frac{\ln(x^3)}{x^2 - 1} &= \lim_{x \to 1} \frac{3}{x + 1} \frac{\ln x}{x - 1} \\
&= \frac{3}{1 + 1} \frac{d}{dx} \ln x \big|_{x = 1} \\
&= \frac 3 2
\end{align*}
as desired.
Answer: $\log x^3 = 3 \log x \sim 3(x-1)$ as $x \to 1$ using Maclaurin series
Comment: $\log x = - \log \frac{1}{1-(1-x)} \sim -(1-x) = x-1$, so you are right
Answer: We have
$$ \frac{3}{2} \lim_{t \to 0} \frac{\ln(t + 1) - \ln(1)}{t} = \frac{3}{2} \frac{\mathrm{d}}{\mathrm{d}x} \ln(x) \vert_{x = 1} = \frac{3}{2}.$$
You forgot the constant factor and $(\ln(x))' = \frac{1}{x}$ evaluated at $x = 1$ is $1$.
Answer: Observe that
$$
\frac{d}{dx}\ln(x)\bigg|_{x=1} = \left.\frac1x\right|_{x=1}=1.
$$

$\lim_{x \to 1} \frac{\ln(x^3)}{x^2-1}$


Accessing Postgres RDS from Kubernetes cluster in AWS

Question: My Kubernetes cluster setup has n-tier web application running in dev and test environments on AWS. For the production environment, postgres RDS was chosen, to ensure periodic backup. While creating a postgres RDS instance, kubernetes-vpc was selected for db-subnet to keep networking stuff simple during pilot run.
Also, security group selected is the same as kubernetes-minions.
Following is the service and endpoint yaml:
apiVersion: v1
kind: Service
metadata:
  labels:
    name: pgsql-rds
  name: pgsql-rds
spec:
  ports:
    - port: 5432
      protocol: TCP
      targetPort: 5432

--
apiVersion: v1
kind: Endpoints
metadata:
  name: pgsql-rds
subsets:
- addresses:
  - ip: 220.127.116.11
  ports:
  - port: 5432
    name: pgsql-rds
    protocol: TCP

When web-app service and deployment is created, it's unable to connect to RDS instance.
The log is as follows:
java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Connection to pgsql-rds:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
What am I missing? any pointers to resolve the issue appreciated.
Comment: I'm having a similar issue and trying to fix the problem. Are your Kubernetes cluster and your RDS instance behind two different VPCs? Likely, you need to use [VPC peering](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-peering.html). That doesn't seem to be the full solution though -- check out [this post](http://ben.straub.cc/2015/08/19/kubernetes-aws-vpc-peering/).
Comment: Shouldn't it try to connect to `pgsql-rds`?
Comment: @JohnA.Ramey, it's the same vpc for k8s cluster and rds instance  (kubernetes-vpc) as mentioned in the post.
Comment: @kichik, thanks for pointing out, it's a typo. I 've updated my post.
Comment: Did you ever get this working?
Answer: This has to do with DNS resolving. When you use the RDS dns name INSIDE the same VPC it will be resolved to a private ip. When you use the same dns name on the internet or another VPC you will get the public ip of the RDS instance.
This is a problem because from another VPC you can not make use of the load balancing feature unless you expose the RDS instance to the public internet.
Comment: This is sort of helpful in that it has some information, but it's not a solution.
Answer: It's been a while the issue was resolved.
Don't exactly remember now, which step I missed that caused connection problem.
But, below are the steps that did work for me.
Pre-requisite: kubernetes cluster is set up with vpc ('k8s-vpc')

Create VPC SUBNET
Go to vpc dashboard, ensure same aws region as k8s minion. (you will see existing 'k8s-vpc')
Create subnet with each availability zone.
Select 'k8s-vpc' as vpc from drop-down.
CIDR could be 172.20.16.0/24 or 172.20.32.0/24
Create DB SUBNET and SUBNET GROUP FOR  VPC of k8s minion if not already available.
Go to RDS Dashboard.
Create subnet group (e.g. my-db-subnet-group) for DB and  add all subnet from step 1 to create subnet group.
From RDS Dashboard create Parameter Group
(e.g. my-db-param-group) for Postgres (version 9.5 in this example)
Copy value for max_connections to the max_prepared_transactions field and save
Create RDS instance for Postgres DB
Launch DB instance -> select Engine Postgres -> Choose stage (Production or Dev/Test)
-> Give instance spec.s (instance type & disk space etc.) and specify DB settings (user/password)
-> Configure Advanced settings

vpc selection as 'k8s-vpc'
DB subnet should be one created in previous step (my-db-subnet-group)
VPC security group should be from Kubernetes minions - so that no additional config. required for access from minions
Select Publicly Accessible - to connect to postgres from internet
Select Parameter Group as 'my-db-param-group'.
Specify Database options, backup and maintenance options and finally launch the instance

Also check security group of VPC and add inbound rule to allow connection to postgres port.
You can test connection from one of the k8s pod (kubectl exec -it) where postgres client is installed.
Make sure to change user to postgres.
Connect to RDS using psql as shown below:
$ psql --host=my-rds-dev.cyhi3va0y2or.ap-northeast-1.rds.amazonaws.com --port=5432 --username=<masterUserName> --password --dbname=<masterDB>

If everything is set up correctly, it should prompt you for password of db user.
Providing correct password will finally connect to RDS.
This article was of great help.
Answer: Your IP is of the form: 184.108.40.206. This is a public IP. See the official RFC
Since you said both are in the same VPC, you could have used the internal IP address instead.
That said, the error "Connection to pgsql-rds:5432 refused" means that the address was resolved, otherwise you would get "psql: error: could not translate host name "psql-rds" to address: Name or service not known". Therefore, it is not a DNS issue as cited on another answer.
The cause of the block is likely that the security group was not configured to accept requests from the EC2 instance external IP address. This if the official AWS documentation on connecting to RDS scenarios.
You might have already whitelisted all connections from VPC, however double check the security groups. I would not recommend using a whitelist for the external IP address, however it works if you put the external IP address there. It is a security concern when you don't have an elastic IP address and there are data transfer costs unless you have a more complex setup.
That said, you could have avoided the Kubernetes resources and used the DNS address of the RDS instance.
If you had to avoid using the DNS address of the RDS instance directly, you could have used the following:
apiVersion: v1
kind: Service
metadata:
  name: psql-rds
spec:
  externalName: my-rds-dev.cyhi3va0y2or.ap-northeast-1.rds.amazonaws.com
  ports:
  - port: 5432
    protocol: TCP
    targetPort: 5432
  sessionAffinity: None
  type: ExternalName

With the setup above, you don't need a Kubernetes Endpoint. You can just use psql-rds, or any variation using the namespace as the domain or the fully qualified version, such as psql-rds.default. This is the documentation for the ExternalName
I see that the original poster mentioned the problem was solved, however it is not clear or well documented that the problem was a combination of using the external IP address and checking the security group rules.


Median value on ordinal scales

Question: I have been reading about appropriate measures of central tendency for ordinal level data.
So far I have learned that the median and mode can be used but that the latter can only be used in some cases. Some sources state that the median can only be used with Likert questions when there is an odd number of scores. It is not clear to me what this means and also which cases the median cannot be used.
Example:
An example may illustrate.

If there was a question: "Climate change is England's most serious environmental problem" on a response scale: 1=strongly agree 2=agree 3=unsure 4=disagree 5=strongly disagree. Would the median be 3=unsure?
What if no respondents stated disagree or strongly disagree and all 100 respondents stated either 1, 2, or 3, is the median then 2?
what if respondents only stated 2 or 3. In this case is it not possible to identify the median?
Comment: This is kind of a cool question, if only because I'm sure lots of people do this without thinking about it very hard.
Comment: Also, it's a good argument for restating questions along the lines of *"on a scale of 0-10, where 10 is absolute agreement, and 0 is absolute disagreement, what do you think of the statement: ..."*
Comment: This is a duplicate of https://stats.stackexchange.com/questions/158920/what-is-the-median-of-the-school-grades-a-a-b-b (and the accepted answer there is pretty good).
Answer: Definitional issues:

The median is the middle value of the data; it is not by definition the middle value of the scale.
When the sample size is even, then the median is the mean of the values either side of middle most point after rank ordering all values (see wikipedia description).

When to use median on ordinal data

In theory the median can be used on data from any variable where the values can be ordered.
In practice, the median is  often not the most useful summary of central tendency with ordinal variables.
This partially depends on what you want to get out of your measure of central tendency.
When you are describing the central tendency of data on an ordinal variable with only a small number of response options (i.e., perhaps less than 20 or 50 or 100), the median can be quite gross (e.g., 1,1,3,3,3 and 1,3,3,5,5 both have a median of 3, but the second example would have a higher mean).
When it comes to summarising the central tendency of Likert items, I find the mean to be much more useful and sensitive to meaningful differences.
Ordinal variables that are ranks do not suffer from this problem of "grossness".
Interpolated medians are another way of overcoming the gross nature of the median on ordinal data with few values.
Comment: @ Jeromy. I understood that if you are using ordinal data "When the sample size is even" and the numbers on either side of the cut point are different then it is not possible to calculate the median. This is because there is no clear mid point between two ordinal values. That is, your values are ordinal not ratio/interval because there are no even distances between them.
Comment: That said, I think that in many applications, scoring 1,2,3,4,5 for a five-point response scale provides a reasonable first pass. In fact, in many cases, I think the exact form of scaling is not likely to make much of a difference (as long as it is a reasonable monotonic transformation) in how the items are rank ordered in terms of their means.
Comment: Surely the mode is relevant here. And potentially more relevant than the mean, since you can't necessarily state that "unsure" is between "agree and disagree" - it could mean "I don't understand the question, but if I did, I'd bee at one extreme", or it could mean "I disagree with the premise of the question" (if there is no opt-out option).
Comment: @naught101 In typical survey/psychological research domains, you may have a set of items all using the same scale and you want to get a sense of which items have higher or lower levels (e.g., of agreement). In that case, the mode might be interesting, but would inadequately discriminate between scores on the different items (e.g., you might have a big bunch of items all with the same mode of 4). I agree that how the ordinal scale is assigned numbers is relevant, and there are ways of empirically assessing what is an appropriate scaling.
Comment: The numbers here are confusing the issue. Say our options are good (G), neutral (N) and bad (B), and the responsses are GGGGNBBB, then the median is the mean of G and N ... what is that? How can that be meaningful? I think a sensible response here is to say that the median is G/N. Maybe that's even worse?
Answer: No, the median is the value where half the data is less than or equal to that value and half the data is greater than or equal to that value.
So if your ordinal scale had 100 respondents then find the value that has at least 50 less or equal and 50 greater than or equal.  It would only be 3 if half the responses were to either side.  If 1 person said 1, 2 people said 2, 3 said 3, 4 said 4, and the remaining 90 said 5, then 5 would be the median.
The median works when the data is ordered, but would not make sense for nominal/unordered data, like what is your favorite color?
Comment: @ Greg, Thank you for your reply. What are the cases when the median cannot be used with ordinal level data?
Comment: I cannot think of any cases of ordinal data that you cannot use the median, there are probably cases where other summaries are more meaningful (small number of levels, just give graph or count of everything).

Median value on ordinal scales


In homology, when we operate the boundary twice we get zero, that is, $\partial^2=0$. Need help understanding proof.

Question: Proof for $S=\Delta_n=(v_0 ... \hat{v_i} ...v_n)=d_i$
$\partial=\displaystyle\sum_i^n(-1)^id_i.$
Thus,
$\partial^2=[\displaystyle\sum_i^n(-1)^id_i][\displaystyle\sum_j^n(-1)^jd_j] $
$=\displaystyle\sum_i\displaystyle\sum_j(-1)^{i+j}d_id_j $
$=\displaystyle\sum_{i\geq j}(d_id_j-d_id_j) $
$=\displaystyle\sum_{i\geq j}(-d_i^2+d_i^2) $
$=0.$
I'm completely new to homology and, in fact, algebraic topology. So i was wondering
why does $\displaystyle\sum_{i\geq j}(-1)^{i+j}d_id_j=\displaystyle\sum_{i\geq j}(-1)^{j+i+1}d_jd_{i+1}$?
I completely understand when we show an example lets say for a tetrahedron simplex, say, $S=(v_0 \ v_1 \  v_2 \  v_3)$ then
$\partial(S)=(v_1 \ v_2 \ v_3) - (v_0 \ v_2 \ v_3) + (v_0 \ v_1 \ v_3) - (v_0 \ v_1 \ v_2)$
$\Rightarrow \partial(\partial(S))=\partial(v_1 \ v_2 \ v_3) - \partial(v_0 \ v_2 \ v_3) + \partial(v_0 \ v_1 \ v_3) - \partial(v_0 \ v_1 \ v_2)$
$=[(v_2 \ v_3) - (v_1 \ v_3) + (v_0 \ v_2)] - [(v_2 \ v_3) - (v_0 \ v_3) + (v_0 \ v_2)]+ [(v_1 \ v_3) - (v_0 \ v_3) + (v_0 \ v_1)] - [(v_1 \ v_2) - (v_0 \ v_2) + (v_0 \ v_1)]
=0$.
Just need help understanding the proof.
Answer: You don't need homology to understand $\displaystyle\sum_{i\geq j}(-1)^{i+j}d_id_j=\displaystyle\sum_{i\geq j}(-1)^{j+i+1}d_jd_{i+1}$. Let us consider
$$\displaystyle\sum_{i\geq j}(-1)^{i+j}d_id_j=\displaystyle\sum_{i\geq j}(-1)^{i+(j+1)}d_{i}d_{j+1}=\displaystyle\sum_{i\geq j}(-1)^{k+(l+1)}d_{k}d_{l+1}$$
Now let $k=j,l=i$. This gives
$$\displaystyle\sum_{i\geq j}(-1)^{i+j}d_id_j=\displaystyle\sum_{i\geq j}(-1)^{j+i+1}d_jd_{i+1}$$
Comment: Indeed! Today I've learnt to always look for the simpler route first
Comment: okay thank you i was looking for something more complicated but it's a lot simpler.


CPU core id values not contiguous

Question: I am trying to understand the "core_id" sequence reported. My machine has 2 sockets, 20 cores and hyperthreading enabled (80 CPU). I am looking at the "core_id" values which are reported using:
<code>root@mybox:~# cat /sys/devices/system/cpu/cpu*/topology/core_id  |  sort -n | uniq
0
1
2
3
4
8
9
10
11
12
16
17
18
19
20
24
25
26
27
28
root@mybox:~#
root@mybox:~# cat /sys/devices/system/cpu/cpu*/topology/core_id  |  sort -n | uniq | wc -l
20
root@mybox:~#
</code>
Here, I can see that the core_id's are not contiguous. They follow a pattern. Last 3 numbers of every octet are skipped (5, 6, 7 then 13, 14, 15 then 21, 22, 23). So, for listing 20 cores, it used sequence numbers from 0 to 28.
I am trying to figure out why it skips some of the sequence numbers but couldn't find any relevant documentation for the same. Can anyone please help me in understanding this in a better way.
Thanks.
Answer: This usually results from one of two things, either:

The CPU actually has more cores, and the firmware is disabling some of them (or the manufacturer disabled some).
The firmware is leaving space in the various tables that the OS reads this data from for the possibility of hot-plugging bigger CPU's.

Given that this is a 2 socket system, I'm betting the second is the case, as it's pretty standard to be able to hot-remove a CPU package and then hotplug a new one, and the firmware has to handle the case where the new CPU has more cores than the old one.  The split into 4 groups of 5 probably also matches the die layout of the CPU's themselves.

CPU core id values not contiguous


convergence of series from $1$ to $\infty$ of $\sin^2(n)/\sqrt{n^2+1}$.

Question: does this series converge??
$$\sum_{n=0}^{\infty} \frac{\sin^2(n)}{\sqrt{n^2+1}}$$
I don't know even if this is decreasing or not.
Comment: Intuitively, on average half of the terms have a numerator $\ge1/2$ regularly, and the denominators behave like $n$. Hence the series diverges like the harmonic one.
Comment: Individual terms have a limit of $0$ since they are positive but less than $\dfrac1n$
Comment: @O.Arcila Is it ok.
Comment: @O.Arcila You were wondering whether the sequence is decreasing: it is not.  For instance, the $n=4$ term is larger than the $n=3$ term.
Comment: Thanks, I really appreciate your help. Please excuse my English I'm still learning.
Answer: we have
$$\frac{\sin^2(n)}{\sqrt{n^2+1}}\sim \frac{1-\cos(2n)}{2n}\; (n\to +\infty)$$
$\sum \frac{\cos(2n)}{n}$ is convergent by Abel's Rule.
$\sum \frac{1}{n}$ diverges.
thus, your positive series diverges and
$$\sum_{n=0}^{+\infty}\frac{\sin^2(n)}{\sqrt{n^2+1}}=+\infty.$$
Comment: The importance of the original series being positive is pretty subtle here, you should probably call more explicit attention to why it's necessary.
Comment: Hello please can you elaborate about the use of Abel's Rule. Thanks.
Comment: I think that instead of Abel's Rule is Dirichlet's?


How to get build to fail when running bcp from an msbuild script?

Question: As part of sql server 2005, there is the bulk copy command "bcp.exe" (http://msdn.microsoft.com/en-us/library/ms162802%28SQL.90%29.aspx)
We are running the bcp command from our msbuild script using the exec task.  Unfortunately, when bcp fails to load a row of data, the build still succeeds.
I tried (per build script snippet below) specifying an error file, and checking for its existence, unfortunately that means the build always fails even if bcp completely succeeds, because it appears that bcp will always create the error file even if there are no errors.
<ItemGroup>
  <bcpFiles Include="$(DataPath)\*.txt" />
</ItemGroup>
<Delete Files="BcpErrors.txt" />
<Message Text="bcp $(DatabaseName).dbo.%(bcpFiles.FileName) in %(bcpFiles.FullPath) -eBcpErrors.txt -c -E -q -t"`" -r"`\n" $(bcpConnectionString)" />
<Exec Command="bcp $(DatabaseName).dbo.%(bcpFiles.FileName) in %(bcpFiles.FullPath) -eBcpErrors.txt -c -E -q -t"`" -r"`\n" $(bcpConnectionString)" />
<Error Condition="Exists('BcpErrors.txt')" Text="One or more bcp commands contained errors." />

Is there any way I can get msbuild to fail the build if bcp fails to load any of the data?
Comment: Does BCP produce any deterministic output when it fails?
Comment: It produces error text on the Console, and information on the number of rows copied on the console, but that's about it.
Answer: If BCP returns a non-zero error code for failure then the MSBuild Exec task should detect that and mark the task as failed.
Comment: Apparently BCP is not returning a non-zero code, unless you can see something that I did wrong on the msbuild code in the question.
Comment: I don't see anything wrong with that code. Personally, I wouldn't fail the build on a staging step.
Comment: I do need the build to fail.  With this data, if it isn't copied in, then the environment will fail to work correctly. I don't want to hand off a bad environment to the test team.
Comment: @Nathan - I don't know your environment, but I'd expect QA to have their own process for prepping the environment to fit their test cases. Sorry I couldn't be more help
Answer: You could use the MSBuild ExtensionPack "File" task to look for error text in the output file:
    <MSBuild.ExtensionPack.FileSystem.File TaskAction="FilterByContent" RegexPattern="Error = " Files="BcpErrors.txt">
        <Output TaskParameter="IncludedFileCount" PropertyName="ErrorFileCount"/>
    </MSBuild.ExtensionPack.FileSystem.File>
    <Error Condition="$(ErrorFileCount) != 0" Text="One or more bcp commands contained errors." />

Comment: unfortunately, the error file appears to also be empty most of the time.
Comment: Oh... so do you get an error response to the console but not to  "BcpErrors.txt"?
Comment: Yep, I get the errors on the console, but not in the error file.
Comment: It's probably a bit late for this since you have a solution now, but you could try and send the output to a file in your Exec command with the ">" character, e.g.
``
Answer: Ok, so it's not exactly using bcp.exe, but BULK INSERT is very similar to bcp.exe, can take the same format of files, and has most of the same options.  The Sql.Execute task will also fail if the BulkInsert query fails. So I ended up with
<ItemGroup>
  <bcpFiles Include="$(DataPath)\*.txt" />
</ItemGroup>
<Sql.Execute ConnectionString="$(ConnectionString)" Sql="BULK INSERT [$(DatabaseName)].dbo.[%(bcpFiles.FileName)] FROM '%(bcpFiles.FullPath)' WITH (DATAFILETYPE='char', KEEPIDENTITY, FIELDTERMINATOR='`', ROWTERMINATOR='`\n', MAXERRORS=1)" />

(Sql.Execute task is defined in Microsoft.Sdc.Common.tasks)


Proving that $f(x)=x^2$ is uniformly continuous on any closed interval, but not on $\mathbb{R}$

Question: Let $f: [a,b]\rightarrow\mathbb{R}$, $x\mapsto x^2$ where $a,b\in\mathbb{R}$
Without loss of generality, assume $|a|>|b|$
Let $\epsilon>0, x$ and $y\in[a,b]$ and $\delta=\min\{1,\frac{\epsilon}{2|a|+1}\}$
Further suppose $|x-y|<\delta$
Then $|x+y|=|x+x-x+y|\le |x+x|+|y-x|=|2x|+|x-y|<2|a|+\delta$
So $|f(x)-f(y)|=|x^2-y^2|=|x-y||x+y|<\delta(2|a|+\delta)\le(2|a|+1)\delta\le\frac{(2|a|+1)\epsilon}{2|a|+1}=\epsilon$
$\therefore\space f$ is continuous on $[a.b]$
Is my approach correct? I can see why this would not work on $\mathbb{R}$ (would not be able to bound $|2x|$ for example) but I am not able to visualize it. Any tips on how to see it graphically at least?
Comment: Because otherwise $|a|$ is infinite which leads to an expression of $\frac{\infty}{\infty}$ in the last inequality. You used the fact that the continuous function is bounded on compact set, which makes your argument work.
Answer: What you did is correct.
In order to prove that $f$ is not uniformly continuous, use the fact that, given $\delta>0$,$$\lim_{x\to+\infty}\bigl(f(x+\delta)-f(x)\bigr)=+\infty.$$


How to apply FILE in views field

Question: I like to make a custom view for the module entity browser. For some reasons I do not want to install the module entity browser empamples.
But I make the experience as I created the view that there are no file options to select only content options.
Can anybody help?
Comment: Is 'File' not available in the 'typ' dropdown at the top of the modal (that currently shows 'Alle'?
Comment: no 'File' is not available that's my problem
Answer: When you create a new view, you can choose on which entity the view is based on. In the first picture the view is based on File, in the second picture it is based on Content (nodes).
You only see the fields of that source you have selected.
Another method to get the fields from File would be to configure a relationship using a reference field. But this is then additional, you get fields from both tables by doing this.

How to apply FILE in views field


expo-app-loading is deprecated in favor of expo-splash-screen

Question: I'm taking on a research project that uses expo to develop a mobile application. However, I am facing the following error expo-app-loading is deprecated in favor of SplashScreen.preventAutoHideAsync() instead. and I don't know how to solve it. I was able to map and see that this error is coming from this part of the code:
import AsyncStorage from '@react-native-async-storage/async-storage'

import DailyLog from "../../models/DailyLog";

export const FETCH_RECORD = "FETCH_RECORD";
export const FETCH_OR_CREATE_RECORD = "FETCH_OR_CREATE_RECORD";
export const FETCH_DAILY_LOGS = "FETCH_DAILY_LOGS";

export const SAVE_LOG = "SAVE_LOG";
export const SAVE_LOG_COMMIT = "SAVE_LOG_COMMIT";
export const SAVE_LOG_ROLLBACK = "SAVE_LOG_ROLLBACK";

export const UPDATE_RECORD = "UPDATE_RECORD";
export const UPDATE_RECORD_ROLLBACK = "UPDATE_RECORD_ROLLBACK";

export const LOAD_RECORD = "LOAD_RECORD";
export const LOAD_DAILY_LOGS = "LOAD_DAILY_LOGS";

import moment from "moment";
import Localhost from "../../constants/Localhost";
import Traducao from "../../components/Traducao/Traducao";

export const fetchRecord = () => {
    console.log("fetchRecord")

    return async (dispatch, getState) => {
        const token = getState().user.token;
        const userId = getState().user.currentUser.id;

        const responseRecord = await fetch(
            `http://${Localhost.address}${Localhost.port}/aes/webresources/secured/record/find/${userId}`,
            {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    Accept: "application/json",
                    Authorization: `Bearer ${token}`,
                },
            }
        );

        if (!responseRecord.ok) {
            throw new Error(Traducao.t("getRegistryError"));
        }
        //console.log("Aqui")
        let record = await responseRecord.json();
        //console.log(record)
        dispatch({
            type: FETCH_RECORD,
            recordId: record.id,
            dailyGoal: record.dailyGoal,
            weeklyGoal: record.weeklyGoal,
            userId: userId,
        });
    };
};

Can anyone help me? I am using expo version 6.0.1 and the project is on SDK version 45.
Comment: Does this solve your issue?
[How to load custom fonts with the useFonts hook in React Native](https://stackoverflow.com/a/77172404)
Answer: you should use SplashScreen.preventAutoHideAsync() instead.
The expo-app-loading package is used to display a loading screen when the app starts.so you need to update your code to use the new API.
you can use SplashScreen.preventAutoHideAsync() to prevent the splash screen from hiding automatically:
import { SplashScreen } from 'expo';

// Call this function in your component's useEffect or componentDidMount lifecycle method.
const preventAutoHide = async () => {
await SplashScreen.preventAutoHideAsync();
}

Note that you may need to import the SplashScreen module from the expo package and call preventAutoHide in your component's lifecycle method.
Also, make sure to call SplashScreen.hideAsync() when you're ready to hide the splash screen, or you can use SplashScreen.hide() if your app is using Expo SDK version >=33.0.0.


Expressão lógica para (Enquanto ou Se) Criar repetição até que o usuário acerte a resposta

Question: Estou tendo problemas em uma questão para definir o resultado de uma pergunta no VisualG, de maneira que se o usuário responde forma errada a pergunta irá se repetir até o usuário acerta.
A pergunta é: "se esta de acordo responda com (s) para sim ou com (n) para não".
Aqui está o código que criei:

var
  RESPOSTA: CARACTERE
inicio
        Enquanto RESPOSTA <> "n" faca
        Escreva("Esta de acordo?:")
        Leia(RESPOSTA)
          Se RESPOSTA <> "n" entao
            Escreval
            Escreval("Resposta incorreta.")
            Escreval("Vamos tentar novamente.")
            Escreval
            Escreval("Lembre-se!")
            Escreval("Para Responder SIM, Digite a LETRA (s), ou Digite a letra (n) para Responder Não.")
            Escreval("Boa Sorte!")
            Escreval
          Fimse
          Se RESPOSTA = "n" entao
            Escreval
            Escreva("Parabéns, voçê acertou!")
          Fimse
        Fimenquanto
fimalgoritmo

O problema é que eu só consegui colocar a letra n para funcionar como "Não".
Gostaria de saber se tem alguma formar de eu também conseguir colocar a letra s para a resposta "Sim".
Isso tudo de maneira que o a frase de resposta incorreta se repita até o usuário acerta a resposta de modo que fique N para não e S para sim.
Comment: Ola Kellvem, bom, não sei se você esta cursando algum curso que é necessario o uso do visualG, mas uma ferramenta muito boa para quem esta aprendendo a programar é o Portugol Studio, tem muito mais funcionalidade que o visualG, possibilita até a criação de partes gráficas na tela, da pra desenvolver seu primeiro joguinho e tudo mais!

bons estudos.
Answer: Seu código otimizado ficará assim:
var
  RESPOSTA: CARACTERE
  CONDICAO: LOGICO
inicio
      CONDICAO <- VERDADEIRO

      ENQUANTO CONDICAO = VERDADEIRO FACA
           Escreval("==========================================")
           Escreval("               Lembre-se!                 ")
           Escreval("         Use LETRAS MAIUSCULAS            ")
           Escreval("  Para Responder SIM, Digite a LETRA (S)  ")
           Escreval("ou Digite a letra (N) para Responder Não. ")
           Escreval("               Boa Sorte!                 ")
           Escreval("==========================================")
           Escreval("    ")

      Escreval("Esta de acordo?: ")
        Leia(RESPOSTA)
        CONDICAO <- FALSO

      ESCOLHA RESPOSTA
         caso "s"
           Escreval("!!!!!!!!!!!!!!!!!!!!!!!")
           escreval("Parabéns, você acertou!")
           Escreval("!!!!!!!!!!!!!!!!!!!!!!!")

         caso "n"
           Escreval("***************************")
           Escreval("    Resposta incorreta.    ")
           Escreval("***************************")
           Escreval("                           ")
           Escreval("  Vamos tentar novamente.  ")
           Escreval("                           ")
           Escreval("                           ")
           Escreval("                           ")

           CONDICAO<- VERDADEIRO

        outrocaso
           Escreval("                           ")
           Escreval("                           ")
           Escreval("############################################")
           Escreval("    Você  digitou um caracter inválido     ")
           Escreval("############################################")
           Escreval("                           ")
           Escreval("                           ")
           CONDICAO<- VERDADEIRO

           fimescolha

      FIMENQUANTO

fimalgoritmo

Optei por usar o comando ESCOLHA-CASO em vez do comando SE-ENTAO, pois será mais complexo implementar seu pseudocódigo usando este comando(se-então).
Entretanto, vale mencionar que a otimização do pseudocódigo é realizada de inúmeras formas, pode ser que encontre, na internet ou com seu professor, a solução do seu problema com outros comandos, entretanto totalmente funcional.
O funcionamento do comando ESCOLHA-CASO esta descrito abaixo:

As palavras reservadas desta instrução são escolha, caso e
  fimescolha, sendo opcional o uso da outrocaso, como ocorre com a
  instrução se... entao que pode usar o senao (seleção composta) ou
  não (seleção simples).
É importante destacar que esta instrução de seleção já possui a sua
  operação relacional definida e não pode ser utilizada outra além da
  igualdade, que é implícita nesta instrução (nunca aparece o símbolo
  = na instrução). Por meio dela só é possível verificar se existe igualdade entre um valor inteiro ou caracter desejado que se queira
  avaliar, onde sua veracidade resultará somente na execução das outras
  instruções disponíveis no caso que corresponde ao valor igual ao
  avaliado.
Caso nenhum dos valores estejam especificados como um caso desta
  instrução de múltipla escolha será executada as instruções disponíveis
  no outrocaso, se o mesmo existir, ou o algoritmo continuará sua
  execução após o fimescolha.
Forma Geral de Sintaxe
escolha (<identificador>)
  caso <valor_1>
    primeiro bloco de instrução
  caso <valor_2>
    segundo bloco de instrução
  caso <valor_3>
    terceiro bloco de instrução
  outrocaso
    bloco de instrução do outro caso (valor diferente de todos anteriores)
fimescolha
// continua as instruções do algoritmo em execução

A grafia <valor_1>, <valor_2> e <valor_3> correspondem aos
  possíveis valores inteiros ou caracter que serão comparados ao valor
  que está armazenado no que será descrito no início
  desta instrução, logo após a palavra reservada escolha, estando o
  mesmo entre parênteses.
Assim, será realizada a operação relacional de igualdade sem que
  símbolo da mesma esteja descrito, explicitamente, na instrução
Fluxograma:

Fonte: Estruturas de Controle em pseudocódigo


Connection refuse when configure "Docker Host Uri" in jenkins in windows. How can solve it?

Question: I have create a Jenkins container in Docker by using docker run -d -u root --name jenkins -p 8080:8080 -p 50000:50000 -v /root/jenkins_2112:/var/jenkins_home jenkins/jenkins:lts
Then configure the Jenkins.
When create the Docker configure I am getting Connection refuse error.

I have also create a container from image alpine/socat using command docker run -d --restart=always -p 127.0.0.1:2376:2375 -v /var/run/docker.sock:/var/run/docker.sock alpine/socat tcp-listen:2375,fork,reuseaddr unix-connect:/var/run/docker.sock.
The ip of the socat container is 172.17.0.3.
I am using windows 10.
How can I solved the problem?
Answer: This problem is arise for socat is not connected with Jenkins. So the connection is needed.
We can solve the problem by 2 steps.
Step 1:
Connect the Jenkins with socat. For the create the Jenkins container with this command:
docker run -d --restart=always -u root --name jenkins-new --link socat:socat  -p 8080:8080 -p 50000:50000 -v /root/jenkins_2112:/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock  jenkins/jenkins:lts.
Step 2:
After create the Jenkins container , set other configuration. Then put the Docker Host URI like this : tcp://socat-container-ip.2375
where the command of you socat container is :
docker run -d --restart=always -p 127.0.0.1:2376:2375 -v /var/run/docker.sock:/var/run/docker.sock alpine/socat tcp-listen:2375,fork,reuseaddr unix-connect:/var/run/docker.sock


OTRS - configure smtp to add a custom sendgrid header?

Question: I'd like to be able to configure OTRS ticket system to send email through sendgrid but I also want to add some configuration parameters through the X-SMTPAPI sendgrid header.
There's no obvious config setting I can see that would allow me to add a header to sent email through smtp in OTRS.
Any idea how I could do this?
A couple of notes of importance:

The server itself uses qmail, but I can't configure the entire local server to go through sendgrid because it runs some other services that shouldn't go through sendgrid
I'd like to avoid as much as possible changing the OTRS source files if possible because a) i don't know perl that well and b) that's asking for trouble
Comment: Can I ask why you use sendgrid? What's the benefit? Also, would you send to sendgrid using SMTP? Please explain, I can probably put you in the right direction for adding headers.
Comment: @Mike. For stats & for signing. Need to add headers to place in a category and also to enable signing of emails. And yes, SMTP seems the way to go
Answer: If you have a working sendmail installation, you can add the SMART_HOST parameter to relay all mail to sendgrid.
See this SendGrid documentation for details.


Is it possible to have a dynamic route as configure module page?

Question: I installed the SEO Checklist module and when I go the search in the Extend (admin/modules) page the module Configure page I don't see it, so I go the the module issue an create a new issue Add link to configure page to solve the problem, I thought at the end this will be very easy, the page exists (admin/config/search/seo-checklist) so, is just search the route and add it to the .info.yml file.
But when I start to check the module files I see that the .info.yml file have the configure page defined with the same route that have as url admin/config/search/seo-checklist
configure: checklistapi.checklists.seo_checklist

So I start to dig a little in the code and I found that this route checklistapi.checklists.seo_checklist is defined dynamically in the Checklist API module
  $routes["checklistapi.checklists.{$id}"] = new Route($definition['#path'], [
    '_title' => (string) $definition['#title'],
    '_form' => '\Drupal\checklistapi\Form\ChecklistapiChecklistForm',
    'checklist_id' => $id,
    'op' => 'any',
  ], $requirements);

I'm missing something here or is not possible to have a dynamic route as configure module page?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/67105/discussion-on-question-by-adrian-cid-almaguer-is-it-possible-to-have-a-dynamic-r).
Comment: The routes added in the code are *dynamic* only during discovery. After that they are the same as if they were discovered from a yaml file
Comment: @4k4 In this case I think that this doesn't works, you can try it by your self.
Answer: It is possible to use any route for the configure link, as long as all route parameters are satisfied (parameters can be specified via configure_parameters).
In the case of the above bug, the access check was failing, preventing the link from displaying.
The problem was solved in: ChecklistapiAccessCheck looks in the wrong place for 'checklist_id' and 'op'


Vector inequality $(\langle Ax,y \rangle^2) \le (\langle Ax,x\rangle * \langle Ay,y\rangle)$

Question:
Let $A = (a_{ij})_{1\le i \le j \le n} \in M_{n \times n}^{\Bbb R}$

such that
$$(a_{ij})=\begin{cases} 2, i = j \\ 1, i\ne j \end{cases}$$

Prove that $(\langle Ax,y \rangle^2) \le (\langle Ax,x\rangle * \langle Ay,y\rangle)$ for every $x,y \in \Bbb R^n$

Where $\langle\cdot,\cdot\rangle$ stands for the standard inner product in the space.
I think I'm supposed to solve this with Cauchy-Schwarz inequality.
Any ideas?
Thanks!
Comment: Okay, *now* we're talking. *That* matrix is positive definite, which makes all the difference in the world. Check out [this question](http://math.stackexchange.com/questions/60136/is-this-equivalent-to-cauchy-schwarz-inequality).
Comment: Possible direction: Let $O$ be the matrix of all ones, then $A=2O-I$.  Observe that $Ox$ is the vector where every entry is the sum of the entries of $x$.
Comment: Maybe this problem was posed on the first of April?
Comment: @HaraldHanche-Olsen Please see my edit to the question, I'm sorry for the mistake earlier.
Answer: What is below is now obsolete, because the OP has made a correction in his text:
I understand now why we (@Michael Burr, me and probably others) had difficulties to prove this property, simply because it is FALSE.
Here is a very elementary counter-example:
$$A=\begin{bmatrix}1&2\\2&1\end{bmatrix}, \ \ X=\begin{bmatrix}1\\0\end{bmatrix}, \ \ Y=\begin{bmatrix}0\\1 \end{bmatrix}$$
$2^2$ cannot be less than $1 \times 1$...
Comment: I'm terribly sorry, I wrote the question wrong and now I fixed it. The diagonal in my previous version was not right. Thanks for your effort!!
Answer: $A$ is the matrix associated with the quadratic form:
$$x_1^2+x_2^2+\cdots+x_n^2+(x_1+x_2+\cdots+x_n)^2$$
This form is $>0$ except in the case where $x_1=x_2=...=x_n=0$. Thus it is a positive definite quadratic form, and $A$ is symmetric positive definite.
It is well known that, with such a matrix, $X^TAY$ is an inner product associated with the norm $\|X\|_A=\sqrt{X^TAX}$ said "$A$-norm".
Thus the target property is a form of the Cauchy-Schwarz inegality.
see for example http://www-users.cs.umn.edu/~saad/csci5304/FILES/LecN7_R.pdf
A direct proof is possible, generalizing the classical proof of Cauchy-Schwarz inequality. Here it is.
Let us expand:
$$(\lambda X+Y)^TA(\lambda X+Y)=\lambda^2(X^TAX)+\lambda(X^TAY+Y^TAX)+Y^{T}AY \ \ (1)$$
As $A^T=A$, $Y^TAX=Y^TA^TX \in \mathbb{R}$ ; being a number, it is the same as its transpose $X^TAY$. Therefore, relationship (1) can be written:
$$(\lambda X+Y)^TA(\lambda X+Y)=\lambda^2(X^TAX)+2\lambda(X^TAY)+(Y^{T}AY) \ \ (2)$$
This positive expression (being of the form $U^TAU$ with a symmetric p.d.m.)  considered as a quadratic expression in $\lambda$ cannot have 2 distinct roots (were it the case, the expression could be $<0$ for certain values). Thus its discriminant must be $\leq 0$. Computing this discriminant gives, up to a factor $4$:
$$(X^TAY)^2-(X^TAX)Y^{T}AY \leq 0$$
ending the proof.
Comment: Thank you so much for your help.


Pop up com Bootstrap ao carregar página

Question: Como posso fazer com que abra um pop up do Bootstrap ao carregar a página?
<button class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal</button>

      ...

Comment: Deveria funcionar assim, é assim que tenho. Estás a importar o JS do Bootstrap?
Answer: Primeiro aplique um ID ao modal:

      ...

Aí em tags  coloque:
$(document).ready(function() {
   $('#myModal').modal('show');
});

Comment: Simplesmente perfeito obrigado

Pop up com Bootstrap ao carregar página


How to do BigInt arithmetic in Dart 2.x, specifically division?

Question: Dart documentation says that BigInt division returns a value of type 'double'. This is a problem. To illustrate, here are two implementations of an algorithm involving division. The first is in Kotlin, the second is in Dart. The Dart version runs accurately for small numbers but loses precision for larger numbers.
Kotlin
import java.math.BigInteger

fun height(n: BigInteger, m: BigInteger): BigInteger {
  var m1  = m
  var s   = BigInteger("1")
  var b   = BigInteger("1")
  var ans = BigInteger("0")
  var i   = 0
  while (i < n.toInt()) {
    s *= m1--
    s /= b++
    ans += s
    i++
  }
  return ans
}

Dart
BigInt height(int n, int m) {
  var m1  = m;   // new BigInt.from(m);
  var s   = 1.0; // new BigInt.from(1);
  var b   = 1.0; // new BigInt.from(1);
  var ans = new BigInt.from(0);
  var i   = 0;
  while (i < n) {
    s *= m1--;
    s /= b++;
    ans += BigInt.from(s);
    i++;
  }
  return ans;
}

As you can see from the commented out Dart code, I have tried various ways to use BigInt.
Here is an example input with answer. The erroneous Dart answer is given below.
height(13, 550),
          equals(BigInt.parse('60113767426276772744951355')));

The erroneous Dart answer is --> 60113767426276764034189615
Can someone show me the best way to do the job in Dart v2.x?
Answer: The following code works.
BigInt height(int n, int m) {
  var m1  = new BigInt.from(m);
  var s   = new BigInt.from(1);
  var b   = new BigInt.from(1);
  var ans = new BigInt.from(0);
  var i   = 0;
  while (i < n) {
    s *= m1;
    m1 -= new BigInt.from(1);
    s = s ~/ b;
    b += new BigInt.from(1);
    ans += s;
    i++;
  }
  return ans;
}

Changes:

x++ and x-- are equivalent to x = x + 1 and x = x - 1 but BigInt.+ and BigInt.- only accept BigInt values... so there's a compiler error.
BigInt./ returns a double and this is not what you want here. You need to use the BigInt.~/ operator instead.


How to convert string to json vb.net

Question: this is the code i have, dim sline from string to json, i have try it and search on google, but i havent done yet...
please help
Dim sURL As String
sURL = TextBox1.Text
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True

wrGETURL.Proxy = myProxy

wrGETURL.Proxy = WebProxy.GetDefaultProxy()
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()

Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0

Do While Not sLine Is Nothing
    i += 1
    sLine = objReader.ReadLine
    If Not sLine Is Nothing Then
        Console.WriteLine("{0}:{1}", i, sLine)
    End If
Loop
Dim respon As Array = sLine.ToArray()
Console.ReadLine()
Console.WriteLine(respon("traceNo"))
Console.ReadLine()

i want to convert the Dim sline to json, how it possible?
Answer: Newtonsoft.JSON is a VERY handy NuGet to easy use JSON in VB.Net.
Seperate your lines into a List(Of Integer, String) (i,sLine)
and Serialize it with
Dim yourJSONString = JsonConvert.SerializeObject(yourList)

Comment: failed to install that package on my visual studio
Comment: If it fails to install just a NuGet, than you should repair your visual studio first
Comment: @Kenzie Which version of Visual Studio are you using?

How to convert string to json vb.net


Can this mesh volume calculation algorithm handle imperfect meshes?

Question: As per this answer, I read this research paper (very brief). To quote the answer:

This all boils down to the following simple function:
public float SignedVolumeOfTriangle(Vector p1, Vector p2, Vector p3) {
    var v321 = p3.X*p2.Y*p1.Z;
    var v231 = p2.X*p3.Y*p1.Z;
    var v312 = p3.X*p1.Y*p2.Z;
    var v132 = p1.X*p3.Y*p2.Z;
    var v213 = p2.X*p1.Y*p3.Z;
    var v123 = p1.X*p2.Y*p3.Z;
    return (1.0f/6.0f)*(-v321 + v231 + v312 - v132 - v213 + v123);
}

and then a driver to calculate the volume of the mesh:
public float VolumeOfMesh(Mesh mesh) {
    var vols = from t in mesh.Triangles
               select SignedVolumeOfTriangle(t.P1, t.P2, t.P3);
    return Math.Abs(vols.Sum());
}

This seems much better than the voxel based approach for determining volume of an advanced 3D object, however, in the models I currently have available to me:

Many of the surfaces are not complete 3D voluminous shapes, but rather hollow 2D meshes wrapped into a 3-D looking shape where the ends don't actually meet up to form a complete surface of a true 3D object.
Some surfaces are outright flat 2D shapes.
Are just plain messy internally.

And I'm unsure about how the algorithm will handle imperfect 3D models.
Do I need to produce models which are made up only of true, complete, voluminous 3D objects for this method to work, or will it work on common 3D models as shown above?
Answer: The method you've found works by iterating over all triangles, for each triangle it connects its corners with (0,0,0) point making a tetrahedron. Then it computes its volume and sum up all the results. The signed word used here means that some tetrahedrons will have negative volume, based on triangle facing. Thanks to this trick overlapping tetrahedrons will cancel out each other.
If you have correct mesh it just works, but your imperfect mesh is basically a perfect one but with few triangles missing, so you'll miss some of your tetrahedrons in your final sum. Statistically some of them are positive volumes and some are negative ones, so this will also cancel out to some extent.
The more triangles you lack and/or the bigger they get then the more error you'll get in computed volume value, but the algorithm won't break or explode, just loose precision.
There's also another problem with this approach:
When you have two perfectly closed cube meshes that are overlapping each other this algorithm will compute the sum of their volumes, not the volume of the shape they've created. We don't know much about your models but I'd consider it a bigger problem than non-closed mesh.
To solve this you'd need to do CSG Union operation, but it works only for closed meshes :/.


Why is this code giving me a strange output

Question: The method below was written to make a String version of a number, I know there are already methods that do this, such as String.valueOf(), Double.toString(), or even just "" + someNumber.
private static String numToString(double i) {
           String revNumber = "";
           boolean isNeg = false;
           if (i == 0) { //catch zero case
               return "0";
           }

           if (i < 0) {
               isNeg = true;
           }

           i = Math.abs(i);
           while (i > 0) { //loop backwards through number, this loop
               //finish, otherwise, i would not get any output in 'main()'
               revNumber += "" + i % 10; //get the end
               i /= 10; //slice end
           }

           String number = ""; //reversed
           for (int k = revNumber.length() - 1; k >= 0; k--) {
               number += revNumber.substring(k, k + 1);
           }

           revNumber = null; //let gc do its work

           return isNeg ? "-" + number : number; //result expression to add "-"
           //if needed.
       }

Although the above method should only be used for ints (32-bit), I made it accept a double (64-bit) argument and I passed a double argument, without a decimal, the output results are the same if I pass an int into the method as well, or with a decimals, etc...
Test:
public static void main(String[] args) {
   double test = -134; //Passing double arg
   System.out.println(numToString(test)); //results
}

Result: (Maximum memory results for double?):
-323-E5.1223-E33.1123-E43.1023-E43.1913-E43.1813-E43.1713-E43.1613-E43.1513-E43.1413-E43.1313-E43.1213-E43.1113-E43.1013-E43.1903-E43.1803-E999999999999933.1703-E999999999999933.1603-E999999999999933.1503-E999999999999933.1403-E9899999999999933.1303-E999999999999933.1203-E999999999999933.1103-E8899999999999933.1003-E9899999999999933.1992-E999999999999933.1892-E999999999999933.1792-E999999999999933.1692-E999999999999933.1592-E999999999999933.1492-E999999999999933.1392-E999999999999933.1292-E999999999999933.1192-E999999999999933.1092-E999999999999933.1982-E999999999999933.1882-E1999999999999933.1782-E999999999999933.1682-E999999999999933.1582-E999999999999933.1482-E999999999999933.1382-E999999999999933.1282-E1999999999999933.1182-E1999999999999933.1082-E2999999999999933.1972-E2999999999999933.1872-E3999999999999933.1772-E2999999999999933.1672-E1999999999999933.1572-E2999999999999933.1472-E999999999999933.1372-E999999999999933.1272-E1999999999999933.1172-E2999999999999933.1072-E2999999999999933.1962-E1999999999999933.1862-E999999999999933.1762-E999999999999933.1662-E999999999999933.1562-E999999999999933.1462-E999999999999933.1362-E999999999999933.1262-E999999999999933.1162-E999999999999933.1062-E999999999999933.1952-E999999999999933.1852-E999999999999933.1752-E999999999999933.1652-E999999999999933.1552-E999999999999933.1452-E999999999999933.1352-E999999999999933.1252-E999999999999933.1152-E999999999999933.1052-E9899999999999933.1942-E9899999999999933.1842-E999999999999933.1742-E999999999999933.1642-E999999999999933.1542-E999999999999933.1442-E999999999999933.1342-E999999999999933.1242-E999999999999933.1142-E9899999999999933.1042-E999999999999933.1932-E8899999999999933.1832-E9899999999999933.1732-E8899999999999933.1632-E8899999999999933.1532-E8899999999999933.1432-E999999999999933.1332-E9899999999999933.1232-E8899999999999933.1132-E7899999999999933.1032-E8899999999999933.1922-E8899999999999933.1822-E7899999999999933.1722-E6899999999999933.1622-E5899999999999933.1522-E5899999999999933.1422-E6899999999999933.1322-E6899999999999933.1222-E6899999999999933.1122-E7899999999999933.1022-E7899999999999933.1912-E7899999999999933.1812-E8899999999999933.1712-E8899999999999933.1612-E7899999999999933.1512-E7899999999999933.1412-E6899999999999933.1312-E6899999999999933.1212-E7899999999999933.1112-E7899999999999933.1012-E7899999999999933.1902-E7899999999999933.1802-E6899999999999933.1702-E7899999999999933.1602-E7899999999999933.1502-E8899999999999933.1402-E8899999999999933.1302-E8899999999999933.1202-E8899999999999933.1102-E7899999999999933.1002-E7899999999999933.1991-E9899999999999933.1891-E9899999999999933.1791-E8899999999999933.1691-E7899999999999933.1591-E8899999999999933.1491-E8899999999999933.1391-E999999999999933.1291-E9899999999999933.1191-E9899999999999933.1091-E999999999999933.1981-E999999999999933.1881-E999999999999933.1781-E999999999999933.1681-E999999999999933.1581-E1999999999999933.1481-E999999999999933.1381-E999999999999933.1281-E1999999999999933.1181-E2999999999999933.1081-E999999999999933.1971-E1999999999999933.1871-E999999999999933.1771-E2999999999999933.1671-E3999999999999933.1571-E3999999999999933.1471-E2999999999999933.1371-E2999999999999933.1271-E2999999999999933.1171-E999999999999933.1071-E999999999999933.1961-E999999999999933.1861-E999999999999933.1761-E999999999999933.1661-E999999999999933.1561-E999999999999933.1461-E8899999999999933.1361-E8899999999999933.1261-E8899999999999933.1161-E7899999999999933.1061-E7899999999999933.1951-E7899999999999933.1851-E7899999999999933.1751-E7899999999999933.1651-E7899999999999933.1551-E6899999999999933.1451-E6899999999999933.1351-E6899999999999933.1251-E6899999999999933.1151-E6899999999999933.1051-E7899999999999933.1941-E6899999999999933.1841-E7899999999999933.1741-E7899999999999933.1641-E9899999999999933.1541-E999999999999933.1441-E999999999999933.1341-E999999999999933.1241-E999999999999933.1141-E999999999999933.1041-E999999999999933.1931-E9899999999999933.1831-E999999999999933.1731-E999999999999933.1631-E8899999999999933.1531-E9899999999999933.1431-E9899999999999933.1331-E8899999999999933.1231-E8899999999999933.1131-E8899999999999933.1031-E7899999999999933.1921-E7899999999999933.1821-E7899999999999933.1721-E6899999999999933.1621-E7899999999999933.1521-E7899999999999933.1421-E8899999999999933.1321-E7899999999999933.1221-E7899999999999933.1121-E8899999999999933.1021-E8899999999999933.1911-E9899999999999933.1811-E999999999999933.1711-E999999999999933.1611-E999999999999933.1511-E999999999999933.1411-E1999999999999933.1311-E2999999999999933.1211-E3999999999999933.1111-E2999999999999933.1011-E2999999999999933.1901-E3999999999999933.1801-E2999999999999933.1701-E2999999999999933.1601-E3999999999999933.1501-E2999999999999933.1401-E3999999999999933.1301-E3999999999999933.1201-E4999999999999933.1101-E5999999999999933.1001-E4999999999999933.199-E3999999999999933.189-E3999999999999933.179-E3999999999999933.169-E4999999999999933.159-E4999999999999933.149-E4999999999999933.139-E4999999999999933.129-E4999999999999933.119-E4999999999999933.109-E4999999999999933.198-E4999999999999933.188-E4999999999999933.178-E3999999999999933.168-E3999999999999933.158-E3999999999999933.148-E3999999999999933.138-E3999999999999933.128-E4999999999999933.118-E3999999999999933.108-E3999999999999933.197-E3999999999999933.187-E3999999999999933.177-E4999999999999933.167-E3999999999999933.157-E3999999999999933.147-E3999999999999933.137-E3999999999999933.127-E3999999999999933.117-E4999999999999933.107-E5999999999999933.196-E5999999999999933.186-E5999999999999933.176-E4999999999999933.166-E4999999999999933.156-E4999999999999933.146-E4999999999999933.136-E3999999999999933.126-E3999999999999933.116-E3999999999999933.106-E3999999999999933.195-E2999999999999933.185-E1999999999999933.175-E2999999999999933.165-E2999999999999933.155-E2999999999999933.145-E2999999999999933.135-E3999999999999933.125-E4999999999999933.115-E4999999999999933.105-E2999999999999933.194-E1999999999999933.184-E2999999999999933.174-E2999999999999933.164-E2999999999999933.154-E1999999999999933.144-E1999999999999933.134-E2999999999999933.124-E2999999999999933.114-E2999999999999933.104-E3999999999999933.193-E3999999999999933.183-E3999999999999933.173-E2999999999999933.163-E2999999999999933.153-E999999999999933.143-E2999999999999933.133-E2999999999999933.123-E2999999999999933.113-E3999999999999933.103-E3999999999999933.192-E3999999999999933.182-E3999999999999933.172-E3999999999999933.162-E4999999999999933.152-E4999999999999933.142-E5999999999999933.132-E6999999999999933.122-E7999999999999933.112-E6999999999999933.102-E6999999999999933.191-E7999999999999933.181-E8999999999999933.171-E8999999999999933.161-E8999999999999933.151-E9999999999999933.141-E8999999999999933.131-E8999999999999933.121-E43.111-E43.101-E43.19-E1000000000000043.18-E1000000000000043.17-E43.16-E43.15-E43.14-E43.143100.04310.0431.043.14000000000000004.30.4
Comment: i never is less than 0 in your loop.
Comment: `i /= 10` will not "slice end" of a double.
Comment: This might work for int, but not sure this would work with doubles. How do you handle decimal points?
Comment: The point is, the unexpected results, also the loop ends, otherwise, not output would be shown.
Answer: This is not because of the complier. It is happening because you are doing
i /= 10; //slice end

So when you do 13.4 after the first run it wont give you 1.34 it will give you something like 1.339999999999999999 which is 1.34.
Check Retain precision with double in Java for more details.
If you just want to reverse the number you can do
private static String numToString(double i) {
        String returnString = new StringBuilder(Double.toString(i)).reverse().toString();
        return i>=0?returnString:"-"+returnString.substring(0,returnString.length()-1);
}

Comment: The loop breaks, otherwise, no output would be shown at all!
Comment: That's probably true but doesn't have anything to do with the problem. The problem is that the break condition of the loop is `i > 0` which is (theoretically) never reached. It doesn't matter if the value becomes exactly 1.34 or 1.33999... because it's still > 0.
Comment: This is not a problem *at all*: the value of `i` is used only in the `i % 10` operation which isn't affected.
Comment: @Juhana please try this code with a breaking condition of i > 1 it will still be a problem ! I tried it and the output was -43.14000000000000004.30.4. Can you explain why this happens ?
Answer: for (; i > 0; ) { //loop backwards through number
    revNumber += "" + i % 10; //get the end
    i /= 10; //slice end
}

This loop never finishes until it breaks at a much later time than it should. i % 10 doesn't cut off the end of a double. It works well with an int but not with a double. Hence the 134->13.4->1.34->.134-> etc.... So you get an argumentoutofrange exception or something similar to that. Else the compiler just keeps doing it for the max memory that a double can handle.


Create a slideshow

Question: I want to create a slideshow in my site, as in the middle bottom of the page at Blottr.com.
I created the gallery with the Views Slideshow module, but my problem is that I don't know how create a slide form video.
Each of my node has one image, but some nodes have am image with a video. I want to show the  video, when there is a video, and an image when no video is present.
Answer: If you can get the slideshow working yourself, it should be pretty simple to get where you want.
All you really need to do is try to display both the video and the image, then in a template_preprocess function for the view, remove either the video or the image field so you only get the one you want.
Alternative you could use js/css to hide unwanted elements.
Answer: You can use global php custom field in view and can manage images/videos using php code.
Comment: plz add details about it
Comment: If we for the moment ignore how extremely short this is on details, -1 on account of me strongly opposing the php module. See [What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?](http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args)
Comment: Welcome to Drupal Answers.  Can you provide a little more detail about how this would work?  As it stands, this answer gives people very little to go on.

Create a slideshow


Eclipse keeps crunching while "updating rpm packages proposal list"

Question: I've recently installed Eclipse Kepler CDT on a Win7 64 machine. It runs fine (well, sort of), but - it keeps crunching, with the status bar saying

Updating RPM packages proposal list

Why is this happening and how can I make it stop?
Answer: It's a bug in the "Linux Tools" plugin.
It seems that the plugin is unable to create the file specified at

Window -> Preferences -> Specfile Editor -> RPM Completions -> Path to packages list file

or

Window -> Preferences -> RPM -> Specfile Editor -> RPM Completions -> Path to packages list file

and therefore keeps trying to create it.
To fix this problem, just create an empty file at that location & name, or create a new empty file at a different location & name and specify it as the "Path to packages list file".
Note: You cannot create the default file (.pkglist) using Windows explorer since it won't let you create a file whose name starts with a dot. So open a console (command prompt) window and run this command:
echo. > path\to\file\.pkglist

Comment: To easily create the file from CMD: `echo. > path\to\file\.pkglist` (Close Eclipse first).
Comment: If you have Cygwin Installed, you can create a `.pkglist` file in that just fine.
Comment: But why would I have a 'Linux Tools' plugin on Windows?
Comment: I guess they are installed by default in the Eclipse IDE for C/C++ developers because I had the same problem and didn't install them explicitly either.
Comment: @Alberto Thanks for that suggestion; I edited the answer with that information. BTW I didn't even have to close Eclipse first; as soon as I created that file, suddenly Eclipse stopped churning with that "updating RPM packages proposal list" message.
Comment: Worked for me, I've just created `.pkglist` file in the eclipse folder and changed the Path unter RPM Completions. Have had this problem since 2020/03 Update
Answer: I was able to solve this in Eclipse Kepler by going to Window -> Preferences -> Specfile Editor -> RPM Completions and un-checking Automatically build the RPM packages proposal list
Comment: Thanks this works! However, in Eclipse 2022-06, this option is hidden under Window --> Preferences --> RPM --> Specfile Editor --> RPM completions
Answer: Run Eclipse as administrator and it will create this fail successfully. Normal program do not have rights to write into this directory.
When developers lean to give meaningful error messages? Also, it will probably tray to write into this file sometimes in the future and that will also fail. Make this fail writable for users, normally programs run with user rights!
Comment: I didn't have admin privileges, unfortunately.
Comment: Is it safe to run Eclipse with admin privileges?
Answer: In Eclipse version 2022-06, the updating can be disabled by goin to Window -> Preferences -> RPM -> Specfile Editor -> RPM Completions (note the first RPM which is not present in Eclipse Kepler) and un-checking Automatically build the RPM packages proposal list
Answer: I was getting this simply because my %USERPROFILE%.pkglist didn't exist, so creating the empty file solved the problem for me.


Determining bounds for double integral

Question: I must find the volume determined by $z \leq 6-x^2-y^2$ and $z \geq \sqrt{x^2+y^2}$.
I know this question must seem very basic, but I just cannot seem to figure out the answer. I am also confused about how to tackle these sorts of problems in general, particularly setting up the integral. This is my attempt so far, although I know my answer is wrong:
Setting the two equations above equal to each other, we solve to find: $$x=\pm 2,y=0,z=2 \text{ OR } x=0,y=\pm 2, z=2$$ Now, using polar coordinates, we set $x=r\cos \theta,y=r\sin \theta$ and our bounds are now $z \leq 6-r^2$ and $z \geq r$. Then, we evaluate: $$\iint_D(6-x^2-y^2)dA=\int_0^{2\pi}\int_0^2 r(6-r^2)drd\theta=\frac{56\pi}{3}$$ However, I know the answer should be $\frac{32\pi}{3}$. I assume I have made an error in the bounds for the $r$ term. What am I doing wrong, and what approach should I use in the future? Thank you for the help.
Answer: In cylindrical coordinates, the region can be described as follows:
$$
E:=\{(r,\theta,z)\;|\; 0\le \theta \le 2\pi, 0\le r\le 2,r\le z \le 6-r^2 \}
$$
It follows that
$$
V=\iiint_E dV = \int_0^{2\pi}\int_0^2\int_r^{6-r^2}rdzdrd\theta =\int_0^{2\pi}\int_0^r(6-r^2-r) rdrd\theta=\frac{32\pi}{3}
$$
In general, you must first concentrate on the bounds of the integral. This is the hard part as  it cannot be done with a computer. To do this, it is a good idea to draw a picture of the region you are considering. Here, the nature of the functions invites us to describe it with cylindrical coordinates.
Answer: Your simultaneous solution is wrong.  If
$$z=6-x^2-y^2\ ,\quad z=\sqrt{x^2+y^2}\ ,$$
then $z=2$ as you have found correcly (rejecting the solution $z=-3$).  However this means that $x,y$ could have any values satisfying
$$x^2+y^2=4\ ,$$
it doesn't have to be that one of them is $0$.
Using polar coordinates is then a good idea and you have $0\le r\le2$, $0\le\theta\le2\pi$.  But to find the volume, you have to integrate $z_{\rm max}-z_{\rm min}$, giving
$$V=\int_0^{2\pi}\int_0^2 \bigl((6-r^2)-r\bigr)\,r\,dr\,d\theta\ .$$
I leave the evaluation up to you.

Determining bounds for double integral