Why is this wrong?

Question: About the Collatz Conjecture:
Every body looks at it from "leaves to root" - to use the tree analogy.
I have another approach.
My approach is to look at it from the root - the number 1 - and see if, by means of the inverse algorithm functions, I can generate all Counting Numbers.
Here I will wait for a first kind response to this:
why is it t that the simple fact that lines 2n and (n-1)/3 - the inverse functions of the algorithm - are obviously continuous and all integers (I mean (n, m) points with m,n integers) belong to one or another isn't enough as a proof?
functions: all integers belong to one or another
(note that  the generated numbers, by 2n function,:  2,4,6,8,10... plus division generates all naturals: 2,6/2,4,10/2,...)
all integers in those lines are hailstorm numbers. : their big bang like origin - a single point - guarantees that.
So, what I seek is to understand what is to prove!
Comment: as you said it at the beginning of your post, you have to prove that if you **begin** with a random integer you will finally end at 1.
Comment: There's a lot of people who looked at the collatz-problem this way. A somehow prominent one (Peter Schorer) thinks that he even has proven the conjecture using the reverse tree and offers a handful of dollars if you find and point to some error/flaw. You can also look at my early fiddlings at http://go.helms-net.de/math/collatz/aboutloop/collloopintro_main.htm and especially open the subpage about "textual" and "graphical" trees.
Answer: Yes, a line like $2n$ is contiguous, but that's not what we're doing.
We're applying the mapping $n \rightarrow 2n$. It's important to realize that the input domain is $\mathbb{N}$. We can never get $3$ with this mapping for example, as there is no integer that we can double to get 3.
Neither mapping $n \rightarrow 2n$ or $n \rightarrow \frac{n-1}{3}$ covers every integer by itself. The interesting part of the Collatz conjecture is that we can combine and alternate these two mappings to construct integers. But it's incredibly hard to prove that this combination can reach all integers.
Answer: Let's define a Collatz sequence recursively, take $a_0$ to be any positive integer as a starting point and say
$$a_{n+1} =
\begin{cases}
\dfrac{3a_n+1}{2} & \text{$a_n$ odd}\\
\dfrac{a_n}{2} & \text{$a_n$ even}
\end{cases}
$$
If $a_n\equiv 0,1 \mod 3$, there is no problem in traversing the Collatz sequence in reverse.  Take $a_{n-1} = 2a_n$.  The problem is when $a_n\equiv 2 \mod 3$.  We don't know whether to take $a_{n-1} = 2a_n$ or whether we should take $a_{n-1}=\dfrac{2a_{n-1}-1}{3}$.  Either choice is possible, so how does one tell which choice is needed to reach any particular integer.
Comment: There are redundancy in the generating algorithm. I think that corresponds (somehow!) to the numbers that have equal steps.
Comment: That possible redundancy is what could ruin any effort to prove the Collatz conjecture by using an inverse sequence from 1 to n, since there is that ambiguity you can't be certain the algorithm in the usual direction will really lead to 1.  If the Collatz conjecture were false, there could be an $n$ which was reachable from 1 traversing in the reverse direction but which did not lead to 1 by applying the usual algorithm.

Why is this wrong?


The difference between 3/2 and 3/4

Question: So, today, the tides washed up this question from years ago: In 3/2 time why is a whole-note rest used as a bar's rest when a whole-note doesn't fill the measure?
This reminded me of a noob question I've been wondering about for years: Is there actually any difference between, say, a 3/2 at ♩ = 60 and a 3/4 at ♩ = 120?
I assume that a composer and/or engraver would choose between those two depending on what would be easier to read for a certain piece of music. But aside from that, is there any difference in how you'd count and emphasize those? Or could I take any generic waltz in 3/4, halve the tempo, halve all the note durations, replace the 3/4 with a 3/2, and get the same piece of music?
Sorry if this sounds like a stupid question, but I'm mostly educated in maths and physics, and as I begin to understand music theory it seems to me that, while music is rooted in maths and physics, and often borrows mathematical concepts, they are not always applied in a way that is consistent with their uses outside of maths.
Comment: Does this answer your question? [What is the difference between 3/2 and 3/4 time signature](https://music.stackexchange.com/questions/86295/what-is-the-difference-between-3-2-and-3-4-time-signature)
Answer: At various historical periods there have been different conventions.  Old British military marches were usually written in 2/4. Now 2/2 (or 'cut time' - that C with a vertical line one) is much more likely.  (Unless it's a 6/8 march, of course.)
Waltzes have pretty generally been written in 3/4.  Maybe 3/8.  3/2 would be unlikely, though I'm sure someone will find an example!    Incidentally, writing a piece in 3/8 rather than 3/4 was by no means always an indication that the music was fast.
But yes,apart from this sort of convention,  3/2 at ♩ = 120 and a 3/4 at ♩ = 60 are exactly the same. (You got it the wrong way round in the question!)   Except that we'd express the 3/2 tempo as half=120 the beat is the half-note not the quarter.
The 'whole bar' rest looks very like a whole note rest except that it is centered in the bar.  It is used for a complete bar's rest in (almost) any time signature (there are exceptions for bars of 3/16 or shorter, 4/2 or longer).

The difference between 3/2 and 3/4


How can we get different mean and median values for residuals when working with the same dataset?

Question: Following this R instruction
> fit <- lm(spending ~ sex + status + income + verbal, data=spending)

I would like to calculate the mean and median of the residuals. Both my friend and I get different answers for the mean for the same data.
> mean(resid(fit))
[1] -3.065293e-17

while with the other model, results are:
> fit1<- lm(spending ~ status + income + sex + verbal, data=spending)
> mean(resid(fit1))
[1] 4.064605e-16

Why did we get the same median but different mean if we are using the same data set?
Comment: It's an intriguing question.  (If "rounding issues" affect your friend, they ought to affect you the same way.) What have you done to rule out simple explanations, such as *any* difference between your data set and your friend's? A single typographical error in one of them would explain this difference.
Comment: The mean of the residuals should be zero. Small deviations from zero may be due to rounding issues. Note that your obtained values are indeed very small.
Comment: "Small" compared to what, @Sven?  See http://stats.stackexchange.com/questions/37522 for an account of the issues.  (You and I know that mean residuals for a linear model with intercept should be exactly zero, but nevertheless an order of magnitude difference between two computations could flag something serious going on and is worth looking into: I applaud the questioner for paying attention to this.)
Comment: @Gavin Try `4.064605e-16 / -3.065923e-17`!  (More important point: just because `all.equal` uses a default tolerance of `.Machine$double.eps^0.5`, which is around $10^{-8}$, does not mean it is appropriate for this comparison. It's not. The appropriate tolerance depends on the typical sizes of the residuals themselves, which we do not know in this case.)
Comment: Please, [register](http://stats.stackexchange.com/faq#login) your account. That will enhance your experience with this site and will allow you to vote on and accept previous answers.
Comment: Sven's point is good. When the computer rounds at very low values, it causes these sorts of problems. Effectively both answers are 0 though. Reminds of me this blog post: http://davegiles.blogspot.com/2011/12/reported-accuracy-for-regression.html
Comment: That begs the point, @John: when two computers are ostensibly doing exactly the same computations with exactly the same data, then they should be making *exactly* the same floating point errors. These little things are often the only clues one gets that something more significant is wrong; they shouldn't be dismissed just because the values are "very low." (Do you remember the [Pentium bug](http://en.wikipedia.org/wiki/Pentium_FDIV_bug)?) In fact, in the scheme of things--doubles range from about $10^{-303}$ to $10^{303}$--values around $10^{-17}$ aren't small at all; they are middling values.
Comment: @whuber it isn't clear to me that they *are* doing the same thing. The ordering of the variables in the model formulae shown is different in the two fits.
Comment: @Gavin: Exactly! That's what I'm getting at. The point is that *something* is different and the first places to look are in the data and the code. (I suspect that a simple check of this nature will enable this question to resolve itself.)
Comment: However, as far as R is concerned the means of the two sets of residuals **are** indistinguishable given machine precision. Try `all.equal(-3.065293e-17, 4.064605e-16)`.
Comment: Maybe the order of variables affects the order in which computations are made and hence affects what the roundoff error will be.  I guess these days computers have the same high precision.  But in the old days the machines could have different numbers of bits for storing numbers and so two machines could differ like this just because the precision of the floating point arithmetic is different.
Comment: @whuber, technically speaking they aren't doing the same calculation. The ordering when computing the inverse is what really matters, I think.
Comment: Yes, I agree @John: that's the likeliest explanation--but not the only possible one.
Answer: By definition, the mean of the residuals of both models should be zero. Deviations are due to rounding issues.
Here's an example:
> x <- rnorm(10)
> y <- rnorm(10)
> z <- rnorm(10)
> res1 <- residuals(lm(y ~ x+z))
> res2 <- residuals(lm(y ~ z+x))

Note that both models include the same variables, but the order is different.
Look at the mean:
> mean(res1)
[1] 3.8849e-17
> mean(res2)
[1] 1.525337e-17
> median(res1)
[1] 0.06405684
> median(res2)
[1] 0.06405684

The mean is not identical, but the median is.
The residuals are nearly identical (as expected):
> all.equal(sort(res1), sort(res2))
 [1] TRUE

Check ?all.equal.
But they are not completely identical:
> identical(as.numeric(sort(res1)), as.numeric(sort(res2)))
[1] FALSE

The deviance from zero is due to rounding issues in R. Hence, the difference in the order of model predictors may cause this kind of differences.
Comment: @whuber...we are using the data from the R library and used a lm as I stated above. Could it have to do with the way we created the lm. I mean the order of predictors in our lm differ but we both used all the predictors?
Comment: Yes, the difference in mean residuals is due to the order of predictors. Mathematically, both models should have mean residuals of excatly 0.
Comment: thank you, my friend and I were both checking if we may have omitted something in each of our linear model when we got different results. This was helpful
Comment: @Gavin@whuber so technically if 5 people using the same dataset from R and the order of the variables being used are different in the lm, then each person will have different means. (Even though the data is the same)


Background Image on pages

Question: I want to display the content of a page in the manner as present in the image below:

Are any module present for this?
Comment: Instead of searching for the module, you should do this by theming. I mean by using css.
Comment: To print like this style you need to write custom css code, to override a default theme you are used, the Idea is very easy, jUst control your block, region and give it you style ..
Answer: As said in other answers you can do that by theming. If you want to go for modules. Then these are for you.
Background Images

Background images is a collection of modules that allows users to add background images to html elements on pages of the site

Background Images Formatter

This module provides an image formatter who allows you to set an image
in background of a div. The images are from a field of an entity and
not from a configuration page or sth else, so it's very easy to setup
and manage.
Use cases

You want to display a image on the back of a div when viewing a
particular node.
You want to display a random image on the back of a div on the
frontpage only. This can be done using Views. Create a block, select
the "Background Image" formatter for your image field, save, place
the block, boom, you're done.

Background Image on pages


Symfony 3 functional test error (KERNEL_DIR or WebTestCase)

Question: I need help regarding this, documentation doesn't help.
I have app/AppKernel.php, I don't use a custom kernel, however the functional test does not run.
phpunit.xml.dist:
<?xml version="1.0" encoding="UTF-8"?>

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="app/autoload.php"
>
    <php>
        <ini name="error_reporting" value="-1" />
        <server name="KERNEL_DIR" value="app" />
    </php>

    <testsuites>
        <testsuite name="Project Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>src</directory>
            <exclude>
                <directory>src/*Bundle/Resources</directory>
                <directory>src/*/*Bundle/Resources</directory>
                <directory>src/*/Bundle/*Bundle/Resources</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

The error:
/usr/bin/php /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/vendor/phpunit/phpunit/phpunit --no-configuration /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/tests --teamcity
Testing started at 21:35 ...
PHPUnit 6.1.0 by Sebastian Bergmann and contributors.

Either set KERNEL_DIR in your phpunit.xml according to https://symfony.com/doc/current/book/testing.html#your-first-functional-test or override the WebTestCase::createKernel() method.
 /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php:126
 /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php:165
 /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php:146
 /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php:33
 /home/jorgee/Desktop/Proyectos/Nano/proyecto-nano/tests/AppBundle/Controller/Security/LoginControllerAcceptanceTest.php:19

Comment: where's your phpunit.xml.dist file located?
Answer: You run phpunit with --no-configuration which prevents phpunit from loading the configuration file.
Either load the file, or set the KERNEL_DIR as an environment variable.
Comment: Thanks, I'm running it through PHPStorm right click -> Run. I will check if I can configure it


Interpreting linear mixed effect model results with log transformed dependent variable and log transformed predictor w/ normal predictors as well

Question: I have a linear mixed effect model that I built using longitudinal country level data to help me predict TB incidence based on country level diabetes prevalence, HIV incidence, prevalence of malnutrition, and income per capita. I found my model diagnostics improved drastically when I log transformed TB incidence, HIV incidence, and income per capita. I am now wondering how I plug known values of HIV incidence, income, malnutrition and diabetes into my model to get a measure of TB incidence that is back in its original units and no longer log transformed. My code is below, please let me know if there is anything I can add to make my question clearer.
AFR_inc_multi <- lmer(log_inc_AFR ~ `Malnutrition_prev ` +
                       log_HIV_AFR +
                    log_income + DM_prev +
                    (1|country), data=tbdata_AFR, REML = FALSE)
summary(AFR_inc_multi)
Linear mixed model fit by maximum likelihood . t-tests use
 Satterthwaite's method ['lmerModLmerTest']
Formula: log_inc_AFR ~ `Malnutrition_prev ` + log_HIV_AFR +
                    log_income +      DM_prev + (1 | country)

Data: tbdata_AFR
 AIC      BIC   logLik deviance df.resid
-45.9    -21.3     29.9    -59.9      240
Scaled residuals:
 Min       1Q   Median       3Q      Max
-2.73917 -0.49148  0.05955  0.56609  2.55527
Random effects:
Groups   Name        Variance Std.Dev.
country  (Intercept) 0.67357  0.8207
Residual             0.02319  0.1523
Number of obs: 247, groups:  country, 31
Fixed effects:
                       Estimate Std. Error         df t value Pr(>|t|)
(Intercept)            5.236917   0.387370 227.927563  13.519  < 2e-16 ***
`Malnutrition_prev `  -0.003530   0.002156 221.745552  -1.638  0.10287
log_HIV_AFR            0.224215   0.026431 242.618976   8.483 2.18e-15 ***
log_income            -0.138508   0.038422 239.064197  -3.605  0.00038 ***
DM_prev               -0.003636   0.006753 220.545834  -0.538  0.59083
-----
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Correlation of Fixed Effects:
            (Intr) `Ml_ ` l_HIV_ lg_ncm
`Mlntrtn_ ` -0.385
log_HIV_AFR -0.671 -0.008
log_income  -0.876  0.423  0.498
DM_prev      0.122 -0.089 -0.041 -0.250

Comment: It might be best to use `emmeans` and its [machinery for bias adjustment](https://cran.r-project.org/web/packages/emmeans/vignettes/transformations.html#bias-adj). Other than that, just take the income and HIV_AFR values you want to predict and log-transform them ...
Comment: Thank you for the link! So just to make sure I have it right to get my prediction for incidence back to normal units I can just do
exp(TB Incidence) = (-0.0035*Malnutrition) + exp(0.224*HIV incidence) + exp(-0.139*income) + (-0.0036*DM prevalence) + 5.23?
Comment: As an aside, why not leave the variables as is and use a nonlinear mixed model?
Comment: I looked into it briefly but I've never used non-linear mixed models before, nor have I learned about them formally in a class or job, so I didn't feel totally comfortable trying to teach them to myself because this is a time limited project I'm working on
Answer: Let's say you want to predict TB incidence for HIV prevalence 0.05, income 10000, diabetes prevalence 0.04, malnutrition prevalence 0.1
pred_data = data.frame("Malnutrition_prev "=0.1, log_HIV_AFR = log(0.05),
      log_income = log(10000), DM_prev = 0.04)
p0 <- predict(AFR_inc_multi, newdata = pred_data), re.form = NA)
exp(p0)

will give you the geometric mean prediction, independent of country. If you want to do bias correction (i.e. get the arithmetic mean), you need to compute exp(mean + var/2), or
v <- c(VarCorr(AFR_inc_multi)$country)
exp(p0 + v/2)

You can also use the built-in machinery from emmeans to handle the bias correction and back-transformation of your response (I think you'll still have to deal with log-transforming the predictor variables yourself ...)
Comment: Thank you so much! This is incredibly helpful, I really appreciate it
Comment: Coming back to this question late, but if I wanted to make a prediction for a specific country than would my code look the same except for

`re.form = NA #would instead become
re.form=(1|country)`

and I specify the country name in the data.frame step? In other words would I have to do anything different in the bias correction?
Comment: Nothing would change about the bias correction. `re.form = NULL` is equivalent to "include all RE terms that were in the original model"


Entity reference use other fields in view modes

Question: I have a student books products in drupal 7 which they have a companion teacher's book product. I want to make a view mode that presents the student book (product display) along with an entity reference to teacher's book which is also a book product.
Thing is that I can display the either id, title, or rendered entity but not other entity fields. I want to display is this:
Student's ISDN:   ______
Teacher's's ISDN: ______
... Other product fields (Student) ...
I 've tried several modules like display suite but nothing, can you please help? what I 'm missing?
Answer: A quick solution is to create a new node template for your content type. E.g: node--student.tpl.php, then use the following code as example:
$referenced_node = node_load($node->field_ref[LANGUAGE_NONE]['0']['target_id']);
print node_view($referenced_node, "teaser");

Hope this helps.
Comment: I don't use views, I just use view mode for displaying a single node.
Comment: Not sure if node_load works with entities, I am  trying to do it through module using hook_node_view()
Comment: This code retrieves the `nid` from the referencing node, then uses `node_load` to load the node object. Nothing strange :)
Comment: I use entity reference. I get entity this way $teachers_book_entity = $node->field_teacher_book[LANGUAGE_NONE][0]['entity']; Also I don't need to print a view mode (teaser) just a field: ISBN.
Comment: If you load the entire teacher book node using the node_load method above, you should then be able to get to any of the fields...
Answer: I did it this way:
  // Initial weight
  $weight = 2;
  // Student's book entity
  $student_book_entity = $node->field_student_book[LANGUAGE_NONE][0]['entity'];

  // Get Student's book ISBN and alter some attributes
  $student_isbn_field = array_merge(field_view_field('commerce_product', $student_book_entity, 'field_book_isbn'), array(
      '#field_name' => 'field_students_book_isbn',
      '#title' => t('Student\'s Book ISBN'),
      '#weight' => $weight++,
    )
  );
  $node->content['field_students_book_isbn'] = $student_isbn_field;

  // Teacher's book entity
  $teachers_book_entity = $node->field_teacher_book[LANGUAGE_NONE][0]['entity'];

  // Get Teacher's book ISBN and alter some attributes
  $teacher_isbn_field = array_merge(field_view_field('commerce_product', $teachers_book_entity, 'field_book_isbn'), array(
      '#field_name' => 'field_teachers_book_isbn',
      '#title' => t('Teacher\'s Book ISBN'),
      '#weight' => $weight++,
    )
  );
  $node->content['field_teachers_book_isbn'] = $teacher_isbn_field;


Remover espaços em branco entre as tds

Question: Olá, estou a desenvolver um projeto que usa a estrutura de tabela e que em cada linha excepto a linha do cabeçalho sempre que existir um hover sobre ela, a mesma fica com um cinza claro mas aqui para se ver bem coloquei um azul forte, mas só que entre as colunas no efeito do hover nota-se um espaço branco e eu queria saber como tiro esse espaço?
Obrigado pelas respostas, ambas funcionam, mas infelizmente só da para aceitar uma!

* {
            margin: 0;
            padding: 0;
            box-sizing:border-box;
        }
        body {
          font-family: Helvetica;
          -webkit-font-smoothing: antialiased;
        }
        ul {
          list-style-type: none;
          margin: 0;
          padding: 0;
          overflow: hidden;
          background-color: #333;
        }
        li {
          float: left;
        }
        li a {
          display: block;
          color: white;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
        }
        li a:hover:not(.active) {
          background-color: #111;
        }
        .wellcome{
            background-color: #444;
        }
        .wc{
    padding: 14px 16px;
    font-size: 18px;
    color: white;
    text-align: center;
  }
  .active {
    background-color: #4CAF50;
  }
  .modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 18%;
}
div#regit{
  width: 90%;
  margin: 10px auto;
}
div#regit table{
  width: 100%;
  padding: 10px;
}
.espca{
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
div#regit table tr:hover:not(.header){
  background: blue;
}
div#select{
  cursor: pointer;
  width: 40px;
  height: 40px;
  border: 1px solid #000;
  padding: 10px;
}
.cruz{
  font-size: 18px;
  cursor: pointer;
}
.desativado{
  visibility: hidden;
}
.noselect{
  user-select: none;
}
<!DOCTYPE html>

<meta charset="UTF-8">
<title>SMART DNS | Controlo de Bloqueios</title>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" media="all">

 Novo Registo

 Lista de Sites

 Lista de Categorias

 Pedidos de Desbloqueios

 Sair

Selecionar
Pagina Web
Categorias

X

google.com
Cat1, Cat2

A carregar registos!

Comment: Valeu a força :)
Answer: Vc tem que adicionar a propriedade border-collapse: collapse; na
 isso vai remover os "espaços" entre as células.
Edit: O border-collapse: collapse; parece que por algum motivo também remover o padding da table. Então pode ser que a melhor opção para vc realmente seja a resposta do @sam. Mas vou deixar essa opção só para constar que tb é uma alternativa, apesar de funcionar de forma diferente do border-spacing

table {
    border-collapse: collapse;
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Helvetica;
    -webkit-font-smoothing: antialiased;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #111;
}

.wellcome {
    background-color: #444;
}

.wc {
    padding: 14px 16px;
    font-size: 18px;
    color: white;
    text-align: center;
}

.active {
    background-color: #4CAF50;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 18%;
}

div#regit {
    width: 90%;
    margin: 10px auto;
}

div#regit table {
    width: 100%;
    padding: 10px;
}

.espca {
    border-bottom: 1px solid #ccc;
    padding: 10px;
}

div#regit table tr:hover:not(.header) {
    background: blue;
}

div#select {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border: 1px solid #000;
    padding: 10px;
}

.cruz {
    font-size: 18px;
    cursor: pointer;
}

.desativado {
    visibility: hidden;
}

.noselect {
    user-select: none;
}
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" media="all">

 Novo Registo

 Lista de Sites

 Lista de Categorias

 Pedidos de Desbloqueios

 Sair

            Selecionar
            Pagina Web
            Categorias

X

            google.com
            Cat1, Cat2

A carregar registos!

Answer: O navegador aplica na tabela um border-spacing (espaço entre as bordas das células) padrão de 2 pixels:

Basta alterar esse valor para 0 usando o id da tabela:
#tabela{
   border-spacing: 0;
}

Veja:

#tabela{
   border-spacing: 0;
}

* {
            margin: 0;
            padding: 0;
            box-sizing:border-box;
        }
        body {
          font-family: Helvetica;
          -webkit-font-smoothing: antialiased;
        }
        ul {
          list-style-type: none;
          margin: 0;
          padding: 0;
          overflow: hidden;
          background-color: #333;
        }
        li {
          float: left;
        }
        li a {
          display: block;
          color: white;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
        }
        li a:hover:not(.active) {
          background-color: #111;
        }
        .wellcome{
            background-color: #444;
        }
        .wc{
    padding: 14px 16px;
    font-size: 18px;
    color: white;
    text-align: center;
  }
  .active {
    background-color: #4CAF50;
  }
  .modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 18%;
}
div#regit{
  width: 90%;
  margin: 10px auto;
}
div#regit table{
  width: 100%;
  padding: 10px;
}
.espca{
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
div#regit table tr:hover:not(.header){
  background: blue;
}
div#select{
  cursor: pointer;
  width: 40px;
  height: 40px;
  border: 1px solid #000;
  padding: 10px;
}
.cruz{
  font-size: 18px;
  cursor: pointer;
}
.desativado{
  visibility: hidden;
}
.noselect{
  user-select: none;
}
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" media="all">

 Novo Registo

 Lista de Sites

 Lista de Categorias

 Pedidos de Desbloqueios

 Sair

Selecionar
Pagina Web
Categorias

X

google.com
Cat1, Cat2

A carregar registos!

Comment: Realmente Sam, o `border-spacing` vai interferir menos no "layout" que ele fez. Deixei o edit na minha resposta que vou eixar lá só pra constar mesmo como uma opção...

Remover espaços em branco entre as tds


Somar valores de diferentes índices do JSON

Question: Tenho uma API que um trecho dela retorna o seguinte array, e para cada index tem um objeto slas que traz todas as transportadoras:
[
  {
    "itemIndex": 0,
    "selectedSla": "Expressa",
    "selectedDeliveryChannel": "delivery",
    "slas": [
      {
        "name": "Expressa",
        "shippingEstimate": "2bd",
        "price": 1390
      },
      {
        "name": "SEDEX",
        "shippingEstimate": "2bd",
        "price": 1990
      },
      {
        "name": "Retira em SÃO PAULO (1936769)",
        "shippingEstimate": "1bd",
        "price": 0
      }
    ]
  },
  {
    "itemIndex": 1,
    "selectedSla": "Expressa",
    "selectedDeliveryChannel": "delivery",
    "slas": [
      {
        "name": "Expressa",
        "shippingEstimate": "2bd",
        "price": 1390
      },
      {
        "name": "SEDEX",
        "shippingEstimate": "2bd",
        "price": 1990
      },
      {
        "name": "Retira em SÃO PAULO (1936769)",
        "shippingEstimate": "1bd",
        "price": 0
      }
    ]
  }
]

Eu queria somar o valor total de cada transportadora.
Exemplo:
0: EXPRESSA 13,90 + 1: EXPRESSA 13,90

0: SEDEX 19,90 + 1: SEDEX 13,90

Comment: Como exemplo pode olhar para [esta](https://pt.stackoverflow.com/questions/221342/agrupar-json-utilizando-reduce-do-javascript) ou [esta](https://pt.stackoverflow.com/questions/342198/l%c3%b3gica-para-agrupar-dados-em-array-javascript)
Comment: Poderia postar o retorno exato da api, como postou não está válido.
Comment: @LeAndrade o json é muito extenso por isso resumi ele no trecho que referente.
Comment: Do jeito como está não tem como formar uma resposta correta, pois, não tem como saber a  estrutura do json.
Comment: @LeAndrade Desculpe, agora esta validado o json.
Comment: Se o objetivo é agrupar pelo `slas` já existem perguntas sobre  isso
Comment: @Isac Não achei nada similar, poderia informar qual perguntas são?!
Answer: Dá para fazer o que quer utilizando os métodos map() e reduce() do seguinte modo:

let retorno = [
  {
    "itemIndex": 0,
    "selectedSla": "Expressa",
    "selectedDeliveryChannel": "delivery",
    "slas": [
      {
        "name": "Expressa",
        "shippingEstimate": "2bd",
        "price": 1390
      },
      {
        "name": "SEDEX",
        "shippingEstimate": "2bd",
        "price": 1990
      },
      {
        "name": "Retira em SÃO PAULO (1936769)",
        "shippingEstimate": "1bd",
        "price": 0
      }
    ]
  },
  {
    "itemIndex": 1,
    "selectedSla": "Expressa",
    "selectedDeliveryChannel": "delivery",
    "slas": [
      {
        "name": "Expressa",
        "shippingEstimate": "2bd",
        "price": 1390
      },
      {
        "name": "SEDEX",
        "shippingEstimate": "2bd",
        "price": 1990
      },
      {
        "name": "Retira em SÃO PAULO (1936769)",
        "shippingEstimate": "1bd",
        "price": 0
      }
    ]
  }
];

let expressa = [];        // arrays que serão guardados os objetos similares
let sedex = [];
let retira = [];

let dados = retorno.map(x => x.slas);          // mapeia os objetos que queremos

expressa = dados.map(x => x[0]);              // insere os objetos similares no array
sedex = dados.map(x => x[1]);
retira = dados.map(x => x[2]);

let valorExpressa = expressa.reduce((a,b) => {   // faz a soma dos valores
  return a + b.price;
},0);

let valorSedex = sedex.reduce((a,b) => {
  return a + b.price;
},0);

let valorRetira = retira.reduce((a,b) => {
  return a + b.price;
},0);

console.log('Valor Expressa: ', valorExpressa);
console.log('Valor SEDEX: ', valorSedex);
console.log('Valor Retira: ', valorRetira);
Comment: No caso do array das transportadoras, em algumas condições será 2 e outra 3.
E futuramente terá mais, como deixar isso dinâmico?
Comment: Como assim? Não entendi.
Comment: você criou um array pra cada transportadora, ali no caso estão 3 definidas como deixar isso dinamico, ao invés de deixar manual, entendeu?
Comment: Então, esses arrays são os recipientes para cada transportadora, eu preciso criar um array para cada um, se não, não consigo fazer a soma dos valores de cada uma.
Comment: Ao invés de criar um array pra cada transportadora, eu vou tirar um único com todas e o valor já somado, assim fica mais fácil de trabalhar e dinâmico.

Muito obrigado pela sua ajuda!
Comment: Sim, pode ser tbm, é que para dar uma reposta mais conclusiva, precisaria ter uma visão maior de como chegariam esses dados, foi uma maneira que vi de fazer no momento, mas, se conseguiu resolver melhor. Sucesso aí man!
Answer: Cheguei em uma solução "dinâmica" utilizando somente métodos de iteração do protótipo do Array:

const data = [{
  itemIndex: 0,
  selectedSla: 'Expressa',
  selectedDeliveryChannel: 'delivery',
  slas: [
    { name: 'Expressa', shippingEstimate: '2bd', price: 1390 },
    { name: 'SEDEX', shippingEstimate: '2bd', price: 1990 },
    { name: 'Retira em SÃO PAULO (1936769)', shippingEstimate: '1bd', price: 0 }
  ]
}, {
  itemIndex: 1,
  selectedSla: 'Expressa',
  selectedDeliveryChannel: 'delivery',
  slas: [
    { name: 'Expressa', shippingEstimate: '2bd', price: 1390 },
    { name: 'SEDEX', shippingEstimate: '2bd', price: 1990 },
    { name: 'Retira em SÃO PAULO (1936769)', shippingEstimate: '1bd', price: 0 }
  ]
}];

function getSumFrom(list) {
  return list
    .map((arr) => arr.slas)
    .flat(1) // Juntamos todos os arrays de objetos em um único array de objetos.
    .reduce((acc, current) => {
      const name = current.name;
      const price = current.price;

      // Basicamente, estamos adicionando ao acumulador (`acc`)
      // o nome da empresa. Para isso, estamos somando o valor do
      // preço da iteração atual ao valor já existente.
      //
      // Se o valor existente ainda não existir, consideramos que
      // ele seja zero.
      // (`acc[name] || 0` diz: se `acc[name]` for falsey, assuma zero).
      acc[name] = (acc[name] || 0) + price;
      return acc;
    }, {});
}

console.log(getSumFrom(data));

Tentei não deixar o código muito complexo no excerto acima para facilitar a leitura do código para quem está iniciando na linguagem. Mas se você já está mergulhando mais fundo no JavaScript, o código acima pode ser reduzido:

const data = [{
  itemIndex: 0,
  selectedSla: 'Expressa',
  selectedDeliveryChannel: 'delivery',
  slas: [
    { name: 'Expressa', shippingEstimate: '2bd', price: 1390 },
    { name: 'SEDEX', shippingEstimate: '2bd', price: 1990 },
    { name: 'Retira em SÃO PAULO (1936769)', shippingEstimate: '1bd', price: 0 }
  ]
}, {
  itemIndex: 1,
  selectedSla: 'Expressa',
  selectedDeliveryChannel: 'delivery',
  slas: [
    { name: 'Expressa', shippingEstimate: '2bd', price: 1390 },
    { name: 'SEDEX', shippingEstimate: '2bd', price: 1990 },
    { name: 'Retira em SÃO PAULO (1936769)', shippingEstimate: '1bd', price: 0 }
  ]
}];

function getSumFrom(list) {
  return list
    .flatMap(({ slas }) => slas)
    .reduce(
      (acc, { name, price }) => ({
        ...acc,
        [name]: (acc[name] || 0) + price
      }),
      {}
    );
}

console.log(getSumFrom(data));

Eu pessoalmente prefiro essa segunda abordagem, mas isso é pessoal. :)


removing an element from String array in android

Question: Am doing a simple android application.In that I am deleting an element from array using the following code.
 arr_fav = {"1","2","3"};
 for(int i= 0;i<arr_fav.length;i++)
 {
     if(current_id == Integer.parseInt(arr_fav[i]))
     {
        arr_fav[1] = null;
     } }

By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
Comment: You can convert it to arraylist
Comment: if you need something more general http://stackoverflow.com/a/122207/619713
Comment: Optimization Parse one time current_id to string and equal it to arr_fav[i]
Answer: its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
 if(current_id == Integer.parseInt(arr_fav[i]))
 {
   // No operation here
 }
 else
 {
     numlist.add(arr_fav[i]);
 }
}
 arr_fav = numlist .toArray(new String[numlist .size()]);

Comment: Yes, but the only feature of the `ArrayList` you're using is `add()`.  If you're just going to add things one by one to the end of a list, you can use a simple array.  The OP wanted to remove something from the middle of a list.  Iterating through the entire list and putting everything **but** the deleted item into a new list is not a solution that requires or takes advantage of the `ArrayList` functionality.
Comment: It is indeed better to use an array list, but the way you're using it does not utilize any of its advantages.  In your code above, `numlist` could be an array.
Comment: @The111, Here i am using arraylist instead of resizing array, as java does not provide resizing of its array by default. please check it carefuylly
Comment: @Madhumitha - Yes it "works", but you really should read the above comment.
Answer: You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Comment: Dear lord, **I was editing when you commented**, which was about 30 seconds after I posted the revision you're complaining about. Nevermind that without trying to be Ranger Rick you could simply have said "Hey, that's not *exactly* correct".
Comment: -1 for "a  `List` which is dynamic". The `List` interface does not require it being dynamic, it can even be immutable.
Comment: THank you Mr. pedantic. I guess "of some sort which would be dynamic" wasn't clear enough? Nevermind, I'll edit it just for you.
Comment: At least be honest. A previous version of the answer was **exactly** as I cited, and not "that would be..." if you later edited it, it's a different story. Long story short - my comment +downvote did exactly what it should have been - made you change the answer to something more accurate.
Answer: Arrays in Java are not dynamic, you can use an ArrayList instead.
Comment: check out my code.if you have more element you should use variables for swapping elements.
Answer: You can copy the array elements that you want into a new array
 j = 0;
 for(int i= 0;i<arr_fav.length;i++)
  {
   if(current_id != Integer.parseInt(arr_fav[i]))
 {
    arr_new[j++] = arr_fav[i];
 } }

Answer: Use an ArrayList instead of an array.  It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);

Comment: this is not exact answer. as he is checking the current_id with in array.
Comment: No, it is not an exact answer.  It's an illustration how to use the `remove()` method of `ArrayList`, clearly.
Answer: This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();

Comment: 1. arr_fav is string array and you remove integer
Comment: Thanks for the tip. Updated to use String.valueOf.
Answer: Try something like this
int[] intAry = new int[5];

// populate array with 0 to 4

for (int i=0; i < intAry.length; i++) {

  intAry[i] = i;

}

List<Integer> aList  = Arrays.asList(intAry); // change the array to a list of integers

aList.remove(3); // remove the item 3 (4th index)

aList.toArray(intAry); // convert list back to array

System.out.println("size of array=" + intAry.size()); // output array size should be 4

for (int i=0; i < intAry.length; i++) {

  System.out.print(intAry[i] + " "); // should output "0 1 2 4 "

}

Answer: try this:
    ArrayList<String> rm = new ArrayList<String>();
    rm .addAll(arr_fav);
    rm .remove(1);

Answer: You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();

for(String item : input)
    if(!deleteMe.equals(item))
        result.add(item);

return result.toArray(input);
}

OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)

Comment: it's internal class com.android.internal.util.ArrayUtils
Comment: Ah Ok but i think he develops for Android
Answer: set
    array_fav[1]=array_fav[2];
    array_fav[2]=null;

Answer:     String[] arr_fav =
    { "1", "2", "3" };

    List<String> myList = Arrays.asList(arr_fav);

            String currentId = String.valueOf(current_id);
    for (int i = 0; i < arr_fav.length; i++)
    {
        if (arr_fav[i].equals(currentId))
        {
            myList.remove(i);
        }
    }

Answer: For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
        String[] arr_fav = { "1", "2", "3" };
        for (int i = 0; i < arr_fav.length; i++) {
            if (current_id == Integer.parseInt(arr_fav[i])) {
                String[] arr_fav_tem = new String[arr_fav.length - 1];
                arr_fav[1] = null;
                int counter = 0;
                for (int j = 0; j < arr_fav.length; j++) {
                    if (arr_fav[j] != null) {

                        arr_fav_tem[counter] = arr_fav[j];
                        counter++;
                    }

                }

                arr_fav = arr_fav_tem;

            }
        }

        for (int i = 0; i < arr_fav.length; i++) {
            System.out.println(arr_fav[i]);
        }

Answer:  private String[] removeItem(String[] names,
            int position) {

        ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList

    for(int i=0;i<names.length;i++)
        {
            al_temp.add(names[i]);
        }

        al_temp.remove(position);
        names= new String[al_temp.size()];//array cleared with new size

        for(int i=0;i<al_temp.size();i++)
        {
            names[i]=al_temp.get(i);
        }

        return names;
    }

Answer: Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
    String[] result = new String[array.length];
    int index = 0;

     ArrayList<String> rm = new ArrayList<String>();

    for(int i = 0; i < array.length; i++) {
        rm.add(array[i]);
    }
    for(int i = 0; i < array.length; i++) {
        if(array[i].equals(poistettava)) {
            index = i;
        }
    }
    rm.remove(index);

    result = rm.toArray(new String[rm.size()]);

    return result;
}

To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);


Como estilizar elementos dentro da tag ?

Question: Oi, eu estava tentando criar um "editor de texto" para programar lua, eu tentei mudar a cor da palavra function toda vez que fosse digitada, mas me deparei com algo, não consigo estilizar nenhum elemento dentro da textarea,
aqui está o codigo que eu estava usando:

var wait = "";
var txt = "";
words = [];

window.onkeydown = function(e) {
  txt = document.getElementById('b').value;
  var z = String(txt);
  if (String.fromCharCode(e.keyCode) == " ") {
    words.push(wait);
    wait = "";
  }
  var y = z.replace("function", "hello");
 document.getElementById('b').value = y

}
function myFunction(event) {
    if (window.event) {
      evt = window.event;
      wait = wait + String.fromCharCode(evt.keyCode);
      console.log(wait)
  };
}
Comment: `textarea` não aceita elementos, apenas texto. Por isso vc não pode estilizar partes do texto a não ser o texto todo.
Answer: Uma maneira de se chegar ao resultado, é fazendo o seguinte:
Crie uma textarea vou setar o atributo id como editor_back.
<textarea id="editor_back"></textarea>

Aplique o CSS
#editor_back {
    color: transparent;
    background: transparent;
    border: 1px solid #ccc;
    position: absolute;
    padding: 10px;
    z-index: 5;
    height: 250px;
    width: 250px;
    font-family: 'Verdana';
    font-size: 0.875em;
}

Crie uma div vou setar o atributo id como editor_front.

Aplique o CSS
#editor_front {
    background: #e9e9e9;
    border: 1px solid #ccc;
    padding: 10px;
    position: absolute;
    z-index: 1;
    height: 250px;
    width: 250px;
    font-family: 'Verdana';
    font-size: 0.875em;
}

Note que a div ficará abaixo da textarea, por isso definimos o background e color como transparentes.
Adicione o evento keypress na textarea
editor_back.addEventListener('keyup', function(e) {
    txt = editor_back.value;
    var y = txt.replace(/(function\s)([a-z]*)(\(\))/g, 'function $2()');
    y = y.replace(/(\s?)function\s/g, '$1function ');
    y = y.replace(/(\s?)\(\)/g, '$1()');
    editor_front.innerHTML = y
});

Veja funcionando:

var txt = "";
var editor_front = document.querySelector('#editor_front');
var editor_back = document.querySelector('#editor_back');

editor_back.addEventListener('keyup', function(e) {
    txt = editor_back.value;
    var y = txt.replace(/(function\s)([a-z]*)(\(\))/g, 'function $2()');
    y = y.replace(/(\s?)function\s/g, '$1function ');
    y = y.replace(/(\s?)\(\)/g, '$1()');
    editor_front.innerHTML = y
});
#editor_front {
  background: #e9e9e9;
  border: 1px solid #ccc;
  padding: 10px;
  position: absolute;
  z-index: 1;
  height: 250px;
  width: 250px;
  font-family: 'Verdana';
  font-size: 0.875em;
}

#editor_back {
  background: transparent;
  border: 1px solid #ccc;
  color: transparent;
  position: absolute;
  padding: 10px;
  z-index: 5;
  height: 250px;
  width: 250px;
  font-family: 'Verdana';
  font-size: 0.875em;
}

span.func {
  color: red;
}
span.func_name {
  color: #069;
  font-weight: bold;
}
span.par {
  color: green;
}

#ver_html {
  bottom: 0;
  position: absolute;
}

<textarea id="editor_back" cols="30" rows="10"></textarea>
Answer: Eu vi por aí vários sistemas de Syntax Highlighting que eu entendi que é o caso, eu poderia te explicar como criar o seu próprio, fazer o textarea ficar invisível por CSS e atrás dele ter um DIV (com barra de rolagem) que formataria automaticamente o texto, mas precisaria entender muito de Expressão regular para converter o texto digitado já formatado para DIV visível.
Sem contar que teria que ter um método de auto-selecionar o texto da DIV se parte do texto escrito na TEXTAREA fosse selecionado.
Então não acho viável, o melhor mesmo é pegar essas APIs prontas pra isso:

https://highlightjs.org/ - Demonstração:
https://highlightjs.org/static/demo/
http://prismjs.com/ - Demonstração: http://prismjs.com/test.html
https://codemirror.net/index.html - Demonstração: https://codemirror.net/demo/fullscreen.html

Mas vai ficar a seu critério escolher um dos exemplos ou encontrar outro que combine com o sistema que você quer montar.


How to modify a view's empty text to show a different message depending the user viewing it

Question: I have created a view displaying a user's blog entries. In view's empty text i have put the simple php code showing below
    You have not created any blog entries.
    You can create a
Now i want to modify it to implement the following scenario.
1. When a user visit his/her profile page the above empty text should be appear. 2. If a user visit an another user profile page then i want the empty text to have the following value
        [username of the user that own's the profile page] hasn't created any blog entries.
Can anyone help me to achieve this? Thanks in advance.
Answer: Do you have the php filter input format turned on for your site? You can do this by adding the following code into your empty text field with the input format 'php code' enabled:
<code>//get the current $user object to determine the logged in user's id
global $user;

//now load the user id from the profile page into another object by pulling it from path
$usertmp = user_load(array('uid' => arg(1)));

if ($user->uid == $usertmp->uid) {
     //we're on the logged in user's page
     print "You need to write more stories..";
} else {
     print $usertmp->name." needs to write more stories.. ";
}
</code>
Comment: Thank you very much for your help. I came up with [script](http://pastebin.com/C4twHLYz). It isn't elegant since i started now to learn php but it get the job done.


Jboss Fuse and Cobertura

Question: I have my application which runs in Jboss Fuse on Linux. I deploy my artifacts as jar files under the /deploy directory. I was planning to make use of Cobertura to get code coverage report after executing my jmeter tests. I instrumented my jars and placed under /deploy. I ran my jmeter tests.
Now I am unable to find  the location where <code>.ser</code> file will be present.
I tried searching inside fuse directory.
Can anyone help me in getting Cobertura working with Jboss Fuse?
Answer: For most versions of Cobertura, you can add:
<code> -Dnet.sourceforge.cobertura.datafile=<filename>.ser
</code>
to the JBoss/JVM startup parameters (e.g. run.conf) to specify explicitly the file where you want the report to be created.
Also, you need to make sure the cobertura.jar itself is present in the classpath if you haven't done so yet.
Comment: Thanks Patrice, I cant find run.conf.  I made changes as follows.
in bash_profile  i have cobertura-2.1.1.jar added in path.I also have -Dnet.sourceforge.cobertura.datafile=/tmp/c.s mentioned in JAVA_OPTS.After these changes i did source .bash_profile and started fuse in same terminal and ran my automation scripts. I cant see file /tmp/c.s generated.   Any idea what other changes will be required ?
Comment: Sorry, I'm not very familiar with JBoss Fuse, but I think you need to somehow make sure JAVA_OPTS is taken into account when it starts up. For the cobertura.jar, you meant added to the classpath, right? Not the PATH which won't give you anything. Typically you can drop it in to some server lib folder, OR package it into your application archive, if that helps.

Jboss Fuse and Cobertura


How to apply a t-test for product failure?

Question: Background: I'm trying to determine if there is a difference in the rate of failure between two populations. Population 1 is an engine run on one type of fuel.  Population 2 is the same engine run on a different type of fuel.
I have 1000 engines in my first group along with the list of when they failed [5,8,10...]
I have 100 engines in the second group [6,12...]
If everything failed I could test if the means were different with a 2 sample unpaired t test, however since most of the engines never failed, I'm not sure how to easily test whether the two populations really the same.
Comment: Since it is unlikely the engine failure times is a normal distribution and many engineers are still running.  I would not recommend the t-test.  I would recommend a ranked sum test such as the Wilcoxon test.  I suggest a Google search on a survival tests.
Comment: @Dave2e the t-test does not require that the distribution of the sample is normally distributed. Even so, performing a t-test on the log transformed performance times to reduce the influence of long-surviving components could avail two times the power of a rank-based test.
Answer: This is a classic situation for survival analysis, which by design takes into account cases for which there has been no failure by the end of the study.
If you only have 2 groups, no predictors other than the type of fuel, and you don't consider any engines that might have been repaired and put back into service, then showing Kaplan-Meier estimates of survival over time for each group and using a log-rank test to compare the 2 groups would be a standard approach. Tools are provided by standard statistical software, for example the survival package in R.
Comment: +1 Echoing that the `survival` also allows for parametric survival regression with censored data, such as an exponential or Weibull distributions which would allow for predictions and post-hoc estimates of mean survival time and perhaps greater power.
Comment: Do you have a recommendation for packages in python?
Comment: @JonathanHay see the [`lifelines`](https://github.com/CamDavidsonPilon/lifelines/blob/master/docs/Survival%20analysis%20with%20lifelines.rst) package. The link is to an explanation of how to use it, starting with Kaplan-Meier and log-rank, then going on to parametric models.


Unique factorization of ideals?

Question: Is it case that even if the domain is not UFD for its elements, the domain is UFD for ideals.
I mean can we uniquely factorize the ideals, whatsoever? Is that possible, and why?
For example, in $\mathbb{Z}[\sqrt{-14}]$, can we factorize: $\langle 30\rangle = \langle 2 \rangle \langle 3 \rangle \langle 5 \rangle$?
Thanks.
Comment: See also http://math.stackexchange.com/questions/39767/lack-of-unique-factorization-of-ideals.
Comment: $(5)$ and $(3)$ are not prime ideals, because $(1+\sqrt{-14})(1-\sqrt{-14})=15\in (3)\cap(5),$ but neither factor is $(3)$ or $(5).$
Comment: So the correct prime factorization is: $$(30)=(2,\sqrt{-14})^2(1+\sqrt{-14},3)(1-\sqrt{-14},3)(1+\sqrt{-14},5)(1-\sqrt{-14},5)$$
Answer: Yes, $\mathbb{Z}[\sqrt{-14}]$ is the ring of integers $\mathcal{O}_K$ for the imaginary quadratic number field $\mathbb{Q}(\sqrt{-14})$. Since $\mathcal{O}_K$ is a Dedekind ring, we have unique factorisation for ideals, although the ring itself is not factorial.
The factorization is referring to prime ideals in $\mathcal{O}_K$. Note that not all ideals $(p)$ with a rational prime $p$ are necessarily prime ideals in $\mathcal{O}_K$. However, with the help of the Legendre symbol, you can decide whether $(2)$, $(3)$ resp. $(5)$ are prime ideals in $\mathbb{Z}[\sqrt{-14}]$.
Comment: Isn't $(1+\sqrt{-14})(1-\sqrt{-14})\in\langle 3\rangle\cap\langle 5\rangle?$ So how can $\langle 3\rangle$ and $\langle 5\rangle$ be prime?
Comment: @ThomasAndrews I didn't say that they are prime. But you can decide it for $(p)$ by computing $(D/p)$ for the discriminant $D$. For example, since $(D/p)=(-14/3)=(1/3)=1$, $(3)$ splits. So $(3)=P_1P_2$. The same holds for $(5)$, since $(-14/5)=1$ as well.
Answer: The domains for which there is unique factorization for ideals are called Dedekind domains. Rings of integers of algebraic number fields are the prime example.
Not all domains are Dedekind. An equivalent definition is integrally closed, Noetherian domain in which every nonzero prime ideal is maximal.
Answer: Yeah, that's kind of the point of ideals, to "restore" unique factorization to a domain that never had it in the first place.
To make sure we're on the same page, let's review the definitions of principal ideals and ideals in general. Let's say $p$ is a prime number, and $a$ and $b$ are some arbitrary numbers in the same domain as $p$. If $p$ is indeed prime and $p \mid ab$, then it must be the case also that $p \mid a$ and/or $p \mid b$.
The ideal $\langle p \rangle$ consists of all numbers of the form $px$, where $x$ is any number in the domain whatsoever. Likewise, $\langle a \rangle$ consists of all numbers of the form $ax$ and $\langle b \rangle$ consists of all numbers of the form $bx$. If $\langle p \rangle$ is a prime ideal and $\langle ab \rangle \subset \langle p \rangle$, then $\langle a \rangle \subset \langle p \rangle$ and/or $\langle b \rangle \subset \langle p \rangle$.
For example, in $\mathbb Z$, we find that 2 is prime but 4 is not. Verify that $\langle 2 \times 14 \rangle \subset \langle 2 \rangle$ and indeed $\langle 2 \rangle \subseteq \langle 2 \rangle$ and $\langle 14 \rangle \subset \langle 2 \rangle$. But even though $\langle 2 \times 14 \rangle \subset \langle 4 \rangle$ we find that $\langle 2 \rangle \not\subset \langle 4 \rangle$ and $\langle 14 \rangle \not\subset \langle 4 \rangle$ either.
A principal ideal is generated by just one number. But an ideal can also be generated by two numbers. Thus $\langle m, n \rangle$ consists of all numbers of the form $mx + ny$, where $x$ and $y$ are any pair of numbers in the domain whatsoever.
Ideals generated by two numbers are really useful in domains like $\mathbb Z[\sqrt{-14}]$. Take a number like $2 + \sqrt{-14}$. This number is not in $\langle 2 \rangle$, because there is no number $x \in \mathbb Z[\sqrt{-14}]$ such that $2x = 2 + \sqrt{-14}$. Nor is this number in $\langle \sqrt{-14} \rangle$, because there is no number $x \in \mathbb Z[\sqrt{-14}]$ such that $x \sqrt{-14} = 2 + \sqrt{-14}$. However, it is in $\langle 2, \sqrt{-14} \rangle$, just set $x = y = 1$.
Furthermore, $\langle 2 \rangle \subset \langle 2, \sqrt{-14} \rangle$ and $\langle \sqrt{-14} \rangle \subset \langle 2, \sqrt{-14} \rangle$ as well. Neither $\langle 2 \rangle$ nor $\langle \sqrt{-14} \rangle$ are prime ideals, but $\langle 2, \sqrt{-14} \rangle$ is.
And so, it turns out that $\langle 30 \rangle = \langle 2 \rangle \langle 3 \rangle \langle 5 \rangle$ is a correct but incomplete factorization, just as $\langle 5 \rangle \langle 6 \rangle$ is also incomplete. The complete factorization of $\langle 30 \rangle$ in $\mathbb Z[\sqrt{-14}]$ is $\langle 2, \sqrt{-14} \rangle^2 \langle 3, 1 - \sqrt{-14} \rangle \langle 3, 1 + \sqrt{-14} \rangle \langle 5, 1 - \sqrt{-14} \rangle \langle 5, 1 + \sqrt{-14} \rangle$.
As an exercise, verify that although $(4 - \sqrt{-14})(4 + \sqrt{-14}) = 30$ is a distinct factorization of 30 as a number, neither $\langle 4 - \sqrt{-14} \rangle$ and $\langle 4 + \sqrt{-14} \rangle$ are prime ideals, and presents no challenge whatsoever to the uniqueness of the factorization of the ideal $\langle 30 \rangle$.

Unique factorization of ideals?


Python + CSV: Need to retrieve index for each blank cell in a row, even if they repeat

Question: I'm attempting to process some CSV data using Python 3 and the csv library, and some rows have blank cells:

ID
attribute
price
color

1
spicy
cheap
red

2

blue

3
fuzzy
expensive
green

I need to reformat the data to hand off to someone else who will load it. It needs to look like the example below. (Why, you ask? See "hand off to someone else who will load.")

ID
VALUE
HEADER

1
spicy
attribute

1
cheap
price

1
red
color

...
...
...

I've put the headers in a dict (keys are integers corresponding to column position). I'm attempting to use the index of each cell in a row to retrieve the corresponding header.
Problem is, when two or more blank cells exist together in a row, the cell index *does not iterate. A snippet showing just this problem is just below.
with open('testdata/csv_test_in_003.csv', encoding = 'utf-8-sig', errors = 'ignore', newline = '') as file_in:
        reader = csv.reader(file_in)
        for row in reader:
            row_is_dict = {}
            for cell in row:
                content = {row.index(cell): cell}
                row_is_dict.update(content)
            print(row_is_dict)

*I suppose rather than saying that the cell index value "does not iterate," I should instead simply say that the second blank cell simply isn't processed.
From output:
{0: '2', 1: '', 3: 'blue'}`

As a result, when I'm writing to an output file (excerpt below)...
import csv
[...]
for cell in row:
   newrow = []
   [...] # skip first cell, only process following cells
      newrow.append(row[0]) # get ID, which must be in leftmost column
      newrow.append(cell) # get value
      newrow.append(headers[cellindex]) # fail :( to get the correct header
      writer.writerow(newrow)

...and I encounter a row with two or more blanks in a row, I get the same header repeated for each of the blanks, something like this:

ID
VALUE
HEADER

2

attribute

2

attribute*

2
blue
color

*This should be 'price'
I suspect many of you with much more Python experience than myself might suggest using a completely different approach for processing the data, perhaps using pandas or another toolset. If possible, please give me answers which not require knowledge of pandas or another such framework, but would simply allow me to tweak my approach.
Answer: You can use csv.DictWriter for the task. I assume the empty cells are strings '':
import csv

with open("data.csv", "r") as f_in:
    reader = csv.DictReader(f_in)

    out = []
    for row in reader:
        for key in row.keys() - ["ID"]:
            out.append({"ID": row["ID"], "VALUE": row[key], "HEADER": key})

with open("out.csv", "w") as f_out:
    writer = csv.DictWriter(f_out, fieldnames=["ID", "VALUE", "HEADER"])
    writer.writeheader()
    writer.writerows(out)

Creates out.csv (screenshot from LibreOffice):
Comment: Belated thank you to [Andrej](https://stackoverflow.com/users/10035985/andrej-kesely).
I ended up going [a different route](https://gist.github.com/briesenberg07/1d3bdc9d079a8581768088dea1111f6b#file-02_reformat_csv-py), just using csv.reader and writer (not DictReader and DictWriter).
Iterating through a [range](https://gist.github.com/briesenberg07/1d3bdc9d079a8581768088dea1111f6b#file-02_reformat_csv-py-L29) equaling the number of header columns (instead of iterating through cells in each row) allowed me to get the correct header for each cell in the row, even when blank cells repeated.
Comment: But the suggestion from [Andrej](https://stackoverflow.com/users/10035985/andrej-kesely) is appreciated! Even if I am still attempting to parse it. The syntax in this line:
`for key in row.keys() - ["ID"]:`
...has thrown me for a loop. Don't understand the `- ["ID"]` part of this syntax.


Prove that $|x^2(y − z) + y^2(z − x) + z^2(x − y)| < xyz.$

Question: If $x, y, z$ are the sides of a triangle, then prove that
$|x^2(y − z) + y^2(z − x) + z^2(x − y)| < xyz.$
This is a self-answered question.
Answer: The given inequality may be written in the form
$|(x − y)(y − z)(z − x)| < xyz.$
Since $x, y, z$ are the sides of a triangle, we know that $|x − y| < z, |y − z| < x$ and $|z − x| < y.$
Multiplying these, we obtain the required inequality.


iptables rules to counter the most common DoS attacks?

Question: Recently I've got a lot of small scale DoS attacks. I am wondering what iptables rules should I use to counter the most common DoS attacks, and generally secure my web server.
The web server sports Varnish -> nginx/php5 -> memcached -> mysql
I tried some generic receipts but they also block access to my database server which  sits at a remote server, so I just flushed the suggested rules, and now feel a bit barehanded and volnurable when I see only fail2ban on iptables.
So appreciate your rules to block the most common attack vectors.
Comment: Depends on what attacks you're facing.  All effective DoS attacks require either S/RTBH or content inspection, though, so iptables rules on the server under attack aren't going to be of any use.
Comment: DROP All would seem to be the way to go to best do what you're asking.  But it really does seem like you're not quite "getting it."  You just can't block a DoS attack at the server.  By the time it's reached you, you're already being DoSed.
Comment: I modified the question to avoid misunderstanding. I simply look for rules to counter the most common DoS attacks .
Comment: You should know that many times the suspected "attacks" are actually bots that misbehave and are accessing too many URLs on your server at once and crash your server, the mod-status I mentioned in my reply should help identifying that. Very rarely someone has something to gain from intentionally attacking your server. Viruses and scripts might force access by FTP and SSH, I recommend limiting that.
Answer: Here are some rules I use:
<code># Reject spoofed packets
iptables -A INPUT -s 10.0.0.0/8 -j DROP
iptables -A INPUT -s 169.254.0.0/16 -j DROP
iptables -A INPUT -s 172.16.0.0/12 -j DROP
iptables -A INPUT -i eth0 -s 127.0.0.0/8 -j DROP

iptables -A INPUT -s 126.96.36.199/4 -j DROP
iptables -A INPUT -d 126.96.36.199/4 -j DROP
iptables -A INPUT -s 240.0.0.0/5 -j DROP
iptables -A INPUT -d 240.0.0.0/5 -j DROP
iptables -A INPUT -s 0.0.0.0/8 -j DROP
iptables -A INPUT -d 0.0.0.0/8 -j DROP
iptables -A INPUT -d 126.96.36.199/24 -j DROP
iptables -A INPUT -d 255.255.255.255 -j DROP

# Stop smurf attacks
iptables -A INPUT -p icmp -m icmp --icmp-type address-mask-request -j DROP
iptables -A INPUT -p icmp -m icmp --icmp-type timestamp-request -j DROP
iptables -A INPUT -p icmp -m icmp -j DROP

# Drop all invalid packets
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A FORWARD -m state --state INVALID -j DROP
iptables -A OUTPUT -m state --state INVALID -j DROP

# Drop excessive RST packets to avoid smurf attacks
iptables -A INPUT -p tcp -m tcp --tcp-flags RST RST -m limit --limit 2/second --limit-burst 2 -j ACCEPT

# Attempt to block portscans
# Anyone who tried to portscan us is locked out for an entire day.
iptables -A INPUT   -m recent --name portscan --rcheck --seconds 86400 -j DROP
iptables -A FORWARD -m recent --name portscan --rcheck --seconds 86400 -j DROP

# Once the day has passed, remove them from the portscan list
iptables -A INPUT   -m recent --name portscan --remove
iptables -A FORWARD -m recent --name portscan --remove

# These rules add scanners to the portscan list, and log the attempt.
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP

iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP
</code>
Comment: Bart, doesn't 'iptables -A INPUT -s 127.0.0.0/8 -j DROP
' kill memcached?
Comment: I see you have the rfc1918 address, presumably not 192.168 because you are using it. You have link-local. You might add to your list TEST-NET(192.0.2.0/24) from rfc3330, benchmarktest(198.18.0/25) from rfc2544, protocol assignment(192.0.0.0/24), testnet2(198.51.100/24) and testnet3(203.0.113/24) from rfc5736 and 5737 and finally carrier grade nat(100.64/10) from rfc6598
Answer:
So appreciate your bullet-proof rules.

You should contact your ISP and have the traffic dropped on the backbone before it hits you. If you're at the point where your firewall has to drop the traffic, then it's already consuming your available bandwidth and using your system's resources.
That's the only "bulletproof" way.
Comment: This answer is perfectly valid, whoever marked this answer down hasn't got a clue what he's talking about.
Comment: Many common DoS attacks look to saturate a server's connection to the Internet. If you're seeing a different kind of attack, like one that aims at resource exhaustion, then you should be much more specific in your question and the answer likely still won't involve iptables.
Comment: I don't care much about bandwidth consumption, as I have a dedicated port and the attacks are usually not so big, as I said.
Answer: I use IPtables in order to limit the access to FTP and SSH, I just allow my computer's IPs to connect to the server. I cannot say I had DOS attacks problems.
<code>/sbin/iptables -A INPUT -p tcp --dport 22 -s 22.214.171.124/16 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 22 -s 126.96.36.199/16 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 22 -j DROP

/sbin/iptables -A INPUT -p tcp --dport 21 -s 184.108.40.206/16 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 21 -s 220.127.116.11/16 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 21 -j DROP
</code>
These rules allow access to ports 22 and 21 on two different IPs. You can probably add the MySQL port of your db server and that way block other clients from connecting directly to your server.
Edit: when server is overloaded I find it helpful to see Apache "mod-status" statistics, the output looks like this: http://www.apache.org/server-status you can see all site visitors , spiders, url requests, etc. Implementation takes under 1 minute: http://httpd.apache.org/docs/2.2/mod/mod_status.html
Comment: How does this prevent a DoS attack? It'll help eliminate brute-force attacks on those protocols, but won't do much to stop a DoS.
Comment: It was more of a general or first-thing to do in order to secure the server (the ftp/ssh filter), then the server-status will help identify the "attack" (by http) because usually it is just a bad web crawler and not an attack. And an iptables rule should also help filtering/blocking his database port requests too.


Complex web site login with Requests

Question: I'm trying to log in to a site using the requests module, and can't figure out how the site's login page actually works. Here's the relevant form:
<form class="ui-corner-all" method="POST" id="login" target="_top">

    Username

    <input value="" id="username" type="text" name="F783713994214KVBZZQ">
    Password

    <input value="" id="password" type="password" name="F7837139942151QISNM">

Forgot password?

    <button class="btn btn-primary" type="submit" name="F783714094216F0PPFD" value="_">LOGIN</button>
</form>

I think the name of the fields are both randomly generated (F783713994214KVBZZQ and F7837139942151QISNM), so I parse those out, but I'm not sure what to do with that information. There's no login page url specified that I can see. I've tried constructing a payload of the above strings and correct login info and posting it with no result.
When I watch the network activity in chrome's inspector, after I click the login button I can see a post to the site but there's no query string parameters (where I would expect to see the username & password).
Does anyone know what else I should be looking at to figure out where the username and password are going and how to access that via requests?
Full login page html: https://pastebin.com/vP1s9esZ
My code: https://pastebin.com/4jG13WfW
The page includes a login.js in the header, but it's only this:
$(document).ready(function() {

$("#username").focus();

// Centers the div
$("#login").position({
    of: window,
    at: "center center"
});

});
Thanks in advance for any help!
Answer: You're looking for Selenium if you want to automate the login flow. But, if you want to make a request to the site, start with the network monitor. Click login and grab the request that goes to the site. They would either send it as a form or a payload.
Read more of the same at What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

Complex web site login with Requests


Get a word between two patterns in preg_match_all

Question: I am trying to get the  percentage value of download from the following string.
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4
[download] 100% of 1.60MiB in 00:21
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a
[download] 100% of 164.86KiB in 00:01

For ex. only the value '100' between '[download]' and '% of'.
This is my code what I've tried so far
$file = file_get_contents("t.txt");
if (preg_match_all("/(?<=\[download\])(.*?)(?=\% of)/s", $file, $result))
for ($i = 1; count($result) > $i; $i++) {
    print_r($result[$i]);
}

But the problem is it grabs from the first line and outputs like
Array ( [0] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4 [download] 100 [1] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a [download] 100 )

If I can grab just before the '% of' that will be okay I think. Should I stick to this code for modifying or change the whole pattern?
Comment: So in this example with the text file, do you want to grab all numbers which are in the pattern: `[number]%` ? Also what would be the expected output?
Comment: Why not split on `[download]`, get the second line, and then run a regex ?
Comment: Actually not . Just the text between '[download]' and '% of '. I need the value for making a progress bar. So I don't need all the numbers. @Rizier123
Comment: I'm not sure in which line the progress status will contain. It may vary I think. @adeneo
Comment: @AbdullahAlMamun So in your file there is 2 times a number in this pattern: `[download]' and '% of ` Do you want to grab the last or the first one?
Comment: I need both two values. Because the first one shows for video file and the second shows for audio file. That's why I'm using preg_match_all. @Rizier123
Answer: This should work for you:
Here I first get your file into an array with file() where every line is one array element. There I ignore new line characters and empty lines.
After this I go through each line with array_map() where I check with preg_match_all() if there is a pattern like this: [download] (\d+)% of. If it finds the number I return it otherwise I return false and at the end I filter the elements with false with array_filter() out.
<?php

    $lines = file("t.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $numbers = array_filter(array_map(function($v){
            if(preg_match_all("/\[download\] (\d+)% of/", $v, $m))
                return $m[1][0];
            else
                return false;
        }, $lines));

    print_r($numbers);

?>

output:
Array ( [1] => 100 [3] => 100 )

Comment: Why not just `if (preg_match_all(...))`  `print_r($result);`?
Comment: I don't really see what the point of the `array_map` and `array_filter` is for though? wouldn't `if (preg_match_all( '|(?mi-Us)(?<=\[download\]\s).*?(?=\% of)|', $lines, $result)) {
  print_r($result);
}` do essentially the same thing?
Comment: @l'L'l For sure you could do it all in one go with a regex. But I thought it would be easier to understand and more readable this way


Odoo: JSON: Inherit view, hide edit button conditionally

Question: I'm trying to hide the edit button in the bill of material form in Odoo, dependent on the state of a boolean.
I managed to remove the edit button permanent with the code below:
<xpath expr="//form[@string='Bill of Material']" position="attributes">
    <attribute name="edit">false</attribute>
</xpath>

Now I tried to make it conditional with a boolean like this:
<xpath expr="//form[@string='Bill of Material']" position="attributes">
    <attribute name="edit">true:realman==True;false:realman==False;</attribute>
</xpath>

This gives error:

SyntaxError: JSON.parse: unexpected non-whitespace character after
  JSON data at line 1 column 5 of the JSON data

When I looked up the javascript file, I've found this is the code to handle the edit attribute:
/**
 * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
 * An action is disabled by setting the corresponding attribute in the view's main element,
 * like: <form string="" create="false" edit="false" delete="false">
 */
is_action_enabled: function(action) {
    var attrs = this.fields_view.arch.attrs;
    return (action in attrs) ? JSON.parse(attrs[action]) : true;
},

I suppose I need to get false in that var attrs when the boolean realman in my form is False?
I've already tried to write it in curly brackets like the answer in this question: JSON.parse unexpected character error
That gave me errors too.
Why do I get this error and how can I fix this? Is this just a syntax error or are there more problems?
Answer: I successfully solved a similar issue by using field_view_get, but only if "realman" is passed into context
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
    res = models.Model.fields_view_get(self, cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
    realman = context.get('realman', True)
    if not realman and view_type == 'form':
        doc = etree.XML(res['arch'])
        for t in doc.xpath("//form[@string='Bill of Material']"):
            t.attrib['edit'] = 'false'
        res['arch'] = etree.tostring(doc)
    return res

if realman is instead a field and you need to enable/disable the edit button, then I'm afraid it is just not possible. AFAIK.
Comment: Just remember to import etree from lxml!
Answer: As Alessandro Ruffolo stated his solution doesn't work for buttons/actions depending on model's field. I have written solution in Javascript for that. It works in ODOO 10 (should in 9 also but I haven't tested it).
Example is checking on model's field "state". If it has value "noEditable" edit and delete buttons would hide. It isn't enough to overwrite is_action_enabled because ODOO is calling the method when there is no datarecord loaded yet. Therefore it's needed to check it again after methods do_show and reload.
// modify default form view for custom model my.custom.model
odoo.define('my.custom_model_form', function (require) {
    "use strict";

    var FormView = require('web.FormView');

    FormView.include({
        is_action_enabled: function(action) {
            if (this.model == "my.custom.model" && this.datarecord && this.datarecord.state == "noEditable" &&
                (action == 'delete' || action == 'edit')) {
                // don't allow edit nor delete
                return false;
            }
            // call default is_action_enabled method
            return this._super.apply(this, arguments);
        },
        deleteItem: null,
        deleteItemIdx: null,
        deleteItemShown: true,
        reinit_actions: function() {
            // apply for my custom model only
            if (this.model == "my.custom.model") {
                // hide/show edit button
                if (this.is_action_enabled('edit')) {
                    this.$buttons.find(".o_form_button_edit").show();
                } else {
                    this.$buttons.find(".o_form_button_edit").hide();
                }

                // find delete item in sidebar's items
                if (!this.deleteItem) {
                    // form view is adding it to "other"
                    if (this.sidebar && this.sidebar.items && this.sidebar.items.other) {
                        for (var i = 0; i < this.sidebar.items.other.length; i++) {
                            // on_button_delete is used as callback for delete button
                            // it's ugly way to find out which one is delete button, haven't found better way
                            if (this.sidebar.items.other[i].callback == this.on_button_delete) {
                                this.deleteItem = this.sidebar.items.other[i];
                                this.deleteItemIdx = i;
                                break;
                            }
                        }
                    }
                }
                // hide/show delete button
                if (this.is_action_enabled('delete')) {
                    if (!this.deleteItemShown) {
                        this.deleteItemShown = true;
                        // add delete item to sidebar's items
                        this.sidebar.items.other.splice(this.deleteItemIdx, 0, this.deleteItem);
                    }
                } else
                if (this.deleteItemShown) {
                    this.deleteItemShown = false;
                    // remove delete item from sidebar's items
                    this.sidebar.items.other.splice(this.deleteItemIdx, 1);
                }
            }
        },
        reload: function() {
            var self = this;
            // run reinit_actions after reload finish
            return this._super.apply(this, arguments).done(function() {
                 self.reinit_actions();
            });
        },
        do_show: function() {
            var self = this;
            // run reinit_actions after do_show finish
            return this._super.apply(this, arguments).done(function() {
                 self.reinit_actions();
            });
        }
    });

});

Answer: I believe a solution with a computed field makes things simpler for these cases.
You can inherit the bill of material form and override it. Point the invisible condition to a computed field where you'll create your validation. Note that is necessary to add your computed field to the form, even though hiding it.
<xpath expr="//form[@string='Bill of Material']" position="attributes">
    <attribute name="attrs">
        {'invisible': [('show_bm_button', '=', False)]}
    </attribute>
    <field name="show_bm_button" invisible="1"/>
</xpath>

Then override the object in python and add the new computed field.
class ProductTemplate(models.Model):
    _inherit = 'product.template'

    show_bm_button = fields.Boolean(
            compute='_compute_show_bm_button',
            readonly=False, store=False
        )

    # @api.depends('realman') #Just as a sample, if you have this field in this Model
    def _compute_show_bm_button(self):
        for record in self:
            realman = self._context.get('realman') or True
            if realman:
                record.show_bm_button = True
            else:
                record.show_bm_button = False


Como somar os valores de uma coluna especifica com a função sum()?

Question: Tenho o seguinte comando:
<code>       select substr(b.chave, 28, 7) numeronf, upper(d.apelido) usuario, decode(b.loja,1,'Loja 1', 2,'CD', 3, 'Loja 2', 5,'Loja 3', 89, 'PANIF', 90, 'Restaurante' ) loja, c.nomerazao, a.data_inicial, a.data_final,
                                  to_char(trunc(( (data_final - a.data_inicial) * 86400 / 3600)),'00') ||':' ||
                                  to_char(trunc(mod( (data_final - a.data_inicial) * 86400 , 3600 ) / 60 ),'00') || ':'||
                                  to_char(trunc(mod ( mod ( (data_final - a.data_inicial) * 86400, 3600 ), 60 )),'00') hora
                                  from tabela1 a, tabela2 b, tabela3 c, tabela d
                                  where a.id_chave = b.id_chave
                                  and a.usuario = d.matricula
                                  and a.usuario = $digitador
                                  and a.status = 'LN'
                                  and c.nrocgccpf = substr(b.chave, 7, 12)
                                  and c.digcgccpf = substr(b.chave, 19, 2)
                                  and trunc(a.data_inicial) between '$data_inicial' and '$data_final'
                                  order by a.data_inicial
</code>
Como fica a tabela:
<code>+------------+-----------+----------+-------+----------+----------+
| Loja       | Data      |Fornecedor| NumNF | Dgitador |Hora      |
+------------+-----------+----------+-------+----------+----------+
|     01     |2014-01-02 |  Fulano  | 000000|  Fulano  |00: 06: 37|
|     01     |2014-02-07 |  Fulano  | 000000|  Fulano  |00: 06: 37|
|     01     |2014-02-16 |  Ciclano | 000000|  Fulano  |00: 06: 37|
|     02     |2014-01-20 |  Fulano  | 000000|  Fulano  |00: 06: 37|
|     02     |2014-03-05 |  Fulano  | 000000|  Fulano  |00: 06: 37|
|     03     |2014-03-12 |  Ciclano | 000000|  Fulano  |00: 06: 37|
|     03     |2014-07-25 |  Ciclano | 000000|  Fulano  |00: 06: 37|
+------------+-----------+----------+-------+----------+----------+
</code>
Como eu faço pra somar os valores da coluna hora?
Answer: Some todas as diferenças de horas para, então, exibir o tempo no formato desejado:
<code>SEC_TO_TIME(SUM(data_final - a.data_inicial))
</code>


Benefits of using lag operator notation as opposed to subscripts

Question: I have a number of random variables that start at some initial state and then vary along time, I am planning on doing relatively straightforward analysis (nothing that the use of lag operators would greatly simplify).
I am debating on whether to use the lag operator or simple subscripts in my writeup. Lag operators seem to have a clear benefit if there is no significant initial state to call $n=0$. It also seems that some algorithms can be much clearer if lag operator notation is used. Otherwise, it seems to add unnecessary complexity.
To be explicit, the lag operator $L$ can be used in the following way where $x$ is a variable at time step $n$:
$$
Lx_n = x_{n-1}
$$
Is there any rule for when to use lag operators vs subscripts in notation?
Answer: The main advantage of the lag operator is that it allows you to use polynomial analysis of models, and put models into alternative forms via polynomial inversion, etc.  If you are not doing any of that then it is unlikely that the lag operator will be of benefit, and you may be better off just using subscript notation.  I really doesn't matter whether your sequence has a starting value at $n=0$ or if it is a sequence that is unbounded in both directions --- in either case you can use subscript notation for your defining model equations.


Erro ao utilizar $this em função estática

Question: Estou tentando utilizar uma função de uma classe da seguinte forma:
$database = database::select("SELECT * FROM eventos");

Quando executo o código, ele me retorna o erro:
Fatal error: Using $this when not in object context in /var/www/html/pasta/class/config.php on line 27
A classe está da seguinte forma:
<?php
class database{

    protected static $driver = 'mysql';
    protected static $host = 'localhost';
    protected static $port = 3306;
    protected static $user = 'root';
    protected static $pass = 'vertrigo';
    protected static $database = 'noweb';
    public $link = null;

    public function __construct(){

        try{

            $this->link = new PDO(self::$driver.":host=".self::$host.";port=".self::$port.";dbname=".self::$database, self::$user, self::$pass);

        }catch(PDOException $i){

            die("Ocorreu um erro ao fazer conexão: ".$i->getMessage()."");
        }

    }

    static function select($sql){

        $query = $this->link->query($sql);
        $rs = $query->fetchAll(PDO::FETCH_OBJ) or die(print_r($query->errorInfo(), true));

        return $rs;
    }
}

?>

Como posso arrumar isso, sendo que quero chamar as funções dessa classe da seguinte forma:
database::FUNÇÃO('parametros');

Comment: Transforme `$link` em propriedade estática e troca as ocorrências de `$this` por `self`
Comment: @rray fiz isso `$query =self::$link->query($sql);` e ele me retorna **Fatal error: Call to a member function query() on a non-object**
Comment: Resolvido. Consegui resolver jogando a conexão para uma função estatica chamada conexao() e tirando a conexão do __construct(); assim, na função select(){ } eu chamei a função self::conexao();
Answer: Como métodos estáticos podem ser chamados sem uma instância do objeto ter sido criada, a pseudo-variável $this não é disponível dentro do método declarado como estático.
Propriedades estáticas não podem ser acessadas pelo objeto usando o operador seta ->.
Chamar métodos não estáticos de maneira estática gera um aviso de nível E_STRICT.
Como qualquer outra variável estática do PHP, propriedades estáticas podem somente ser inicializadas usando um valor literal ou constante; expressões não são permitidas. Então você pode inicializar uma propriedade estática para um inteiro ou array (por exemplo), você não pode inicializar com outra variável, com um retorno de função, ou um objeto.  fonte: PHP
Answer: No seu exemplo, existe um método estático que tenta acessar um atributo de uma instancia(objeto) em algum momento foi criar o objeto? não logo $this->algo não estará acessivel.
Leitura recomendada:
Quando usar self vs $this em PHP?


Getting wrong results in evaluating $\text{lim}_{x\to 0} \frac{\sin(\pi \cos^2x)}{x^2}$

Question: I have to evaluate the following limit: $$\text{lim}_{x\to 0} \frac{\sin(\pi \cos^2x)}{x^2}$$
So I used this result: $\lim_{x\to 0} \frac{\sin x}{x}=1$
Now I multiplied and divided this term: $(\pi \cos^2x)$.Hence:
$$\text{lim}_{x\to 0} \frac{\sin(\pi \cos^2x)}{(\pi \cos^2x)}\cdot\frac{(\pi \cos^2x)}{x^2}$$
Treating $\sin(\pi \cos^2x)=\alpha$, We get:$$\text{lim}_{x\to 0}\frac{(\pi \cos^2x)}{x^2}\cdot 1$$
Now applying L'Hopital: $$\text{lim}_{x\to 0}(-\pi \cos x)\frac{\sin x}{x}=-\pi$$
But answer is $\pi$, and I couldn't find any mistake also. But I proceeded another way:
$$\text{lim}_{x\to 0} \frac{\sin[\pi-\pi \sin^2x]}{x^2}$$
$$\text{lim}_{x\to 0} \frac{\sin(\pi \sin^2x)}{x^2}$$
And then in the same fashion, as done above, I got the correct answer $\pi$. I really can't figure out why the first method was wrong? So I need help there, as to why the first method leads to the wrong answer. Thanks in advance!
Comment: $\lim_{x\to0}\pi\cos^2x\ne0$
Answer: In the first method you are assuming that $\frac  {\sin (\pi \cos^{2}x)} {\pi \cos^{2}x} \to 1$.  This is not correct because $\pi \cos^{2}x $ does not tend to $0$ as $x \to 0$.


Bayesian model - how to emphasize later observations?

Question: I have a very general question, any links to relevant papers or which book I should consult should suffice.
So, let's say I've got a Bayesian model (for example) to predict the outcome of a soccer game in the current season. I have some data for the current season (since not all games have been played), and then I have the data from the previous couple of seasons.
Is there a method in Bayesian statistics whereby you would develop a model that provides more weight for the current season results compared to the results from the previous seasons?
Appreciate the help!
Comment: There are several global ways to think about this.  Two of them: incorporate a time trend in the model, or use prior seasons to formulate a prior distribution, and discount this by mixing this prior with an uninformative prior or by using a power prior.
Comment: Hi Dr Harrell, thanks for your response. I was wondering if you could tell me of  any references/sources that you think might cover this? I've only ever done an introductory course in Bayesian statistics where we didn't cover mixing priors.
Answer: This sounds like a Hidden Markov Model. You have some data about the state of your system in the past (data = soccer game results, state = how likely teams are to win (e.g.)). Then you have some data about the state of the system in the present. You assume that the system's current state is somewhat similar to its state in the recent past. If you could somehow formalize this temporal relationship ($p(x_t|x_{t-1})$, where $x_t$ is the state of the system at time $t$), you could then use Recursive Bayesian estimation to infer the current state of the system from both present and previous data. This gives you a better estimate of the current state (i.e. how good the different soccer teams currently are), and that then allows you to make better predictions.
This automatically puts more weight on the more recent data, as long as your state transition model allows for some stochasticity. That is, as long as you assume that previous states are not perfectly predictive of current states, then (all else being equal, e.g. equal noise) the more recent data is always a statistically better source of information, which will therefore be weighted more heavily.


Is swap file required for a Postgres database running on AWS EC2 instance with 122 GB memory?

Question: What is the downside for running a Postgres database without a swap file?
This database resides on an AWS EC2 machine with 122 GB memory.
Answer: That depends on the OS that this VM runs. For instance, Solaris requires swap file, because swap in Solaris is an integral part of the it's virtual memory stack. I'd say that FreeBSD also fits better in swap-enabled configurations, but tweaking can eliminate this. Linux, on the other hand, doesn't require swap out-of-the-box.
Answer: Just to avoid any worst case scenario, you can add swapfile and set swappiness to a small value. (vm.swappiness = 10). So the system won't swap unless the memory utilization is reached up to 90%.


Solution for generalized Euler's Theorem $a^m\equiv a^{m-\phi(m)} \pmod{m}$?

Question: The above identity holds for any integer $a$. Since my solution(?) does seem neither elegant nor rigorous enough, I want to get some advice to improve it.
My solution:
If $(a,m)=1$, this identity is obvious from Euler's Theorem. So, assume that $(a,m)\neq 1$.
Let $g=(a,m)$, and then $\exists k, n\in\mathbb{Z}\:s.t. (k,n)=1$, $a=gk$ and $m=gn$. So the identity can be rewritten as the following:
$$(gk)^m\equiv (gk)^{m-\phi(m)} \pmod{gn}$$
Dividing the both sides by $k$, we obtain:
$$g^{m}k^{gn-1}\equiv g^{m-\phi(m)}k^{gn-\phi(gn)-1} \pmod{n}$$
$$g^{m}\equiv g^{m-\phi(m)}k^{-\phi(g)\phi(n)}\equiv g^{m-\phi(m)}\pmod{n}...(*)$$
Thus, we can reduce the identity to the identity (*), and as we continue this process for finite times, we will eventually reach at Euler's identity with $(a,m)=1$.
Answer: Hint Let $m=p_1^{\alpha_1}....p_k^{\alpha_k}$.
It suffices to prove that
$$ a^m\equiv a^{m-\phi(m)} \pmod{p_i^{\alpha_i}}$$
Now split the problem in two cases: $p_i |a$ and $p_i \nmid a$. The second case is almost identical with your first case...


Using playwidget with customized scene update functions (like play3d)

Question: play3d supports customized scene update function, i.e., you can do basically do whatever you want from frame to frame, including adding/updating shapes, surfaces, lighting, or viewpoint. See demo(flag) where the surface of the flag is redrawn every frame.
playwidget is somewhat more limited. It only supports par3dinterp-style controls that can be passed in order to update par3d. If you want to change attributes of the 3d plot beyond the elements available in par3d, e.g., adding a shape, I don't see how you can do it.
Is there a way to make playwidget behave similarly to play3d?
Thanks.
Answer: There are at least three ways to do it.
If you have a fairly limited number of changes (like a simple version of the flag example), you can plot all the frames at once, and set all but one of the objects to alpha = 0 which makes it invisible.  Then change which frame gets alpha = 1 in response to the playwidget.
Another way to do it is to write Javascript.  The first example in the Legacy WebGL Methods vignette does this.  Be aware that the internal structure of the rgl objects in Javascript is subject to change, so this may be hard to maintain.
A final way is to use Shiny.  Make the changes in R code, and the replot the scene.  demo("shinyDemo", "rgl") does this.


nginx proxy to different path

Question: I've read through the documentation for nginx's HttpProxyModule, but I can't figure this out:
I want it so that if someone visits, for example http://ss.example.com/1339850978, nginx will proxy them http://dl.dropbox.com/u/xxxxx/screenshots/1339850978.png.
If I was to just use this line in my config file:
proxy_pass http://dl.dropbox.com/u/xxxxx/screenshots/;,
then they would have to append the .png themselves.
Answer: You could combine proxy_pass with a rewrite directive:
rewrite /([^/]+) /$1.png break;
proxy_pass http://dl.dropbox.com/u/xxxxx/screenshots/;

Comment: This didn't quite work but after some experimentation I found this was fine:
    `rewrite         /(.*) /u/70152/screenshots/$1.png break;`
    `proxy_pass      http://dl.dropbox.com/;`
Comment: @DavidRobertson, I am sorry it did not work. will try to fix it as soon as I can get to test the rules. Thank you for the points.

nginx proxy to different path


Does there exist an irreducible factor of $x^{32}-x \in\mathbb{Z_3}[x]$ with degree 4?

Question: I would like to find whether there exist an irreducible factor of $x^{32}-x \in\mathbb{Z_3}[x]$ with degree $4$.
Firstly, this polynomial is expressed as the product
$x(x-1)(x^{30}+x^{29}+...+x+1)$ over $\mathbb{Z}_3$
Then, how can i check whether the 3rd term is irreducible ?
And is this statement true?
Answer: Compute the gcd of this polynomial with $x^{3^4}-x$. The Euclidean algorithm will help you compute the gcd. We know that all irreducibles of degree $4$ are a factor of $x^{3^4}-x$, so you need only work from there. This is also relatively easy to do

$$x^{81}-x = (x^{49}+x^{18})(x^{32}-x) +x^{19}-x=q(x)(x^{32}-x)+r(x)$$

iterating gives
$$x^{32}-x = x^{13}(x^{19}-x) + x^{14}-x$$
$$x^{19}-x = x^5(x^{14}-x)+x^6-x$$
$$x^{14}-x = (x^8+x^3)(x^6-x)+x^4-x$$
$$x^6-x = x^2(x^4-x) + x^3-x$$
$$x^4-x = x(x^3-x)+x^2-x$$
$$x^3-x = (x+1)(x^2-x)+0$$
So the gcd is of degree $2<4$, making it impossible to have a factor of degree $4$. The nice thing about this approach is it doesn't require you to figure out if the extra factor is reducible or not!