Why is it that during my replication (master-slave), it keeps inserting data, then deleting data, then inserting data?

Question: I followed this tutorial for master-slave replication: http://www.howtoforge.com/mysql_master_master_replication
Basically, this is what I did.

Uninstalled mysql on both servers.  Installed mysql on both servers.
Loaded the data onto both servers.
Followed the replication procedure.
The replication deleted my tables, then created them again.
Then, the replication started inserting rows into the table.  Then deleting them after they reach 3 million rows...then inserting rows again.

Why can't it just insert all the rows, and make it exactly the same as my master? WHy is it deleting stuff and inserting over and over?
show slave status\G;
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host:
                Master_User:
                Master_Port:
              Connect_Retry: 60
            Master_Log_File: mysql-bin.000025
        Read_Master_Log_Pos: 694442541
             Relay_Log_File: mysqld-relay-bin.000039
              Relay_Log_Pos: 201628150
      Relay_Master_Log_File: mysql-bin.000018
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB:
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 201628013
            Relay_Log_Space: 8213564485
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 6343
1 row in set (0.00 sec)

ERROR:
No query specified

 show master status\G;
*************************** 1. row ***************************
            File: mysql-bin.000033
        Position: 540194
    Binlog_Do_DB: fal
Binlog_Ignore_DB:
1 row in set (0.01 sec)

Comment: I don't see any evidence of this purported insertion/deletion cycle.  Also, the contents of the global `my.cnf` and the output of `SHOW SLAVE STATUS` on the other server might be handy, too.
Answer: In MySQL replication, the master writes out "binlog" files, detailing only queries which change replicated databases (UPDATE, DELETE, INSERT, CREATE TABLE..., not SELECT etc...).
Starting from identical copies of a database, the master writes binlog files, and the slave reads them, and executes all the changes: Thus replication occurs.
Your status messages indicate the slave's replica of the master is not completely up to date (6343s = 105 minutes out), and there is a queue of SQL statements to run, sitting in the binlog files:
master:
File: mysql-bin.000033
Position: 540194

slave:
Master_Log_File: mysql-bin.000025
Read_Master_Log_Pos: 694442541
...
Exec_Master_Log_Pos: 201628013
....
Seconds_Behind_Master: 6343

I suspect that some DELETE/INSERT type operation has occured on the master, and the slave is just replicating the changes, albeit with nearly a couple of hours of delay.
To identify which queries it is running/about to run, you can use mysqlbinlog to view the contents of the (binary) binlog files.
Lockie


Vertical text in table cell

Question: How do I properly set some of the table cell to display text vertically.
with some help in forums I came up this following idea:
http://jsfiddle.net/hr4tkg9q/
I am using the following jquery:
$(document).ready(function () {
    $('td.rotate').css('height', $('td.rotate').width());
});

the problem is, it properly sets the vertical text in 1st column but not the second or third one. will appreciate if you can help.
Comment: Maybe you should give the vertical cells the height of the other cells width and the width of the other cells height?
Comment: I cannot specify the height. height depends on the size of the text
Answer: try to rotate a div in your cell not the cell.

   G

 ....

UPDATE:
$(document).ready(function () {
  $('tr').each( function() {
    $(this).find('td.rotate').css('height', $(this).find('div.rotate').width());
  });
});

i think this will help you
try this
http://jsfiddle.net/hr4tkg9q/2/
Comment: I tried but the height is too small. the height of the cell should be as the size of the cell text: http://jsfiddle.net/hr4tkg9q/2/

Vertical text in table cell


Best way to architect an ajax-ready application

Question: I am using the MVC model with PHP. What's the best way to code an ajax-ready application?
To help you answer me I have a list of questions:

Should it be able to render content without javascript?
Should the main page consist only of a header and a footer and the content to be brought via ajax?
Should ajax bring directly html or json code? If json, it should be processed and rendered.
Any other idea?

UPDATE: Forget about search engines in this discussion
Answer:
Yes
You should include the content in the pages
Your choice

In order to allow search engines to index your site, all content must be available without Javascript.
Answer:
Yes, it should be able to render HTML directly, at least for the first time a person lands on the page.
No, like I said, the main/first page should be loaded as HTML automatically, there's no need to load a page partially and then do an ajax request, it will just make it slower and the whole point of ajax is to make things faster.
This one really depends on what you need. If you're only loading content to be put into the layout then I would just load the HTML directly, but if you want to load variables that can be converted easily to objects for further manipulation than go with JSON.

Hope this helps :)
Answer: The only thing you need is templates.
Any site that utilizes templates, already is ajax-ready.
To change a template call to json_encode is a matter of 1 line.

Should the main page consist only of a header and a footer and the content to be brought via ajax?

Neither.
AJAX has a lot of disadvantages and should be used only for sensible reason. So, Most of your site will remain ajax-free.
Answer: Personally, I would always strive for making the application work without javascript if it is possible to provide at least basic usability / information without Javascript. If that is the case, the way to go is Progressive_enhancement.
You seem to approach the issue the wrong way. Doing lots of requests of any kind usually is a bad thing, especially with AJAX requests. Browsers put very stingy limits on parallel resources and each request add latency. So generally, you want the least amount of AJAX or other resource requests possible.
Construct the base of your application in just HTML/CSS or javascript-only and then ask yourself where additional AJAX requests or other Javascript behavior are going to enhance your application the most.
Answer: My two cents...
Start by getting the site to function correctly without JS and AJAX calls.
It will be better on the long term.
After that, gradually start AJAXifing things that will provide a better UX to your intended audience.
To get JSON only or HTML in your requests really depends on the content you are getting.
AJAX has its advantages and disadvantages, and every case need a different judgment on whether AJAX will provide a better UX on not.


"A is not B" vs "A is (not B)"

Question: I'm a little bit scared about the "is not" operator and the possibility that "is not X" is interpreted when "is (not X)" was intended. Do exist some expressions A and B such that:
A is not B

is different from
A is (not B)

?
addendum.
Is it considered good practice to use this operator? Should't not (A is B) be preferred?
Comment: possible duplicate of [Python "is" statement: what is happening?](http://stackoverflow.com/questions/3718513/python-is-statement-what-is-happening)
Comment: In some cases, `not B` will be an error, if `B` can't be used as an implicit Boolean.
Answer: They're definitely different.  The latter case evaluates not X in a boolean context first and then checks to see if the two objects are the same object (either True or False).
Consider:
False is not []

This expression is trivially True since False and [] are quite clearly different objects. 1
vs.
False is (not [])

This expression is False since not [] evalutes to True and False and True are different objects.
Of course, this is just one example.  It gets even easier to find examples if you don't use False and True explicitly as the second expression will always be False and the first expression will (almost) always be True...
3 is not 0   # True
3 is (not 0)   # False

1Note that is not is a single operator in the same vein as not in.
Comment: Same result for me in Python 2.7 and Python 3.3. Use `False is not []` to see a difference.
Comment: @Matthias -- Thanks.  Early morning brain fog I guess.  I'm always surprised by the number of upvotes you can pull in even with a wrong answer :-)
Answer: Yes:
A = 0
B = 1

Try it and you'll be really scared:
>>> A = 0
>>> B = 1
>>> A is not B
True
>>> A is (not B)
False

"A is not B" vs "A is (not B)"


What is the best way to show category by image?

Question: I have a online store with commerce module .
I have a category/taxonomylike this :
Writing Product

pen
pencil

Art Product

paper
something

All i want is to show writing product sub category in a page with image.
i've added image field to taxonomy and create a views from taxonomy .
How can i get sub category (image field) from views ?
Thx
Answer: In you view change the Format section to show fields and after that add the image field from your taxonomy, then add the filter Taxonomy term: Parent term
Comment: follow my previous comment and give the parent id equal to `id of Writing Product`
Comment: Thx , i don't want to show parent .
Comment: If you add the filter `Taxonomy term: Parent term` then it will show only the child terms.
Comment: thx a lot maaaan and how can i show it from specify parent not two of them ?
How can i filter it ?
Comment: no , when i add equal , it only shows both parent
Comment: what filter you have added
Comment: Taxonomy vocabulary: Machine name (= product)
Taxonomy term: Parent term (= Writing Product)
Comment: did you give the **term id** of Writing Product
Comment: how can i get that ?
go to taxonomy page and put my cursor on edit and see the term id is : term/7
Comment: then the id is 7, use that
Comment: You're perfect and teach me something new .
Thx a million ;)


Erro: python boolean

Question: def INSERTION_SORT(A):
    for j in range(len(A)-1):
        key = A[j]
        i = j+1
        print("***********")
        print(j >= 0)
        print(key > A[i])
        print(j >= 0 & key > A[i])

A = [5,2,4,6,1,3]

INSERTION_SORT(A)

operation result:
***********
True
True
False
***********
True
False
False
***********
True
False
False
***********
True
True
False
***********
True
False
False
[Finished in 52ms]

why are all true, the result is false
Comment: In particular, note that `j >= 0 & key > A[i]` is _not_ `(j >= 0) & (key > A[i])` but `j >= (0 & key) > A[i]`, i.e. `j >= 0 > A[i]`. First comparison is true, second comparison is false for all values, hence the entire chained comparison is false.
Comment: That `&` looks suspicious.
Comment: Only for `j >= 0` are "all true", and that's because for `for j in range(len(A)-1)`, all `j >= 0`. What exactly is your question?
Comment: `&` is a bitwise operator, maybe you meant `and`?
Comment: What is meant by "why are all true, the result is false"? There isn't a result anywhere in this code. It's not clear to me what it's supposed to do, seeing how ``INSERTION_SORT`` doesn't insert anything.
Comment: Did you intend to ``print((j >= 0) & (key > A[i]))``?
Comment: Use the keyword `and`, not `&` because `&` is a bit operator.
In Python `and` and `or` are used for boolean comparisons.

It should be like this

`print(j >= 0 and key > A[i])`
Comment: Please don't invalidate existing answers via edits. The new question state makes the answers fail to even address the question.
Answer: You should use and keyword instead of &

and: this is the logical and
&: this is the bitwise operator
Comment: Note that ``True & True`` is ``True``. The problem isn't that one works "logically" and the other "bitwise".
Comment: The real problem is the different operator precedence. `and` is evaluated after comparisons, whereas `&` is evaluated before.
Comment: No, that's lazy evaluation. See my comment on the question. With `&`, there are not "two conditions", but just a single chained comparison.
Comment: So if first condition is false, the other one will not be checked if Im using `&`?
Comment: Ah ok. Understood thanks
Answer: You are using the bitwise operator &, in the line print(j >= 0 & key > A[i]). Instead you can use and logical and operator.
By the way, your code is not yet doing any sorting operation.

Erro: python boolean


How to distribute file storage to a different filesystem with Ubuntu 14.04?

Question: First of: I just got started using CLIs to manage a whole server, sorry if this question is stupid, but I couldn't find any solution to this.
I ran into a problem with apt-get -f install, because my disk is full. df -h returns:
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/vg00-lv01   37G  8.1G   28G  23% /
none                   4.0K     0  4.0K   0% /sys/fs/cgroup
udev                   483M   12K  483M   1% /dev
tmpfs                   99M  592K   99M   1% /run
none                   5.0M     0  5.0M   0% /run/lock
none                   494M     0  494M   0% /run/shm
none                   100M     0  100M   0% /run/user
/dev/sda1              464M  459M     0 100% /boot

As you can see, my filesystem /boot is full. How could I go on about "giving" boot some space from /dev/mapper/vg00-lv01? I am pretty stuck. Appreciate any help on this
Comment: What is on your /boot? If it is a lot of older kernels, move a few of them (other than the latest and the currently booted one) away, finish the installation, then properly uninstall old kernels you do not need any longer. In general, a few 100 MB ought to be enough for /boot.
Comment: You can try running: `apt-get autoremove`.
Comment: Can't run it, because then it says "run apt-get -f install" :(((
Comment: In general, you could move some data to another mountpoint and symlink it back. Since it is /boot (and has to be loaded by the bootloader) it might render your system unbootable, though (General, I don't think there is any way (unless you have space directly after /boot on your drive) to online resize /boot.
Comment: or in case you really want to grow /boot, add `lsblk` output to your post, so we see the partition layout.
Comment: `/boot` generally does not use LVM, so you would need to expand the partition manually (using parted, gparted, etc) but that requires sequential blocks free after the /boot partition, which generally doesn't happen. (People don't usually intentionally leave space between partitions when systems are built). This will take some major work to do, but decide up front if it would be faster to reload the whole system, giving /boot much more space the 2nd time around.
Comment: @mihi thank you for the insight! I begin to understand a little more.
Comment: @TimS. thank you, too. I guess it makes sense in the end, I just realised, what /boot is for. I thought it's full because I installed packages over gem......... My bad. Quite confusing at first, though
Answer: You can try running:
sudo apt-get autoremove

This command removes packages that were installed by other packages
  and are no longer needed.

I assume you have unused kernel images making boot partition full. And if you can't run the above command then you will need to clean /boot partition manually. First you can use the following command to find out the installed kernel:
sudo dpkg --list 'linux-image*' | grep ^ii

The other kernel versions (other than that listed above) can be removed manually like this:
sudo  rm /boot/*-unused-kernel-version*

Always be very carefull when using rm -rfas root and delete only the unused kernels.
When you have some space free in /boot then run again:
sudo apt-get -f install

You may find this post very usefull:
https://askubuntu.com/questions/345588/what-is-the-safest-way-to-clean-up-boot-partition
Comment: Hello, thank you really much for the answer. I checked your answer and the answer on askubuntu, but I think I am doing something wrong. So I tried to delete the oldest version like this: sudo rm -rf /boot/*-3.13.0-24.47, but it is still there. Also tried without the dash, or do I have to delete "abi-3.13.0-24-generic" each on it's own?
Comment: @FrederikWitte, you are welcome. yes, you can write the full filename. Do like this, first `cd /boot`, and then `ls -al` this will list all files. then you can use, `rm filename`.
Comment: @FrederikWitte, the `*` is used to match multiple similar file names in one command.


Como colocar a opção de marcar todos os Checkbox no JQGrid

Question: Preciso colocar a opção de Marcar e Desmarcar todos os checkbox listado pelo JQGRID
não imagino como fazer. Abaixo o JS da tabela.
var grid = $("#jqGrid").jqGrid({
        url: '/Expedicao/Minuta/CarregaTransportadorNotas',
        datatype: 'json',
        mtype: 'GET',
        postData: {
                  transportador: function () { return jQuery("#transportador").val(); }
        },
        colModel: [
             {name: "Escolher",width: 70, align: "center",
              formatter: "checkbox", formatoptions: { disabled: false},
              edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"},
            stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" } },
            { label: 'Codigo', name: 'doc', width: 250 },
            { label: 'Série', name: 'serie', width: 180},

        ],

        viewrecords: true,
            rowNum: 20,
            rowList: [20, 40, 100],
            height: "auto",
            //height: 400,
            emptyrecords: "Nenhuma Minuta ...",
            loadtext: "Buscando e carregando...",
            //rowNum: 20,
            pager: "#jqGridPager",
            loadonce: true

    });

    $("#jqGrid").jqGrid('navGrid', 'jqGridPager', { edit: false, add: false, del: false })

Answer: Crie um <input type="checkbox" id="selAll"> Selecionar tudo fora da tabela (pode colocar acima da tabela. Você pode formatar da forma que quiser):
<input type="checkbox" id="selAll"> Selecionar tudo

Ficará algo assim:

E insira dois eventos no script para pegar os clicks nos checkboxs que irá fazer o controle, capturando os checkboxes da tabela pela classe table.ui-jqgrid-htable, que é a classe gerada pelo plugin:
$(":checkbox", "table.ui-jqgrid-htable").click(function(){

   if(!$(this).is(":checked")) $("#selAll").prop("checked", false);

   var cbs = $(":checkbox", "table.ui-jqgrid-htable");
   var allchkd = true;

   for(var x=0; x<cbs.length; x++){
      if(!$(cbs[x]).is(":checked")){
         allchkd = false;
         break;
      }
   }

   if(allchkd) $("#selAll").prop("checked", true );

});

$("#selAll").click(function(){
   var boxes = $(":checkbox", "table.ui-jqgrid-htable"); // pega os checkboxes da tabela
   boxes.prop("checked", $(this).is(":checked"));
});

Comment: Obrigada. Sua resposta funcionou também. Optei em usar o multiselect:true . que fica no próprio Grid. Valeu
Answer: Consegui de uma forma bem simples usando multiselect: true,
var grid = $("#jqGrid").jqGrid({
        url: '/Expedicao/Minuta/CarregaTransportadorNotas',
        datatype: 'json',
        mtype: 'GET',
        postData: {
                    transportador: function () { return jQuery("#transportador").val(); }
        },
        colModel: [
                    { label: 'Codigo', name:'doc', width:50 },
                    { label: 'Série', name:'serie', width:50 },
                 ],

                loadonce: true,
                viewrecords: true,
                width: 780,
                height: 200,
                rowNum: 20,
                rowList : [20,30,50],
                rownumbers: true,
                rownumWidth: 25,
                multiselect: true,
                pager: "#jqGridPager"

    });

$("#jqGrid").jqGrid('navGrid', 'jqGridPager', { edit: false, add: false, del: false })


Get contents of a particular row

Question: I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.
.
.
.

        xyz

    address
    phone number

.
.
.

I can get 'xyz' easily by using
required = soup.find('a', text = 'xyz')
print(required[0].text)

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.
Expected output:
xyz
address
phone number

Comment: set id for html tag
Comment: @Internship TY use selenium with find_elements_by_css_selector:   https://selenium-python.readthedocs.io/locating-elements.html
Answer: With bs4 4.7.1 combine pseudo classes of :has and :contains to retrieve the row and tds within.
This bit targets the right a tag if present by its text
a:contains("xyz")

You then retrieve the parent row (tr) having this a tag
tr:has(a:contains("xyz"))

And finally use a descendant combinator and td type selector to get all the tds within that row. Using a list comprehension to return the list.
from bs4 import BeautifulSoup as bs

html = '''

        xyz

    address
    phone number

'''

soup = bs(html, 'lxml')
items = [item.text.strip() for item in soup.select('tr:has(a:contains("xyz")) td')]
print(items)

Answer: You can use xpath. find_elements_by_xpath().
https://www.softwaretestingmaterial.com/how-to-locate-element-by-xpath-locator/

Answer: Replace your code with this:
from bs4 import BeautifulSoup

html = '''

        xyz

    address
    phone number

'''

soup = BeautifulSoup(html, 'lxml')
required = soup.find('a', text = 'xyz')
print(required.text)
td = required.parent
siblingsArray = td.find_next_siblings()

for siblings in siblingsArray:
    print(siblings.text)

O/P:
xyz
address
phone number

Where parent is Get immediate parent tag and find_next_siblings return list of next siblings tag.
Answer: If you have modern BeautifulSoup, you can use CSS selector :contains. Then traverse back with find_parent() method.
from bs4 import BeautifulSoup

s = '''

    Other1
    Other1
    Other1

        xyz

    address
    phone number

'''

soup = BeautifulSoup(s, 'lxml')

for td in soup.select_one('a:contains(xyz)').find_parent('tr').select('td'):
    print(td.text.strip())

Prints:
xyz
address
phone number

Get contents of a particular row


Opening an image file into WritableBitmap

Question: Here is the problem.
I want to open a file from local drives, then make it into a WritableBitmap so i can edit it.
But the problem is, i cannot create a WritableBitmap from Uri or something like that. Also i know how to open a file into BitmapImage but i cannot figure out how to open a file as WritableBitmap.
Is there way to open a file directly into a WritableBitmap,if there is not, is there a way to convert a BitmapImage to a WritableBitmap?
Thanks guys.
Comment: it seems that we can pass a bitmap directly into writablebitmaps constructor. My VS gave me errors while i first tried it but it seems working now. It wasn't a good question at all, sorry guys.
Comment: It will work, but it will be resized if above some mega pixels.
Answer: You can load your image file into a BitmapImage and use that as a source for your WriteableBitmap:
BitmapImage bitmap = new BitmapImage(new Uri("YourImage.jpg", UriKind.Relative));
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap);

Comment: Actually, in Siverlight, it gives me exception.  So it's not a solution
Comment: `BitmapImage bi = new BitmapImage(new Uri("header.png", UriKind.Relative)); WriteableBitmap wb = new WriteableBitmap(bi);` The 2nd line `System.NullReferenceException was unhandled by user code: Object reference not set to an instance of an object.`
Comment: @Peter, which exception do you receive?
Comment: @Peter, did you check that `bi` is not `null` after the call to the `BitmapImage` constructor? If it is, it would be quite logical for the `WriteableBitmap` constructor to fail.
Comment: Yes, I did check. See my answer.  Would you mind test my code on your machine?
Comment: Loading a WriteableBitmap from a BitmapImage is actually a workaround as the final image is scaled to physical device limitations. Thus, a 5MP can be rescaled to a 1MP image. Not useful, considering WriteableBitmap is used for image processing.
Comment: @Peter Lee. What do you get when using CreateOptions set to None?
Comment: @LéonPelletier  i set creation option to None, Error exist (Silverlight 5). In created bitmap image source PixelHeight and PixelWidth is zero.
Answer: I'm no expert and don't have immediate access to intellisense and whatnot, but here goes...
var fileBytes = File.ReadAllBytes(fileName);
var stream = new MemoryStream(fileBytes);
var bitmap = new BitmapImage(stream);
var writeableBitmap = new WritableBitmap(bitmap);

Even if not a perfect example this should be enough to point you in the right direction. Hope so.
Comment: you cannot pass a bitmap directly into a writablebitmap
Comment: `File.ReadAllBytes(fileName);` not allowed in Silverlight, unless in OpenFileDialog
Answer: In Silverlight 5 you can use below method to open file from local disk and convert it to BitmapImage and make it in to WriteableBitmap;
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Multiselect = false;

        dlg.ShowDialog();
        byte[] byteArray = new byte[] { };
        if (dlg.File == null) return;
        BitmapImage bi = new BitmapImage();
        bi.CreateOptions = BitmapCreateOptions.None;
       // bi.UriSource = new Uri(@"C:\Users\saw\Desktop\image.jpg", UriKind.RelativeOrAbsolute);
        bi.SetSource(dlg.File.OpenRead());
        WriteableBitmap eb=new WriteableBitmap(bi);

setting new Uri gave me error (Object reference not set to an instance of an object) while trying to create WriteableBitmap


Why does $a(p^k)\mapsto\frac1ka(p^k)$ send $\sum_n a(n)$ to $\ln\left(\sum_n a(n)\right)$

Question: In a recent Numberphile video on the Chebychev bias, Grant Sanderson (of 3blue1brown fame) uses what I guess would be the following theorem:

Given a multiplicative function $a$ where $\sum_n a(n)$ converges to a positive real number, consider the function $b$ defined as follows:
$$
b(n) = \cases{\frac1k a(n) & if $n = p^k$ is a prime power \\ 0 & otherwise}
$$
We have
$$
\sum_{n = 1}^\infty b(n) = \ln\left(\sum_{n = 1}^\infty a(n)\right)
$$

I have looked through my number theory books at home, and I haven't been able to find this result there. In the video they don't go into detail about it, they really just use it for some heuristics on the bias.
Is this the actual statement of the theorem? Or are there assumptions that I've missed (like convergence issues, or a need for complete multiplicativity)? And how do you prove it?
Comment: You need summability and complete multiplicativity of $a(n)$. With $a(n)= \chi(n)/n$ a non-trivial Dirichlet character it still works but once you proved generalized Mertens' theorem (and for $\sigma > 1/2$ it works  as well with $\chi(n)/n^\sigma$ once you assume the GRH).
Answer: It is just taking the logarithm of an Euler product.  Certainly there are convergence requirements, but that's irrelevant to understanding the structure of the formula itself.  I'll explain the formula without dwelling on convergence issues. Everything to be done is valid on an open half-plane where the products converge absolutely, such as ${\rm Re}(s) > 1$ for Dirichlet $L$-functions.
The key background fact is that
$$
\log\left(\frac{1}{1 - z}\right) = -\log(1-z) = \sum_{k \geq 1} \frac{z^k}{k}
$$
when $|z| < 1$.
Now suppose
$$
L(s) = \prod_p \frac{1}{1 - b_p/p^s}.
$$
Then (ignoring convergence issues)
$$
\log(L(s)) = \sum_p \log\left(\frac{1}{1 - b_p/p^s}\right) = \sum_p \sum_{k \geq 1} \frac{(b_p/p^s)^k}{k} = \sum_{p^k} \frac{b_p^k}{kp^{ks}}.
$$
In the video, for prime $p$ we have $b_p = 1$ if $p \equiv 1 \bmod 4$, $b_p = -1$ if $p \equiv 3 \bmod 4$, and $b_2 = 0$.
This can be extended to Euler products with more than one linear factor in $1/p^s$ in the denominator. If
$$
L(s) = \prod_p \frac{1}{(1 - b_{p,1}/p^s)\cdots (1-b_{p,d}/p^s)}
$$
is an Euler product "of degree $d$" then (again ignoring convergence issues)
$$
\log(L(s)) = \sum_p \sum_{i=1}^d\log\left(\frac{1}{1 - b_{p,i}/p^s}\right) = \sum_p \sum_{i=1}^d\sum_{k \geq 1} \frac{(b_{p,i}/p^s)^k}{k} = \sum_{p^k} \frac{b_{p,1}^k + \cdots + b_{p,d}^k}{kp^{ks}}.
$$


Formatar nomes de cidades e ignorar palavras como "do", "dos", "das", "da", etc

Question: Estou trabalhando com Webservice cujo nome das cidades estão todos desformatados e eu gostaria de criar uma função para tratar os nomes uniformemente. Um exemplo é este:
PORTO DE GALINHAS
Gostaria que ficasse assim:
Porto de Galinhas
Eu teria que dar um explode na string tratar todas as variáveis de uma só vez colocando tudo em minúsculo e logo após dar um ucfirst em cada palavra fazendo exceções de ucfirst em palavras pré-definidas como da, das, do, dos ...
Conheço o processo mas não sei colocar em execução.
Ensaiei alguma coisa:
$string = "PORTO DE GALINHAS";
$array = explode(' ', $string);

foreach ($array as $ar) {
    $dados = strtolower($ar);
    $dados .= " ";

    // Imprime porto de galinhas
    $cidade = trim($dados);
}

Answer: Um esboço que pode ser facilmente adaptado:
function properCase( $string ) {
   $ignorar = array( 'do', 'dos', 'da', 'das', 'de' );
   $array = explode(' ', strtolower( $string ) );
   $out = '';
   foreach ($array as $ar) {
      $out .= ( in_array ( $ar, $ignorar ) ? $ar : ucfirst( $ar ) ).' ';
   }
   return trim( $out );
}

echo properCase( 'PORTO DE GALINHAS' ).PHP_EOL;

Veja funcionando no IDEONE.

Importante: se for usar com UTF-8, lembre-se de usar mb_convert_case no lugar das funções ucwords e strtolower, para que as letras com acentuação não fiquem com case errado.
Comment: @MarcosVinicius isso é bom na hora de cadastrar as coisas no DB, só tem que tomar cuidado em algumas situações. Por exemplo, Rua XV de Novembro vai dar problema. Mas pra maioria dos casos, funciona. Se a pessoa pensar um pouco adapta fácil fácil a lógica para cuidar dos romanos (e por tudo em upper).
Comment: Tá ai uma pergunta com respostas que podem ajudar muita gente :)
Comment: Tá blz, então não o que eu quis dizer é pra tirar o `strtolower` de dentro do `foreach`, assim: http://ideone.com/6zHiGe
Comment: @GuilhermeNascimento no fim, ja que era pra otimizar apelei :D
Comment: Vale um +100 :D
Comment: `properCase` é nome que só os filósofos dão as suas funções ;)
Comment: @WallaceMaxters espero que isso não seja ruim :P
Comment: Não, não é ruim. Eu gosto de lançar os nomes em inglês também, rsrsrsrs
Comment: Mas se o usuario colocar mais de um espaço?
Comment: @Luhhh Fica com mais de um espaço na saida ué (mas funciona da mesma maneira :) . A pergunta não pede para mudar os espaços. O código preserva conforme foi digitado.
Comment: @Luhhh se quiser remover espaços duplos, tem várias maneiras. pode usar replace, explode com array_filter, preg_replace, depende do que for conveniente para o seu código específico.
Answer: Eu faria assim:
str_replace(array("De ", "Do ", "Dos ", "Da ", "Das "),
     array("de ", "do ", "dos ", "da ", "das "), ucwords(strtolower("PORTO DE GALINHAS")));

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Documentação do ucwords().
Documentação do str_replace().
Dá para melhorar a forma de tratar essas coisas. Essa é uma forma simplista de fazer o intento, mas é o que pede a pergunta.
Vendo os comentários espalhados vou fazer a versão da função que pode personalizar as exceções:
function capitalize($string, $search = array("De ", "Do ", "Dos ", "Da ", "Das "), $replace = array("de ", "do ", "dos ", "da ", "das ")) {
    return str_replace($search, $replace, ucwords(strtolower($string)));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Seria, mas nem todo mundo precisa de UTF-8. Aí seria *overkill*.
Comment: E porque teria uma `DO` no `$search`, basta não colocar. A função é flexível, se usar ela de um jeito, ela vai dar um resultado, se usar de outro, vai dar outro resultado. Se não quer esse outro, não use deste jeito. A única forma de evitar isto é tirar a flexibilidade. Acho que só piora a função, mas fique à vontade para tirar, é só tirar as variáveis e usar o literal fixo.
Comment: Ah legal, bom exemplo +1
Comment: Essa função talvez tenha um problema ... e se dentre os itens do `array $search` tiver uma string ***DO***? Na função demonstrada, não vai tratar ... Por isso que eu acho que se faz o contrário ... verifica se existe a "palavra" em qualquer uma de suas formas "maiúsculo, minúsculo, misturado" e dá um `strtolower` nela. Pelo menos eu acho.
Comment: mb_convert_case não seria melhor por conta do utf-8?
Answer: Como alternativa, eu faria assim:
<?php
function formatarString($str, $glue = ' ')
{
    //torna minúscula e divide string por espaços, tabs e outros do meta-caractere \s (remove espaços desnecessários)
    $palavras = preg_split('#\s+#', strtolower($str));

    //Lista de palavras ignoradas
    $ignoreList = array('de', 'as', 'do', 'dos', 'da', 'das');

    foreach ($palavras as &$palavra) {
        if (in_array($palavra, $ignoreList) === false) {
            $palavra = ucfirst($palavra);
        }
    }

    return implode($glue, $palavras);
}

Para HTML pode usar assim:
echo formatarString('PORTO DE GALINHAS', ' '); //Saída: Porto de Galinhas

Mas isto é opcional, o segundo parâmetro é o que terá entre as palavras, por padrão usa espaços
echo formatarString('PORTO DE GALINHAS'); //Saída: Porto de Galinhas

Nota: para usar acentos use o mb_convert_case($dados, MB_CASE_TITLE), isto precisará estar ativo no seu php.ini e/ou instalado via repositório (por exemplo apt no Debian), então ficaria assim:
$palavras = preg_split('#\s+#', $str);

//Lista de palavras ignoradas
$ignoreList = array('de', 'as', 'do', 'dos', 'da', 'das');

foreach ($palavras as &$palavra) {
    if (in_array($palavra, $ignoreList) === false) {
        $palavra = mb_convert_case($palavra, MB_CASE_TITLE);
    }
}

Note também que não defini o charset das strings, ele usa por padrão o valor retornado de mb_internal_encoding(), então se pretende usar outro codec ajuste antes de usar a função, assim:
mb_internal_encoding('UTF-8'); //Se for usar utf-8

echo formatarString('DECORAÇÃO DE AMBIENTES');

Exemplos de uso (teste online no repl.it: https://repl.it/@inphinit/de-do-da-com-ucwords):
$string = "PORTO DE GALINHAS";

echo "Original: $string\n";

$string = formatarString($string, ' ');

echo "Ajustado: $string\n";

echo "----------------\n";

$string = "DEMAIS AFAZERES";

echo "Original: $string\n";

$string = formatarString($string, ' ');

echo "Ajustado: $string\n";

echo "----------------\n";

$string = "OS DEMAIS AFAZERES";

echo "Original: $string\n";

$string = formatarString($string, ' ');

echo "Ajustado: $string\n";

Saída:
Original: PORTO DE GALINHAS
Ajustado: Porto de Galinhas
----------------
Original: DEMAIS AFAZERES
Ajustado: Demais Afazeres
----------------
Original: OS DEMAIS AFAZERES
Ajustado: Os Demais Afazeres

Comment: Está sem saída @Guilherme Nascimento ...
Comment: Como eu disse que precisava de uma função, provavelmente a resposta certa vai ser do Guilherme mas a do Bacco também está ótima.
Comment: Sim, eu sei ... essa adaptação eu consigo fazer. Obrigado vocês.
Comment: @MarcosVinicius acabei de editar o código, pra melhor performance acaso for usar com vários processos :)
Answer: Gosto de usar expressões regulares para isso pela simplicidade que a mesma proporciona. A função preg_replace() fornece o que precisamos usando expressão regular.
function nomeProprio($input) {
    return preg_replace('/\sd(\ws?)\s/i', ' d$1 ' , mb_convert_case($input, MB_CASE_TITLE, "UTF-8"));
}

$input = 'PORTO DE GALINHAS'; // texto vindo do webservice

echo nomeProprio($input);

(veja funcionando aqui ideone)
a primeira coisa que vai acontecer na string PORTO DE GALINHAS é que ela passará pela função mb_convert_case() que tem o parâmetro MB_CASE_TITLE e UTF-8 Que Servem Para Converter A String Em Case Title e o charset em UTF-8 respectivamente. Resultando em:
"Porto De Galinhas"

a expressão regular será utilizada nessa string
Dissecando a expressão regular: /\sd(\ws?)\s/i

/ // delimitador de início da expressão regular
\s // exige que haja um espaço
d // exige que haja a letra d
( // inicia um grupo de captura para ser utilizado na sequência -> $1
\w // que exige que tenha uma letra(\w), também poderia ser [aeiou]
s? // seguido ou não da letra s
) // finaliza o grupo de captura
\s // mais uma vez exige que haja outro espaço
/ // delimitador de fim da expressão regular
i // faz com que a expressão seja case insensitive considerando o d ou D

que encontrará " De ", fará a extração apenas da letra "e" e a colocará no grupo de captura $1 fazendo com que
" De "

seja substituido por
" de "

exibindo como resultado final:
"Porto de Galinhas"

como o \w pode ser qualquer letra encontraria também
" Da ", " Di ", " Do ", " Du ", " D(qualquer letra) "...

no caso acima apenas as vogais entram no grupo de captura. E também:
" Das ", " Dis ", " Dos ", " Dus ", " D(qualquer letra)s "...

nesse outro caso entram as vogais acompanhadas da letra s que serão colocadas no lugar de $1 resultando em:
" das ", " dis ", " dos ", " dus ", " d(qualquer letra)s "...

Repare que a substituição será apenas na parte " De " pois o restante já ficou correto com a utilização da função mb_convert_case.


Pivot unclear grouping / remove result rows

Question: I am having issues to understand the pivot table in POI
I could generate a compact pivot, but I have still issues to identify how to remove the result rows (red marked)

how are these rows named? So maybe I could have found them by searching for them.
the code which is creating the table:
import java.io.FileOutputStream;

import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;

public class CreatePivotTableComplex {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   Sheet pivotSheet = workbook.createSheet("Pivot");
   Sheet dataSheet = workbook.createSheet("Data");

   Row row;
   Cell cell;
   Object[][] data = new Object[][]{
    new Object[]{"Name", "Country", "Count", "Value", "Date"},
    new Object[]{"A", "C1", 2d, 123.56, "2023-05-22"},
    new Object[]{"B", "C1", 4d, 34.56, "2023-05-23"},
    new Object[]{"A", "C2", 1d, 56.78, "2023-05-24"},
    new Object[]{"B", "C2", 7d, 23.45, "2023-05-25"},
    new Object[]{"A", "C1", 3d, 234.56, "2023-05-26"},
    new Object[]{"A", "C1", 2d, 132.56, "2023-05-27"},
    new Object[]{"B", "C1", 5d, 78.90, "2023-05-28"}
   };
   for (int r = 0; r < data.length; r++) {
      row = dataSheet.createRow(r);
      Object[] rowData = data[r];
      for (int c = 0; c < rowData.length; c++) {
         cell = row.createCell(c);
         if (rowData[c] instanceof String) {
            cell.setCellValue((String) rowData[c]);
         } else if (rowData[c] instanceof Double) {
            cell.setCellValue((Double) rowData[c]);
         }
      }
   }

   AreaReference areaReference =
         new AreaReference(new CellReference(0, 0), new CellReference(data.length - 1, data[0].length - 1), SpreadsheetVersion.EXCEL2007);

   XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference, new CellReference("A4"), dataSheet);

   pivotTable.addRowLabel(0);
   pivotTable.addRowLabel(1);
   pivotTable.addRowLabel(4);
   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Sum of count");
   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Sum of value");

   pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName("PivotStyleDark7");

   pivotTable.getCTPivotTableDefinition().setCompact(false);
   pivotTable.getCTPivotTableDefinition().setCompactData(false);
   pivotTable.getCTPivotTableDefinition().setGridDropZones(false);

   pivotTable.getCTPivotTableDefinition().setRowGrandTotals(false);

    pivotTable.getCTPivotTableDefinition().setColGrandTotals(true);
    pivotTable.getCTPivotTableDefinition().setRowGrandTotals(true);
    pivotTable.getCTPivotTableDefinition().setEnableDrill(false);

   // pivotTable.getCTPivotTableDefinition().setMultipleFieldFilters(false);
   // pivotTable.getCTPivotTableDefinition().setItemPrintTitles(true);
   for (org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField pivotField : pivotTable.getCTPivotTableDefinition().getPivotFields()
         .getPivotFieldList()) {
      pivotField.setCompact(false);
      pivotField.setOutline(false);
   }

   workbook.write(fileout);

  }

 }

Comment: code adopted from: https://stackoverflow.com/questions/75528597/need-to-enable-classic-pivot-table-layout-option-in-excel-using-apache-poi-jav/75529485#75529485
Answer: Those totals are properties of the pivot table fields, not of the whole table. Only grand totals are properties of the whole table.
But much pivot field properties can only be set if a proper pivot table definition and pivot table cache definition is present. Neither the one nor the other can Apache POI create so far.
See How to set default value in Apache POI pivot table report filter, Apache POI XSSFPivotTable setDefaultSubtotal and java: How to create a pivot with apache poi?.
Following uses my addRowLabel method to extend XSSFPivotTable.addRowLabel to provide semi-proper pivot table definition and pivot table cache definition per field.
Complete example:
import java.io.FileOutputStream;

import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;

class CreatePivotTableClassicLayoutNoFieldSubTotals {

 static void addRowLabel(XSSFPivotTable pivotTable, Sheet dataSheet, AreaReference areaReference, int column,
  boolean defaultSubtotals) {

  DataFormatter formatter = new DataFormatter(java.util.Locale.US);
  //create row label - apache poi creates as much fields for each as rows are in the pivot table data range
  pivotTable.addRowLabel(column);

  //determine unique labels in column
  java.util.TreeSet<String> uniqueItems = new java.util.TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
  for (int r = areaReference.getFirstCell().getRow()+1; r < areaReference.getLastCell().getRow()+1; r++) {
   uniqueItems.add(formatter.formatCellValue(dataSheet.getRow(r).getCell(column)));
  }
  //System.out.println(uniqueItems);

  //build pivot table and cache
  org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField ctPivotField
   = pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(column);
  int i = 0;
  for (String item : uniqueItems) {
   //take the items as numbered items: <item x="0"/><item x="1"/>
   ctPivotField.getItems().getItemArray(i).unsetT();
   ctPivotField.getItems().getItemArray(i).setX((long)i);
   //build a cache definition which has shared elements for those items
   pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(column)
    .getSharedItems().addNewS().setV(item);
   i++;
  }

  //set pivot field settings
  ctPivotField.setDefaultSubtotal(defaultSubtotals); // no subtotals for this field

  //remove further items
  if (ctPivotField.getDefaultSubtotal()) i++; //let one default item be if there shall be subtotals
  for (int k = ctPivotField.getItems().getItemList().size()-1; k >= i; k--) {
   ctPivotField.getItems().removeItem(k);
  }
  ctPivotField.getItems().setCount(i);

 }

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {

   Sheet pivotSheet = workbook.createSheet("Pivot");
   Sheet dataSheet = workbook.createSheet("Data");

   Row row;
   Cell cell;
   Object[][] data = new Object[][]{
    new Object[]{"Name", "Country", "Count", "Value", "Date"},
    new Object[]{"A", "C1", 2d, 123.56, "2023-05-22"},
    new Object[]{"B", "C1", 4d, 34.56, "2023-05-23"},
    new Object[]{"A", "C2", 1d, 56.78, "2023-05-24"},
    new Object[]{"B", "C2", 7d, 23.45, "2023-05-25"},
    new Object[]{"A", "C1", 3d, 234.56, "2023-05-26"},
    new Object[]{"A", "C1", 2d, 132.56, "2023-05-27"},
    new Object[]{"B", "C1", 5d, 78.90, "2023-05-28"}
   };
   for (int r = 0; r < data.length; r++) {
    row = dataSheet.createRow(r);
    Object[] rowData = data[r];
    for (int c = 0; c < rowData.length; c++) {
     cell = row.createCell(c);
     if (rowData[c] instanceof String) {
      cell.setCellValue((String) rowData[c]);
     } else if (rowData[c] instanceof Double) {
      cell.setCellValue((Double) rowData[c]);
     }
    }
   }

   AreaReference areaReference =
    new AreaReference(new CellReference(0, 0), new CellReference(data.length - 1, data[0].length - 1),
    SpreadsheetVersion.EXCEL2007);

   XSSFPivotTable pivotTable = ((XSSFSheet) pivotSheet).createPivotTable(areaReference,
    new CellReference("A4"), dataSheet);

   // pivotTable.addRowLabel(0);
   // pivotTable.addRowLabel(1);
   // pivotTable.addRowLabel(4);
   addRowLabel(pivotTable, dataSheet, areaReference, 0, false);
   addRowLabel(pivotTable, dataSheet, areaReference, 1, false);
   addRowLabel(pivotTable, dataSheet, areaReference, 4, false);

   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Sum of count");
   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Sum of value");

   pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName("PivotStyleDark7");

   pivotTable.getCTPivotTableDefinition().setCompact(false);
   pivotTable.getCTPivotTableDefinition().setCompactData(false);
   pivotTable.getCTPivotTableDefinition().setGridDropZones(true);

   // pivotTable.getCTPivotTableDefinition().setMultipleFieldFilters(false);
   // pivotTable.getCTPivotTableDefinition().setItemPrintTitles(true);
   for (org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField pivotField : pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldList()) {
    pivotField.setCompact(false);
    pivotField.setOutline(false);
   }

   workbook.write(fileout);

  }
 }
}

Comment: I really tried to understand your added code. But had my issues. I cannot follow your changes you have added. Can you explain a bit more?


Kernel of morphism of graded modules is graded submodule

Question: This is related to my earlier question regarding the category of graded modules.
Let $A$ be a commutative unital $\mathbb{Z}$-graded ring, and $f:M\to N$ be an $A$-linear map where $f=\sum_if_i$ and each $f_i$ is homogeneous of degree $i$. To show that $\text{ker}(f)$ is graded, we need to show that $m\in\text{ker}(f)$ implies $m_i\in\text{ker}(f)$ for all $i$.
We have that $$f(m)=\sum_{i,j}f_i(m_j)=\sum_k\sum_{i+j=k}f_i(m_j),$$ where $\sum_{i+j=k}f_i(m_j)\in N_k$ for each $k$. So $\sum_{i+j=k}f_i(m_j)=0$ for all $k$. But here I am stuck and am doubting whether or not the kernel is graded.. what can I do from here?
Answer: Such an $f$ is not what people use when talking about the category of graded modules, and its kernel need not be graded. For example if $A=k$ is a field and $M = k \oplus \Sigma k$, $N = k$, and $f$ the map sending $(a, \Sigma b)$ to $a - b$, then the kernel is not graded.
Comment: Depending on the author, either degree $0$ maps or "graded maps," meaning homogeneous maps of any degree.
Comment: What explicitly are the morphisms $M\to N$ that are used in standard practice for the category of graded modules?


Code not identifying Swedish characters despite #include in c++

Question: I have to write a code in C++ that identifies and counts English and non-English characters in a string.
The user writes an input and the program must count user's letters and notify when it finds non-English letters.
My problem is that I get a question mark instead of the non-English letter!
At the beginning of the code I wrote:
...
#include <clocale>

int main() {

    std::setlocale(LC_ALL, "sv_SE.UTF-8");
...

(the locale is Swedish)
If I try to print out Swedish letters before the counting loops (as a test), it does work, so I guess the clocale is working fine.
But when I launch the counting loop below,
for (unsigned char c: rad) {
    if (c < 128) {
        if (isalpha(c) != 0)
            bokstaver++;
    }
    if (c >= 134 && c <= 165) {
        cout << "Your text contains a " << c << '\n';
        bokstaver++;
    }

}

my non-English letter is taken into account but not printed out with cout.
I used unsigned char since non-English letters are between ASCII 134 and 165, so I really don't know what to do.
test with the word blå:
Comment: UTF-8 is not ASCII; it's a variable-length encoding of Unicode.
Comment: Did you verify that your terminal supports utf-8?
Comment: @user2079303 yes it does, it prints out the word 'blå' once.
Comment: which platform are you on? Even if your `setlocale` is effective a single `char` will only contain ascii characters not utf-8 code sequences which need 2 characters for european non-ascii characters.
Comment: @AlanBirtles on mac and CLion.
Comment: In that case the `setlocale` is probably unnecessary and you just need to deal with the multi byte utf-8 characters
Answer:
non-English letters are between ASCII 134 and 165

No, they aren't. Non english characters are not between any ASCII characters in UTF-8. Non ASCII characters consist of two or more code units (those individual code units themselves can represent some character in ASCII) . å for example consists of 0xC3 followed by 0xA5.
The C and C++ library functions which only accept a single char (such as std::isalpha) are not useful when using UTF-8 because that single char can only represent a single code unit.
Comment: Also, ASCII only exists from 0 to 127 inclusive. Anything outside that is not ASCII, but may be from an extended encoding, like iso-latin-1, UTF-8 and myriad others.


In terms of performance, is it better to lazy load, inline, or hook_init a Javascript library?

Question: I'm working on a module to embed Highcharts into nodes. Other chart modules provide a PHP helper function to trigger the necessary library loading. To avoid enabling the PHP module, I tried creating an input filter with a token for loading the Javascript library. Unfortunately, filter output gets cached, so calls to drupal_add_js within a filter function don't get called on every page load.
I can think of a few workarounds:

a small inline script to load the library, after a node containing a chart has loaded
embed the whole library file inline, on pages where it's needed
load the library on every page, via hook_init

From a performance perspective, what is my best option?
For what it's worth, the compressed Highcharts library is 81k. The site I plan on using this on has Javascript aggregation enabled, but few content items will have charts, especially initially. Plus, I'd like to contribute the module on d.o, so I'd like to solve this in a way that would make sense on most sites.
Comment: If this is going to be for D6; open up an issue on [AdvAgg](http://drupal.org/project/advagg), I think we can come up with a good solution.
Answer: You could also hook into the node's presave, check whether the body contains whatever it is, then set a flag on the node (perhaps using flag or taxonomy) if it does. Then on view, you look for the flag and use drupal_add_js if necessary. This will survive the cache and let you aggregate the script if you want to. If you'd prefer, rather than storing the flag in the DB, you can check for highcharts on every view (via hook_nodeapi()) and just add the JS there directly.
Btw, strongly recommend against the hook_init() approach - there are definitely better ways imho. hook_init is called on every full bootstrap, which includes eg. 404s and imagecache generation (as well as every normal node view). Generally it's a good idea not to use this if your code is only needed in specific circumstances (eg. only when there's Highcharts code embedded). In those situations, you want to find a way to add your code only to appropriate pages.
Comment: Agreed, hook_init() is way too early in the bootstrap process and can result in some really funky results.
Comment: Can either of you elaborate on *why* to avoid hook_init? I've noticed several contrib modules that add Javascript that way. In any case, thanks for the feedback!
Comment: @Matt V. updated answer.
Comment: @DeeZone - I'm not sure the results should be particularly funky, just not such a good idea from a perf perspective...
Comment: See the doc page for hook_init - http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_init/7

The documentation states: "To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file."

The "funkiness" is a result of "This hook is not run on cached pages."
Comment: @DeeZone Although the hook's not run on cached pages, that doesn't matter as the cache includes the HTML for including the CSS/JS file. It _would_ be important if for example you had a function that updated the database every page view. I didn't realise you could add CSS/JS files in the .info file in D7, thanks for the info.
Comment: @Andy (or DeeZone)... How would you go about adding the "flag" to the node inside hook_nodeapi? I'd like to avoid adding a table just to track what nodes to add the JS to, but I'm not seeing a way around that. As it stands, I'm searching for [highcharts][/highcharts] inside the filter and then wrapping the  portion, as needed. I'm working in Drupal 6, by the way. Thanks again!
Comment: @Matt V. I've updated my answer, but as far as I know you either have to create a table yourself, or leverage a module that does that for you (eg. taxonomy) if you want to use the flag approach.
Comment: If you do the hook_init() thing with the library, it will be on every page, but the browser will cache it.  First access to site will be slightly longer, but subsequent accesses will be fine.  Net result is pages with charts will be a little faster.
Comment: @MPD Even if the server's configured correctly to allow caching client-side, you're still requiring Drupal to call (yet another?) hook init (and drupal_add_js) on every single full bootstrap (imagecache, node views of the wrong type, Views, taxonomy pages, admin pages, 404s, etc.). At the very least it would make more sense to just add it on hook_nodeapi view while checking the content type, no?
Answer: That's kind of a toss-up.  Note that 81kB is the "minimized" size - when gzipped it's further reduced to 32kB.  Still, I'd lean towards inline - adding


Question about a vector norm

Question: I am struggling to find a counter-example for this question.
QUESTION:
Is $\nu$ a vector norm on $\mathbb{C}^n$?
We define the function $\nu: \mathbb{C} \to \mathbb{R}$ by
$$\nu(x)= \sum_{i=1}^n (|\text{Re }x_i|+|\text{Im }x_i|).$$
ANSWER
I know that is not a vector norm since $\nu(\alpha x) \ne |\alpha| \nu (x)$ for all $\alpha \in \mathbb{C}$, that is $$|\alpha|\sum_{i=1}^n (|\text{Re }x_i|+|\text{Im }x_i|) \ne \sum_{i=1}^n (| \alpha \text{Re }x_i|+| \alpha \text{Im }x_i|)$$
Comment: And how do you know that the inequality in your answer is true? (Consider the case $n=1$)
Comment: My advice: keep it simple. First, choose a very low value of $n$. If $n = 1$ doesn't work (which it will), then try $n = 2$. The question only looks plausible because we tend to think too "real" when it comes to scalar multiplication, so try some non-real numbers.
Comment: Thanks, I found the answer now.
Answer: I have been thinking about this and I have found the answer to my question, we just need to think about the following:
$$(1-i)(1+i)=2$$
What I mean is that I have found a counter-example with $x=1+i$ and $\alpha=1-i$.

Question about a vector norm


Is ${R /I} \cong {{\mathbb Z} /{9\mathbb Z}}$?

Question: If $$R = \mathbb Z[\sqrt2] = \{a+b\sqrt2\mid a,b \in \mathbb Z\}\\I = \{a+b\sqrt2\mid a,b \in 3\mathbb Z\}$$
Is ${R /I} \cong {{\mathbb Z} /{9\mathbb Z}}$?
Comment: In fact, $R/I$ is a field with $9$ elements.
Comment: @user26857:  I plead lack of early morning clarity!
Answer: No. Note that $1 + 1 + 1 = 0$ in $R/I$ but not in $\mathbb{Z}/9\mathbb{Z}$. (In fact, $R/I$ is the field with 9 elements).
Comment: So right, sorry for the confusion.


Using group and rules modules to automatically create group for new user

Question: I am using the Group (not OG ...) and rules modules for this task. I created group type, Applications Support. Then I created a rule, After saving a new user.
Under the rule, I used the following configuration, but it did not create a group.
My previous question was related to the OG module, this one is for the Group module. So I think it is a different question.
Comment: @Pierre.Vriens Sorry, didn't catch that one. Close vote retracted :)
Comment: @Jdrupal group and og are ***not*** the same modules ... so how can this be a duplicate???
Comment: this looks like D7 question, not D8, right?
Comment: @Pierre.Vriens it is for D8 actually. I moved the website from D7 to D8.
Answer: You didn't mention any errors, but for starters your group name should be:
test group {{ user.uid }}


Why is an untranslated string not showing up?

Question: In my module I have some custom strings. I use these in the t() function.
When I go to admin/config/regional/translate/translate and filter the untranslated strings my custom strings do not show here.
What could be going wrong?
Comment: Please show us your code. We can't debug what we can't see. Read [SSCCE](http://sscce.org).
Comment: If code is OK, go to *Home > Administration > Configuration > Regional and language > Translate interface* and simply hit the *Refresh Strings* button. I don't really know if it will help you, hence just a mere comment and  not an answer. But if it'll work, I will add some meat to it and post as answer ;)
Comment: Did you cleared the cache ? Maybe that's the solution to your problem.
Comment: Flush cache saved my life.
Answer: The strings needs to be rendered a first time on a page in the not default language and your string keys will be visible in the Translate interface.
An important detail, the search is case sensitive. For example My text is different than my text.
Answer: If you're trying to see the site in English the t() function will not try translate the string, so you need to see the site in other language in order to for the translation system to add your translatable string to the database.
Once you do it, you will be able to translate your string.
Answer: Beside visiting the page showing your strings in a non-default language, make sure to have the version number of the module set in the .info file.

version = 7.x-1.0

Here a trouble shooting blog post to getting your strings into the translate interface.


Find the values of both $\alpha$ and $\beta$ such that the vector $x + \alpha y + \beta z$ is orthogonal to both y and z.

Question: Given the vectors $x = (1, −4, 3)^T$, $y = (0, 1, 1)^T$ and $z = (2, 0, −1)^T$, find the values of both $\alpha$ and $\beta$ such that the vector $x + \alpha y + \beta z$ is orthogonal to both $y$ and $z$.
I'm not totally sure where to begin? I think I'm suppose to look at the Null Space of the transpose of a matrix formed of vector y and vector z? If that's the case thought, I see no point to be given an x vector?
Thanks for the help!
Answer: The cross product of the vectors y and z will give a vector that is perpendicular to both y and z.
The cross product of <0,1,1> and <2,0,-1) is <1,-2,2>.
Setting this equal to the vector x+αy+βz gives $\alpha = -2$ and $\beta = 2$.
Answer: If you don't know the cross product:
You want to find
$a$ and $b$
such that
$V = x+ay+bz$
 is orthogonal
to both $y$ and $z$.
Then,
using "$\cdot$"
for dot product,
you want
$V\cdot y
=V\cdot z
= 0
$.
$V\cdot y
=(x+ay+bz)\cdot y
= x\cdot y+a (y\cdot y) + b (z\cdot y)
$
and
$V\cdot z
=(x+ay+bz)\cdot z
= x\cdot z+a (y\cdot z) + b (z\cdot z)
$.
You therefore have
two equations in the
two unknowns $a$ and $b$:
$x\cdot y+a (y\cdot y) + b (z\cdot y) = 0$
and
$x\cdot z+a (y\cdot z) + b (z\cdot z)=0$.
Solve these and you are done.
Comment: This is a dumb question, but what would those two equations look like in matrix form in order to solve them? $$ \begin{bmatrix}
        xy & y^2 & zy \\
        xz & yz & z^2 \\
        \end{bmatrix} v = 0$$
Does that look correct?


Use html2pdf from $this->renderpartial in Yii

Question: Can I do something like this:
$content = $this->renderpartial('DeedCertificate',array('deed'=>$deed,'cnt'=>$cnt));
$html2pdf = new HTML2PDF('P','A4','en');
$html2pdf->WriteHTML($content);
$html2pdf->Output('/var/www/myapp/images/example.pdf','F');

$html2pdf->Output when using $content = "hello"l works like a charm.
Now I'm trying to pass the output of yii's renderpartial .. so it can become a pdf.. but my pdf is blank.
Answer: you can make renderPartial to return the html generated for you ,like this:
 $this->renderPartial('DeedCertificate' , array('data'=>$data) , true); // set this to true

Comment: I don't know that, I guess you could check that out yourself :D
Comment: Of course, I'm sorry for that!! I should check it out myself. And thanks for the quick response!


Making menu wrapped in nav tag

Question: I've got problem with making main-menu wrapped in  element.
I've tried:

Using hooks in template.php like:
function koko_menu_link_main_menu($variables) { /* For block override */
$output = '';
      foreach ($variables['links'] as $link) {
        $output .= l($link['title'], $link['href'], $link);
  }
  $output .= '';
  return $output;
}

function koko_links__system_main_menu($variables) {
  $output = '';
foreach ($variables['links'] as $link) {
  $output .= l($link['title'], $link['href'], $link);
}
  $output .= '';
    return $output;
}

Using preprocesss/block.preprocess.inc:
  switch ($variables['block']->module) {
    case 'system':
      switch ($variables['block']->delta) {
        case 'help':
        case 'powered-by':
          break;

      case 'main':
          // Use a template with no wrapper for the page's main content.
          $variables['theme_hook_suggestions'][] = 'block__minimal';
          break;

      default:
          // Any other "system" block is a menu block and should use
          // block--nav.tpl.php
          $variables['theme_hook_suggestions'][] = 'block__nav';
          break;
      }
      break;

      case 'menu':
      case 'menu_block':
      // Use block--nav.tpl.php template.
      $variables['theme_hook_suggestions'][] = 'block__nav';
      break;
  }

case 'main':
  // Use a template with no wrapper for the page's main content.
  $variables['theme_hook_suggestions'][] = 'block__minimal';
  break;

default:
  // Any other "system" block is a menu block and should use
  // block--nav.tpl.php
  $variables['theme_hook_suggestions'][] = 'block__nav';
  break;
 }
 break;

case 'menu':
case 'menu_block':
    // Use block--nav.tpl.php template.
     $variables['theme_hook_suggestions'][] = 'block__nav';
     break;
   }

That contains. block--nav.tpl.php
    <nav<?php print $attributes; ?>>
      <?php print render($title_prefix); ?>
      <?php print render($title_suffix); ?>
      <?php print $content; ?>

Still nothing happends. Main-menu is not wrapped in anything different than:
.
Answer: Did you read this and this posts? I thinks it's not so difficult to achieve this:
function MYTHEME_links__system_main_menu($variables) {
  $html = "
\n";
  $html .= "  \n";
  foreach ($variables['links'] as $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }
  $html .= "  \n";
  $html .= "
\n";
  return $html;
}

Comment: Nothing happends. Even after copy&cut of your code (with changing `MYTHEME`) nothing happends. Cache cleared and CRON updated.

Making menu wrapped in nav tag


Android: get latitude/longitude from pixel coordinate

Question: I'm currently developing an Android application that "emulates" a mouse (with pointer) on a map. I've implemented the pad, which is able to move the pointer (a simple little view) over the map layer. Now I need to create the addMarker feature. What I have is:

(x,y) coords of pointer in pixels (or also in dip);
the width and height map properties.

My question is: how can I calculate latitude/longitude of point been touched by pointer? Thanks a lot!
Comment: If it is a real map, you should be able to get a clicked position on it in GoogleMap
Comment: Hi @Eenvincible, thanks for your reply! Is an Android mapview, and I can't tap my device since I should use the pointer!
Answer: you can do:
Projection myProjection = myMap.getProjection()

to get the Projection of the map: https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#getProjection()

Returns a Projection object that you can use to convert between screen
  coordinates and latitude/longitude coordinates.
The Projection returned is a snapshot of the current projection, and
  will not automatically update when the camera moves. As this operation
  is expensive, you should get the projection only once per screen.
  Google Maps uses the Mercator projection to create its maps from
  geographic data and convert points on the map into geographic
  coordinates.

And then:
LatLng markerPosition = myProjection.fromScreenLocation(pointerPosition);

https://developers.google.com/android/reference/com/google/android/gms/maps/Projection.html#fromScreenLocation(android.graphics.Point)

Returns the geographic location that corresponds to a screen location.
  The screen location is specified in screen pixels (not display pixels)
  relative to the top left of the map (not the top left of the whole
  screen).
Parameters:
     point  A Point on the screen in screen pixels.
Returns: The
  LatLng corresponding to the point on the screen, or null if the ray
  through the given screen point does not intersect the ground plane
  (this might be the case if the map is heavily tilted).
Comment: Thanks, this is perfect! It has been my fault cause there was an error on my code that passes wrong points coordinates!


Floor function proof using division algorithm

Question: How could I prove that if $n,k\in\mathbb{Z}$ such that $n\geq1$ and $k\geq2$, then
$$\lceil{n/k}\rceil = \lfloor{\frac{n-1}{k}}\rfloor +1$$
I was thinking of using Euclidian algorithm of division but I have a brain fart if you will that I dont know how to conclude.
$\exists q,r\in\mathbb{Z}$ such that $0\leq r<k$ and $n = qk + r \Rightarrow \frac{n}{k} = q + \frac{r}{k}$ where since  $0\leq r<k$ then $0\leq\frac{r}{k}<1$
Therefore $q\leq\lceil{n/k}\rceil =\lceil{q + r/k}\rceil\leq q+1 $,
My idea was to express $\lfloor{\frac{n-1}{k}}\rfloor +1$ in the same way and then show that $0\leq \lceil{n/k}\rceil -\lfloor{\frac{n-1}{k}}\rfloor +1\leq 0$  but for some reason I don't know how to do it.
I think I'm either missing some intuition about the floor function or the division algorithm.
Answer: Let $n = qk + r; 0 \le r < k$ by the division algorithm.
$\lceil \frac nq \rceil = $ $q$ if $r = 0;$ or $q+1$ if $r > 0$.
Meanwhile
$n - 1 = qk + (r-1)$
$= (q-1)k + (k + r -1)$
If $r > 0$ then $\lfloor \frac {n-1}k\rfloor = q$
But if $r = 0$ then $(k+r -1) = k-1 < k$ and $\lfloor \frac {n-1}k\rfloor = q - 1$
So $\lfloor \frac {n-1}k\rfloor + 1 = q|q+1$ depending upon whether $r=0$ or $r > 0$.
Which are the same conditions as to whether $\lceil \frac nq \rceil = q|q + 1$.
So whether $r=0$ and $\lceil \frac nq \rceil = \lfloor \frac {n-1}k\rfloor + 1 = q$, or whether $r > 0$ and  $\lceil \frac nq \rceil = \lfloor \frac {n-1}k\rfloor + 1 = q+1$,
either way $\lceil \frac nq \rceil =\lfloor \frac {n-1}k\rfloor + 1$.


CXF message's context outside of interceptors

Question: I'm sending a SOAP message using apache cxf and what I want is to get both request and response payloads after the call is finished. Currently I'm using two interceptors and put payloads into messages' context like that message.getExchange().put(ExchangeContextEnum.RESPONSE_PAYLOAD.toString(), new String(payload, Charset.forName(StandardCharsets.UTF_8.name())));.
I don't want to process them right away in the interceptor itself because I need requests and responses for the series of calls. Also, I'd like to avoid making any kind of storage for the sake of simplicity and not having to deal with possible concurrency issues.
Can I get those values after the call is finished or the context is completely lost at this point?
Some code:
webService.call(object)
//here i'd like to get payloads

Interceptor for response:
public class LogInInterceptor extends AbstractPhaseInterceptor<Message> {

public LogInInterceptor() {
    super(Phase.RECEIVE);
}

@Override
public void handleMessage(Message message) throws Fault {
    InputStream in = message.getContent(InputStream.class);
    byte payload[] = new byte[0];
    try {
        payload = IOUtils.readBytesFromStream(in);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ByteArrayInputStream bin = new ByteArrayInputStream(payload);
    message.setContent(InputStream.class, bin);

    message.getExchange().put(ExchangeContextEnum.RESPONSE_PAYLOAD.toString(), new String(payload, Charset.forName(StandardCharsets.UTF_8.name())));
}
}

Interceptor for request:
public class WSSLogOutInterceptor extends AbstractSoapInterceptor {

public WSSLogOutInterceptor() {
    super(Phase.USER_PROTOCOL);
}

@Override
public void handleMessage(SoapMessage message) throws Fault {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        SOAPMessage messageContent = message.getContent(SOAPMessage.class);

        messageContent.writeTo(baos);
        message.getExchange().put(ExchangeContextEnum.REQUEST_PAYLOAD.toString(), baos.toString());

    } catch (SOAPException | IOException e) {
        throw new Fault(e);
    }
}
}

Answer: I ended up with the following solution:
Instead of putting values in message's exchange i simply do message.put(key, value) in the interceptor. To get those values after the call you
need to get response context like that (String) ((BindingProvider) webService).getResponseContext().get(key) where key is the same value you used before to put payload in the message. Now here's the problem - you won't find values that you put in the outgoing chain in response context. You can use simple workaround and put value in the exchange of the message and then, in the ingoing chain get it and put it into message. Pay attention to the phase I used (POST_PROTOCOL), it'd helpful if you use WSS.
Here's the code:
public class LoggingOutPayloadInterceptor extends AbstractSoapInterceptor {

public static final String OUT_PAYLOAD_KEY = "use.your.package.name.OUT_PAYLOAD_KEY";

public LoggingOutPayloadInterceptor() {
    super(Phase.POST_PROTOCOL);
}

@Override
public void handleMessage(SoapMessage soapMessage) throws Fault {

    Document document = soapMessage.getContent(SOAPMessage.class).getSOAPPart();
    StringWriter stringWriter = new StringWriter();
    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(stringWriter));
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    soapMessage.getExchange().put(OUT_PAYLOAD_KEY, stringWriter.toString());
}

}
public class LoggingInPayloadInterceptor extends AbstractSoapInterceptor {

public static final String IN_PAYLOAD_KEY = "use.your.package.name.IN_PAYLOAD";

public LoggingInPayloadInterceptor() {
    super(Phase.POST_PROTOCOL);
    addAfter(SAAJInInterceptor.class.getName());
}

@Override
public void handleMessage(SoapMessage message) throws Fault {
    Document document = message.getContent(SOAPMessage.class).getSOAPPart();
    StringWriter stringWriter = new StringWriter();
    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(stringWriter));
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    message.put(IN_PAYLOAD_KEY, stringWriter.toString());
    message.put(LoggingOutPayloadInterceptor.OUT_PAYLOAD_KEY, message.getExchange().get(LoggingOutPayloadInterceptor.OUT_PAYLOAD_KEY));
}

}
webService.call(...);
String inPayload = (String)((BindingProvider)webService).getResponseContext().get(LoggingInPayloadInterceptor.IN_PAYLOAD_KEY);
String outPayload = (String) ((BindingProvider) webService).getResponseContext().get(LoggingOutPayloadInterceptor.OUT_PAYLOAD_KEY);


JQuery Mobile: focused input text doesn't respect z-index, appearing above everything else

Question: I have a Phonegap application for Android with jQuery Mobile.
On an HTC Desire, if an input box is focused, it always go to the front, no matter which elements has above.
Comment: This is a known issue with android. Checking with the platform developers site is a great way to find out if what your experiencing is a bug or not. http://code.google.com/p/android/issues/detail?id=18370
Comment: Did you add similar to below code to remove flickering in your app?.ui-page {
 -webkit-backface-visibility: hidden;
}    Above code has side effects in Android .Please comment code and try it.
Answer: Did you try to apply the css property -webkit-transform : translate3d(0,0,0); to your input field ?


What distinguishes Rock-n-roll from Rhythm-n-Blues?

Question: Rock changes are basically Blues changes. Rock instrumentation (Guitar, Bass, Drums[, Keyboard, Horns]) is basically the same as Blues instrumentation (Guitar, Bass, Drums[, Keyboard, Horns]). Can one make an objective, quantifiable distinction between Rock-n-roll and Rhythm-n-Blues?
Comment: No shuffle and a strong backbeat?
Answer: The term "Rhythm and Blues" or "R&B" was coined by Jerry Wexler (who went on to be a famous record company executive and producer) when he was working as a journalist at Billboard Magazine, circa 1952. (Wikipedia link). Billboard published a weekly chart displaying their estimates of the relative position of retail sales of single recordings which were also broadcast on radio stations with an African-American audience, and the chart was called "Race" (as in "racially-oriented", or perhaps "oriented to the minority race" which in the United States of America meant African-Americans). Recordings made by and marketed and sold to African-Americans had previously been called "race records". Wexler proposed the name "Rhythm and Blues" at a staff meeting of Billboard magazine when they discussed wanting to change the name of the "Race" chart to something else, and his suggestion was accepted.
As was mentioned earlier, influential radio personality Alan Freed coined the term "rock and roll" circa the mid-1950s. Freed seems to have intended the usage to refer to music made by both African-American musicians and white musicians.
Quickly, though, in popular usage in the United States of America, "rock and roll" came to refer to music of a certain style recorded by white musicians and marketed and sold to a white audience. "Rhythm and Blues" refers to music that was recorded by African-American musicians and marketed and sold to an African-American audience.
Note that the key to this is the term "marketed and sold". Both "Rock and Roll" and "Rhythm and Blues" came to be designations used by the commercial music industry to describe how the music was marketed and sold, and to whom it was marketed.
Notwithstanding, there are certainly distinct artistic characteristics to each kind of music.
Stylistically
The rhythms used in the two styles are similar. I would note that rock and roll has usually involved simple instrumentation of bass, guitar, and drums, small ensembles, and strictly diatonic chord progressions (mostly just I, IV, V7 or bVII if mixolydian mode is used). R&B, on the other hand, freely incorporates the expanded harmonic palette of jazz chords, uses larger ensembles, and can be found frequently to incorporate keyboards, horn sections, woodwinds, and string orchestras. R&B also tends toward more mid-tempo and slow-tempo pieces. The rock singing style is straightforward and narrative, whereas the R&B singing style involves florid melisma and other embellishments. It can also be noted that female singers are much more prevalent in R&B than they are in rock, where male singers strongly predominate. There is also a lot of influence of hip-hop and rap found in R&B in the last fifteen or twenty years, whereas hip-hop and rap have a much more limited influence on rock (and country) in the same time period.
Answer:
Can one make an objective, quantifiable distinction between
  Rock-n-roll and Rhythm-n-Blues?

Short answer: No.
Long Answer:
Alan Freed's use of the term rock-n-roll in the 1950s is often considered definitive. He used the term to refer to R&B combos, black vocal groups, saxophonists, black blues singers, and white artists playing in the authentic R&B style.
Rhythm-n-Blues was early Rock-n-roll.
Early rock-n-roll was the popular, and commercial (and often "white") face of Rhythm-n-Blues.

First, try to define rock and roll. I thought it was that driving back beat, until I heard an Egyptian band that could give Bo Diddley lessons. - Harry Hepcat

Whilst Wikipedia says...

"The Fat Man" is a rhythm and blues song co-written by Fats Domino and Dave Bartholomew and recorded by Fats Domino. It is considered to be one of the first rock and roll records.

Once you get towards the end of the 1950s however both terms have started to evolve along interweaving paths into RnB and the all encompassing umbrella term of Rock music.
Comment: Yes, and the meanings are constantly shifting too. Compare what's in today's "R&B" chart to what was in a 1960s "R&B" chart.


"Mean pooled difference" or "pooled mean difference"?

Question: Perhaps this is purely semantics but meta-analyses use these in interchangeably but which is more legitimate or are neither because there should be a hyphen?
I would say pooled mean difference because you're pooling the mean difference. I wouldn't use a hyphen because the "mean difference" is being pooled, not just the "mean".
No this question doesn't belong in English literature or semantics because it's a statistical term and sense of it must be made from a statistical standpoint
Comment: I'd go with "polled mean difference", as in "pooled covariance". It's describing something( the mean) as pooled.
Answer: Mean difference is just a type of effect size. We also have median difference, Cohen's d and Hedges' g which are standardized mean difference, etc. In meta-analysis, these effect sizes are pooled, weighted, or averaged then you get things like pooled mean difference.


if $M_1,M_2$ are two structures for FOL $L$ that differ in interpretations of signs not in statement $A$, then $M_1 \vdash A$ iff $M_2 \vdash A$

Question: Let $L$ be a first order language. Let $A$ be statement, and let $M_1,M_2$ be two structures for $L$.
I want to prove that if $M_1$ and $M_2$ differ in interpretation only of signs that aren't in $A$ then: $M_1 \vdash A$ iff $M_2 \vdash A$
Naturally I would think to prove it by induction on the structure of $A$. However, in first order logic, formulas are created recursively, and not statements. So I can't do that.
Then I thought about using induction on the structure of formulas and the induction claim will be: for every formula without free variables. (because a statement is a formula without free variables).
But here I also have a problem in that step: $A = \exists_x B$, because $x$ might be free in $B$ and thus, I won't be able to use the induction claim.
So my real problem is here is to determine what exactly will be the induction claim.
Help would be appreciated.
Comment: You will probably want the domains of $M_1$ and $M_2$ to be the same. Ohterwise we get an easy counterexample: $A$ could express "there are at least 5 elements" (our language now only contains equality). Then $M_1$ could have 4 elements and $M_2$ could have 6 elements.
Comment: yes the domains are the same
Answer: As you seem to recognize, the subset of closed formulas is not inductively defined (at least not in the "natural" way). (Open) Formulas are an inductively defined set. This situation happens often, and the resolution is called "strengthening the induction hypothesis". I feel that this is often subtly misleadingly presented. A typical presentation makes it look like we attempt an induction and that the problem was that our induction hypothesis was too weak and so we strengthen it. What usually (always?) actually happening is that we trying to do induction on something that isn't inductively defined in the first place, and "strengthening the induction hypothesis" is really formulating the correct induction hypothesis for an actual (more general) inductively defined set.
That said, you still need to figure out what the general theorem is for the inductively defined set containing the subset you care about which will specialize to the theorem you care about on that subset. In this case, that theorem is simply that the interpretation of (the potentially open) formula $A$ with respect to $M_1$ is the same as the interpretation of $A$ with respect to $M_2$ under the assumptions you gave (including the one on domains in the comments). The proof by induction is completely straightforward and largely just a reflection that interpretations are defined in a compositional manner.
Answer: As you suspected you have to proceed by induction over the formulas (not necessarily closed).
The trick is to consider the semantics of first-order logic as an assignment of truth functions to open formulas: if $M$ is a $L$-structure and $\varphi(x_1,\dots,x_n)$ is a $L$-formula (with free variables $x_1,\dots,x_n$) then its truth-function is the
$$
F_\varphi^M \colon M^n \longrightarrow \{0,1\}
$$
where $F_\varphi^M(a_1,\dots,a_n)=1$ if and only if $M \models\varphi(a_1,\dots,a_n)$,
or equivalently if $M,a_1,\dots,a_n \models \varphi(x_1,\dots,x_n)$, where $M,a_1,\dots,a_n$ is the $L \cup \{x_1,\dots,x_n\}$-structure that interprets the symbols of $L$ as in $M$ and the constants $x_1,\dots,x_n$ with $a_1,\dots,a_n$ respectively
What you need to show is that for every formula $\varphi$ you have that $F_\varphi^{M_1}$ and $F_\varphi^{M_2}$ are equal.
This is the statement to be proven by induction on the complexity of the formulas.
Of course in the special case where $\varphi$ is a closed formula, and so the relative functions $F_\varphi^{M_1}$ and $F_{\varphi}^{M_2}$ are $0$-ary functions (that is they are constants), the theorem states that the formula has the same truth value in the two models.
Hope this helps.
Comment: Could it be possible to know why the -1, so I can improve the answer?


Alterar output de um input type time

Question: Tenho um form com um input do type="time", quando eu clico no submit a url envia os dados assim:
hrentrada=HH%3AMM&hrsaida=HH%3AMM.
 Gostaria que mandasse assim:
hrentrada=HHMM&hrsaida=HHMM.
 Alguém sabe como manipular isso?
<form name="teste" method="GET" action="index.html">
   <input type="time" name="hrentrada"style="width:70px" maxlength="4 required>
   <input type="time" name="hrsaida"style="width:70px" maxlength="4" required>
   <input type="submit" name="submit">
</form>

de preferencia so com html e no máximo javascript puro
Comment: O browser faz isso de propósito para evitar ter `:` no URL. Podes descodificar isso com JavaScript usando `decodeURIComponent('HH%3AMM&hrsaida=HH%3AMM')`... mas o servidor deve receber isso corretamente. Estás a usar um servidor?
Comment: Eu queria justamente tirar esse %3A
Answer: Nada impede de você tratar a informação no destino (index.html). Porém se for uma restrição do seu projeto você pode fazer da seguinte forma:
<input type="time" name="hrentrada_get"style="width:70px" maxlength="4">
<input type="time" name="hrsaida_get" style="width:70px" maxlength="4">
<form name="teste" method="GET" action="index.html" onsubmit="return ajustarHora()">
   <input type="hidden" name="hrentrada">
   <input type="hidden" name="hrsaida">
   <input type="submit" name="submit">
</form>

Nesta solução você vai precisar validar o preenchimento dos campos que estão fora do form e de acordo com sua necessidade fazer o ajustarHora() retornar true ou false para enviar ou não os dados.
Segue link de exemplo funcionando https://jsfiddle.net/76wzqupt/2/

Alterar output de um input type time


Unable to interact with a CKEditor_link hook

Question: TL;DR;
My function MYMODULE_ckeditor_link_TYPE_revert() is never called.
Context
I developed a custom module MMS which works pretty fine regarding its own task, but I've trouble when interacting with the CKEditor_link module.
The problem is that node titles are internally multilingual, including all needed translations of the real title, so they're looking like [multi][en]The title[fr]Le titre[/multi].
The module is responsible to make the final display to be only The title when current language is en, Le titre when it's fr, and so on.
This works fine everywhere else, through different strategies.
Regarding CKEditor_link, I've to do the same when it looks for nodes, first to create autocomplete list of titles, then to revert to a title from a path.
What's working fine
Looking at the ckeditor_link.api.php contents, I first found the hook_ckeditor_link_autocomplete_alter() template from which I could successfully generate the expected autocomplete list using this:
function mms_ckeditor_link_autocomplete_alter(&$results, $string) {
  if ($results) {
    foreach ($results as $key => $value) {
      $results[$key] = ...extract real title from $value...
    }
  }
}

The issue
Regarding the revert process, ckeditor_link.api.php doesn't cite an equivalent hook_ckeditor_link_revert_alter(), so the above strategy can't be used.
At the opposite it shows hook_ckeditor_link_TYPE_revert(), so I imagined I could work like this:
function mms_ckeditor_link_node_revert($path, &$langcode) {
  fb($path, 'Hook revert');##
  $result = ckeditor_link_ckeditor_link_node_revert($path, $langcode);
  if ($result) {
    $result = ...extract real title from $value...
  }
  return $result;
}

But this hook is never called, as I could check using the fb() included above.
I looked for information about that and notably found these issues:

https://www.drupal.org/node/2101293
https://www.drupal.org/node/1107954

Although they seem to address my exact problem, I can't figure out what's turning wrong.

EDIT: precisions, based on received comments.
As evoked by @Mantas Karanauskas I'd been already puzzled by this:

these hooks can only be implemented by the module that "owns" the types

and I was (and I remain) not really sure of anything about what it actually means.
But we must notice that the MYMODULE__ckeditor_link_autocomplete_alter() hook works fine, while it uses the same node type: so I tend to think that this type, in the context of my module, is well considered as "owned", whatever it means.
Now based on the @Raf suggestion about ckeditor_link_get_types() I just noticed that the CKEditor_link module calls it the same way both in the autocomplete and revert processes: one more time this makes me tend to think that type is not the problem, since it's well recognized in the autocomplete process.
In the other hand, another point puzzles me from the beginning.
From what I could understand of the general Drupal rules about added module hooks interacting with pre-existing original module hooks I notably retain that there are two distinct situations, which need two different strategies to be preliminary enforced by the original module:

For added module to be able to alter original module hook results after it worked, original module must have placed a drupal_alter() in its own process.
For added module to be able to execute its own hook in place of the original module one, original module must have placed a module_invoke_all() in its own process.

Among the templates showed in ckeditor_link.api.php, we find hook_ckeditor_link_autocomplete_alter(), which relates to #1 above, and hook_ckeditor_link_TYPE_revert() which relates to #2.
Now we can notice that in CKEditor_link module:

the autocomplete process includes a drupal_alter() call (relates to #1 and works fine)
but despite what is suggested by ckeditor_link.api.php, the revert process doesn't include any module_invoke_all() call (should relate to #2 and doesn't work)

Strictly following the above reasoning would make conclude that the ckeditor_link.api.php templates are not reliable and that there is no solution for my issue.
But I hope I'm wrong and a solution exists...
Comment: I'm not 100% sure but check last comment https://www.drupal.org/node/2101293#comment-7921275
it says "these hooks can only be implemented by the module that "owns" the types"
so if type is defined not in your module, the hook is not going to be called. you could try using function node_ckeditor_link_node_revert(). If it is not used in any other module, it should work, of course it is not very good solution.
Comment: @MantasKaranauskas Thanks for your interest to my question. Please look at my edit.
Answer: My first guess is that TYPE is wrong, and the hook isn't called because of that. It's a vague term, anywasys. I checked the code and found that ckeditor_link_get_types() gets the types. You may want to add a dpm or such in there, so you know for sure which options the module looks for internally.
Edit As discussed in the comments, recapping it here, you may want to patch the CKEditor_link module. From what you explained in your edit, this seems to be a technical flaw in the module itself. Play around in the module to see if any of the options you found, work, make a patch of it, and contribute it to the original module.
Comment: Thanks for your interest to my question. Please look at my edit.
Comment: Seeing your edit, the best way I see, is altering the revert so it follows either one of the two points you mentioned. If it works, make a patch for it and treat it as any other patches in your project. Contributing that patch back to the project may be nice too then,
Comment: If I correctly understand, your suggestion is to patch *the original CKEditor_link* module? I must confess I'm a bit afraid to eventually _create_ new issues otherwise :) but it's true that, at least keeping it purely at my own module level, it might be a solution. Please include this suggestion to your answer, so I can accept it before the bounty ending if no other answer appears.
Comment: Done. Also, it's very much appreciated by module maintainers if a bug / issue is raised and a patch is provided along with it. It's the core principle of open source ;-)
Comment: Great: I just tried your suggestion and it works fine! Thanks a lot.


Is there a general formula for the integral $I_{n} = \int_{0}^{\frac{\pi}{2}} \sin^{2n-1}x + \sin^{2n-3}x + ... + \sin x dx, n\in \mathbb{N}$.

Question: $$I_{n} = \int_{0}^{\frac{\pi}{2}} \sin^{2n-1}x + \sin^{2n-3}x + ... + \sin x dx, n\in \mathbb{N}$$
I'm using this integral to form part of answer to someone's question, but I'm struggling to find a formula for this integral (if one exists).
Edit:
I believe the formula for $J_{n} = \int_{0}^{\frac{\pi}{2}}\sin^{2n+1}xdx$ is:
$J_{n} = \frac{2^{2n+1}n!(n+1)!}{(2n+2)!}$
Comment: \begin{eqnarray*}
J_n= \frac{2^{2n} (n!)^2}{(2n+1)!}
\end{eqnarray*}
Comment: I think that in this case for the product of the odd numbers, you use n+1 since if n=1, then the number of odd numbers is 2
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\int_{0}^{\pi/2}\sum_{k = 1}^{n}\sin^{2k - 1}\pars{x}\,\dd x =
\int_{0}^{\pi/2}\sin\pars{x}\,{\sin^{2n}\pars{x} - 1 \over \sin^{2}\pars{x} - 1}
\,\dd x\,\,\, \stackrel{\cos\pars{x}\ \mapsto\ x}{=}\,\,\,
\int_{0}^{1}{1 - \pars{1 - x^{2}}^{n} \over x^{2}}\,\dd x
\\[5mm] = &\
-1 + \int_{0}^{1}{1 \over x}\bracks{-n\pars{1 - x^{2}}^{n - 1}}\pars{-2x}\,\dd x =
-1 + 2n\int_{0}^{1}\pars{1 - x^{2}}^{n - 1}\,\dd x
\\[5mm] \stackrel{x^{2}\ \mapsto\ x}{=}\,\,\, &\
-1 + n\int_{0}^{1}x^{-1/2}\,\pars{1 - x}^{n - 1}\,\dd x =
-1 + n\,{\Gamma\pars{1/2}\Gamma\pars{n} \over \Gamma\pars{1/2 + n}} =
-1 + {\pars{-1/2}!\,n! \over \pars{n - 1/2}!}
\\[5mm] = &\
{1 \over \ds{{n - 1/2 \choose n}}} - 1=
\bbx{\ds{{2^{2n} \over \ds{{2n \choose n}}} - 1}}
\end{align}

A proof of the last identity can be seen in one of my previous answers.
Comment: $\int_{0}^{\pi/2}\sin\pars{x}\,{\sin^{2n}\pars{x} - 1 \over \sin^{2}\pars{x} - 1}
\,\dd x\,\,\, \stackrel{\cos\pars{x}\ \mapsto\ x}{=}\,\,\,
\int_{0}^{1}{1 - \pars{1 - x^{2}}^{n} \over x^{2}}\,\dd x
\\ $ Could you explain how you arrived at this?
Comment: @mrnovice It's equivalent to $t = \cos\left(x\right)$. Note that $\sin^{2}\left(x\right) = 1 -  \cos^{2}\left(x\right) = 1 - t^{2}$ and $\sin^{2n}\left(x\right) = \left[1 -  \cos^{2}\left(x\right)\right]^{n} = \left(1 - t^{2}\right)^{n}$. Moreover, $\mathrm{d}t = -\sin\left(x\right)\,\mathrm{d}x$.
Comment: Ah okay thanks, also what is $(-\frac{1}{2})!$?
Comment: @mrnovice In general, the factorial is defined as $z! = \Gamma\left(z +1\right)$. So, $\left(-\,{1 \over 2}\right)! = \Gamma\left(1 \over 2\right) = \,\sqrt{\,\pi\,}\,$.
Comment: Ah... I didnt noticed that $\sqrt\pi=\Gamma(1/2)$. Sorry but it is not correct to write $(-1/2)!$ because factorial is not defined for negative numbers, but the binomial is correct because the generalized binomial is defined from falling factorials, what are well defined for any $x\in\Bbb C$.
Comment: @Masacroso  $z!$ is defined $\forall z \in \mathbf{C}\setminus\left\{-1,-2,-3,\ldots\right\}$. I already talk about it in a previous comment. [See this link](http://mathworld.wolfram.com/Factorial.html). Thanks for your remark.
Comment: @FelixMarin this is not the general consensus about the definition of the factorial. Just [one example](https://en.wikipedia.org/wiki/Factorial#Extension_of_factorial_to_non-integer_values_of_argument). The reason is that exists infinite possible extensions of the factorial function to other values.
Answer: The terms of your integral can be evaluated one by one
\begin{eqnarray*}
\int_{0}^{\pi/2} \sin^{2n+1}x dx =\frac{(2n)!!}{(2n+1)!!}
\end{eqnarray*}
So your integral can be written as a sum
\begin{eqnarray*}
I_n = \sum_{i=0}^{n-1}\frac{(2i)!!}{(2i+1)!!}
\end{eqnarray*}
Comment: I don't think that formula is correct
Comment: Take n = 1, then $\int_{0}^{\frac{\pi}{2}}sin^{3}xdx = \frac{2}{3}$. But according to your formula it would be much much smaller than that.
Comment: Oh ... is it the double factorial notation ? $(2n)!! =(2n)(2n-2) \cdots 4 \times 2$ ... I do not mean $((2n)!)!$
Comment: Oh I did not know that, then it probably is correct
Comment: phew ... I easily doubt myself ... I do think it is correct. ... goto Wolfram alpha & check ? integral_0^{pi/2} (sin(t))^11 dt
Answer: HINT: by integration by parts we have that
$$I_n:=\int(\sin x)^n\mathrm dx=-\cos x(\sin x)^{n-1}+(n-1)\int (\cos x)^2(\sin x)^{n-2}=\\=-\cos x(\sin x)^{n-1}+(n-1)\int (1-\sin x)^2(\sin x)^{n-2}=\\=-\cos x(\sin x)^{n-1}+(n-1)(I_{n-2}-I_n)$$
hence
$$I_n=\frac1n((n-1)I_{n-2}-\cos x(\sin x)^{n-1})\tag{1}$$
where clearly $I_1=-\cos x$ and $I_0=x$. Evaluating in $A:=[0,\pi/2]$ we have that $I_1|_A=1$, then because (1) we have that $I_3|_A=2/3$, $I_5|_A=\frac23\cdot\frac45$, and in general $$I_{2k+1}|_A=\frac{(2k)!!}{(2k+1)!!}=2^k\frac{k!}{(2k+1)!!}=\frac{2^kk!(2k)!!}{(2k+1)!}=\\=\frac{4^k(k!)^2}{(2k+1)!}=\frac{4^kk!}{(2k+1)^\underline{k+1}}=4^kk!k^\underline{-k-1}$$
Hence
$$\int_0^{\pi/2}\sum_{k=0}^n (\sin x)^{2k+1}\mathrm dx=\sum_{k=0}^{n}I_{2k+1}\big|_A$$
what dont seems to have a closed form of elementary functions. From Wolfram Mathemathica I get a "closed" solution in terms of the gamma function
$$\begin{align}\int_0^{\pi/2}\sum_{k=0}^n (\sin x)^{2k+1}\mathrm dx&=\frac{2 \sqrt{\pi } n \Gamma (n+2)+3 \sqrt{\pi } \Gamma
   (n+2)-2 \Gamma \left(\frac{1}{2} (2 n+5)\right)}{2 \Gamma
   \left(\frac{1}{2} (2 n+5)\right)}\\&=\frac{\sqrt\pi(n+1)!}{\Gamma(n+3/2)}-1\end{align}$$
Comment: Your formula for $I_{2k+1}$ seems to be incorrect, unless I'm making a mistake.
Comment: @mrnovice I think my formulas are correct. I checked it with mathematica from both approaches: the integral and the summation, and both coincide.
Comment: By your own formula $I_{3} = 4^{1}*1!*1^{-2} = 4$ But $ I_{3} = \frac{2}{3}$
Comment: @mrnovice the elements $a^\underline k$ are falling factorials, not powers, then $I_3|_A=4/6=2/3$, because $1^\underline{-2}=\frac12\cdot\frac13=\frac16$
Comment: Oh ok, there's some more factorial notation I have now learned lol, sorry for the confusion.
Comment: @mrnovice it was my fault, sorry... its too late now and I forget that not everyone know this notation. This notation was introduced many years ago by Donald Knuth and it is common nowadays.