Simplify $\ \frac{(0.81)^2 × (0.6×0.21)^2}{35^5 × 0.252} $ into $2^n × 3^m×5^p×7^k$

Question: $\ \frac{(0.81)^2 × (0.6×0.21)^2}{35^5 × 0.252} $
Simplify the following equation into this form :
$2^n × 3^m×5^p×7^k$
where $n, m, p, k$ are integers.
Comment: Where are you finding difficulty?  For example, can you write $.81^2$ in the desired form?
Comment: Just rewrite each term in the desired form $0.81=2^{-2} \times 3^4 \times 5^{-2}$ etc... and then use the laws of exponents.
Comment: and take your calculator to do this
Answer: $$\frac{(0.81)^2 × (0.6×0.21)^2}{35^5 × 0.252}$$
$$\frac{\left(\frac{81}{100}\right)^2\times \left(\frac{3}{5}\times \frac{21}{100}\right)^2}{(5\times 7)^5\times \frac{63}{250}}$$
$$\frac{(3^4\times 2^{-2}\times 5^{-2})^2\times (3^2\times 7\times 2^{-2}\times 5^{-3})^2}{5^5\times 7^5 \times 7\times 3^2\times 2^{-1}\times 5^{-3}}$$
$$\frac{3^8\times 2^{-4}\times 5^{-4}\times 3^4\times 7^2\times 2^{-4}\times 5^{-6}}{2^{-1}\times 3^2\times5^2\times 7^6}$$
$$\frac{ 2^{-8}\times 3^{12}\times  5^{-10}\times 7^2}{2^{-1}\times 3^2\times5^2\times 7^6}=2^{-8}\times 3^{12}\times  5^{-10}\times 7^2\times 2^{1}\times 3^{-2}\times 5^{-2}\times 7^{-6}=
\color{red}{2^{-7}\times 3^{10}\times 5^{-12}\times 7^{-4}}$$


Using chi square on unequal groups with unequal repeated trials

Question: My dataset includes four groups (A, B, C, D) of unequal numbers of individuals. Each individual engages in an activity that results in one of three categorical outcomes (X, Y, Z). The individuals repeated this activity multiple times, with the total number of trials varying across individuals.  That is, everyone has counts of X, Y, and Z, but counts vary across individuals, as does the sum of X+Y+Z.
I was planning to a run a test of independence on this data, comparing group (A, B, C, D) by outcome (X, Y, Z). In doing so, I originally, sought to account for the varying number of individuals per group by setting probabilities (argument p within chisq.test in R) based on the relative group sizes.
However, I'm unsure if the above is appropriate. The frequencies used for analysis are not actually counts of the number of individuals per group that experienced each outcome. Rather, the frequencies reflect the total number of trials across all individuals within that group that resulted in each outcome.
More, even if appropriate, I'm now unsure if this is possible. Can one set expected probabilities for one variable when conducting a test of independence between two variables? Or is setting expected probabilities only possible for comparing observations in a goodness of fit test? In which case, I could conceivably compare groups A, B, C, and D in three separate tests (one per outcome X, Y, and Z).
In turn, I am wondering:
1) Is it possible and appropriate to run a single test of independence in this scenario or instead three separate tests (one per outcome) to compare groups?
2) In either case is there a means to separately account for both the variability in group size and the variability in trials?
3) Do either of these variabilities even need to be accounted for, considering chi square tests are non-parametric, and unequal sample sizes are thought to be a non-issue?
4) Alternatively, is there a different predictive test that can be used in this scenario? Logistic regression, notably, would require require a continuous predictor (rather than nominal groups).
Thanks your guidance, technical and conceptual.
Comment: You say that `individuals repeated this activity for multiple times`, does that mean that you have repeated measures, that is each individual was measured multiple times?
Comment: Correct.  Each individual was measured across multiple trials.  The total number of trials/measures varied across individuals (based on the number they could complete within a set amount of time).  First paragraph now updated to better clarify.  Thanks!
Answer: Given that you have a repeated measures design a Chi-square test is not appropriate anymore, since it assumes independence of data. There is no workaround with it, you need a different model. Given that your dependent variable is categorical a logistic regression model could work. However, because your DV is also a count variable then a logistic model would not really work so you need a Poisson model. And because there is dependence in the data you need a Poisson mixed model, where your individuals are your random effects.
Comment: Thanks for the insight, much appreciated.  To confirm, if taking a Poisson approach, I would need to run test three separate models (one for each outcome), correct? That is, I presume I would have to run a model comparing the four groups' (A, B, C, D) respective counts for outcome A, then a second for outcome B, and then a third for outcome C.
Comment: @jjcii As I see it you have a categorical outcome variable with three possible outcomes X, Y and Z. So the simplest option would be to build three different models each on one outcome and for each model compare the counts for each of the groups A, B, C and D (independent categorical variable). This is not the prettiest solution. I don't know of alternatives to this.
Comment: I'll give that a go, as it seems the most straightforward option at this point.  Thanks again!


Why should you use theme(), rather than calling the theme functions directly?

Question: Why should you use theme(), rather than calling the theme functions directly?
theme('box', $title, drupal_get_form('comment_form', $edit, $title));

Why doesn't the code call the theme function directly, as in the following code?
theme_box($title, drupal_get_form('comment_form', $edit, $title));

Answer: You have to use the theme() function for the override system to work. For example, your theme may override the theme function for a module, or a template (.tpl.php) file might be used instead.
Comment: http://drupal.org/node/457740 explains what's meant by theme overriding. Overriding is an important feature because it's the magic that allows customizing the look & feel of a site.
Answer: In the example you made, when you call theme_box() you are calling a specific function; when you are calling theme('box'), the function is calling a function that normally istheme_box(), but if a module implements hook_theme_registry_alter() using the following code, the function being called is theme_mymodule_box().
function mymodule_theme_registry_alter(&$theme_registry) {
  // Kill the next/previous forum topic navigation links.
  if (!empty($theme_registry['box'])) {
      $theme_registry['box']['function'] = 'theme_mymodule_box';
    }
  }
}

Notice that in Drupal 7 every theme function has a preprocess function, not just the theme functions using a template file. This means that, in few cases, it is not necessary to override a theme function. If the code just need to change the content of a variable passed to the theme function, using a preprocess function is what should be done in Drupal 7.


Why the convergence is pointwise in this question and why the translation is continuous?

Question: I was reading this question here Proving that $f'$ is measurable on $\mathbb R$ if$f$ is differentiable on $\mathbb R$.
But I did not understand the following points in the solution:
1- why the translation $f_{h}(x)= f(x + h)$ continuous? could anyone give me a rigorous proof for this, please?
2- Why the convergence is pointwise everywhere here: " Now, you have
$$\frac{f_h - f}{h} \to f'$$
pointwise everywhere"? could anyone give me a rigorous proof for this, please?
Answer: By definition,
$$f'(x)=\lim_{h \to 0} \frac{f(x+h)-f(x)}{h}=\lim_{h \to 0} \frac{f_h(x)-f(x)}{h}$$
And for 2, just check the definition of pointwise convergence.
Comment: @hopefully $f$ is differentiable on $\mathbb{R}$, hence continuous. So it's continuous at $x+h$ as well, because $x+h\in\mathbb{R}$.
Comment: @hopefully a sequence is a null-sequence if it's limit is zero. And you should pick one because you have $h\to 0$ in the definition of derivative.
Comment: I have edited my first question. Could please show me the details of 1 & 2?
Comment: @hopefully for the second one, pick your favorite null-sequence, which is non-zero, for example $h_n = 1/n$. Note that \frac{f(x+1/n)-f(x)}{1/n}\to f'(x)$, because $f$ is differentiable at $x$.
Comment: what do you mean by $null-sequence$ and why should I pick it null?
Answer: $f'(x) =\lim_{n \to \infty} f_n(x)$ where $f_n(x)=\frac {f(x+\frac 1 n)-f(x)} {1/n}$. So it is enough to check that each $f_n$ is measurable. But $f_n$ is continuous and that finishes the proof.
1) If $x_k \to x$ then $x_k+\frac 1 n \to x+\frac 1 n$ so $f(x_k+\frac 1 n) \to f(x+\frac 1 n)$  in view of the fact that any differentiable function is continuous.
2) This is by definition of derivative.
Comment: which proof that is finished? the proof of the question is already mentioned in the link but it lacks the following details I am asking about.
Comment: @hopefully I have edited my answer.
Comment: you mean the definition of the derivative say that it is a pointwise convergence everywhere?
Comment: Yes, at each point $x$ apply the definition of derivative. @hopefully


Drupal database performance tuning - switching particular tables to InnoDB from MyISAM

Question: I've got a drupal site that gets low traffic, but has tons of new content being added by a custom feed importer module. This module creates nodes and associated taxonomies for imported articles.
Currently, I believe ALL our drupal tables are MyISAM. I was considering switching the heavy write tables:

node
watchdog
sessions
accesslog
What other tables would you consider?

To InnoDB.
Do you think this is a good idea? Am I likely to see a performance gain? The reason I'm looking at this as part of my overall solution is that, on import, mysqld is running out of memory often and taking the entire system down. It ONLY happens on import.
I'll end up seeing things like this:
<code>xml import at [01/Jun/2011:13:26:38 -0400] "GET /import/xml_import HTTP/1.1" 200
....
14:02:38 [ERROR] /usr/libexec/mysqld: Out of memory (Needed 1049152 bytes)
</code>
The box is x32 so we are limited to the amount of memory we can allocate to mySql. We also have PHP, JAVA, SVN and more running on this box ... it's taxed as is. heh.
So, any input on performance tuning the db in general would be appreciated, I'm doing the research now.
TIA.
EDIT: (I've included my current my.cnf):

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
tmpdir=/var/lib/mysql/tmp
#old_passwords=1
skip-locking
key_buffer = 2048M #doubled from 1024
max_allowed_packet = 16M
table_cache = 5000
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 64 #doubled from 32
thread_concurrency = 8
query_cache_size = 1024M #doubled from 512
tmp_table_size=1024M
max_heap_table_size=1024M
back_log = 100
max_connect_errors = 10000
join_buffer_size=1M
open-files = 20000

interactive_timeout = 600
wait_timeout = 600

ft_min_word_len=3
ft_stopword_file=''
max_connections=1000

#innodb_data_file_path = ibdata1:2000M;ibdata2:10M:autoextend
#innodb_log_file_size = 100M

#innodb_buffer_pool_size = 384M
#innodb_additional_mem_pool_size = 20M

#log-slow-queries=/var/lib/mysqllogs/slow-log
#long_query_time=2
#log-queries-not-using-indexes

#log-bin=/var/lib/mysqllogs/bin-log
#log-slave-updates
#expire_logs_days = 14
server-id       = 1

[mysql.server]
user=mysql
#basedir=/var/lib

[mysqld_safe]
err-log=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
open_files_limit=65536
Comment: As an alternative, you could for example log watchdog messages to a different place, for example syslog (just enable syslog.module instead of dblog.module) or mongodb (http://drupal.org/project/mongodb). Also, try to pin-down which queries are actually slow. In another, similar question, it turned out to be a single missing index on a table from notifications module which extremely slowed down the whole import: http://drupal.stackexchange.com/questions/3021/bulk-update-got-slower-after-conversion-of-database-tables-to-innodb
Answer: If you know for a certainty that the website will be low trafficked, by all means remain in MyISAM.
However, should that pattern ever change and you become high traffic again, you could configure everything into InnoDB for two major reasons
REASON #1 : InnoDB does row level locking. As for MyISAM, any INSERT, UPDATE, or DELETE query executed will cause a full table lock. Even in a low trafficked website, the possiblility exists of two or more DB Connections Locking the Same Table. With InnoDB, that possibility is totally eliminated.
REASON #2 : InnoDB Caches Data and Indexes. MyISAM only caches Index Pages.
The key cache (sized by key_buffer_size) hold index pages for MyISAM tables. There is always disk I/O to read data from a MyISAM. A record read for the first time will cache the Index Pages used to find the row in to key cache. Subsequent lookups will find the key needed in the key cache, but there will always be mandatory disk I/O to get the data. With InnoDB, both Data and Index Pages Reside in the InnoDB Buffer Pool (size by innodb_buffer_pool_size). Disk I/O is dramatically reduced with everything cached in the Buffer Pool.
I have always recommended Drupal databases using InnoDB instead of MyISAM. It is actually easy to convert using straight MySQL.
Until then, MyISAM is all the firepower you need, especially on servers with modest RAM.
Answer: Generally speaking, InnoDB is slower than MyISAM as InnoDB is atomic while MyISAM is not. With the tradeoff of performance you gain data reliability.
If you can, disable indexes before import, you will see a performance gain. Its more efficient to rebuild the indexes all at once rather than for every single insert.
You do not want to configure mysql to exceed available memory. The memory settings are spread across several settings. You can use something like this http://mysqltuner.pl/mysqltuner.pl to determine how well your mysql install is tuned.
Comment: Row level locking will help in a situation in which multiple connections are in contention for the same table. If its an import process with a single thread, it wont make much of a difference.
Comment: That general statement is not correct. InnoDB can, correctly tuned, perform much better on tables with many writes for example, due to row-level locking.
Comment: That was my understanding as well, this is why I'm proposing using InnoDB on the heavy-write tables. I will checkout the mysqltuner script now, thanks.
Comment: Ah ok, interesting point. Perhaps I'll leave the tables for now and just tune the my.cnf.


Entity query to select current dates

Question: The situation: I have a drupal 7 node which has a date field. This uses the date module and it has multiple values each with a start and end date.
The problem is that I want to query drupal for all nodes where the current date is between the start and end dates of a single delta.
The entity query I have at the moment doesn't check the same value for both start and end dates.
For example if the first date value started 1/1/2013 and ended 30/1/2013 and if there was a second value which started 1/12/2013 and ended 30/12/2013. Using the current date of today 11/10/2013 this node should NOT be fetched. However under the query below it is because there is a start date in the past and an end date in the future, even though they're not from the same field delta.
<code>  $current_date = date("Y-m-d");

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=')
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=');
    ->execute();
</code>
Answer: Having actually read the fieldCondition documentation the fourth property turns out to be $delta_group which allows specifying dependent conditions. So it turns out all I needed was the below:
<code>$current_date = date("Y-m-d H:i:s");
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=', 1)
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=', 1);
    ->execute();
</code>

Entity query to select current dates


Help with filetype association!

Question: I have the actual association part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened?
I think it is something like sys.argv? But that just returns the path to the python program, not the associated file.
Answer: The __file__ attribute of your module looks what you're looking for.  E.g., save in foo.py:
$ cat foo.py
print 'Hello', __file__
$ python foo.py
Hello foo.py

os.path.abspath will help you if you want the absolute rather than relative path, etc, etc.
Comment: Huh? I need the pathanme of the file I double clicked to open the program i.e. I double click file1.dgf and it opens prog.exe. How do I get the full path to file1.dfg?
Comment: You tagged your question as `python`, so what's `prog.exe` got to do with it?  Anyway, I suspect your question is strongly OS-dependent, and since you have no OS-related tags, I don't know whether the "association" is in Windows, MacOSX, KDE, Gnome, or what else.  Isn't your (python?) program getting the clicked file's path as `sys.argv[1]`?  It should, in these environments, but since I don't know your environment, it's hard to guess!-)
Comment: It is a Windows platform. Prog.exe is the Python program compiled to .exe, thus filetype association. It is only getting the path of itself when I use sys.argv[1], I'm not sure why.
Answer: The contents of sys.argv are platform-dependent, as noted in sys.argv. I do know that sys.argv[0] is the full path on Windows only when you open .py files using the shell by double-clicking on it. Using the command line just results in the script name.
The os module provides platform-independent solutions. The full path to your script should always be available with the following code:
import os.path
import sys

print os.path.abspath(sys.argv[0])

Help with filetype association!


SQL: Sort Results of a Query Based on the Order of values from another Query

Question: Suppose I have a table with 3 columns:

YEAR
COMPANY
DEPARTMENT
SALES

And I wanted to display the following:

COMPANY
DEPARTMENT
SUM(SALES)

The additional requirement being that the COMPANY with the Maximum Sales (across all departments) shows first, and the rest of the results ordered accordingly.
How would I go about writing my query?
I've tried the following, and it doesn't work:
SELECT t1.company,
   cs1.deparment,
   SUM(cs1.sales)
FROM   company_sales cs1,
   (SELECT cs2.company,
                   SUM(cs2.sales)
            FROM   company_sales cs2
            WHERE  cs2.company IS NOT NULL
            GROUP  BY cs2.company
            ORDER  BY 2 DESC) t1
WHERE  cs1.company = t1.company
GROUP  BY t1.company,
      cs1.deparment;

Comment: BTW, I'm trying this in PostgreSQL.
Comment: select company,department,sum(sales) from table group by company,department    order by company
Comment: @ivan, there is more to the requirement than just grouping and ordering at one level. Please refer to my question again.
Answer: You can do this using window functions:
select company, department, sum(sales)
from t
group by company, department
order by sum(sum(sales)) over (partition by company) desc, company;

You can also include the expression in the select clause to see the sum of sales for the entire company.
Comment: Worked like a Charm !! Thanks for the solution.
Comment: you require a second condition in that order by clause i.e. `, department`
Comment: @Used_By_Already . . . Actually, it does need a second condition -- `company` -- to handle ties.  I'm not sure what subsequent keys should be.
Comment: `the rest of the results ordered accordingly.` is very unclear but suggests it needs both company (as tie breaker) and department after that. cheers.
Answer: Try:
 SELECT company,department,sum(sales)
 FROM table GROUP BY company,department
 ORDER BY Max(sales)

Comment: Anton, this won't work for me, as I'm looking at Sales of a Company across all departments, not just one department.


jquery saber se campo foi validade com padrão correto

Question: Bom, tenho um campo de texto:
<input pattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />

Como faço em JQuery para saber se o preenchimento está de acordo com o padrão?
Sim, eu sei que o html5 já faz isso para mim.
Mas a validação vai ser feita por um botão de fora do form.
coia de maluco. Mas é assim que precisará ser feita.
Answer: Não precisa de jQuery, a propria API de validação lhe permite isto.
Você pode usar o método checkValidity para verificar se o input é valido, então pode acessar as propriedades da propriedade validity para saber em que validações o input não passou.

var campo = document.getElementById("campo");
var verifica = document.getElementById("verifica");
verifica.addEventListener("click", function (event) {
  if (!campo.checkValidity()) {
    if (!campo.validity.valueMissing) {
      console.log("Campo Obrigatorio");
    }
    if (!campo.validity.patternMismatch) {
      console.log("Campo com valor invalido.");
    }
  }
});
<form>
  <input pattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />
</form>
<input id="verifica" type="button" value="Verificar" />

a propriedade validity possui outros campos uteis.:
customError
patternMismatch
rangeOverflow
rangeUnderflow
stepMismatch
tooLong
typeMismatch
valueMissing
valid

EDIT - Em resposta ao comentatio
O objeto jQuery nada mais é que uma abstração para os seus objetos DOM, então ele acaba por funcioanar como um container para o mesmo, desta forma você irá conseguir ter acesso estes objetos pelo indice, de forma similar à como você acessar objetos em um Array.
$("#campo")[0] será semelhante a document.getElementById("campo");, porém com um overhead enorme.

var campo = $("#campo");
var verifica = $("#verifica");
verifica.on("click", function (event) {
  if (!campo[0].checkValidity()) {
    if (!campo[0].validity.valueMissing) {
      console.log("Campo Obrigatorio");
    }
    if (!campo[0].validity.patternMismatch) {
      console.log("Campo com valor invalido.");
    }
  }
});

<form>
  <input pattern="[0-9]{2}[.][0-9]{3}[-][0-9]{3}" type="text" id="campo" required />
</form>
<input id="verifica" type="button" value="Verificar" />
Comment: Sim. Mas já uso JQuery. No caso ficaria assim?
if (!$("#campo").checkValidity()
Comment: Consegui:if (!$("#cep")[0].checkValidity(). Obrigado!
Comment: @CarlosRocha, fiz uma edição na resposta.


Proof that if $x,y>0$ and $x+y=1$, then $(2x)^{\frac 1 x}+(2y)^{\frac 1 y}\leq 2$

Question: For positive reals $x$ and $y$ such that $x+y=1$, prove that $$(2x)^{\frac 1 x}+(2y)^{\frac 1 y}\leq 2$$
I have tried using Jensen's inequality but it won't cover all the possible choices for $x$ and $y$ since the concavity varies. I am trying to find a neat solution so that a generalization could also be made. Thank you.
Comment: $(2x)^{1/x} + (2y)^{1/y} + \frac{1}{2}x(1-x)(2x-1)^2 \le 2$ is also true. We may determine the best constant $k$ such that $(2x)^{1/x} + (2y)^{1/y} + k x(1-x)(2x-1)^2 \le 2$ is true.
Comment: @RiverLi you can use my answer an strongly convex function https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6244717/ .
Comment: @c-love-garlic Thanks.
Answer: $$(2x)^{\frac 1 x}=\frac{1}{\left( \frac{1}{2x}\right) ^{\frac{1}{x}}}\leq \frac{1}{1+\frac{1}{x}\left( \frac{1}{2x}-1\right)}=\frac{2x^2}{2x^2-2x+1}$$ by Bernoulli's inequality. The same holds for $y$ and one immediately computes that if $x+y=1$, $$\frac{2x^2}{2x^2-2x+1}+\frac{2y^2}{2y^2-2y+1}=2$$ and the result follows.(just observe that the denominator are the same $=x^2+y^2$)
Comment: You should select this answer, which is more elementary and generalisable +1.  Further there is an error in my post.
Comment: @William Sun By derivatives we can prove that for any $x>0$ we have: $(2x)^{\frac{1}{x}}\leq\frac{1}{30}(6144x^7-20352x^6+26720x^5-16240x^4+2880x^3+1568x^2-694x+75),$ but it leads to wrong inequality.
Answer: Question : Can we use Jensen's inequality here ? No .
Hint :
One can show that the function :
$$f(x)=1-\frac{1}{(2a(1-x)+2bx)^{\frac{1}{a(1-x)+bx}}}$$
Is concave on $I=[0,1]$ where $1>a\geq 0.5\geq b>0$ and $a+b=1$
So we can apply Jensen's inequality with weight we get :
$$(2a)^{\frac{1}{a}}f(0)+(2b)^{\frac{1}{b}}f(1)\leq ((2a)^{\frac{1}{a}}+(2b)^{\frac{1}{b}})f\Bigg(\frac{(2b)^{\frac{1}{b}}}{(2a)^{\frac{1}{a}}+(2b)^{\frac{1}{b}}}\Bigg)$$
But :
$$\frac{(2b)^{\frac{1}{b}}}{(2a)^{\frac{1}{a}}+(2b)^{\frac{1}{b}}}\leq 0.5$$
One can show that the function $f(x)$ is decreasing on $I$ so :
$$f\Bigg(\frac{(2b)^{\frac{1}{b}}}{(2a)^{\frac{1}{a}}+(2b)^{\frac{1}{b}}}\Bigg)\geq f(0.5)=0$$
Now we can conclude !
Update :
I think we can use weighted Karamata's inequality (but I'm not sure) to get :
$$(2a)^{\frac{1}{a}}f(0)+(2b)^{\frac{1}{b}}f(1)\leq (2a)^{\frac{1}{a}}f(0.5)+(2b)^{\frac{1}{b}}f(0.5)=0$$
Since :$$0(2a)^{\frac{1}{a}}\leq 0.5(2a)^{\frac{1}{a}} \quad 0.5(2a)^{\frac{1}{a}}+0.5(2b)^{\frac{1}{b}}\geq 1(2b)^{\frac{1}{b}}+0(2a)^{\frac{1}{a}}$$
Wich is the desired inequality .
I think that the update is false but with strong convexity it seems to work (numerically) with particular value for $a,b$ .
Curious fact :
We cannot use Jensen's inequality directly but we can use it to refine the result and I found it very strange .
One can show that the function :
$$g(x)=\frac{1}{\ln\Big((2x)^{\frac{1}{x}}+(2(1-x))^{\frac{1}{1-x}}-1\Big)}$$
where $0<x<0.5$ is concave .To prove it we can use the proof of William Sun .
Now except the extrema and the equality case the equality :
$$h(x)=(2x)^{\frac{1}{x}}+(2(1-x))^{\frac{1}{1-x}}=c\quad (1)$$
Have four solutions on $I=(0,1)$
So two solutions on $0<x<0.5$ and two solutions on $0.5<x<1$ we can express it as :
$$h(x)=h(y)=h(1-y)=h(1-x)$$
Where $0<x<y<0.5$
So if we apply Jensen inequality we have :
$$g(x)+g(y)=g(x)+g(1-x)=2 g(x)\leq 2g\Big(\frac{x+y}{2}\Big)$$
To conclude we can use numerical methods to solve $(1)$
Comment: Can someone tells me if the majorization is correct ? Thanks !
Comment: @RiverLi Can you confirm ?Good day !
Comment: From $A \le B$ and $B \ge 0$, we can not get $A \le 0$, right?
Comment: @RiverLi If you speak about the inequality of Jensen's it's the goal to see we cannot use it here .And we cannot use Karamata's inequality furthermore .
Comment: OK. You want to prove that we can not use Jensen. But maybe we can use Jensen in other way?
Comment: @RiverLi Not directly I think .
Comment: But you only prove that your approach of using Jensen does not work. You can not conclude that we can not use Jensen, right?
Comment: @RiverLi Well that's right but I strongly believe that (if there exists) a proof with Jensen's inequality is horrendous and inadequate . In my case the proof using Jensen + strongly convex function works but it's nightmarish to solve . So if you have a nice proof with Jensen I shall open a bounty for you even if I don't believe you got just one .Good day !
Comment: No, since there is a nice solution by Bernoulli's inequality, I won't consider Jensen.


Duplicar  sem duplicar o JavaScript

Question: Preciso da seguinte ajuda: consegui juntar dois códigos que achei na internet, e editei a formatação a meu gosto.
Tenho uma galeria com imagens e overflow na horizontal, meu código funciona, porém  preciso repetir a div completa uma ou mais vezes no site, e como sou leigo na área, não consigo resolver sem dar conflito, tentei até criar dois nomes e scripts e css para tudo, porém deu muitos conflitos de código e a semântica ficou horrível, eu sei que é possível criar mais de um com pequenos ajudstes no código, porém cheguei a conclusão de que sem ajuda eu não vou achar a resposta!
Como está:

Como preciso:

Código:

* {
 box-sizing: inherit;
}

.pn-ProductNav_Wrapper {
 position: relative;
 padding: 0 11px;
 box-sizing: border-box;
}

.pn-ProductNav {
    /* Make this scrollable when needed */
    overflow-x: auto;
    /* We don't want vertical scrolling */
    overflow-y: hidden;
    /* For WebKit implementations, provide inertia scrolling */
    -webkit-overflow-scrolling: touch;
    /* We don't want internal inline elements to wrap */
    white-space: nowrap;
    /* If JS present, let's hide the default scrollbar */
    .js & {
        /* Make an auto-hiding scroller for the 3 people using a IE */
        -ms-overflow-style: -ms-autohiding-scrollbar;
        /* Remove the default scrollbar for WebKit implementations */
        &::-webkit-scrollbar {
            display: none;
        }
    }
 /* positioning context for advancers */
 position: relative;
 /*Crush the whitespace here*/
 font-size: 0;
}

.pn-ProductNav_Contents {
 float: left;
 transition: transform .2s ease-in-out;
 position: relative;
}

.pn-ProductNav_Contents-no-transition {
 transition: none;
}

.pn-ProductNav_Link {
 text-decoration: none;
 color: #888;
 /*Reset the font size*/
 font-size: 1.2rem;
 font-family: -apple-system, sans-serif;
 display: inline-flex;
 align-items: center;
 min-height: 44px;
 border: 1px solid transparent;
 padding: 0 11px;
 & + & {
  border-left-color: #eee;
 }
 &[aria-selected="true"] {
  color: #111;
 }
}

.pn-ProductNav_Indicator {
 position: absolute;
 bottom: 0;
 left: 0;
 height: 4px;
 width: 100px;
 background-color: transparent;
 transform-origin: 0 0;
 transition: transform .2s ease-in-out, background-color .2s ease-in-out;
}

#caixas{
 flex-direction: row;
 justify-content: center;
 align-items: center;
 width: 100%;
 margin-top: 10px;

}
.conteudocaixas{
 overflow-x: scroll;
 overflow-y: hidden;
 white-space: nowrap;
}
.imagemcaixas{
 margin-top: 5px;
 width: 12.15%;
 max-width: 170px;
 height: auto;
 display: inline-block;
}
.position_btcx{
 display: inline-block;
}
.button_cx{
 background: #fff;
 height: 30px;
 width: 30px;
 border: 1px solid #000;
 border-radius: 5px;
}

.caixa1{
 margin: 0 0.5% 0 0.5%;
}
.caixa2{
 margin: 0 0.5% 0 0.5%;
}

                    Galeria1
                    Galeria2
                    Galeria3

Answer: Simplifiquei seu código, e usei apenas um comando em JQuery, que vi que estava incluído em seu código.
Primeiro o código Javascript, esqueça aquelas funções todas, use só isso:

Depois o CSS, modifiquei poucas coisas. A principal mudança, foi pra realizar aquele efeito da linha a baixo do menu selecionado. Criei uma classe active, ao invés de criar um elemento. Essa classe manipula as bordas do item a selecionado, já com os efeitos de transição via CSS.

Por fim o HTML. Retirei a repetição das imagens para economizar espaço aqui. Ficaria assim:

                    Galeria1
                    Galeria2
                    Galeria3

                    Galeria1
                    Galeria2
                    Galeria3

De um modo geral, fiz de modo que a manipulação se desse em referência ao elemento clicado e não a IDs. A tag ID do HTML pressupõe que aquele elemento é único, o que no seu caso não é verdade. Dessa forma usando classes, a lógica é aplicada de forma homogênea a todos elementos e possíveis duplicatas. Sem contar a simplicidade da programação aplicada para resolver o problema. A seção é localizada através de um atributo personalizado criado no HTML, o atributo item. O âncora clicado e a div compartilham o mesmo valor, ligando assim um ao outro.
Resultado final:
Comment: Como seria esse efeito? Porque o sublinhado muda de um pro outro. E a cor seria aleatória?
Comment: Cara, para ficar perfeito só faltou o efeito sublinhado correndo e mudando de cor, mas ja me ajudou muito!
Comment: O efeito faz com que quando mude de aba a linha não some de um e aparece na outra, ela corre de uma para a outra.

No javascript tinha uma lista sequencial com as cores definidas, cada uma aba ele dava uma cor ligada a variavel colours, pra mim é um pouco útil a definição de cor em cada aba.
Comment: se conseguisse me ajudar eu ficaria grato, o efeito consegui aqui: http://jsfiddle.net/xY7tx/4845/
Comment: Outro mais simples, efeito está apenas em css, porém como Hover.
link: https://codepen.io/rm/pen/ldhon

Duplicar  sem duplicar o JavaScript


Generating indices using np.triu_indices

Question: I would like call a function on each entry of an upper-triangular matrix. In order to avoid a messy nest of for loops, I am using the numpy.triu_indices function. My function works but I would like to know if there is a cleaner way to implement the indexing.
import numpy as np
def weighted_edges(adjmat):
    indices = np.triu_indices(len(adjmat))
    return ((x, y, adjmat[x,y]) for (x,y) in zip(indices[0], indices[1]))

I suspect that there is a way to implement this without needing to reference indices[i] in the zip call. Is there indeed a way to do so?
Answer: If you have an N x N matrix from which you want the upper triangular values, just do
import numpy as np
N = 5
x = np.arange(N**2).reshape(N, N)
upper = x[np.triu_indices(N, 0)]

If you want the triangular values offset from the main diagonal by k columns, then do
upper = x[np.triu_indices(N, k)]

Comment: @EricKightley What `np.triu_indices` returns is a 2 element tuple, holding two arrays, one for indexing the rows, another for the columns. `np.vstack` needs a tuple (or list) of arrays to stack, so by adding the single element tuple `(adjmat[indices,)` to the `indices` tuple, we concatenate them and create a three element tuple, that gets stacked, and then transposed to fit your original output.
Comment: The only thing left to get the same as the OP function returns, is to stack the three arrays together and transpose them: `np.vstack(indices+(adjmat[indices],)).T`
Comment: Thanks very much. @Jaime: That is exactly what I needed to finish. I am struggling to understand the + operation. `indices + adjmat[indices]` gives me a result I understand, but I do not understand why `indices + (adjmat[indices],)` performs a union, instead of vector addition (adding nothing to the second array in indices).


vim colorscheme shows wrong color

Question: I want to change my colorscheme to this: earthsong on http://daylerees.github.io/
but it changes color something srange. like this (up: molokai, down: earthsong)
I try :colorscheme earthsong in vim, it gives same result.
I using vim on mac (latest version)
I got .vim code from https://github.com/daylerees/colour-schemes/blob/master/vim/colors/earthsong.vim
Can I get some help?
Answer:
The very first place to look for help with an open source project is its issue tracker if it exists.
That colorscheme only uses your terminal palette. This means that you must adjust it to the colors used in the colorscheme which don't seem to be listed anywhere else than in the colorscheme itself.

If you use Vim 8 and an up-to-date iTerm you could tell Vim to use your GUI colors in the terminal with:
set termguicolors

vim colorscheme shows wrong color


Is there a name for affinely extended complex numbers?

Question: Consider the way $\widehat{\mathbb R}$ relates to $\overline{\mathbb R}$. This set would relate to $\widehat{\mathbb C}$ in a similar way, with $\aleph_1$ infinities, each at different angles, forming somewhat of a circle with an infinite radius encapsulating the complex plane.
Such a set could possibly be defined as:
$$
\overline{\mathbb C}=\mathbb C \cup \left\{ x : (\exists \theta \in [0,2\pi)) \left[x=\lim_{r\to\infty} re^{i\theta} \right] \right\}
$$
I'm not sure that the above is a rigorous definition, but I feel like it gets the point across.
Is there some way this structure could be rigorously defined, and does it have a conventional name?
Note that I am not talking about $\widehat{\mathbb C}$, which contains a single point for infinity akin to the projectively extended real line.
Comment: Possibly related: https://math.stackexchange.com/questions/1638303/many-point-compactification
Comment: In Mathematica computer algebra system there is a term "directed infinity" on the complex plane. It can return results in terms of directed infinities.
Answer: I think the thing you're talking about is very similar $\Bbb RP^2$, the real projective 2-space. There's a point at infinity for each possible "direction" in the plane.
The distinction is that in $\Bbb RP^2$, the point at infinity for lines at angle $\theta$ is the same as that for lines at angle $\theta + \pi$. So arguably, the thing you're really getting at is called
"the closed unit disk", with points on $\partial D$ corresponding to your points at infinity. But it's the disk with some underlying geometry, etc., that's not the one from the standard embedding.
This has actually been studied pretty carefully, in a PhD thesis by Jorge Stolfi at Stanford. It's called Oriented Projective Geometry, and I think it was published by IEEE, but it's been a long time, so I'm not certain of that last part. Anyhow, there's a solid reference for you. Here's a link to it on Amazon: https://www.amazon.com/Oriented-Projective-Geometry-Framework-Computations/dp/148324704X


Onload function not working?

Question: Onload function is not working.I cannot play the song automatically when the song is loaded.Here is my view.

<?php echo str_replace('_',' ',$name);?>

            <audio id="audio" controls="controls" >
                    <source src="<?php echo base_url();?>musics/<?php echo $name;?>"  type="audio/mp3" >

            </audio>

        <a href="<?php echo base_url();?>admin/audio/showaudio" class='back'>Back to All song list

i like to play the song when user click the song name.but here user have to click the "play" button to play the song.
Answer: The onload event can only be used on the body itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.
Answer: as far as I know, onload function can be used on  tag, it doesn't seem to work on other tags. try adding it on  or just running the function in js.

Onload function not working?


How to build a lengths converter

Question: I'm very new to JS and want to create a basic converter (mm, cm, dm, m, km).
I want that if the mm input is bigger than 0, the converted cm will be entered into the cm input.
Does anyone know what I'm doing wrong?

function convert() {
  let milliM = parseFloat(document.getElementById("mm").value);
  let centiM = parseFloat(document.getElementById("cm").value);
  let deciM = parseFloat(document.getElementById("dm").value);
  let Meter = parseFloat(document.getElementById("m").value);
  let kiloM = parseFloat(document.getElementById("km").value);

  let mm = parseFloat(document.getElementById("mm"));
  let cm = parseFloat(document.getElementById("cm"));
  let dm = parseFloat(document.getElementById("dm"));
  let m = parseFloat(document.getElementById("m"));
  let km = parseFloat(document.getElementById("km"));

  if (milliM > 0) {
    centiM = milliM / 10;
    cm.value = centiM;
  }
}

Converter

Length

  <input type="text" id="mm" value="0"> mm
  <input type="text" id="cm" value="0"> cm
  <input type="text" id="dm" value="0"> dm
  <input type="text" id="m" value="0"> m
  <input type="text" id="km" value="0"> km

  <button onclick="convert()">Convert</button>

Comment: Your example code threw an error because you used the same varaible name `m` twice. I fixed your code changing the second `m`  to `km` as it should be, to make at least what you have so far work.
Comment: You've set `cm` equal to a float value but are calling `cm.value = centiM` as if it were and input element.
Comment: Hi Palexer. Welcome to SO. It seems that your code has an error `SyntaxError: redeclaration of let m`. Try to solve that one first and see if it runs.
Comment: Variable cm needs to be document.getElementById('cm'). Parsefloat tries to convert whole node.
Answer: Meter (m) as reference unit:
const converter = {
    "mm": 1000,
    "cm": 100,
    "dm": 10,
    "m": 1,
    "km": 0.001,
    "mile": 3.600/3.937 * 1.760
};

Example
Convert 30 dm to km

let res = 30 * 0.001 / 10;
console.log(res);

Complete solution

// Meter as reference unit
const converter = {
  "mm": 1000,
  "cm": 100,
  "dm": 10,
  "m": 1,
  "km": 0.001,
  "mile": 3.600 / 3.937 * 1.760
};

const units = Object.keys(converter);

function convertAll(currentValue, currentUnit) {
  units.forEach((unit) => {

    // If not the current input
    if (unit !== currentUnit) {
      let input = document.getElementById(unit);
      input.value = Number(currentValue) * converter[unit] / converter[currentUnit];
    }
  })
}

units.forEach((unit) => {
  let input = document.getElementById(unit);
  input.addEventListener("input", function() {
    convertAll(this.value, this.id);
  })
})
ul {
  list-style: none;
  padding: 0;
}

ul span {
  margin-left: 5px;
}

<input type="text" id="mm" value="0">mm

<input type="text" id="cm" value="0">cm

<input type="text" id="dm" value="0">dm

<input type="text" id="m" value="0">m

<input type="text" id="km" value="0">km

<input type="text" id="mile" value="0">mile

Answer: The first thing I can see you should remove parseFloat from this section. You are looking for element reference so it's not needed here:
let mm = parseFloat(document.getElementById("mm"));
let cm = parseFloat(document.getElementById("cm"));
let dm = parseFloat(document.getElementById("dm"));
let m =  parseFloat(document.getElementById("m"));
let km = parseFloat(document.getElementById("km"));

Should be like this:
let mm = document.getElementById("mm");
let cm = document.getElementById("cm");
let dm = document.getElementById("dm");
let m =  document.getElementById("m");
let km =  document.getElementById("km");

Answer: 2 Things:

You accidentally declared m twice. The second one should be km. (Not relevant for the problem you're trying to solve, but worth pointing out).
Ditch the parseFloats when defining your selectors. So change this part:

let mm = parseFloat(document.getElementById("mm"));
let cm = parseFloat(document.getElementById("cm"));
let dm = parseFloat(document.getElementById("dm"));
let m =  parseFloat(document.getElementById("m"));
let m =  parseFloat(document.getElementById("km"));

To this:
let mm = document.getElementById("mm");
let cm = document.getElementById("cm");
let dm = document.getElementById("dm");
let m =  document.getElementById("m");
let km = document.getElementById("km");

You don't need to use parseFloat since you're just using those variables as references to the selectors.
Answer: In addition to the issues addressed in the comments and answers so far, here's a fully working example with a different approach that I'd prefer. Instead of requiring the user to click a button to trigger the recalculation (btw, which value would you take as the base value in that case? You could highlight the last changed field to give visual feedback to the user and use this field as the base, but that still seems overly complicated to me...), trigger the calculation every time one of the inputs is changed, and use this input as the base for your calculations:

const mm = document.getElementById("mm");
const cm = document.getElementById("cm");
const dm = document.getElementById("dm");
const m = document.getElementById("m");
const km = document.getElementById("km");

[mm, cm, dm, m, km].forEach((inputEl) => {
  inputEl.addEventListener('input', () => convert(inputEl));
});

function convert(inputEl) {
  switch (inputEl.id) {
    case 'mm':
      let milliM = parseFloat(document.getElementById("mm").value);
      cm.value = milliM / 10;
      dm.value = milliM / 100;
      m.value = milliM / 1000;
      km.value = milliM / 1000000;
      break;
    case 'cm':
      let centiM = parseFloat(document.getElementById("cm").value);
      mm.value = centiM * 10;
      dm.value = centiM / 10;
      m.value = centiM / 100;
      km.value = centiM / 100000;
      break;
    case 'dm':
      let deciM = parseFloat(document.getElementById("dm").value);
      mm.value = deciM * 100;
      cm.value = deciM * 10;
      m.value = deciM / 10;
      km.value = deciM / 10000;
      break;
    case 'm':
      let Meter = parseFloat(document.getElementById("m").value);
      mm.value = Meter * 1000;
      cm.value = Meter * 100;
      dm.value = Meter * 10;
      km.value = Meter / 1000;
      break;
    case 'km':
      let kiloM = parseFloat(document.getElementById("km").value);
      mm.value = kiloM * 1000000;
      cm.value = kiloM * 100000;
      dm.value = kiloM * 10000;
      m.value = kiloM * 1000;
      break;
  }
}
.last-touched {
  box-shadow: red 0px 0px 8px
}

Converter

Length

  <input type="text" id="mm" value="0"> mm
  <input type="text" id="cm" value="0"> cm
  <input type="text" id="dm" value="0"> dm
  <input type="text" id="m" value="0"> m
  <input type="text" id="km" value="0"> km

How to build a lengths converter


How are custom kernel functions in Gaussian processes statistically justified?

Question: I am confused about one aspect of the use of Gaussian processes for Bayesian inference. I understand that it relies on the assumption that your train and test data points form a multivariate normal distribution where you define a prior mean and covariance for the distribution. What I don't understand is that I believed covariance had a strict statistical definition $\text{cov}(X, Y) = \mathbb{E}\left(X-\mu_X)(Y-\mu_Y)^\top\right)$. How is it justified statistically to just use what seems like any old function we like? I am pretty new to this so would appreciate if anyone could direct me to good resources on the topic too.
Comment: Choosing a covariance function for a Gaussian process is analogous to choosing a variance for a normal distribution prior. Just as you can have a prior with any $\sigma^2$ you like, so you can have a Gaussian process with any covariance function (the only requirement is that it will be positive-definite)
Comment: So following this, is it accurate to say that choosing a covariance function when sampling random functions is analogous to choosing a variance scalar when sampling random  variables?
Answer: In Gaussian Process, your task is to learn the distribution over functions $$f(\mathbf{x}) = [f(x_1), f(x_2), \dots, f(x_n)]'$$ This distribution is modeled by Gaussian Process $\mathcal{GP}\left(m(\mathbf{x}),\, k(\mathbf{x}, \mathbf{x}')\right)$ parametrized by the mean function and covariance function
$$\begin{align}
m(\mathbf{x}) &= E[f(\mathbf{x})] \\
k(\mathbf{x}, \mathbf{x}') &= E\big[\big(f(\mathbf{x}) - m(\mathbf{x})\big)\big(f(\mathbf{x}') - m(\mathbf{x}')\big)\big]
\end{align}$$
So the covariance function is the function that tells us what would the covariance be. It's the same as saying, for example, that the conditional expectation $E[y|\mathbf{x}]$ is given by a function $g(\mathbf{x})$, where in linear regression it would be a linear function $g(\mathbf{x}) = \mathbf{x}\boldsymbol{\beta}$. It doesn't say that we are not taking the integral to calculate the expectation anymore, but that the integral has a solution given by $g(\mathbf{x})$. It also doesn't say that any conditional expectation is like this, but that this particular random variable has an expectation that takes such form.
Gaussian Process defines such a distribution that if using the regular definition of covariance you calculated the covariance of $f(\mathbf{x})$ it would take the form of the covariance function.
Comment: Thank you, could you elaborate on the last point a bit more?
Comment: @3orange1red you can define a family of right triangles with sides $a,b,c$ such that $b = 2a$, so $c = \sqrt{a^2 + 2a^2}$. In the same way, you can define a family of distributions that share some property, or where some parameter is a function of something else.


accessing values in array after quiting the app

Question: In my iphone application I am storing values(string) in an array and I want to retrieve it when I reload the application.That is,When the user exits my app, I want this array to be saved so that when the app is loaded again by the user it want to be accessed
Comment: possible duplicate of [getting values in an array after exiting+objective c](http://stackoverflow.com/questions/5893694/getting-values-in-an-array-after-exitingobjective-c)
Answer: You cant save an array after an application has been closed.But this only "saves" when you press the home button(multitasking).
Im not sure as im an beginner in objective c also but i think you need to make an database in ur app so it saves the things needed to be saved for ur app.
Answer: As long as the contents of the array are all property list objects (in your case they are as they are all NSString), you can save the array contents to a file using the
<code>- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
</code>
method on NSArray.
Then when the app is starting up again you can reinitialize the array from the file using :
<code>- (id)initWithContentsOfFile:(NSString *)aPath
</code>


Compile errors with Fortran90

Question: All, I've been fighting these errors for hours, here's my code:
program hello
implicit none
integer :: k, n, iterator
integer, dimension(18) :: objectArray

call SetVariablesFromFile()
do iterator = 1, 18
    write(*,*) objectArray(iterator)
end do

contains
subroutine SetVariablesFromFile()
    IMPLICIT NONE
    integer :: status, ierror, i, x

    open(UNIT = 1, FILE = 'input.txt', &
    ACTION = 'READ',STATUS = 'old', IOSTAT = ierror)
    if(ierror /= 0) THEN
        write(*, *) "Failed to open input.txt!"
        stop
    end if

    do i = 1, 18
        objectArray(i) = read(1, *, IOSTAT = status) x
        if (status > 0) then
            write(*,*) "Error reading input file"
            exit
        else if (status < 0) then
            write(*,*) "EOF"
            exit
        end if
    end do
    close(1)

END subroutine SetVariablesFromFile

end program hello

I'm getting compile errors:

make: * [hello.o] Error1
Syntax error in argument list at (1)

I read online that the latter error could be due to a long line of code exceeding 132 characters, which doesn't appear to be the problem.I have no where to begin on the first error... any help would be much appreciated!
Answer: This,
objectArray(i) = read(1, *, IOSTAT = status) x

is not valid Fortran. You need to write it as,
read(1,*,iostat=status) objectArray(i)

Setting it in this correct form, I received no compiler errors with ifort 12.1, nor with gfortran 4.4.3
Comment: Excellent, compiles now! Thank you

Compile errors with Fortran90


TextField JavaFX pegando o evento

Question: Gostaria de saber qual o evento que ao sair do objeto TextField do JavaFx, altera um valor de um outro objeto.
if (textFieldC1.getText().equals("50")) {
    slider1.setValue(Double.valueOf(textFieldC1.getText()));
}

Comment: Tenta com focus: http://stackoverflow.com/questions/16549296/how-perform-task-on-javafx-textfield-at-onfocus-and-outfocus
Comment: Não resolveu Jerfesson Assis
Answer: Tente dessa maneira:
textFieldC1.setOnAction( (ActionEvent e)-> {
 if(textFieldC1.getText().equals("50")) {
     slider1.setValue(Double.valueOf(textFieldC1.getText()))
 } });

Comment: Muito obrigado. Deus lhe abençoe!

TextField JavaFX pegando o evento


Group Theory: Alternate proof of the 2nd Isomorphism Theorem

Question: I can prove the 2nd Isomorphism Theorem in the usual way, but for fun I'm trying to prove that the map $HN \rightarrow H/(H\cap N)$ given by $\phi(hn)=h(H\cap N)$ is a homomorphism. I've gotten as far as showing that $ \phi(h_1n_1h_2n_2) = h_1h_2n'(H\cap N)$ but can't see my way to forward.  Is this the right map to have chosen?
Statement of the 2nd Isomorphism Theorem: Let $H\leq G$ and $K\trianglelefteq G$. Then $K\trianglelefteq HK$ and $H\cap K \trianglelefteq H$ and $HK/K \equiv H/(H\cap K)$.
Comment: Can you state the second isomorphism theorem? I want to know if there are any assumptions on $H$ and $N$, which you can use at this point where you are stuck.
Comment: @астонвіллаолофмэллбэрг Added to the post.
Answer: First it's not difficult to show that your $\phi$ is well defined, i.e. if $hn=h'n'$, then $\phi(hn)=\phi(h'n').$
Since $HN$ is a subgroup, this means $h_1n_1h_2n_2\in HN$ for $h_1,h_2\in H,n_1,n_2\in N$. Thus there exists $h'\in H,n'\in N$ such that
$$h_1n_1h_2n_2=h'n',\quad (*).$$
For each $h\in H$, denote $[h]:=h(H\cap N)\in H/(H\cap N)$. To prove that $\phi$ is a homomorphism, it suffices to prove that
$$[h_1][h_2]=[h'].$$
Noting that $[h_1h_2]=[h_1][h_2]$, it suffices to prove that
$$(h_1h_2)^{-1}h'\in H\cap N.$$
To see this fact: since $N$ is normal, there exists $m\in N$ such that
$$n_1=h_2mh_2^{-1},$$
and by $(*)$ we have
$$h_1h_2mn_2=h'n'.$$
It follows that
$$mn_2(n')^{-1}=(h_1h_2)^{-1}h',\quad (**).$$
Since
$$\text{LHS of }(**)\in N,\quad \text{RHS of }(**)\in H,$$
it follows that $(h_1h_2)^{-1}h'\in H\cap N$. This proves that $\phi$ is a homomorphism.
It's trivial that $\phi$ is surjective with $\text{Ker}(\phi)=N$. Thus by the first isomorphism theorem
$$(HN)/N\cong H/(H\cap N).$$


Validation on key-press

Question: I have the following WPF code to validate key-press and based on the key pressed it either allows user to enter the key or simply stops the key press event to stop entering invalid keys..
<TextBox PreviewKeyDown="PreviewKeyDown" />

private void PortPreviewKeyDown(object sender, KeyEventArgs e)
{
    bool allowedKeys;
    allowedKeys = // logic for validation

    e.Handled = allowedKeys;
}

My question is, is this the right approach to do validation in WPF.. I want to restrict user to enter invalid character..
I know I can use dependency properties and call validation and then display error or success message, but I don't want to get that far, I simply want to stop user from entering invalid characters.
Answer: Seems like a valid approach to me, however I would try to display some message telling the user when a character is invalid, otherwise they might think something is broken.
It might also be a good idea to make the logic generic by subclassing TextBox and providing properties which characters are allowed. Some libraries already have controls like this, like the MaskedTextBox of the extended WPF toolkit which also provides format highlighting.

Validation on key-press


I can match pitch/melodies if played at a piano but not if i directly hear a song is it normal for a beginner?

Question: Hi guys i'm 6 month into singing, and i have started where i wasn't able to match any pitch at all.
With the help of a piano (and a app to see if i'm correctly matching the pitches) i started to match single pitches/ scales or something like that.
I've became quite good at it, if i play a note/small melody on the piano in my range i can match it , (maybe not right away, but watching if the pitches are higher/lower on the keybord and listening to it 4/5 times and then i can match it)
But the problem comes when i hear directly a song, my ears really can't "understand" the melody even if it just the first part of a song so of course i can't match it at all ( i go up when the song goes down or something like that, i'm totally wrong).
if the same melody is played then on the piano where i can visually see the pitches than i can match it humming quite well.
Why is this happening ? is a fact that i'm a beginner and this will came with time ?
is this kind of exercise that i'm doing every day ( paly pitch/scales on the piano and then with an app understand if i can match it) is right ? or i need to change something ?
Answer: What you need is ear training. The main skills are:

ability to recognize what you hear (intervals, chords, rhythms, melodies)
ability to sing something you hear (e.g. repeat the notes or a melody you hear, repeat rhythm)
ability to sing something you haven't heard before, e.g. by reading it from a music score

It is normally part of education in music schools, but there are also individual courses and other materials in the internet, even phone apps. Look for ear training learning materials, or a teacher – this will help you to work efficiently.
The exercises you describe seem fine to me. Play something and then try to repeat it with voice. At the beginning go slowly, with short phrases, even as short as one or two notes. Identify parts of the song that cause more trouble and work on them more. As you get better, invert the order: first sing, and the check on piano if you sung it right.
While it's not strictly needed, it will help you to learn some basic music theory (if you don't know it yet), mainly: intervals names and how they sound, and also reading scores. E.g. if you learn that C-E is a major third, then if you need to sing D-F#, which is also a major third, you will know to sing the same thing, just starting from a different note. You write that you have trouble with "understanding" what you hear – this is exactly what music theory is for.
Concerning songs, if it helps you to play music on piano, look for scores – it should be easy to find scores for popular songs.
Issues with singing in pitch may also originate from lack of voice training. You mention that you "hum". Perhaps you're shy to sing loud and don't use good breath support? That would surely affect the intonation. This is where a singing/vocal teacher can help, and with a good teacher you can make good progress already after several lessons.
Finally, I'm not exactly sure what you mean by "matching". I should mention that there are two types of hearing: relative pitch and absolute pitch. If a person with good relative pitch knows that a song starts from some note, e.g. C, and hear that first note played, they are able to follow and sing the whole song. However if they don't hear that first note (or other musical cue), they may sing the whole melody shifted up or down, e.g. starting from D or B. A person with absolute pitch doesn't need that first note. Most of the people, even most of the musicians have only relative pitch. Absolute pitch isn't really something that can be learned. Relative pitch can be trained and that's where you should put your work.
Comment: Absolute hearing = absolute *pitch* - sometimes referred to as perfect pitch.
Answer: Ear training is not the real issue based on your question and description.  If you can go to an instrument and find notes your ear is not bad.  I have had this issue, recently starting classical voice lessons after 45 years of playing guitar, violin, and classical bass.  I can hear a lick and immediately find it on the guitar, I can identify chords, inversions, modes, etc.  Sometimes when I sing I can't even hear myself and have no concept of whether I am in tune.  With all instruments the key is to develop a reliable calibration that connects what you hear in your head to a specific physical movement or state in your body.  For guitar that is moving the hand to the correct position and getting the correct fingers to align with strings and frets (no need to look, you feel it with the correct training).  Singing works the same way.  It takes a lot of internal coordination, diaphragm support, mouth shape, air flow, resonance in the head, etc.  If this is not all correct the not is off, the tone is off, everything is out of whack.
Are you actually taking singing lessons form a teacher or just trying to sing on your own?  If the latter, I'd recommend taking lessons to be sure you learn correct technique.  6 months is not a long time to be trying to learn this, especially without help.
Answer: 6 months into singing. The majority of folk will start singing when quite young, even as a bit of fun, and develop that as they get older. Not many will wake up one morning and think 'I need to learn how to sing, not having sung a note previously!'.
Right now, you seem to need to watch as notes on the piano are played, and realise that those further to the right are higher, left, lower. That's o.k., but by now, you shouldn't need to rely on visuals to determine pitch. Try getting used to playing notes chromatically on the piano, and singing each in turn as you play them. I say this way, rather than with scales, as you may only be conversant with C major, using the white keys. If you can do this using scale notes from other keys, fine, do that.
So, play and sing up (and down!) 2 or 3 notes initially, in sequence. Get used to doing this before and after the piano gets played, as well as with it. Then gradually increase the spaces between notes, over several weeks. A nice little trick is to decide on one particular piano note, and try to sing it, before playing it, every time you plass said piano. Then try to play the note you sung. Eventually, with a lot of practice, you may even find you hit the note right each time!


Analysis: Integration (Riemann/Step functions)

Question:
Using the definition of the integral of a continuous function, and
  that $\displaystyle\sum_{j=0}^{2^n-1} j = (2^n-1)2^{n-1}$ to show that
  $\int_0^1x \ dx = \frac{1}{2}$

I'm having trouble even starting this question as I'm not sure how to take advantage of the sum given.
Thanks!
Answer: Since $f$ is continuous, it is integrable. Hence any Darboux sum converges to integral of $f$ when partition's tightness tends to $0$. Now I suggect you to consider the simplest partition $\Delta_j:=[\frac{j}{2^n},\frac{j+1}{2^n}]$ with points $\xi_j=\frac{j}{2^n}$, where $j=0,\ldots, 2^{n}-1$


Context free grammar for the language

Question: I had to make a context free grammar for the following language:
$$
\{a^m b^n \mid 1 \le m \le n \le 2m\}
$$
What I thought is:
\begin{align*}
S &\to aXbb \\
X &\to a|aab|abb|ab|E
\end{align*}
Is this correct way of writing a CFG?
Comment: Your grammar allows only five words: aabb, aaabbb, aabbb, aabbb, abb. Note that, in addition to missing longer words, you are also missing the short word ab.
Answer: It's interesting to see so many different ideas. My own hint is that we can produce words by "creating" as and bs iteratively, and each step we can do one of two things: create one a and one b, or create one a and two bs.
(be aware that each answer so far is leading towards a different presentation of the grammar: you can't combine the hints directly, and should probably only think about one at a time)
Comment: Well, I don't see how this is different. You may render the grammar in different ways, but the idea is the same: with every $a$ you generate one or two $b$s; only you decide on this right away, Ayman delays the substitution $B \to b$ for later, and my solution forces the order in some particular way (the multiplication of $b$s is commutative after all). For me it is exactly the same. +1 for the comment in parentheses -- I can imagine that one could easily miss that.
Comment: The actual execution of our three answers are different, and I get the vague impression that we went through very different thought processes to arrive at our answer. It looks like you had a very algebraic approach to the problem. When I read Ayman's, I get a vague impression of a general technique of inserting intermediate symbols to allow and constrain further choices in a construction. Neither idea crossed my mind when I looked at the problem.
Answer: It's not correct. Consider the word $a^4b^5$. This word belongs to the language because $m=4$, $n=5$ and $1 \le 4 \le 5 \le 2 \times 4$. However, your grammer cannot produce it, as it can produce three "$a$"s at most.
Here is a hint: Make $S$ produce one $a$, one $b$ and one $B$ recursively. Make $B$ produce one $b$ at most. This ensures that $1 \le m \le n$, and $n \le 2m$.
Comment: I can have this.
Comment: Whats if I change to S-> S1 S2 and S1-> ab S2-> aXbb and X-> aX|aaXb|aXbb|aXb|E. Will this be too long?
Comment: Among the words that grammar produces are ababb and abaaaaaaaaaaaaaaaabb.
Comment: @RichaSachdev - Still incorrect, I'm afraid. This grammar can generate the word $ababb$.
Answer: Hint:
$$a^m b^n = a^{2m-n}a^{n-m}(bb)^{n-m}b^{2m-n}$$
Answer: CFG should be $$S\rightarrow aSb|aSbb|ab|abb$$
where $S$ is the start symbol.
So for example if you have to produce the word $a^mb^n$ then as we know $m\leq n\leq 2m$ then you will use $2n-m$ times this production ($S \rightarrow aSb$) and $m-n$ times this production ($S \rightarrow aSbb$).
hence you will get  $(2n-m)+(m-n) \times a$ and $(2n-m)+2(m-n)\times b$ which is desired.
Again if $m\leq n\leq km$ then
CFG would be
$$S\rightarrow aSb|aSbb|.....|aS\underbrace{bb....b}_{\text{k times}}|ab|abb|......|a\underbrace{bb....b}_{\text{k times}}$$
and here also logic is same.
Comment: There's a small oversight: the empty string is a word in your grammar.
Comment: yes the empty string cannot be there. so that needs to be taken care of.
Comment: We could modify it to be S -> aAb and A-> aAb, aAbb and empty string
Comment: @Richia: the underlying idea will work, but don't forget that `abb` is in your grammar....
Comment: @RichaSachdev if you are talking about this $$S\rightarrow aAb \\ A\rightarrow aAb|aAbb|\epsilon$$ then how will you produce $abb$ which is in the language
Comment: @RichaSachdev well you can do $S \rightarrow aAB|aAbb$ and else is same
But if written in short it will be the same as I have written in my answer
Comment: @SaurabhHota: But I cannot include empty string so I can include in my definition A in addition to all also just goes to b. Then I can have abb. Do you think the definition is complete now
Comment: @RichaSachdev yes now your grammar is complete and sound.
Comment: I think that there is a simpler grammar: $S\rightarrow aSbV|\epsilon $ $V\rightarrow b|\epsilon $

Context free grammar for the language


Our hot question

Question: The question is pretty broad and vague, and many answers to that question appear unscientific and inaccurate to me. I have protected the question for now.
Please down vote questions that you feel are not up to standards of this site.
I know that the question is attracting a lot of traffic, which in general is not a bad thing. But, judging from the content, it appears to be layman answers to a layman question - which is not something we should encourage here. If you disagree with the protection, down vote me :)
Comment: But then the question is why did YOU bother to answer it if you find it "unscientific" (whatever that means ... ) ?
Answer: I agree with protecting it. However, I am not a layman and I don't think the question is neither vague or broad. He basically asked:

Is $A \Rightarrow B$ correct?

and I answered:

No, check this counterexample. And here is some more information if
  you are interested.

Given that we are economists the term person A loses and person A gains is fairly common and I guess most economists would automatically add "in terms of utilities, given some reference point" (like I did). If that was not clear someone should have asked and improved the question.
As this question unfortunately attracted a lot of attention from the outside, we had many answers and comments like:

I have an example, so it is always correct. QED.
You have not mentioned that it IS possible that B could follow from A.
You pretend as if capitalism is a good thing but it is bad!

I don't think this has anything to do with the quality of the question, I think it is a general problem with economic questions: everyone has an opinion about it and if they think they understand the question they will answer. We just have to learn to deal with them (i.e. downvoting, protecting these questions and making them as precise as possible).
I won't argue that it is not a great question and I would not mind not allowing these kind of simple questions here, but that is a different matter.
Btw I think your answer is also inaccurate (see my comment) ;-)

Our hot question


Div height 100% em div height auto?

Question: Tentarei ser bem explicativo. Tenho a estrutura de um site comum como podem ver no html abaixo. E Quero que a altura da sidebar aumente conforme a altura do container ao lado. Também pode ser entendido se eu disser que preciso com que o sidebar atinja sempre a altura máxima do #wrap, que esta com height automático. Tenho o seguinte código:

*{margin:0;padding:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;-o-box-sizing:border-box;box-sizing:border-box;}
#wrap{width:90%;margin:30px auto;background:#DDD;padding:20px;overflow:hidden;}
#posts{float:left;width:68%;height:2000px;background:#333;}
#sidebar{float:right;width:30%;background:#CD0000;padding:10px;}
#sidebar .widget{width:100%;height:300px;background:#111;margin:0 0 20px;}
#sidebar .widget:last-of-type{margin-bottom:0}

Link: https://jsfiddle.net/xeL80e1o/4/

Eu sei que poderia resolver isso facilmente usando o position:absolute e adicionando estes comandos css a suas respectivas classes:

#wrap{position:relative;}
#sidebar{position:absolute;right:0;height:100%}

No entanto, acontece que uma vez que o conteúdo que esta dentro do sidebar seja maior que o proprio sidebar, o conteúdo será cortado. Pois o sidebar não ultrapassa os limites do #wrap, que foi onde eu define o position:relative. Veja: https://i.stack.imgur.com/rVAXv.png
Agora que tudo já foi bem explicado, resumidamente preciso com que o sidebar acompanhe a altura do container ao lado, porém quando o conteudo que está dentro do sidebar for maior, ele redimencione normalmente como se estivesse usando o position:static, e de forma com que o #wrap não o corte. Pois bem, alguém que possa mi ajudar?
Answer: Veja funcionando aqui JSFiddle.
Basicamente, você força que o display do elemento wrap seja uma tabela (table) e que as divs principais dentro dele sejam forçadas a serem semelhantes às células de uma tabela (table-cell).
#wrap {
    width: 100%;
    display: table;
}

#wrap #sidebar {
    display: table-cell;
    width: 25%;
    background: teal;
    min-height: 100%;
}

#wrap #posts {
    display: table-cell;
    width: 75%;
    background: orange;
    min-height: 100%;
}

Comment: Valeu, funcionou^^

Div height 100% em div height auto?


Replace @Query parameter with the value from a map

Question: I have the following query
<code>@Query("SELECT g.id as name FROM Group g")
List<Group> findGroups(Map<Long, String> groupNameMap)
</code>
I only have the id from entity Group.  And I want to map the id to the name using the groupNameMap.  I want to do something like the following
<code>@Query("SELECT :groupNameMap[g.id] as name FROM Group g")
List<Group> findGroups(Map<Long, String> groupNameMap)
</code>
so that it will return a list of Group names instead of ids.  Can this be accomplished?
Answer: You can simply implement that as a new method:
<code>@Query("SELECT g.id as name FROM Group g")
List<Long> findGroups();

default List<Group> findGroups(Map<Long, String> groupNameMap) {
    return findGroups().stream()
        .map(id -> new Group(groupNameMap.get(id)))
        .collect(toList());
}
</code>


Undefined reference to `mysqlx::abi2::r0::Schema::Schema(mysqlx ::abi2::r0::Session&)'

Question: I had a problem when linking to mysqlcppconn (version 8.0.30) (similar to the issue described here).
Here is my code:
        mysqlx::Session sess2("localhost", 33060,
                                   "root", "test",
                                   "postManufDB");
        Schema mySchema(sess2);

CMakeLists.txt (used to compile my app):
cmake_minimum_required(VERSION 3.5)
project(PostManuf VERSION 0.1 LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(CPP_CON_VERSION_MAJOR 8)
set(CPP_CON_LIB mysqlcppconn${CPP_CON_VERSION_MAJOR})
set(FULL_PATH_TO_MYSQL_CONNECTOR_CPP_DIR "/usr/local/mysql/connector-c++-8.0.30")
set(CPP_CON_LIB_INC ${FULL_PATH_TO_MYSQL_CONNECTOR_CPP_DIR}/include/)
set(CPP_CON_LIB_LINK ${FULL_PATH_TO_MYSQL_CONNECTOR_CPP_DIR}/lib64/debug/)
include_directories(${CPP_CON_LIB_INC})
link_directories(${CPP_CON_LIB_LINK})

set(PROJECT_SOURCES
        main.cpp
        mainwindow.cpp
        mainwindow.h
)

add_executable(PostManuf ${PROJECT_SOURCES})

target_link_libraries(PostManuf PRIVATE ${CPP_CON_LIB})

Error:
mainwindow.cpp:(.text+0x3ab6): undefined reference to `mysqlx::abi2::r0::Schema::Schema(mysqlx
::abi2::r0::Session&)'
collect2: error: ld returned 1 exit status

Steps I've followed:

Download mysqlcppconn binaries and used it for development
Compiled mysqlcppconn binary from source and linked to it
Added add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) to CMakeLists.txt, but
then I have a lot more errors:

mainwindow.cpp:(.text+0x3bb2): undefined reference to `mysqlx::abi2::r0::Schema::Schema(mysqlx
::abi2::r0::Session&)'
/usr/bin/ld: CMakeFiles/PostManuf.dir/mainwindow.cpp.o: in function `mysqlx::abi2::r0::string:
:traits<char>::from_str(mysqlx::abi2::r0::string&, std::string const&)':
mainwindow.cpp:(.text._ZN6mysqlx4abi22r06string6traitsIcE8from_strERS2_RKSs[_ZN6mysqlx4abi22r0
6string6traitsIcE8from_strERS2_RKSs]+0x23): undefined reference to `mysqlx::abi2::r0::string::
Impl::from_utf8(mysqlx::abi2::r0::string&, std::string const&)'
/usr/bin/ld: CMakeFiles/PostManuf.dir/mainwindow.cpp.o: in function `void mysqlx::abi2::r0::in
ternal::Settings_detail<mysqlx::abi2::r0::internal::Settings_traits>::set<true, mysqlx::abi2::
r0::SessionOption, std::string const&, mysqlx::abi2::r0::SessionOption::Enum, unsigned int&, m
ysqlx::abi2::r0::SessionOption::Enum, mysqlx::abi2::r0::string const&>(mysqlx::abi2::r0::Sessi
onOption, std::string const&, mysqlx::abi2::r0::SessionOption::Enum&&, unsigned int&, mysqlx::
abi2::r0::SessionOption::Enum&&, mysqlx::abi2::r0::string const&)':
mainwindow.cpp:(.text._ZN6mysqlx4abi22r08internal15Settings_detailINS2_15Settings_traitsEE3set
ILb1ENS1_13SessionOptionEJRKSsNS7_4EnumERjSA_RKNS1_6stringEEEEvT0_DpOT1_[_ZN6mysqlx4abi22r08in
ternal15Settings_detailINS2_15Settings_traitsEE3setILb1ENS1_13SessionOptionEJRKSsNS7_4EnumERjS
A_RKNS1_6stringEEEEvT0_DpOT1_]+0xbc): undefined reference to `mysqlx::abi2::r0::internal::Sett
ings_detail<mysqlx::abi2::r0::internal::Settings_traits>::do_set(std::list<std::pair<int, mysq
lx::abi2::r0::Value>, std::allocator<std::pair<int, mysqlx::abi2::r0::Value> > >&&)'
/usr/bin/ld: CMakeFiles/PostManuf.dir/mainwindow.cpp.o: in function `void mysqlx::abi2::r0::in
ternal::Settings_detail<mysqlx::abi2::r0::internal::Settings_traits>::set<true, mysqlx::abi2::
r0::SessionOption, std::string>(mysqlx::abi2::r0::SessionOption, std::string&&)':
mainwindow.cpp:(.text._ZN6mysqlx4abi22r08internal15Settings_detailINS2_15Settings_traitsEE3set
ILb1ENS1_13SessionOptionEJSsEEEvT0_DpOT1_[_ZN6mysqlx4abi22r08internal15Settings_detailINS2_15S
ettings_traitsEE3setILb1ENS1_13SessionOptionEJSsEEEvT0_DpOT1_]+0x56): undefined reference to `
mysqlx::abi2::r0::internal::Settings_detail<mysqlx::abi2::r0::internal::Settings_traits>::do_s
et(std::list<std::pair<int, mysqlx::abi2::r0::Value>, std::allocator<std::pair<int, mysqlx::ab
i2::r0::Value> > >&&)'
/usr/bin/ld: CMakeFiles/PostManuf.dir/mainwindow.cpp.o: in function `void mysqlx::abi2::r0::in
ternal::Settings_detail<mysqlx::abi2::r0::internal::Settings_traits>::set<true, mysqlx::abi2::
r0::SessionOption, mysqlx::abi2::r0::string const&>(mysqlx::abi2::r0::SessionOption, mysqlx::a
bi2::r0::string const&)':
mainwindow.cpp:(.text._ZN6mysqlx4abi22r08internal15Settings_detailINS2_15Settings_traitsEE3set
ILb1ENS1_13SessionOptionEJRKNS1_6stringEEEEvT0_DpOT1_[_ZN6mysqlx4abi22r08internal15Settings_de
tailINS2_15Settings_traitsEE3setILb1ENS1_13SessionOptionEJRKNS1_6stringEEEEvT0_DpOT1_]+0x56):
undefined reference to `mysqlx::abi2::r0::internal::Settings_detail<mysqlx::abi2::r0::internal
::Settings_traits>::do_set(std::list<std::pair<int, mysqlx::abi2::r0::Value>, std::allocator<s
td::pair<int, mysqlx::abi2::r0::Value> > >&&)'
collect2: error: ld returned 1 exit status

I can run the application successfully when using more common classes (e.g. Session).
But when using Schema, I can't link.
CMake configuration to compile mysqlcppconn from source (contains compiler info):
=== Booststrap ===
-- generator: Unix Makefiles
-- build type: Debug
-- ----
-- The C compiler identification is GNU 9.4.0
-- The CXX compiler identification is GNU 9.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Check if the system is big endian
-- Searching 16 bit integer
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of unsigned short
-- Check size of unsigned short - done
-- Using unsigned short
-- Check if the system is big endian - little endian
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zmpl/tmp/mysql-connector-cpp/build/platform-cache
=== Booststrap done ===
-- Check if the system is big endian
-- Searching 16 bit integer
-- Using unsigned short
-- Check if the system is big endian - little endian
-- BIG_ENDIAN: 0
Building version 8.0.30
Building on system: Linux-5.15.0-46-generic (x86_64)
Using cmake generator: Unix Makefiles
Using toolset:
Building 64bit code
Building shared connector library
Configuring CDK as part of MySQL_CONCPP project
-- Looking for SSL library.
-- found OpenSSL headers at: /usr/include
-- OpenSSL library: /usr/lib/x86_64-linux-gnu/libssl.so
-- OpenSSL crypto library: /usr/lib/x86_64-linux-gnu/libcrypto.so
-- Using OpenSSL version: 1.1.1f
-- Looking for SHA512_DIGEST_LENGTH
-- Looking for SHA512_DIGEST_LENGTH - found
-- Looking for X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
-- Looking for X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS - found
-- Looking for SSL_get0_param
-- Looking for SSL_get0_param - found
-- Looking for X509_VERIFY_PARAM_set_hostflags
-- Looking for X509_VERIFY_PARAM_set_hostflags - found
-- Looking for X509_VERIFY_PARAM_set1_host
-- Looking for X509_VERIFY_PARAM_set1_host - found
-- found required X509 extensions
-- Setting up RapidJSON.
Skipping second declaration of config option: THROW_AS_ASSERT (found in: /home/zmpl/tmp/mysql-
connector-cpp/cdk/CMakeLists.txt)
-- Performing Test HAVE_STATIC_ASSERT
-- Performing Test HAVE_STATIC_ASSERT - Success
-- Performing Test HAVE_IS_SAME
-- Performing Test HAVE_IS_SAME - Failed
-- Performing Test HAVE_SHARED_PTR
-- Performing Test HAVE_SHARED_PTR - Success
-- Performing Test HAVE_SYSTEM_ERROR
-- Performing Test HAVE_SYSTEM_ERROR - Success
-- Check size of wchar_t
-- Check size of wchar_t - done
-- Setting up Protobuf.
== configuring external build of protobuf
-- sources at: /home/zmpl/tmp/mysql-connector-cpp/cdk/extra/protobuf
-- generator: Unix Makefiles
-- option CMAKE_BUILD_TYPE: Debug
-- option CMAKE_SYSTEM_NAME: Linux
-- option CMAKE_SYSTEM_VERSION: 5.15.0-46-generic
-- option CMAKE_SYSTEM_PROCESSOR: x86_64
-- option CMAKE_C_COMPILER: /usr/bin/cc
-- option CMAKE_CXX_COMPILER: /usr/bin/c++
-- ----
Not searching for unused variables given on the command line.
-- Check if the system is big endian
-- Searching 16 bit integer
-- Using unsigned short
-- Check if the system is big endian - little endian
-- BIG_ENDIAN: 0
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Performing Test protobuf_HAVE_BUILTIN_ATOMICS
-- Performing Test protobuf_HAVE_BUILTIN_ATOMICS - Success
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zmpl/tmp/mysql-connector-cpp/build/cdk/protocol/mys
qlx/protobuf
== done configuring external build of protobuf
-- Setting up compression libraries.
== configuring external build of zlib
-- sources at: /home/zmpl/tmp/mysql-connector-cpp/cdk/extra/zlib
-- generator: Unix Makefiles
-- option CMAKE_BUILD_TYPE: Debug
-- option CMAKE_SYSTEM_NAME: Linux
-- option CMAKE_SYSTEM_VERSION: 5.15.0-46-generic
-- option CMAKE_SYSTEM_PROCESSOR: x86_64
-- option CMAKE_C_COMPILER: /usr/bin/cc
-- option CMAKE_CXX_COMPILER: /usr/bin/c++
-- ----
Not searching for unused variables given on the command line.
-- Check if the system is big endian
-- Searching 16 bit integer
-- Using unsigned short
-- Check if the system is big endian - little endian
-- BIG_ENDIAN: 0
-- Check size of off64_t
-- Check size of off64_t - done
-- Looking for fseeko
-- Looking for fseeko - found
-- Looking for unistd.h
-- Looking for unistd.h - found
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zmpl/tmp/mysql-connector-cpp/build/cdk/protocol/mys
qlx/zlib
== done configuring external build of zlib
== configuring external build of lz4
-- sources at: /home/zmpl/tmp/mysql-connector-cpp/cdk/extra/lz4
-- generator: Unix Makefiles
-- option CMAKE_BUILD_TYPE: Debug
-- option CMAKE_SYSTEM_NAME: Linux
-- option CMAKE_SYSTEM_VERSION: 5.15.0-46-generic
-- option CMAKE_SYSTEM_PROCESSOR: x86_64
-- option CMAKE_C_COMPILER: /usr/bin/cc
-- option CMAKE_CXX_COMPILER: /usr/bin/c++
-- ----
Not searching for unused variables given on the command line.
-- Check if the system is big endian
-- Searching 16 bit integer
-- Using unsigned short
-- Check if the system is big endian - little endian
-- BIG_ENDIAN: 0
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zmpl/tmp/mysql-connector-cpp/build/cdk/protocol/mys
qlx/lz4
== done configuring external build of lz4
== configuring external build of zstd
-- sources at: /home/zmpl/tmp/mysql-connector-cpp/cdk/extra/zstd
-- generator: Unix Makefiles
-- option CMAKE_BUILD_TYPE: Debug
-- option CMAKE_SYSTEM_NAME: Linux
-- option CMAKE_SYSTEM_VERSION: 5.15.0-46-generic
-- option CMAKE_SYSTEM_PROCESSOR: x86_64
-- option CMAKE_C_COMPILER: /usr/bin/cc
-- option CMAKE_CXX_COMPILER: /usr/bin/c++
-- ----
Not searching for unused variables given on the command line.
-- Check if the system is big endian
-- Searching 16 bit integer
-- Using unsigned short
-- Check if the system is big endian - little endian
-- BIG_ENDIAN: 0
-- ZSTD_LEGACY_SUPPORT not defined!
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zmpl/tmp/mysql-connector-cpp/build/cdk/protocol/mys
qlx/zstd
== done configuring external build of zstd
-- Looking for sys/endian.h
-- Looking for sys/endian.h - not found
-- Looking for sys/byteorder.h
-- Looking for sys/byteorder.h - not found
Wrote configuration header: /home/zmpl/tmp/mysql-connector-cpp/build/cdk/include/mysql/cdk/con
fig.h
Preparing to merge SHARED library: connector (xapi;devapi)
Connector library name: mysqlcppconn8
Building version 8.0.30
Generating INFO_SRC
Generating INFO_BIN
Install location: /usr/local/mysql/connector-c++-8.0.30
Connector libraries will be installed at: lib64

Project configuration options:

: BUILD_STATIC: OFF
Build static version of connector library

: WITH_SSL: system
Either 'system' to use system-wide OpenSSL library, or custom OpenSSL location. (default : sys
tem)

: WITH_JDBC: OFF
Whether to build a variant of connector library which implements legacy JDBC API

-- Configuring done
-- Generating done

Answer: I assume you already figured it out. Schema is missing reference to mysqlx.
mysqlx::Session sess2("localhost", 33060,
                                   "root", "test",
                                   "postManufDB");
mysqlx::Schema mySchema = sess2.getSchema(name_of_database);


Puppet: remote clients are not updated by puppetmaster

Question: I'll start with the fact that I'm noob to Puppet, I have 2 servers; one is called puppetmaster and the other is called puppetclient.
I've installed puppet-3.2.2 and created some basic nodes.pp file, the nodes.pp file includes settings for both puppetmaster and puppetclient.
When i apply the relevant manifest the changes are only affecting the puppetmaster but not the client.
On the server I see the next error:
[root@puppetmaster puppet]# puppet apply manifests/nodes.pp
hostname: Unknown host
dnsdomainname: Unknown host
hostname: Unknown host
dnsdomainname: Unknown host
hostname: Unknown host
dnsdomainname: Unknown host
Notice: Finished catalog run in 0.71 seconds
[root@puppetmaster puppet]#

Even though a DNS server is configured on /etc/sysconfig/network-scripts/ifcfg-eth0 and in /etc/resolv.conf.
While checking the puppetmaster log i see the next error:
[2013-08-08 11:03:00] ERROR OpenSSL::SSL::SSLError: SSL_accept returned=1 errno=0 state=SSLv3 read client certificate A: tlsv1 alert unknown ca
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:34:in `accept'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:34:in `listen'
    /usr/lib/ruby/1.8/webrick/server.rb:173:in `call'
    /usr/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
    /usr/lib/ruby/1.8/webrick/server.rb:162:in `start'
    /usr/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
    /usr/lib/ruby/1.8/webrick/server.rb:95:in `start'
    /usr/lib/ruby/1.8/webrick/server.rb:92:in `each'
    /usr/lib/ruby/1.8/webrick/server.rb:92:in `start'
    /usr/lib/ruby/1.8/webrick/server.rb:23:in `start'
    /usr/lib/ruby/1.8/webrick/server.rb:82:in `start'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:32:in `listen'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:31:in `initialize'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:31:in `new'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:31:in `listen'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:28:in `synchronize'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/http/webrick.rb:28:in `listen'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/server.rb:92:in `listen'
    /usr/lib/ruby/site_ruby/1.8/puppet/network/server.rb:104:in `start'
    /usr/lib/ruby/site_ruby/1.8/puppet/daemon.rb:137:in `start'
    /usr/lib/ruby/site_ruby/1.8/puppet/application/master.rb:215:in `main'
    /usr/lib/ruby/site_ruby/1.8/puppet/application/master.rb:165:in `run_command'
    /usr/lib/ruby/site_ruby/1.8/puppet/application.rb:364:in `run'
    /usr/lib/ruby/site_ruby/1.8/puppet/application.rb:456:in `plugin_hook'
    /usr/lib/ruby/site_ruby/1.8/puppet/application.rb:364:in `run'
    /usr/lib/ruby/site_ruby/1.8/puppet/util.rb:504:in `exit_on_fail'
    /usr/lib/ruby/site_ruby/1.8/puppet/application.rb:364:in `run'
    /usr/lib/ruby/site_ruby/1.8/puppet/util/command_line.rb:132:in `run'
    /usr/lib/ruby/site_ruby/1.8/puppet/util/command_line.rb:86:in `execute'
    /usr/bin/puppet:4
[root@puppetmaster ~]#

The puppet log on the client is blank. I investigated a little bit on the internet and saw that there's some command called puppetca in older version but as it seems, it's not part of the 3.2.2 version.
Anyone knows how to get it to work?
Comment: Any reason not to use the puppetlabs repository? using a recent puppet will be really helpful. Also, why webrick? IIRC that was deprecated quite a while back.
Comment: That's the repo i'm using: `baseurl=http://yum.puppetlabs.com/el/$releasever/products/$basearch/` , is it not the regular one?
Answer: Firstly, you should be using the PuppetLabs Yum repositories - details here.

Secondly, you should either be using Passenger or Mongel behind Apache - WEbrick is a very basic web-server and will not scale well beyond one or two nodes. Using Passenger is the most scalable option and is relatively easy to set up, so it should save you bundles of time in the long-run. Take a look at the PuppetLabs Passenger docs for more details.
Your DNS should be set up so that the CNAME puppet.mydomain (replacing mydomain with your FQDN) should point to your master - this is how nodes will automatically discover your master. If they cannot find puppet.mydomain and no further configuration is provided on either the CLI or in /etc/puppet/puppet.conf, the nodes will not be able to contact the master.
When running Puppet on the master, you can use puppet apply --modulepath=/etc/puppet/modules /etc/puppet/manifests/site.pp to bootstrap your master's configuration (Puppet can - and ideally should - be used to configure the master itself), and subsequent runs can be run by invoking either puppet agent --test or the puppet apply command above.

Thirdly, you should be using Puppet modules instead of adding configuration to manifests/nodes.pp. Take this example:
manifests/nodes.pp:
node mynode {
  include mymodule
}

modules/mymodule/init.pp:
class mymodule {
  file { '/path/to/some/file':
    ensure => file,
    owner  => 'myuser',
    group  => 'mygroup',
    mode   => '0755',
    source => 'puppet:///modules/mymodule/myfile',
  }
}

In this example, your module will deploy the file, and your node definition within your manifest uses include to import the module into that node's manifest.

The puppetca command has been superceded by puppet cert. Once you have your master configured, you will need to use this command to sign your nodes' certificates. Example:
On node:puppet agent --test (generate the SSL certificate and ship it to the master)
On master: puppet cert list (to list the outstanding unsigned certificates)
On master: puppet cert sign mynode.myfqdn (to sign the node's certificate)
On node: puppet agent --test (to re-run Puppet, now that your node's certificate has been signed)


Permanently change color of selected text and revert in HTML with JavaScript

Question: I want to be able to select text click on a button and have the text color change e. The text color change should persist after the text is no longer selected.
I know that there are many solutions that do this already with CSS. However; I want to be able to have access to the nodes so that on another button click, I can revert the color change. I have tried looking into window.getSelection() and Ranges and DocumentFragment, but I am having trouble understanding how to select the nodes in a DocumentFragment, modify each node, insert it in the right position in the document and also create a reference so that I can, in a later click, change the color again back to black.
I also found this thread which essentially does what I"m trying to do, but it uses execCommand which is obsolete.
I don't want a CSS solution and I don't want a solution that uses jQuery.
Below is the js code and codepen with a similar html structure that I am working with.
I have 2 buttons, one that changes the selections color and one that will revert the color of the selection even after the text is no longer selected.
I am using window.getSelection() to get a Selection of the selected text. I check that the Selection is valid and then get a Range with getRangeAt(0) followed by a call to extractContents().
This is where the hard part comes in because:

It extracts the DocumentFragment from the document so how can I re-insert the DocumentFragment in the same position it was extracted from?
I am having trouble figuring out how to modify the nodes in the DocumentFragment styles

var changeColorButton = document.getElementById('xyz');
var revertColor = document.getElementById('zyx');

const changeSelectionColor = () => {
  let selection = window.getSelection()
  if (selection) {
    let range = selection.getRangeAt(0)
    if (range) {
      let frag = range.extractContents();
    }
    /*
      2 problems:
      1. accessing each node in the DocumentFragment and modifying the style then re-inserting into the correct spot
      2. Creating a reference to this fragment for revertColorChange() to use to change the color back to black
    */
  }
}

const revertColorChange = () => {
  // revert color
}

changeColorButton.addEventListener('click', changeSelectionColor);

Minimal Reproducible Example - https://codepen.io/NoobCodePenner/pen/GRoKNRd
Comment: You want the text color to change permanently or only while being selected?
Comment: You want to change something's colour but don't want to use CSS?
Comment: Please share what you already tried and provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: You can add 's. with classes for colors. If the whole selection is with on one node that's easy. It gets more complicated when several text nodes, parts of 's etc are spanned.
Comment: The task is quite complex, it's easy to get the nodes, but if you've a cross-element selection, you've to create new elements so that all the insertion and layout rules of the enclosed elements are fullfilled. As an example, you're selecting a couple of cells from a table, and additionally some text below the table, you can't just wrap that selection in a HTML element with the style of the wanted color, you'd need to add multiple elements within the table and after the table.
Comment: Thanks for the feedback. I have updated the original topic with more details and an example. In short, I want to permanent change the Selection's color with one button click. In another button click, I want to revert the change even when I don't have anything selected
Comment: Just an idea, you could try to keep the selection alive (use CSS to color the characters). Store the selection in a range, and when ever the selection is going to be removed, rebuild it from the stored range. Then when you need to restore the color, just let the selection go. A lot depends on the page itself, if it's a simple page without a lot of (or any ...) interactivities, this might work ..?
Comment: @Teemu could you please provide a small example? I think that sounds viable, but the colors of selections will vary depending on what is clicked after a selection. once a selection is colored, we should not be able to overwrite that color unless we revert first.
Comment: The point is, that you'd try to keep the selection alive, then the colors won't change. That means you can't select anything else before the selection is removed. You've just to capture all the events which would remove the current selection (pointer and keyboard events at least) and rebuild the selection, if it's going to be removed. If you need other selections on the page, then this won't solve your problem, but eg. button clicks would be possible. If you're going to wrap the selected nodes to extra elements, you'd almost need to implement your own HTML parser in JS.
Comment: ok i understand now and i think you're right. i definitely don't want to keep the selection 'alive'. i tried going down the route of get the Selections parent, extractContents() modifying the DocumentFragment from extractContents() then append it to the Selections parent, but running into some troubles here since some of these methods are read-only....
Answer: <!DOCTYPE html>

<button onClick="changeColor()">Change color</button>

<button onClick="changeColorBack()">Change to previous color</button>

Javascript

Is this what you are looking for?
Comment: no. i am working on a minimal reproducible example. the flow is: 1. user selects some part of the dom. 2. user clicks on a button 3. the selected text should not be a different color even when the selection is deselected
Comment: ok got it now. The clarity of the question can be improved to understand more precisely.
Comment: I added an example


display default values in node form

Question: Can  you help me please with node form in the Drupal 7?
I have a three forms (node/add/A, node/add/B, node/add/C).
Values in the node/add/A are created after registration.
How to display a values with node/add/A to the node/add/B like default values a field?
Sorry for my English.
Thank you everyone for your help
Comment: well you explained your problem not so good, but as far as I get what you mean maybe you can try entity reference?
Comment: I am sorry ... I have a form node/add/A and in the node form a field with machine name field_blog_author. I need use value with field_blog_autor in other form (example node/add/B) like default value for field field_blog_name. I hope you understand me.
Comment: you still not explaining the problem properly, anyway seems like I can't help but search google for "Drupal Entity refrence" it might help you a bit :)
Comment: I am sorry ... I have a form node/add/A and in the node form a field with machine name field_blog_author. I need use value with field_blog_autor in other form (example node/add/B) like default value for field field_blog_name. I hope you understand me.
 OK I try it "Drupal Entity reference". I am sorry and thank you very much :)
Answer: well based on your comment:
Use the Computed Field module

Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of CCK fields. So start cooking up your PHP based values!

display default values in node form


Mongooseim : mod_vcard crashing

Question: I configured mod_vcard as follows:
<code>{mod_vcard, [
        {allow_return_all, true},
        {search_all_hosts, true},
        {matches, 1},
        {search, true},
        {host, localhost},
        {backend, odbc}
      ]},
</code>
But when I restart mongoosIm i get the following error:
<code>2015-03-16 12:31:08.620 [error] <0.708.0> CRASH REPORT Process <0.708.0> with 0 neighbours exited with reason: bad argument in call to re:replace(localhost, "@HOST@", <<"localhost">>, [global,{return,binary}]) line 355 in mod_vcard:init/1 line 141 in gen_server:init_it/6 line 330
</code>
What am I doing wrong ?
Comment: Did you try with latest version of ejabberd ? Latest version have Yaml config file and configuration checker. It should make it easier to find configuration issues.
Answer: The host parameter should be a string and not atom. Try this line:
<code>{host, "localhost"},
</code>
Or any other host, depending on what you have in the hosts paramet

Mongooseim : mod_vcard crashing