wxPython class doesnt show in window

Question: So i created a class that runs a big calculation in a seperet thread.
This is what i expected to see:

And this is what i do see:

This is the frame class
class ThreadFrame(wx.Frame):

def __init__(self,parent=None):
    wx.Frame.__init__(self,parent=parent)
    self.frame = wx.Frame(None, title='Bitte Warten',style=wx.FRAME_NO_TASKBAR)
    self.frame.SetSize(500,100)
    self.panel=wx.Panel(self.frame)
    self.parent=parent
    self.WaitLbl=wx.StaticText(self.panel,-1)
    self.WaitLbl.SetLabel('Geotags werden ausgelesen und abgerufen.')
    self.progress = wx.Gauge(self.panel,size=(500,30), range=self.parent.list_ctrl.GetItemCount())
    self.btn = wx.Button(self.panel,label='Abbrechen')
    self.btn.Bind(wx.EVT_BUTTON, self.OnExit)

    self.Sizer=wx.BoxSizer(wx.VERTICAL)

    #Add Widgets LeftSizer
    self.Sizer.Add(self.WaitLbl,0,wx.ALL|wx.CENTER,5)
    self.Sizer.Add(self.progress,0,wx.ALL,5)
    self.Sizer.Add(self.btn,0,wx.ALL|wx.CENTER,5)

    self.panel.SetSizer(self.Sizer)
    self.Sizer.Fit(self.panel)
    self.panel.Layout()
    self.Centre()

    #Bind to the progress event issued by the thread
    self.Bind(EVT_PROGRESS_EVENT, self.OnProgress)
    #Bind to Exit on frame close
    #self.Bind(wx.EVT_CLOSE, self.OnExit)
    self.Show()

    self.mythread = TestThread(self.frame, self.parent)
    #Enable the GUI to be responsive by briefly returning control to the main App
    while self.mythread.isAlive():
        time.sleep(0.1)
        wx.GetApp().Yield()
        continue

    try:
        self.OnExit(None)
    except:
        pass

def OnProgress(self, event):
    self.progress.SetValue(event.count)
    #or for indeterminate progress
    #self.progress.Pulse()

def OnExit(self, event):
    if self.mythread.isAlive():
        print('Thread lebt noch')
        self.mythread.terminate() # Shutdown the thread
        print('Thread wird beendet')
        self.mythread.join() # Wait for it to finish

    self.Close()

And this is the thread where the calculation is running
class TestThread(Thread):
def __init__(self,parent_target,toplevel):
    Thread.__init__(self)
    self.parent = toplevel
    self.ownparent=parent_target
    self.stopthread = False
    self.start()    # start the thread

def run(self):
    print('Thread gestartet')
    i=0
    while self.stopthread == False:
           #if calculation is not finished:
                #do calculation and count i one up
                evt = progress_event(count=i)

                    #Send back current count for the progress bar
                try:
                    wx.PostEvent(self.ownparent, evt)

                except: # The parent frame has probably been destroyed

                    self.terminate()
                i=i+1
        else:
            print('Thread Terminated')
            self.terminate()

def terminate(self):
    self.stopthread = True

And this is how i call the class from my main programm:
frame=ThreadFrame(self)

The main program also has a frame open. So this is a frame which is opend and then starts a thread which does calculation and then stops.
I think thats all that is to know. I replaced the caluclation with speudo code because my brain hurts and i cant come up with a plachold right now. But i feel like between all the fiting and sizers and panels and frames i went somewhere wrong. And i totaly dont look through all of this stuff at the moment.
Answer: The code you show doesn't seem to correspond to the screenshots. Whatever problem with the layout you might have, you should still have "Bitte warten" in the frame title, but your screenshot doesn't even show this. Either you're not executing the code you show at all, or you create some other frame elsewhere in your code which you see here. Or, of course, you've uploaded a wrong screenshot or code version. But something just doesn't fit here.
Comment: This is indeed a second window im opening. Is that a problem? The Parent that i give has another window with his own panel and sizers. But those work fine.
Comment: @Odatas it's not a problem to have multiple windows. It is a problem that your frame title doesn't show "Bitte warten". I.e. this is just not the right frame.
Answer: So im not sure what caused the problem. I started from scratch and now it works. This time i didnt use a new frame because the class itself is allready a frame.
class GeoThreadFrame(wx.Frame):

def __init__(self, radsteuer):
    wx.Frame.__init__(self,parent=radsteuer.frame,style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP|wx.FRAME_NO_TASKBAR)
    panel = wx.Panel(self)
    self.SetWindowStyle(wx.FRAME_NO_TASKBAR|wx.STAY_ON_TOP)

    self.progress = wx.Gauge(panel,size=(300,30), pos=(10,50), range=radsteuer.list_ctrl.GetItemCount())

    self.btn = wx.Button(panel,label='Abbrechen', size=(200,30), pos=(10,10))
    self.btn.Bind(wx.EVT_BUTTON, self.OnExit)
    panel.Center()
    #Bind to the progress event issued by the thread
    self.Bind(EVT_PROGRESS_EVENT, self.OnProgress)
    #Bind to Exit on frame close
    self.Bind(wx.EVT_CLOSE, self.OnExit)
    self.Center()
    self.Show()

    self.mythread = GeoLocationThread(self, radsteuer)
    #Enable the GUI to be responsive by briefly returning control to the main App
    while self.mythread.isAlive():
        #time.sleep(0.1)
        wx.GetApp().Yield()
        continue

    try:
        self.OnExit(None)
    except:
        pass

def OnProgress(self, event):
    self.progress.SetValue(event.count)
    #or for indeterminate progress
    #self.progress.Pulse()

def OnExit(self, event):

    if self.mythread.isAlive():
        self.mythread.terminate() # Shutdown the thread
        #self.mythread.join(3) # Wait for it to finish
    self.Destroy()

class GeoLocationThread(Thread):
    def __init__(self,parent_target,mainparent):
        Thread.__init__(self)
        self.parent = parent_target
        self.mainparent=mainparent
        self.stopthread = False
        self.start()    # start the thread

    def run(self):
        # A loop that will run for 5 minutes then terminate
        i=0
        while self.stopthread == False:

            if i < self.mainparent.list_ctrl.GetItemCount():
                self.calculation(i)
                evt = progress_event(count=i)
                i=i+1
                #Send back current count for the progress bar
                try:
                    wx.PostEvent(self.parent, evt)
                except: # The parent frame has probably been destroyed
                    self.terminate()
            else:
                self.terminate()

    def terminate(self):

        self.stopthread = True

    def calculate(self,i):
        #your calculation here

wxPython class doesnt show in window


Managed file input is removing input values of appended input fields by ajax

Question: I have a form with checkboxes that are calling ajax callback on checked. This ajax callback is appending another inputs:
$form['expertise']['op-cat-'.$op_cat['id']]['op-'.$op['id']]['checked'] = array(
    '#type' => 'checkbox',
    '#title' => $op['name'],
    '#default_value' => isset($usr['user_scope']['tid'][$op['id']]) ? 1 : 0,
    '#ajax' => array(
        'callback' => 'activit_full_profile_expertise_ajax',
        'wrapper' => 'expertise-div',
    )
);

Ajax callback:
function activit_full_profile_expertise_ajax($form, &$state) {

    $commands = array();
    $commands[] = ajax_command_html('#expertise-div', render($form['expertise']));
    $commands[] = array('command' => 'reinitializeTooltipster');
    return array('#type' => 'ajax', '#commands' => $commands);

}

In form is also an another managed file input:
$form['image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Profilová fotografia (nepovinné)'),
    '#default_value' => isset($usr['picture']->fid) ? $usr['picture']->fid : 0,
    '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg')),
    '#upload_location' => 'public://user_images/'
);

Everything works fine if image field is not used after checkbox. If checkbox is used before image upload, it brings another input fields, but they are not present in $state['values'] in form validate & submit function (only original checkbox is present). They are not present in validate & submit function called by ajax of this image upload input, therefore they are not present in final validate & submit functions on form submit.
I have another custom ajax callbacks in form, but the appended input values are allways present. Is this a Drupal bug or am I missing something?
Answer: I'm not sure if this is a good solution, but now I'm taking values from $state['input'] instead of $state['values'].


Another user onedrive files using access token

Question:
I'm userX. I need to access userY onedrive files from api and upload files.

When I send request for user token to https://login.microsoftonline.com/tenant/oauth2/token I got it.
POST token Request:
   url: https://login.microsoftonline.com/tenant/oauth2/token
   grant_type: password
   username: userY
   password: ***(my password)***
   resource: ***(my resource)***
   client_id: ***(my client id)***
   client_secret: ***(my client secret)***
Response:
   "token_type": "Bearer",
   "scope": "AllSites.FullControl AllSites.Manage AllSites.Read AllSites.Write Calendars.Read Calendars.Read.Shared Calendars.ReadWrite Calendars.ReadWrite.Shared Contacts.Read Contacts.Read.Shared Contacts.ReadWrite Contacts.ReadWrite.Shared Directory.AccessAsUser.All Directory.Read.All Directory.ReadWrite.All email Files.Read Files.Read.All Files.Read.Selected Files.ReadWrite Files.ReadWrite.All Files.ReadWrite.AppFolder Files.ReadWrite.Selected Group.Read.All Group.ReadWrite.All IdentityRiskEvent.Read.All Mail.Read Mail.Read.Shared Mail.ReadWrite Mail.ReadWrite.Shared Mail.Send Mail.Send.Shared MailboxSettings.ReadWrite Member.Read.Hidden MyFiles.Read MyFiles.Write Notes.Create Notes.Read Notes.Read.All Notes.ReadWrite Notes.ReadWrite.All Notes.ReadWrite.CreatedByApp offline_access openid People.Read profile Reports.Read.All Sites.Read.All Sites.ReadWrite.All Sites.Search.All Tasks.Read Tasks.Read.Shared Tasks.ReadWrite Tasks.ReadWrite.Shared TermStore.Read.All TermStore.ReadWrite.All User.Read User.Read.All User.ReadBasic.All User.ReadWrite User.ReadWrite.All",
  "expires_in": "3599",
  "ext_expires_in": "0",
  "expires_on": "1485157695",
  "not_before": "1485153795",
  "resource": ***(my resource)***
  "access_token": "***here is my access token***"
  "refresh_token": "***here is my refresh token***"

I try to use this token:

First example (is not appropriate: Kevin explained below):
    GET Request
    url: https://api.office.com/discovery/v2.0/me/services
    Header Authorization: Bearer  ***here is my access token***
    Response:
    {
    "error": {
    "code": "-2147024891, System.UnauthorizedAccessException",
    "message": "Access denied. You do not have permission to perform this action or access this resource."
    }
    }

Second example:
    GET Request
    url: http://tenant.sharepoint.com/_api/search/query?querytext='*'
    Header Authorization: Bearer  ***here is my access token***
    Response:
    {"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}

Third example:
    POST Request:
    url: https://tenant-my.sharepoint.com/_api/v2.0
    Header Authorization: Bearer  ***here is my access token***
    Response:
    {"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}

The question is: why I can't use my access token? What I'm doing wrong?

Thanks
Answer: Your first example is a request to the Discovery service, which ordinarily is used to discover the resource ID if you don't already know it. This request will require a token acquired with resourceId == the discovery service URL. Once you have obtained the correct resource ID from the discovery service, you can request a new access token with the new resourceId.
"The question is: why I can't use my refresh token? What I'm doing wrong?":
The refresh token is not a valid token for making API calls, you need the access_token for that. The refresh token is used to get a new access token when it expires.
Comment: Thanks Kevin. As I see 1st example is not one of the best. I understand my mistake  - I've tried to use access token from my resource. I should use access token for discovery service URL. The question "why I can't use my refresh token" should be "why I can't use my access token" and it's current for the rest 2 examples.
Answer:
Solved!
The problem with my requests is "resource: ***(my resource)***".
If I want to access to resource I can't use app id or client id (in my case those two were the same).
Which resource I want - I need token for it. I should read from response for https://api.office.com/discovery/v2.0/me/services list of available resources

So

 1. POST https://login.microsoftonline.com/tenant/oauth2/token with resource "https://api.office.com/discovery/"
 2. GET https://api.office.com/discovery/v2.0/me/services with refresh_token from point 1
 3. POST https://login.microsoftonline.com/tenant/oauth2/token with resource "https://tenant-my.sharepoint.com/" in my case
 4. And use refresh token from point 3 e.g. GET https://tenant-my.sharepoint.com/_api/v2.0/me/drive/special/documents


Coleta de informações em massa de arquivos

Question: Pretendo coletar ctime, atime, mtime e crtime de uma massa considerável de arquivos.
Como solução parcial montei o seguinte scritp:
sudo debugfs -R 'stat <1055890>' /dev/sda1|awk -F': ' -v c='' -v a="" -v m="" 'BENGIN {} $1==" ctime" {c=$2} $1==" atime" {a=$2} $1==" mtime" {m=$2} $1=="crtime" {print c, a, m, $2}'

debugfs 1.42.13 (17-May-2015)
  0x5ade9510:c7eb0e9c -- Mon Apr 23 23:23:12 2018 0x5b05601f:111ab67c -- Wed May 23 09:35:43 2018 0x5ade9510:c7eb0e9c --
  Mon Apr 23 23:23:12 2018 0x5ade9510:c7eb0e9c -- Mon Apr 23 23:23:12
  2018

Pretendo capturar as informações da seguinte forma:
Mon Apr 23 23:23:12 2018, Wed May 23 09:35:43 2018, Mon Apr 23 23:23:12 2018, Mon Apr 23 23:23:12 2018
Onde serão respectivamente ctime, atime, mtime e crtime em um futuro csv.
Como posso tratar as variaveis para pegar somente após " -- "?
Answer: Você pode usar um script awk para resolver o seu problema (script.awk):
BEGIN {
    OFS = ",";
    FS = " -- ";

    print "ctime,atime,mtime,crtime"
}
{
    for( i = 0; i < 4; i++ ){
        split( $(i+2), a, " 0x" );
        b[i] = a[1];
     }

     print b[0], b[1], b[2], b[3];
}
END {
}

Uso:
debugfs -R 'stat <1055890>' /dev/sda1 | awk -f script.awk > saida.csv

Tudo em uma linha:
debugfs -R 'stat <1055890>' /dev/sda1 | awk 'BEGIN{OFS=",";FS=" -- ";print "ctime,atime,mtime,crtime"}{for(i=0;i<4;i++){split($(i+2),a," 0x");b[i]=a[1]};print b[0],b[1],b[2],b[3];}' > saida.csv

Saída (saida.csv):
ctime, atime, mtime, crtime
Mon Apr 23 23:23:12 2018,Wed May 23 09:35:43 2018,Mon Apr 23 23:23:12 2018,Mon Apr 23 23:23:12 2018

Answer: Resumindo minha resposta, o comando completo ficaria:
sudo debugfs -R 'stat <1055890>' /dev/sda1 |
awk -F'--' '{gsub(/0x[a-z0-9:]+/, ""); print $2, $3, $4, $5}' |
sed -r 's/^ //;s/  +/, /g'

Resposta completa:
Com awk não é estritamente necessário atribuir variáveis arbitrárias, uma vez que os valores posicionais já servem ao seu propósito de possibilitar o retorno só daquilo que você quer.
Assim, definindo o separador de campos como a string "--", através da flag -F, é só dar um print nos campos desejados. No exemplo abaixo executei um gsub para também remover os valores hexadecimais:
[stat...] | awk -F'--' '{gsub(/0x[a-z0-9:]+/, ""); print $2, $3, $4, $5}'

> Mon Apr 23 23:23:12 2018    Wed May 23 09:35:43 2018    Mon Apr 23 23:23:12 2018    Mon Apr 23 23:23:12 2018

Por fim, para eliminar espaços indesejados e adicionar as virgulas entre campos, um sed rápido:
sed -r 's/^ //;s/  +/, /g'

O comando completo, de acordo com a pergunta, ficaria:
sudo debugfs -R 'stat <1055890>' /dev/sda1 |
awk -F'--' '{gsub(/0x[a-z0-9:]+/, ""); print $2, $3, $4, $5}' |
sed -r 's/^ //;s/  +/, /g'

Mon Apr 23 23:23:12 2018, Wed May 23 09:35:43 2018, Mon Apr 23 23:23:12 2018, Mon Apr 23 23:23:12 2018

Para fins de desempenho, caso pretenda executar o stat de muitos arquivos, sugiro guardar o resultado completo de todas as execuções de stat em um só arquivo e depois executar esse awk | sed uma só vez, passando o arquivo de stats como entrada para o awk:
awk -F'--' '{gsub(/0x[a-z0-9:]+/, ""); print $2, $3, $4, $5}' arquivo-de-stats |
sed -r 's/^ //;s/  +/, /g'

Answer: Utilizando o awk, você pode definir como delimitador o conjunto "-- ".
Um script simples utilizando seu comando como exemplo ficaria:
#!/bin/bash

var=$(sudo debugfs -R 'stat <1055890>' /dev/sda1|awk -F': ' -v c='' -v a="" -v m="" 'BENGIN {} $1==" ctime" {c=$2} $1==" atime" {a=$2} $1==" mtime" {m=$2} $1=="crtime" {print c, a, m, $2}')

ctime=$(echo $var | awk -F"-- " '{print $2}'| rev | cut -d" " -f3-7 | rev)
atime=$(echo $var | awk -F"-- " '{print $3}'| rev | cut -d" " -f3-7 | rev)
mtime=$(echo $var | awk -F"-- " '{print $4}'| rev | cut -d" " -f3-7 | rev)
crtime=($echo $var | awk -F"-- " '{print $5}')
echo "$ctime", "$atime", "$mtime", "$crtime"

Mon Apr 23 23:23:12 2018, Mon Apr 23 23:23:12 2018, Mon Apr 23
  23:23:12 2018, Mon Apr 23 23:23:12 2018

Explicação:
No awk, a flag -F indica o delimitador que será usado, e o print indica a coluna que será exibida.
Como o resultado desse parse traz um conjunto de caracteres não desejados, foi necessário utilizar o cut em conjunto com o rev para remover a última coluna e manter apenas a data.
Obs.: Para o crtime, como não existe a última coluna, podemos dispensar o cut no filtro.
Se for rodar o comando muitas vezes, recomendo encapsular a solução abaixo em uma função:
function parse_date {
  ctime=$(echo $1 | awk -F"-- " '{print $2}'| rev | cut -d" " -f3-7 | rev)
  atime=$(echo $1 | awk -F"-- " '{print $3}'| rev | cut -d" " -f3-7 | rev)
  mtime=$(echo $1 | awk -F"-- " '{print $4}'| rev | cut -d" " -f3-7 | rev)
  crtime=$(echo $var | awk -F"-- " '{print $5}')

  echo "$ctime", "$atime", "$mtime", "$crtime"
}

Depois você chamaria a função passando o resultado do seu comando como argumento:
parse_date "$var"

Mon Apr 23 23:23:12 2018, Mon Apr 23 23:23:12 2018, Mon Apr 23
  23:23:12 2018, Mon Apr 23 23:23:12 2018


Countermeasures versus incoming DNS reflection attack

Question: i am currently experiencing a DNS reflection attack towards my server.
I am getting a massive amount of answers via UDP from Port 53 that my server has never asked for:

02:53:57.626156 IP (tos 0x0, ttl 50, id 0, offset 0, flags [DF], proto UDP (17), length 267) REFLECTING.OPEN.DNS.SERVER.domain > mydomain.com.11803: 30781- q: RRSIG? . 0/13/1 ns: . NS A.SOMENAMESERVER.NET., .[|domain]
02:53:57.626382 IP (tos 0x0, ttl 50, id 0, offset 0, flags [DF], proto UDP (17), length 267) REFLECTING.OPEN.DNS.SERVER.domain > mydomain.com.11803: 30781- q: RRSIG? . 0/13/1 ns: . NS B.SOMENAMESERVER.NET., .[|domain]
02:53:57.627804 IP (tos 0x0, ttl 50, id 0, offset 0, flags [DF], proto UDP (17), length 267) REFLECTING.OPEN.DNS.SERVER.domain > mydomain.com.24188: 30781- q: RRSIG? . 0/13/1 ns: . NS C.SOMENAMESERVER.NET., .[|domain]

So the countermeasure i thought about is limiting the number of incoming Packets with a source port of 53. Should be no problem with iptables right?
So i put this together with my little iptables skills:

-A INPUT -s A.TRUSTED.NAMESERVER -j ACCEPT
-A INPUT -s B.TRUSTED.NAMESERVER -j ACCEPT
-A INPUT -s C.TRUSTED.NAMESERVER -j ACCEPT
-A INPUT -p udp -m udp --sport 53 -m limit --limit 10/min -j LOG --log-prefix "53 DENY FROM: " --log-level 7
-A INPUT -p udp -m udp --sport 53 -m limit --limit 10/min --limit-burst 20 -j ACCEPT

Logging the attack and bursting it when it gets too much.
Well i would not write here if it worked out.
Something must be wrong and i cant figure out what. It logs correctly but it doesn't DROP any packages even if the number is > burst limit.
I am very thankful for help.
Greets
Marcel
Answer: I can't see any DROP in your rules. Perhaps you want to append
-A INPUT -p udp -m udp --sport 53 -j DROP

at the end of your rules?
Comment: oh my... ofcourse how could i be so blind... thanks a lot! now it works!
Comment: how about accepting my answer then? I'm trying to gain some reputation in here :-)
Comment: i couldnt do it before for some reason it said wait 7 minutes - so i did :)
Answer: If the reflected packets are being sent to a closed UDP port, then the kernel on the receiving end is going to be generating an ICMP error message. This processing is quite cheap, so the processing time needed to process the UDP packet and send an ICMP error is likely to be the least of your concerns.
In some scenarios the upstream bandwidth consumed by the ICMP errors may be a real concern. In such scenarios, rate limit of the ICMP errors may be needed.
Silently dropping all the UDP packets without ever sending an ICMP error is however not advisable. The ICMP errors is the only signal the owners of the involved DNS servers have, that could tell them, that their DNS server is involved in a reflection attack. In other words, by silently dropping the packets, you are hiding the attack from the very people, who could mitigate it.
It is technically possible to design a DNS server with automatic mitigation of reflection attacks. However such mitigation would have to rely on ICMP error messages. If such mitigation methods become widespread, you would make yourself an easier target for A DDoS attack by silently dropping all attack traffic.
If the reflected UDP packets would be arriving at an open UDP port, then processing those reflected packets would become more expensive in terms of CPU time. In such scenarios it would be advisable to use iptables rules to REJECT packets whose source port is 53 or any other used by services commonly abused in reflection attacks and whose destination port is that of the service you are running. I would still not DROP them, but rather use the REJECT target to produce an ICMP error identical to what is seen on a closed port.


Drupal 7 Exposed Filter Display Text

Question: I have an exposed filter in drupal, but some text is not displaying as expected. One list displays exactly as I want and that is the Acoustic Guitars as shown in the picture, but I cannot for the life of me figure out why the other filters are not displaying like the Acoustic Guitars. Here is the picture, does anyone know what settings I would need to change to get this to display the description instead of the category like the Acoustic Guitars list?
Answer: I'ts in your content type. You might have mistaken the label with the value, or not used the label at all. Open the content type, edit each field and change the allowed values as described above the textarea.
If I'm not mistaken it is
<code>Label|value
</code>
Comment: Is there a way to do this via the admin panels?
Comment: `/admin/structure/types` and then choose the content type, which contains the wrong fields. Hit the manage fields link and then edit all fields. If you can't see the manage fields link, make sure the `fields ui` module is enabled.

Drupal 7 Exposed Filter Display Text


Multilanguage in IE does not allow to switch languages

Question: My drupal site is built with 2 languages English/Portuguese, and the default language is English.
But in IE the default language (English) is overwritten and it only displays the  Portuguese version, and if i click the English icon it does not change to English.
However if i browse with an English computer the English is displayed, but i can't still switch from Portuguese to English.
Some advice is appreciated.
Comment: Try to use another jQuery version. With this error i can't say what is actually the problem.
Comment: Make sure there are no errors in your console. IE doesn't like javascript errors for example. IE doesn't like console.log's as well.
Comment: The only error i get is in JQuery https://www.dropbox.com/s/kvv7p0v47m9ejyn/Untitled.png?dl=0
Comment: `{for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e)  {throw new Error("Syntax error, unrecognized expression: "+e)}  ,a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s`
Comment: And you get no error, if you click the language switch button?
Comment: The only error that appears when clicked is that shown above.
Comment: Yes is too much broad, will try to do that, thanks for the input. Cheers
Answer: This answer is as simple as ticking a checkBox for the browser language, that for some reason in IE and Edge override the manual language switcher.
The reason that i didn't find this before was that it was in a tab far from view.


What are large read requests in sshfs and is it recommended to enable them?

Question: sshfs has the following option:

<code>  -o large_read
         issue large read requests (2.4 only)
</code>

What exactly does this do and how large are large read requests?
Would it be recommended generally or specifically for me to enable this (and is it enabled by default)?
Use: I use sshfs to edit a lot of code.
Thanks!
Answer: Large read requests are only valid for FUSE version 27+ and Linux kernels not fresher than 2.4 (2.6 onwards use dynamic sizing).
From http://manpages.ubuntu.com/manpages/precise/man8/mount.fuse.8.html:
<code>large_read
      Issue  large  read  requests.   This can improve performance for
      some filesystems, but can also degrade performance. This  option
      is only useful on 2.4.X kernels, as on 2.6 kernels requests size
      is automatically determined for optimum performance.
</code>
For editing code, you won't benefit much from this option. Chances are, you don't have an ancient 2.4-something kernel.


How to change user field value after node form is submitted?

Question: I currently have a user field called field_reputation with a default integer value of 0 (if a user registeres).

The idea is that this field increases when certain actions are executed. For example, when a user publishes a new article, field_reputation should be its current value + 10.
I am trying to achieve this using a form hook:
function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'node_article_form') ) ) {
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_increase_reputation';
        }
      }
}

And then this function is called:
function _increase_reputation(array &$form, FormStateInterface $form_state) {
  // Do something here
}

However I can't seem to figure out what code should be written in this function.
Comment: That should be done in `hook_node_presave()`, a submit handler is too late as the node is already saved
Answer: As @Clive says, form submit handler is a bit too late. Do it in hook_node_presave or hook_entity_presave. If you do it in hook_node_presave:

Check the node type first: if ($node->bundle() === 'article')
Get the current user:
$user = User::load(\Drupal::currentUser()->id());
Then set the field value: $value = (int) $user->get('field_reputation')->getString() + 10; $user->set('field_reputation', $value); (I'm not 100% sure on this code, but I'm sure there are better ways to do it when you have more than 5 minutes :D. Feels dirty to use getString() and then type-cast it into int)
Save the user entity with $user->save();

If you use hook_entity_presave then you just need to check for the entity type additionally: $entity->getEntityType->Id() === 'node'
Comment: Thanks for your reply! Could you help me out a little more? I am quite newby at Drupal... I tried using the following code: https://jsfiddle.net/6bst99ut/1/. But it does not work, nor gives me any errors.
Comment: Any updates? :)
Comment: @Rubenxfd, if you're putting that code in `mytheme.theme`, it might not work. Create a new module and put that code in the `.module` file. Also make sure you put `use \Drupal\user\Entity\User` at the top of the module file.
Comment: I have tried adding a custom module like you said, but provided code does nothing :(
Comment: Did you enable your custom module?
Comment: Yes I did, the module is loaded correctly, but when I press "save" when writing an article. The article is published but nothing happens to the user field_reputation. The code in my module: https://jsfiddle.net/gf77gtt6/1/
Comment: What's the current value in `field_reputation`? Can you do some debugging and see where it's failing? What's in `$value` before `$user->set`? Do you get any warnings/errors in your logs? I'm a bit new to D8 myself so hope someone else can chime in.
Comment: Take a look at this answer too: https://drupal.stackexchange.com/questions/180388/how-do-i-change-a-field-with-hook-node-presave
Comment: @Rubenxfd I'm sorry, forgot we're changing the user entity and not the node so we need to save the user after changing it with $user->save()


how does rpart handle missing values in predictors?

Question: From the ?rpart documentation -

na.action : the default action deletes all observations for which y is missing, but keeps those in which one or more predictors are
  missing.

How does it impute missing values in predictors?
Answer: This is where the surrogate variables come in - for each split, observations where the split variable is missing are split based on the best surrogate variable, if that's missing by the next best and so on, this is detailed in:

Therneau, Terry M. & Atkinson Elizabeth J. (March 28, 2014). An Introduction to Recursive Partitioning Using the RPART Routines, Mayo Foundation, section 5.

The document is accessible through rpart help (pdf).
Comment: I am struggling to understand this sentence: "or each split, observations where the split variable is missing are split based on the best surrogate variable".
Observations where the split variable is missing are split? How is it possible to split a variable is missing? Also I am not sure about the definition of a split variable.
Comment: This by no means answers your question completely, but maybe my answer in a related question illustrates the idea better. The linked documentation in the above answer explains in detail how the surrogate split is calculated. https://stats.stackexchange.com/a/345033/


manutenção off-line dos módulos Python

Question: Devido a problemas com internet onde estou morando, preciso manter os pacotes e instalar novos sem a conexão com a internet, mantendo um microservidor montado em NanoPi para que nele eu obtenha os arquivos.
Qual ferramenta e procedimento devo adotar para manter e instalar tais módulos do Python?
Answer: Uma solução é utilizar a ferramenta minirepo que permite fazer download de pacotes Python do PyPI sem internet.

A maneira mais fácil de instalá-lo é usar o pip:
$ pip install minirepo

Ou faça o download do arquivo do pacote em https://pypi.python.org/pypi/minirepo em seguida:
$ tar xvzf minirepo-1.0.3.tar.gz
$ cd minirepo-1.0.3
$ python setup.py install

Você também pode usar o git:
$ git clone https://github.com/sganis/minirepo.git
$ cd minirepo
$ python setup.py install

A documentação de uso é simples.

manutenção off-line dos módulos Python


Triangle Bisector Challenge

Question: I've found this olympic geometry problem, which remains to be unsolvable by all my teachers and friends;
In a triangle $ABC$ $[BE],[CD]$ are bisectors, $[BE]\cap[CD]=F$
$m(\widehat{FDE})=18^\circ$
$m(\widehat{FED})=24^\circ$
According to the given knowledge find $m(\widehat{EBC})=\alpha$ (m: the measure of the angle) (sometimes used differently in other countries)
My Attempts
This problem has a complete smackdown on me, I have tried to take the symmetric of point $D$ (in respect to line $BC$) which I named $D'$ then drew an edge between $D$ and $D'$ $DBD'C$ is also a deltoid....(1)
I also was able to find that $m(\widehat{A})=96^\circ$...(3)
And that $\alpha+<FCB=42^\circ$
I am now stuck here, a full solution might be incredible but I am open to any sorts of direction.
Thank you:))
Answer: The hint.
We have $$\frac{\beta}{2}+\frac{\gamma}{2}=18^{\circ}+24^{\circ}$$ or
$$\beta+\gamma=84^{\circ}.$$
In another hand, by law of sines we obtain:
$$\frac{DF}{EF}=\frac{\sin24^{\circ}}{\sin18^{\circ}}.$$
from this system we can find $\frac{\beta}{2}$.
I got $\frac{\beta}{2}=6^{\circ}$.
Answer:
As you noticed, $\widehat{EFD}=\widehat{BFC}=\pi-\frac{B}{2}-\frac{C}{2}=90^\circ+\frac{A}{2}=138^\circ$ from which $A=96^\circ$.
By the sine theorem
$$ \frac{\sin 18^\circ}{CE}=\frac{\sin(C/2)}{ED},\qquad \frac{\sin 24^\circ}{BD}=\frac{\sin(B/2)}{ED}, $$
hence
$$\frac{\sin(B/2)}{\sin(C/2)}=\frac{\sin(24^\circ)}{\sin(18^\circ)}\cdot\frac{CE}{BD}=\frac{\sin(24^\circ)}{\sin(18^\circ)}\cdot\frac{\frac{ab}{a+c}}{\frac{ac}{a+b}}=\frac{\sin(24^\circ)}{\sin(18^\circ)}\cdot\frac{\sin B}{\sin C}\cdot\frac{\sin(A)+\sin(B)}{\sin(A)+\sin(C)}$$
leads to a trigonometric equation in $\sin(\alpha)=\sin(B/2)$, since $\frac{C}{2}=42^\circ-\frac{B}{2}$ and $\sin(A)$ is known.
Comment: I got $\tan\frac{\beta}{2}=\sqrt3-4\sin24^{\circ}$ and from here $\frac{\beta}{2}=6^{\circ}$. It seems there is a nice solution for this problem. If so then it's really beautiful problem.
Comment: @MichaelRozenberg: I agree on the whole line.
Comment: Could you tell me what software you used to draw the figure?
Comment: @pisco125: it is just www.geogebra.org

Triangle Bisector Challenge


im having a problem in javascript output it is not showing

Question: I want to solve this question with CSS, form, javascript and I tried to do javascript and included 3 if statements but it not really showing me the output
is it because the if statements should each be closed with brackets? or maybe there is a mistake in the way I write the variables I tried many things, and it's not working please help I'm still a beginner programmer and I can't figure it out

 function myFunction(){

var Fname= document.getElementById("fname").value;
var Lname= document.getElementById("lname").value;
var Name = Fname + "   " + Lname;

var date= document.getElementById("date").value;

var tr= document.getElementById("t").value;

var tour= document.getElementById("tour").value;

var request= document.getElementById("request").value;

var v = Number(document.getElementById("visitor").value);
var city = document.getElementById("city").value;
var x="";
var y="";
var z="";
    var total=x+y+z;

{
        if (v<=0){

                v=prompt(" minimum visitors are 1 try again");
                }

         else if (city == "Amman $50") {
         x = v * 50;
         }

         else if (city == "Salt $20")  {

         x = v * 20;
         }

         else   {

         x = v * 10;
         }

  }

  {

           if ( tour==Yes )
                 {
             y= 50;
                  }
            else {
             y=x;
                 }
               }

{

            if (trans==Car)
                {
                z= 30;
                        }

                 else{
                 z=20;
                      }

    }

document.getElementById("result").innerHTML = "Arrival date" + date + "
"
+ Name.toUpperCase() +
"
"+" City " + city + v + "visitors"
+"
" + " transportation " + tr +
"
" + "tour leader :" + tour
"
"+ "any medical:" + request +
"
" +"Amount=$ " + total ;

return false;
};

 body{
margin:20px;
text-align:center;
}

form{
background-color:orange;
}

div.sec {
margin-left:300px;
}

div.transpo {
margin-right:450px;
}

 Visit J ordan

<form>

    <input type="text" id="fname" size="30" placeholder="First Name">

    <select id="city">
      <option value="select your city "> Select your city </option>
      <option value="50 ">Amman $50</option>
      <option value="20 ">Salt $20</option>
      <option value="10 ">Jarash $10</option>
    </select>

    Number of visitors

    <input type="number" id="visitor">

     Transportation

    <input type="radio" id="car" name="transportation" value="car" id="t">
    car $30
    <input type="radio" id="bus" name="transportation" value="bus" id="t">
    bus 20$

    <input type="text" id="lname" size="30" placeholder="Last Name">

    Arrival Date:

    <input type="date" id="date">

     Any medical Request:

    <textarea rows="1" cols="20" id="request"></textarea>

     Tour Leader $50

    <input type="radio" id="yes" name="tour" value="yes" id="tour">
    yes
    <input type="radio" id="no" name="tour" value="no" id="tour">
    no

  <button type="button" onclick="myFunction()"> PREVIEW </button>
  <button type="submit" onClick=""> Submit </button>
</form>

Comment: Check your browser console and see if you have errors
Comment: The console says `Invalid or unexpected token line 122`. You are missing a few characters at `+ "visitors
  "" +`. Your script crashes at start, it's not even running at all.
Answer: If you open your console in your browser (pressing F12 as default) you can see that the Javascript is returning an error.
Uncaught SyntaxError: "" string literal contains an unescaped line break

This refers two missing quote marks on row 174 and row 176, both are missing on the end of the file.
However your code still don't work, if you press preview you get another error
<input type="radio" id="car" name="transportation" value="car" id="t">
<input type="radio" id="bus" name="transportation" value="bus" id="t">

on these two lines you specify id twice which is not allowed.
Tips so you can more easily solve these issues on your own:

You should start to use the console to find errors in your code.
Try to reread your code and look for small errors like a missing "
If you are unsure how something works like a html or javascript feature use websites like w3school to look up well expained documentation.

Good luck in your future coding adventures.


Proof that $ e^{-x} = x $ has only one solution

Question: I want to prove that the equation $ e^{-x} = x $ has only one solution in $ \left(0, 1\right) $. Here is my proof but I am not sure whether it's correct or not.
Proof:
Define $ f(x) = e^{-x} - x $. If the equation above has more than one solution, then according to Rolle's Theorem, there exists a minimum or a maximum in $ \left(0, 1\right) $, because $ f(x) $ is continuous.
According to Fermat's Theorem, if $ f(x) $ has an extrema point, then there exists a $ c \in \left(0, 1\right) $  such that $ f'(c) = 0 $.
But if $ f'(x) = -e^{-x} - 1 = 0$.
$$ -e^{-x} = 1 $$
$$ e^{-x} = -1 $$
$$ -x = \ln(-1) $$
However, the  domain of $ \ln(x) $ is $ \left(0, +\infty \right)$, which is a contradiction. Therefore, the equation has at most one solution.
$ f(x) $ is a continuous function because it's the sum of two continuous functions. Therefore, according to the Intermediate Value Theorem, if there exists a $ x_1 $ such that $ f(x_1) > 0 $ and there exists a $ x_2 $ such that $ f(x_2) < 0 $, then there exists an $ x $ such that $ f(x) = 0$.
$ f(0.1) = 0.8 $
$ f(0.9) = -0.49 $
Therefore there exists at least one solution to the equation.
Thus there exists exactly one solution to the equation.
Is my proof correct?
Comment: I'm bothered by your line $-x=\ln(-1)$, because $\ln(-1)$ is undefined $-$ so it's not so much a _contradiction_, as a _meaningless statement_. I think it's cleaner just to say that since $e^{-x}$ is always positive, $e^{-x}=-1$ has no solutions.
Comment: yes, your proof seems correct to me :)
Comment: In your final step, how do you know that $f(1) = .8$ and $f(.9) = -.49$? (And aren't those statements actually false?)
Comment: A stylistic comment: you should use correct grammar when writing math; don't just write down a list of equations with no punctuation.
Comment: @littleO Those are approximations. I just plugged the values in the calculator
Comment: How do you know the calculator was correct?
Comment: One shouldn't make false statements in a proof. The statement $f(.1) = .8$ is false.
Comment: $x-e^{-x}$ is increasing, hence injective: $x-e^{-x}=0$ cannot have more than one solution.
Answer: Let $f(x)=e^{-x}-x \implies f'(x)=-e^{-x}-1<0$. So $f(x)$ is a decreasing function, hence $f(x)=0$ has at most one real root. Next since $f(-\infty)>0$ abd $f(\infty)<0$ by IVT $f(x)=0$ will have exactly one real root.
Further since $f(0)=1>0$ and $f(1)=e^{-1}-1<0$, the single real root lies in $(0,1).$


Uninstall joomla from xampp

Question: I've installed xampp on local computer (local host) and then installed joomla on xampp, now I need to remove only the joomla completely from xampp. How do I do it.
Answer: Try locating in ../xampp/htdocs/you-folder. You can delete the whole folder for your website files.
As for database, run XAMPP and type localhost in your browser. Navigate to your database and delete it.
Hope this helps.
Answer: Delete site folder via Explorer, delete database via phpMyAdmin.

Uninstall joomla from xampp


How do i prevent mouse and touch events from trigger for DisplayObjects below a backdrop

Question: I have several display objects in createjs and event using easeljs i want to prevent from mouse and touch event passing through them.
i want like a easy one liner like .mouseEnabled or .mouseChildren is there something will will prevent any other interaction for the objcts below this. i can try adding all events to a backdrop movieclip which tint background color and prevent default and stopPropogation will that help?
so how to i prevent from any type of interaction taking place in canvas just by placing a displayobject that's like wall which will not allow the other displayobjects from getting click, mouseover or touch events.
Answer: You can add obj.mouseEnabled= obj.mouseChildren = false; to any you don't want to receive events.
If you just want to block events with a child on top, simply add a mouse handler to it.
cover.on("click", function(){});

You don't need stopPropagation, since that will only prevent events from bubbling in the current hierarchy (ie, surfacing an event to its direct parent). Events do not "pass through" objects that have mouse handlers on them.
Hope that helps!


Proving that a certain sequence of functions contains a subsequence uniformly convergent

Question: Let $\{f_n\}_n$ be a sequence of real-valued continuous functions defined on $[0,1]$ such that $\int^1_0|f_n(y)|dy\leq3$ for all $n$. Define $g_n:[0,1]\rightarrow\mathbb{R}$ by
$g_n(x)=\int^1_0\sqrt{x+y}f_n(y)dy$
I have to prove that $\{g_n\}_n$ contains a subsequence that converges uniformly on $[0,1]$.
I really don't know where to start, could you help me please?
Comment: Sounds typical of problem where the key is to find a compact subset of the space of functions on $[0,1]$ under the uniform norm which contains all $g_n$'s.
Comment: My very first instinct is to grab for [Arzelà-Ascoli](http://en.wikipedia.org/wiki/Arzela-Ascoli).
Comment: yeah, that was my first instinct too. But I don't know how to apply it
Comment: $|g_n(x)|\leq 3\sqrt{x+1}$ so the sequence is pointwise bounded. $|g_n(x)-g_n(y)|\leq 3 \sup_{z} |\sqrt{x+z}-\sqrt{y+z}| \leq 3\sqrt{|x-y|}$ so it's also equicontinous.
Comment: yeah the $g_n's$ are equicontinuous and $|g_n(x)|\leq 3\sqrt{2}$ so it suffices to find a compact subspace of the continuous functions with the uniform norm that contains all $g_n's$ and apply Ascoli-Arzelà
Comment: I don't really know why you want to find such a subspace, the sequence is already precompact...(If you must though, the sequence is in the ball centered at 0 and radius $3\sqrt{2}+3$ of $C^{0,1/2}$)
Comment: What result are you applying? To say that it's precompact (what you mean precisely with precompact? that there is a subsequence converging?)
Comment: A set is precompact if it has compact closure. Arzelà-Ascoli tells you that a subset of $C[0,1]$ is precompact if it is pointwise bounded and equicontinous. Since in metric spaces compactness is equivalent to sequential compactness you have your result.
Answer: Notice that $$g_n'(x)=\int_0^1\frac{f(y)}{2\sqrt{x+y}}\,\mathrm dy,$$ so that $$|g_n'(x)|\leq \int_1^1\frac{|f(y)|}{2\sqrt{x+y}}\,\mathrm dy\leq\frac1{2\sqrt{x}}\int_0^1|f(y)|\,\mathrm dy\leq \frac{3}{2\sqrt{x}}.$$ This implies that all the derivatives of all the $g_n$ are bounded in $[\varepsilon,1]$ for all $\varepsilon\in(0,1)$. Ascoli-Arzelà implies that there are uniform convergent subsequences there. This does not solve you problem, but may be useful!


Is multiple imputation required when performing an external validation of a published Cox model?

Question: I have a sample size of n=150 - I know this may not meet the required number of events and non events, but the analysis still has to be performed.
I am missing 50 sample's results. Some have no entries (4 independent variables), and some have 1 or 2.
To account for this, would multiple imputation be necessary or recommended?
Answer: No. Or maybe yes. The "Cox model" isn't externally validated, but a Cox model may provide inputs to develop a risk model. The risk model, therefore, is what you validate externally. The risk model should also tell you how to handle missing covariate data. The problem is that if I'm an oncologist counseling my patient on risk, I can't multiply impute their missing family history with my N of 1. The model has to tell me how to handle that.


CSS is not aggregated anymore - how to debug?

Question: On a rather complex Drupal 6 site (multi domain etc.) CSS files are not aggregated anymore and CSS style definitions appear directly inside the HTML pages.  The output of ´drupal_get_css´ is ok, but when I installed the Advanced CSS/JS Aggregation module, I see that the module reports the aggregated css files as Missing files.  But when these files are opened manually, they are ok.  The problem itself is not related to the the advagg-module, I only enabled it for debug reasons.
I have not switched themes on the site affected, but I have been playing around with a new theme (mobile jquery) and a correcponding jquerymobile module on a different module from the same installation.  I do not currently think, that the problem has been caused by this module.
I guess the problem is caused by some module weights, but I am having trouble debugging the theming process.  I am looking for help, where I should start debugging, why the aggregated CSS files are not used.
Update:
I have edited drupal_add_css to default to not preprocess files.  The difference is, that each css-block is inserted in a seperate style statement, whereas right now, only a single aggregated CSS style statement is generated.  So I am really tryng to find out, why I am ending up with the long css style definition, instead of a link to the aggregated stylesheet.
Comment: Only CSS Files added with `drupal_add_css` will be aggregated.
Comment: @kantu yes thank you, I should have been clearer about that.  I am of course using drupal_add_css and the aggregation was working until recently, obviously except parts where explicitely specified not to be included in the aggregate file.  Now the aggregate files are generated, but they are not used inside the generated HTML pages.  Instead the complete CSS data is included in the pages.
Comment: If you disable advagg, and enable JS and CSS optimization on admin/settings/performance, do you still have the problem?
Comment: @MPD yes, the problem occured before enabling advagg and persists after disabling and uninstalling it.
Comment: So you edited core and now something weird is happening?
Comment: @MPD No, I have not "hacked" anything.  I am debugging a problem by trying to narrow it down where it occurs and I am asking for help in debugging it.  My problem is that drupal_get_css initially returns the correct information into the the style section of the theme variables, but it is probably overwritten by some preprocess functions.  I am asking where I could systemetically find the relevant hooks.
Answer: I am extremely sorry, but I have found out that the problem was not caused by Drupal.  It seems that the a proxy has been installed by the ISP that automatically compresses pages and rewrites stylesheets to be included into the page directly.
The pages work correctly when being fetched via other networks.
Comment: Interesting and good job tracking this down.  Was this a normal ISP or a mobile carrier?  Broadband or dial-up?  I have only heard of mobile carriers doing this.


Can anyone help with solving these questions on vectors?

Question: Given the vectors:
a =(−7,3,−10),b =(2,1,5), and c =(18,4,m), with m being a real number.
e) Use the determinant det (a,b,c) to determine m so that the three vectors are linear
dependent.
f) Calculate for the m value from the previous part the coefficients α and β in the linear
combination: c = αa + βb.
Thanks
Comment: What have you tried?
Comment: for e) I've tried putting the vectors into a matrix to get the determinant. For f) I don't actually know where to start
Answer: e) The vectors are linearly dependent if the determinant ($510-13m$) is zero.  Solve that.
f) Plug in your $m$ and solve for your $\alpha$ and $\beta$.
Comment: So just work out 510-13m=0 and solve for m?
Comment: Thanks so much for your help!!


Eliminating blank gap row after row

Question: I would like to eliminate blank gap row after row! Please refer to the pic for better overview. What is wrong with the code? notepad format seems fine while when viewed from excel, space just occur for every entries including the first time after the header input
Comment: python 2.7 here
Comment: Even though your problem is solved make sure you look at the duplicate question read the accepted answer for *why* this was happening.  Also, if Leuthus's answer helped you, upvote his answer and mark it as accepted.
Answer: Depending on the python version you are using:
# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

Credits to: https://stackoverflow.com/a/3348664/5415084
So, in summary: python 3 requires an additional parameter newline='' while using the w parameter and python 2 requires the wb parameter while opening the file.
Comment: `"sample_data.csv"` needs to be opened `"rb"` not `"wb"`.
Comment: @KaelTee:  Your `"sample_data.csv"` is blank because on a previous run of your program it was opened for writing (`with open("sample_data.csv", "wb") as f`).  So when you call `next(reader)` there is no next row because there are no rows in the file.  Opening a file for writing overwrites the existing file.
Comment: python 2.7 here
Comment: Did you try what's been described above? Is it working for you?
Comment: i merely added "b" in wb `with open("sample_data.csv") as f, open("out.csv", "w") as out:` however error returned
Traceback (most recent call last):
  File "C:\Users\xxxx\Desktop\Function 6 - still in progress.py", line 7, in
    next(reader)
StopIteration
Comment: Change 2 - `with open("sample_data.csv", "wb" ) as f, open("out.csv", "wb") as out:`
Traceback (most recent call last):
  File "C:\Users\Acer\Desktop\Function 6 - still in progress.py", line 7, in
    next(reader)
IOError: File not open for reading
Comment: Is the previous run still running?
Comment: previous refering to the first change? @Steven Rumbalski Traceback (most recent call last):
  File "C:\Users\xxxx\Desktop\Function 6 - still in progress.py", line 7, in
    next(reader)
StopIteration
Comment: use `rb` parameter on the file you will read from and use `wb` param on the file you will write to. Just like @StevenRumbalski said.
Comment: @StevenRumbalski IT WORKS NOW! As you said, my sample_data.csv is blank. Thank ou!

Eliminating blank gap row after row


Exercises to speed up power chord strumming

Question: I've been learning for a while, and can play power chord songs with simple rhythms (like Boulevard of Broken Dreams, Polly, etc). However, most interesting rock songs seem to have a complicated mixture of full on strumming and palm muting. Playing this at slow speeds is fine, but at fast speeds, at which the song has usually been recorded, trying to palm mute at the right places becomes tricky.
An example of such a song is Basket Case. Each chord is played for 2 bars (8 beats), some of them have full strums at 1st and 7th beats, some at 1st and 6th, and doing this at fast speeds seems almost impossible. Would it be rather better to just play along and palm mute at random places, at your own judgement, or continue to speed up this "precise" palm muting?
Comment: Welcome to the Music Stack Exchange Beta! This is a good question, but can you elaborate on your actual question a little more?
Answer: You can definitely start slow, but go for precision here- these will not be difficult to play once you become a bit more proficient.
There are some really fast songs with intermittent palm muting from bands like Al di Meola, Dragonforce and Yngwie Malmsteen - have a listen to them to see what is possible with practice.


How determine the right xml to write out

Question: <?xml version="1.0" encoding="UTF-8"?>
<idmef:IDMEF-Message version="1.0"  xmlns:idmef="http://iana.org/idmef">
 <idmef:Alert messageid="abc123456789">
   <idmef:Analyzer analyzerid="bc-corr-01">
     <idmef:Node category="dns">
       <idmef:name>correlator01.example.com</idmef:name>
     </idmef:Node>
   </idmef:Analyzer>
       <idmef:CreateTime ntpstamp="0xbc72423b.0x00000000">2000-03-09T15:31:07Z
   </idmef:CreateTime>
   <idmef:Source ident="a1">
     <idmef:Node ident="a1-1">
       <idmef:Address ident="a1-2" category="ipv4-addr">
         <idmef:address>192.0.2.200</idmef:address>
       </idmef:Address>
     </idmef:Node>
   </idmef:Source>
   <idmef:Target ident="a2">
     <idmef:Node ident="a2-1" category="dns">
       <idmef:name>www.example.com</idmef:name>
       <idmef:Address ident="a2-2" category="ipv4-addr">
         <idmef:address>192.0.2.50</idmef:address>
       </idmef:Address>
     </idmef:Node>
     <idmef:Service ident="a2-3">
       <idmef:portlist>5
       </idmef:portlist>
     </idmef:Service>
   </idmef:Target>
   <idmef:Classification text="Login Authentication">
     <idmef:Reference origin="vendor-specific">
       <idmef:name>portscan</idmef:name>
       <idmef:url>http://www.vendor.com/portscan</idmef:url>
     </idmef:Reference>
   </idmef:Classification>
 <idmef:Assessment>
     <idmef:Impact severity ="high" completion ="failed" type ="file" >
     </idmef:Impact>
 </idmef:Assessment>
 </idmef:Alert>
 </idmef:IDMEF-Message>

I'm working with a xml messaging system, where a message packet is read from a queue, and applied against a rule with a pattern in it. If the pattern matches, the rule fires and some elements, node etc of the xml are read and stored. The definition of what to be read from the message is defined using Xpath expression. For example, the following xpath takes the severity attribute and store it.
name.set(".//idmef:Classification/idmef:Assesment/idmef:Impact/@severity","high");
So, I would take that xpath, compile it, and read the serverity attribute and store for latter use.
When I go to create the new XML message using the stored value, there may be a case that the completion and type attribute are mandatory.
So question is, how do I check if those attributes need to be written out. I know that schema is involved somehow, but how do you do it.  More to the point, if the user selects only the severity attribute, how would I go about, adding in the rest of the structure, like Classification, Message and other elements, when have additional xpath lookups, for example down at
Bob.
Comment: This XML is not well-formed. Are you missing some of it?
Comment: Yea i'm missing a wee bit.
B
Comment: Ubtil you have well formed xml you cannot do anything with it - so please provide us with the correct xml
Comment: I'm not certain what you are trying to do. It sounds like the trouble is that you want to create a well formed, and valid XML message. You can get the well-formed, but to validate you need to know the schema.
Comment: Yes, I want to do. When the user creates a xpath expression and binds a suitable value around it, I want to take that and build suitable xml around that xpath. I have the schema.

Bob.
Comment: The schema is huge. It runs to 80 odd pages. So any ideas. Is it a case of somehow flattening the schema, some mechanical process?
Comment: If somebody specifies this.
name.set(".//idmef:Classification/idmef:Assesment/idmef:Impact/@severity","high");

I want to build the xml around it which is well formed.
Comment: Its also worth mentioning that the xml is being written out using the xsd generated c# classes before being serialize.
Comment: I was using XMLSpy this morning, and it can take the schema and write out a fully well formed xml document from it. So their must be a way of reading the schema and building the xml from it.
Answer: The commenters are correct - you need to first fix your XML to make it well formed.
However, If I understand your problem correctly, you need write out some XML, adding or changing some attributes.
If this is what you need I would try using an XSL transform to add the attributes.
Here is a modified version of the identity transform that should be close to what you need.
if you need some conditional logic then surround the attribute tags with    xsl:if
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:idmef="http://iana.org/idmef" xpath-default-namespace="http://iana.org/idmef">
        <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="Impact">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:attribute name="severity">high</xsl:attribute>
                <xsl:attribute name="completion">failed</xsl:attribute>
                <xsl:attribute name="type">file</xsl:attribute>
                <xsl:apply-templates/>
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>

Comment: Hi Nont,
That different xml. I edited the question to put in real xml, as opposed to the example. So how does that work. I've not done of xslt before.
Comment: I can see how it works, as your selecting node, and then matching on the attributes, but how would it work, if a user gave me the xpath string to set portlist to 5 as below.

 5

How would I go about building the   nodes around it and including any mandatory xml nodes with in, obviously attribute fields would be blank, or default values, as the user has not supplied them.

I think your quite close, but I need to see how it works on different parts of the xml packet.
Comment: XSLT is made for transforming XML. The idea is that you take one piece of XML and it transforms it into another. I got the impression from you question that your output document looks alot like your input document. If this is the case, then XSL would be a good choice. If its very different, and I'm mistaken, then its not a good choice. I use Saxon to run the transform. The example I gave only modifies the Impact node, and leaves the rest as it was. For a general XSL tutorial, try http://www.w3schools.com/xsl/
Comment: If you're looking for a dot-net XSl intro, try this: http://www.xml.com/pub/a/2002/08/14/dotnetxslt.html
Comment: Hi Nont, I've got xslt reference book from Wrox, but I never got round to reading it.  As regards above, output doc and input doc use the same schema, as i',, building a rule engine, which take IDMEF packets, in, and select node from selected message, based on a xpath set. If the rule hits, it selects certain xml out of it, and when later, that xml is built up into another composite packet, and  sent out. Could you show me how it would work with using the example from my previous comment. If the user selected 5 I would have to built
Comment: Also how would it link the xpath expression, if the user specifed

name.set(".//idmef:Classification/idmef:Assesment/idmef:Impact/@severity","high")

How would I link that xpath expression to define the above xslt. Maybe code blocks, with all xpaths having an xslt transform?

would it be a mechami
Comment: I have read, I need more concrete examples to see how it would work with elements as well.
Comment: Nont,
Thanks for your help.
Bob.
Comment: The correct way to say thanks is to upvote my answer. Unless you're being sarcastic.
Answer: I found an answer here on stackoverflow, and here it is. Create XML Nodes from XPath I know it is as far away from how I described it above, but at the time I was designing it, I
didn't have a scobie how it would work.
Answer: You could:

Open original XML (A)
Create a new XML document (B)
Run your xpath against (A)
Add matching results to (B)
Save (B)

This makes any sense?
Comment: Sure that the way it need to be done, but how is it done for the 4th and 5th actions. When you run the xpath against A, how do you apply a chunk of A into B.


Criar Tabela com 3 linhas depois criar outra tabela com mais 3 linhas

Question: Gostaria de criar varias tabelas com três linhas cada.
Exemplo:
GRUPO A
TIME 1
TIME 2
TIME 3
GRUPO B
TIME 4
TIME 5
TIME 6
Segue meu code:
<?php include 'masterpage.php';
      include 'conexao.php';

$sql = "SELECT G.NOME_CHAVE, G.ID_EQUIPE, E.ID_EQUIPE, E.NOME
FROM Grupos_Sorteados AS G
INNER JOIN Equipe AS E
ON G.ID_EQUIPE = E.ID_EQUIPE
ORDER BY NOME_CHAVE";
$resultado = mysqli_query($conn, $sql);

?>

Grupo: <?php echo $chave?>

      <?php

while($dados = mysqli_fetch_array($resultado)){
   $chave = $dados['NOME_CHAVE'];
   $equipe = $dados['NOME'];
  ?>

               Equipe
               Chave

      <?php echo $equipe ?>
      <?php echo $chave?>

<?php } ?>

[![inserir a descrição da imagem aqui][1]][1]

<?php include 'footer.php'; ?>

EDIT*
Consegui O seguinte resultado, porém ainda não é o que eu espero. Eu preciso colocar 3 times dentro de uma tabela apenas. Alguém pode me da uma luz?
Answer: Realize uma query no seu banco utilizando o distinct (https://www.w3schools.com/sql/sql_distinct.asp) para puxar todos os grupos.
SELECT DISTINCT NOME_CHAVE FROM Grupos_Sorteados

Teremos um array com todos os grupos do campeonato, basta jogar isso dentro de um foreach e dentro dele realizar um select buscando por times daquele grupo. Pode aproveitar esse seu comando SQL apenas adicionando no final:
WHERE G.NOME_CHAVE = {{ aqui vem a variavel com nome do grupo do foreach }}

Acho que ficaria algo como isso:
<?php foreach($grupos as $grupo): ?>

Grupo: <?php echo $grupo["NOME_CHAVE"] ?>

            Equipe

    <?php
    $sql = "SELECT E.ID_EQUIPE, E.NOME
    FROM Grupos_Sorteados AS G
    INNER JOIN Equipe AS E
    ON G.ID_EQUIPE = E.ID_EQUIPE
    WHERE G.NOME_CHAVE = {$grupos}";
    $resultado = mysqli_query($conn, $sql);
    while($dados = mysqli_fetch_array($resultado)):
    ?>

            <?= $dados['NOME'] ?>

    <?php endwhile; ?>

<?php endforeach; ?>

Uma sugestão é  depois colocar os pontos do lado do nome da equipe.
Comment: Deu certo! Valeu pela ajuda.
Comment: Fico feliz em ter ajudado.


What's the explanation for these (infinitely many?) Ramanujan-type identities?

Question: Define the function,
$$F(\beta) := \sqrt[3]{\beta+x_1}+\sqrt[3]{\beta+x_2}+\sqrt[3]{\beta+x_3}\tag1$$
where,
$$x_1 =2\cos\big(\tfrac{2\pi }{7}\big),\;x_2 =2\cos\big(\tfrac{4\pi }{7}\big),\;  x_3 =   2\cos\big(\tfrac{8\pi }{7}\big)$$
or the $x_i$ are the roots of the cubic $x^3+x^2-2x-1=0$. We have two nice identities,
$$F(0) = \sqrt[3]{5-3\sqrt[3]7}$$
$$F(1) = \sqrt[3]{-4+3\sqrt[3]7}$$
The first one is by Ramanujan.  (See The Problems Submitted by Ramanujan to the Journal of the Indian Mathematical Society, p. 9, by Bruce Berndt, et al.)
These two (and other pairs) can be explained by the negative and positive cases of $\pm \sqrt{d}$ in this answer. However, davidoff303 found a plethora of others,
$$F\Big(\frac{74}{43}\Big) = 2\,\sqrt[3]\frac{7^2}{43}$$
$$F\Big(\frac{5105}{11349}\Big) = 3\,\sqrt[3]\frac{7}{11349}$$
$$F\Big(\frac{-2306997866696}{1047656140569}\Big) = -10980\,\sqrt[3]\frac{7^2}{1047656140569}$$
$$F\Big(\frac{9658771264742899051}{5361029308457632889}\Big)= 13\cdot 127\cdot 1381\sqrt[3]{\frac{7}{5361029308457632889}}$$
and so on. Note that, for general rational $\beta$, then $\big(F(\beta)\big)^3$ is a root of a $9$th deg equation.

Q1: Are there infinitely many rational $\beta$ such that $\big(F(\beta)\big)^3$ is also rational, like the ones found by davidoff303? Is there a formula for $\beta$?

$\color{blue}{Update:}$
I formed the $9$th deg equation satisfied by $\big(F(\beta)\big)^3$. Acting on a hunch, it turns out that the $\beta$ used by davidoff303 satisfies the simple relation,
$$\beta^3-\beta^2-2\beta+1 =w^3\tag2$$
This can be transformed into an elliptic curve, and it has infinitely many rational points. And the $LHS$ of $(2)$ in fact is a factor of the discriminant of the $9$th deg eqn.

Q2: Is it true that if rational $\beta$ satisfies $(2)$, then $\big(F(\beta)\big)^3$ is also rational?
Comment: This has definitely something to do with Kummer sums (https://en.wikipedia.org/wiki/Kummer_sum) and the fact that the Galois group of the minimal polynomial of $\cos\left(\frac{2\pi}{n}\right)$ is a cyclic group with $\frac{\varphi(n)}{2}$ elements.
Comment: @davidoff303: How did you find the $\beta$? It's a vague feeling, but does the growth of $\beta$ involve an elliptic curve?
Comment: @davidoff303: I figured it out. There ***is*** an elliptic curve involved. However, I still don't know why it works.
Comment: In other words, (2) means $(\beta+x_1)(\beta+x_2)(\beta+x_3)=w^3$.
Comment: correct me if I'm wrong but $\beta=0$ satisfies $(2)$, but $(F(0))^3$ is not rational ? (though, it is a root of a degree $3$ polynomial)
Comment: @ccorn: Yes, it can also be expressed that way.
Comment: @mercio: I just noticed the same can be said for $\beta =1$. Maybe $(2)$ implies that $\big(F(\beta)\big)^3$ is a root of a cubic (instead of a nonic). Then there might be an additional condition such that this cubic has a linear factor.
Answer: Since there are $3$ ways to choose each of the cube roots, in general, $F(\beta)$ is a root of a degree $27$ polynomial whose coefficients are expressions in $\beta,(x_1+x_2+x_3),(x_1x_2,x_2x_3,x_3x_1),(x_1x_2x_3)$.
Since multiplying each root by $\zeta_3$ doesn't change the value of $F(\beta)^3$, this polynomial is in fact a polynomial of degree $9$ in $F(\beta)^3$.
Assume now that we have $(\beta+x_1)(\beta+x_2)(\beta+x_3) = w^3$.
Then the degree $9$ polynomial factors after extending our coefficients field with $w$, into a cubic and a sextic : gather in the cubic the three choices of roots giving $(\beta+x_1)^{1/3}(\beta+x_2)^{1/3}(\beta+x_3)^{1/3} = w$
Then, $F(\beta)^3 = (3\beta+x_1+x_2+x_3) + 6w + 3\sum_{i \neq j} (\beta+x_i)^\frac 23(\beta+x_j)^\frac 13 \\
= (3\beta+x_1+x_2+x_3) + 6w + 3w\sum_{i \neq j} (\beta+x_i)^\frac 13(\beta+x_j)^{-\frac 13}$
And so $(F(\beta)^3$ is rational if and only if the sum is. At this point, a choice of $F(\beta)$ among the $3$ possibilities is equivalent to a choice of only one term if the sum. Or equivalently, you go from one value to the others by multiplying $(\beta+x_2)^\frac 13$ by $\zeta_3$ and $(\beta+x_3)^\frac 13$ by $\zeta_3^2$
Split the sum into two parts $z_1 + z_2$ (one for each coset of $A_3$ in $S_3$). When applying this automorphism, one is multiplied by $\zeta_3$ and the other is multiplied by $\zeta_3^2$, so their product $z_1z_2$ has to be invariant, and indeed, $w^2z_1z_2 = 3\beta^2-2\beta-2+(3\beta-1)w+3w^2$.
If the original Galois group between $x_1,x_2,x_3$ had been $S_3$, things would have been more complicated, but here, since the Galois group is cyclic, $x_1/x_2+ x_2/x_3 + x_3/x_1$ is rational, and this implies that $z_1^3$ and $z_2^3$ are rational :
$\{(wz_i)^3\} = 9\beta^3-9\beta^2-11\beta+3w(3\beta^2-2\beta-2)+3w^2(3\beta-1) + \{2;9\}$
If one of them is $0$, then the other is $\pm 7$, and this corresponds to the $\beta = 0,1$ cases.
If not, then $F(\beta)^3$ is rational if and only if one of those two rational numbers is a cube (since their product is a nonzero cube, this is equivalent to both being a cube).

The map $(\beta,w) \mapsto \\
(X = 3\beta^2-2\beta-2+(3\beta-1)w+3w^2 ; \\
Y = 9\beta^3-9\beta^2-11\beta+3w(3\beta^2-2\beta-2)+3w^2(3\beta-1))$
is a rational isomorphism between the elliptic curves $E_1 : w^3 = (\beta+x_1)(\beta+x_2)(\beta+x_3)$ and $E_2 : (Y+2)(Y+9) = X^3$ (it can't be ramified, and the only preimage of the point at infinity from $E_2$ is the point at infinity with $\beta/w = 1$)
Since $Y+2$ has a triple pole at the point at infinity of $E_2$ and a triple zero at $(X=0,Y=-2)$, $Y+2$ is not a cube (there is no degree $1$ map from an elliptic curve into $\Bbb P^1$), but the extension obtained by adding a cube root of $Y+2$ is a $3$ fold unramified covering $f : E_3 \to E_2 \cong E_1$
Then the rational points on $E_1$ whose $F(\beta)^3$ is rational are (aside from the two exceptions with $X=0$) the images of the rational points on $E_3$.
Choose a rational point on $E_3$ (such as any example where $F(\beta)$ is a cube, or the rational point above the point at infinity of $E_2$) so we can have a group law on $E_3$ and $E_2$.
If $\hat f : E_2 \to E_3$ is the dual map to $f$ then $f \circ \hat f = [3]$, so $f(E_3(\Bbb Q))$ is a subgroup of $E_2(\Bbb Q)$ that has to contain $[3](E_2(\Bbb Q))$
If you name $u = (Y+2)^\frac 13,v = (Y+9)^\frac 13$, then $E_3$ is given by $v^3=u^3+7$ and $f : E_3 \to E_2$ is given by $(X = uv, Y = u^3-2)$. After composing this with the isomorphism $E_2 \to E_1$ (that I didn't compute), you get a nice rational algebraic parametrization by $E_3$ of the points you want, $(u,v) \mapsto (\beta,w,F(\beta)^3)$

From here on, things might be different with other choices of $(x_1,x_2,x_3)$ or other base fields.
According to http://www.lmfdb.org/EllipticCurve/Q/441/d/2
$E_2(\Bbb Q)$ 's torsion subgroup has order $3$ and is generated by $Q_1 = (X=0, Y=-2) = (\beta = 1, w = -1)$. Since $Y+9$ is not a cube, it doesn't have a rational preimage in $E_3$ and $F(1)^3$ is not rational.
The other point of order $3$ is $2Q_1 = Q_2 = (X=0, Y=-9) = (\beta = 0, w = 1)$ and is in the same case.
$E_2(\Bbb Q)$ has rank $1$ and its free part is generated by $R = (X=2,Y= -1) = (\beta = \frac {74}{43}, w = - \frac {29}{43})$. Since $Y+2$ and $Y+9$ are nonzero cubes, it has a rational preimage in $E_3$, and $F(\frac {74}{43})^3$ is rational.
This is enough to determine that the subgroup of "good" points is generated by $(X=2,Y= -1)$.
For example $2R = (X = -\frac{20}9, Y = -\frac{118}{27}) = (\beta = \frac {5105}{11349}, w = - \frac {2521}{11349})$, and so on.
Since $E_3$ also has a group law, there are addition formulas that combine triplets of rationals $(\beta,w,F(\beta)^3)$, so if you compute those formulas, you get an easy way to generate the points you want.

As you noticed, $\tau : (\beta,w) \mapsto (-\frac 1{\beta-1},\frac w{\beta-1})$ is the translation by $Q_2$ (a point of order $3$), and thus for any rational point $P$ on $E_1$, exactly one of $\{P,\tau(P),\tau^2(P)\}$ has a rational preimage in $E_3$ (has $F(\beta)^3$ rational).
Comment: @davidoff303: I found the general formula. It works for ***any*** cubic $x^3+ax^2+bx+c=0$. For example, for $d=13$ we have $$\sqrt[3]{p+x_1}+\sqrt[3]{p+x_2}+\sqrt[3]{p+x_3} = \sqrt[3]{15^3 q}$$ where $p = \frac{-12901}{20367}$ and $q = \frac{-13}{20367}$ and the $x_i$ are the roots of $x^3+x^2-4x+1=0$ and can be expressed as sums of $\cos\big(\tfrac{\pi\,k}{13}\big)$.
Comment: Thanks! A small question though. I've realized that $\beta^3-\beta^2-2\beta+1 = w^3$ is a necessary but not sufficient condition such that $\big(F(\beta)\big)^3$ is rational. For example, $\beta=9/5$. Is there an explicit rational Diophantine equation that $\beta = 74/34$ satisfies, but $\beta = 9/5$ does not?
Comment: after looking at http://www.lmfdb.org/EllipticCurve/Q/441/d/2 the generator they give corresponds to $\beta = 74/43$, it gives $X=2,Y=-1$ which has a rational preimage because $Y+2$ and $Y+9$ are cubes. However the torsion points $(X=0,Y=-2)$ and $(X=0,Y=-9)$ don't have rational preimages because $7$ and $-7$ are not cubes, so the "good" subgroup has index $3$ in $E_2(\Bbb Q)$. Using the multiplication formulas with the torsion subgroup should give you, from a $(\beta,w)$, formulas for the $3$ candidate $\beta$, only one of which is good
Comment: instead of a diphantine equation, I think it's possible that there is a simple modular condition on $\beta$ that tells you by which torsion element you have to compose to get to a good rational point.
Comment: By the way, I noticed that if $\beta_1 = \frac{p}{p+q}$ satisfies $\beta^3-\beta^2-2\beta+1  = \text{cube}$, then so does $\beta_2 = \frac{p+q}{q}$. For example, $\beta_1 = \frac{31}{74}$ and $\beta_2 =\frac{74}{43}$ though usually (excluding the case $\beta = 1/2,\,2$) only one of them yields a cubic with a rational root.
Comment: also $\beta_{3}=-\frac{q}{p}$
Comment: @davidoff303: What were your guidelines to find your $\beta$? I guess it is not brute search since the numbers are too big. Did you use $\beta^3-\beta^2-2\beta+1 =w^3$?
Comment: @mercio: In my answer below, can you show that $(1),(2),(3)$ simultaneously holds for infinitely many rational points?
Comment: @Tito Piezas III: I used PARI/GP: http://pari.math.u-bordeaux.fr
Comment: @davidoff303: Ah, thanks. By the way, I checked and the _rational_ $\big(F(\beta)\big)^3$ phenomenon works for $d = 7,19,37$. I'm not sure if it also works for $d=13,31,43$ since the search bounds I used may have been too small. Would you like to check with PARI? If you find anything, can kindly you post it as a new answer here? (Only the short ones, pls.)
Comment: @Tito Piezas III: I will try.
Comment: @Tito Piezas III: it's very interesting! did you use elliptic curve?
Comment: @davidoff303: Well, yes, it was a point on an elliptic curve. I may ask the general question in MathOverflow. I'll send you the link if I do so.
Comment: @Tito Piezas III: ok, it's interesting for me.
Answer: This is a long comment/addendum to mercio's answer. Given rational solutions to,
$$\beta^3-\beta^2-2\beta+1 = w^3\tag1$$
As pointed out by mercio, if we define,
$$X = 3\beta^2-2\beta-2+(3\beta-1)w+3w^2 \\Y = 9\beta^3-9\beta^2-11\beta+3w(3\beta^2-2\beta-2)+3w^2(3\beta-1)$$
then this obeys the elegant relation,
$$(Y+2)(Y+9) = X^3$$
However, if we require $\beta$ such that
$$Y+2 = u^3\tag2$$
$$Y+9 = v^3\tag3$$
holds separately, then we can define $\big(F(\beta)\big)^3$ as,
$$\big(F(\beta)\big)^3 = \frac{3(t+19)(u+v)+(3uv+7)(27u^4v-63u^3+105uv-196)}{t+19}\tag4$$
where,
$$t=27(u^3+3)(u^3+4)$$
Thus, if $\beta$ satisfies the rational Diophantine conditions $(2),(3)$ in addition to $(1)$, then $\big(F(\beta)\big)^3$ is rational.
Example. Let $\beta = \tfrac{74}{43}$, we get $u=1,\;v=2,\;t=540,$ and using formula $(4)$,
$$\big(F(\tfrac{74}{43})\big)^3 = \frac{2^3\cdot7^2}{43}$$
the same as in the post above. All six examples in the post obey $(1)$, but only the last four obey all $(1), (2),(3)$. Presumably there are infinitely many rational $\beta$ that obey all three conditions, but I do not know how to prove it so.
Comment: @mercio: By the way, how did you find $X,Y$? For example, if we use the cubic involved with $\cos(\pi/19)$, and solve, $$t^3-t^2-6t+7 = w^3$$ this has infinitely many solutions. Does this also have a $X,Y$ such that $$(Y+a)(Y+b) = X^3$$ and $-a+b=19$?
Comment: @mercio: I figured out the general case. :)   So I'm making a question for $d=19$.
Comment: (I didn't get pinged) I don't think anything should change much in the first two paragraphs with $d=19$. I found $Y$ by looking carefully at $F(\beta)^3$. The sum was the source of the potential non-rationality, and looking at how the Galois group acted on its terms naturally leads to $z_1$ and $z_2$ and figuring out that they live in the same cubic radical extension so they both need to be cubes.
Comment: finding the formulas for $(wz_i)^3$ and $(w^2z_1z_2)$ was just a matter of computation and replacing the symmetric expressions of the $x_i$ by the coefficients of their cubic.
Comment: @mercio: The question is done. Can you kindly look at [this post](http://math.stackexchange.com/questions/1844225/generalizing-ramanujans-cube-roots-of-cubic-roots-identities).


Formatting my Link field with multiple values

Question: I believe I have a way to do this, but as I'm learning I want to make sure I'm not doing it horribly wrong or reinventing a wheel that already exists (the module search on the Drupal site leaves a lot to be desired).
I've got a Link field with multiple values (just URLs). When this field is being rendered, I would like to sort of preprocess each of the URLs. If it's a youtube or vimeo link, I'd like to change it so that a video embed is rendered instead. If it's a link to an audio file (with certain extensions) then I want to render an html5 audio tag.  Else, I just want to render the link normally.
It looks like I could override mytheme_field__links__mycontenttype() (although I'm not exactly sure how to implement that method just yet, any examples are welcome).
It also looks like I could create a template in my theme named field--links--mycontenttype.tpl.php
Is this the right way to go?
Is one better than the other?
Do you have any links to a good example of how to implement/override these?
Thanks!
Answer: The two best ways to do this are the one you suggest by creating a tpl.php like you mention and doing your work in there directly.  Another (and preferred by many, but a bit more complex) is to use template_preprocess_field.
A very good explanation of how to go down the second route is http://www.digett.com/blog/01/18/2012/change-output-single-field-drupal-7-node
That way you don't end up with a whole bunch of field.tpls and you can isolate your changes in that function.
Comment: Wonderful, thank you for the example link! It was exactly what I needed.
Comment: No problem. All credit due to the person who wrote that explanation.  I've used it myself. Very handy.


Uniqueness conjecture

Question: Define an H-Triple (a, b, c), where a > b > c > 1, as one where a, b and c = $\frac{ab+1}{a+b}$ are all integers. (There are 'lots' of these!)
Conjecture; if (a, b, c) and (d, e, f) are distinct H-Triples, then abc$\neq$def.
That is, the product of the terms of an H-Triple is unique.
Can anybody help with this? Computers suggest any counterexample will not be small.
The reason the problem arises? Consider the family of elliptic curves $xy\frac{xy+1}{x+y}=k$ and the integer points that lie on them. If (a,b,c) is an H-Triple and k = abc then (a,b) is an integer point on this elliptic curve. The uniqueness conjecture would narrow down the possibility that there might be any others.
Comment: I don't think the conjecture is phrased perfectly.  For example, for the distinct triples
Comment: https://mathoverflow.net/questions/250172/when-is-fa-b-fraca2b21ab-a-perfect-square-rational-number/250300#250300
Comment: @individ But this is $f(a,b)=\frac{a^2+b^2}{1+ab}$, and not  $\frac{ab+1}{a+b}$?
Comment: By distinct triples I mean that (a, b, c) is not equal to (d, e, f).
Comment: @individ the original version of this problem is I think famously the only question that Terry Tao did not solve at the IMO where he won a gold medal.
Answer: Here is an idea to search for a counterexample. We have the following universal $H$-triples, namely
$$
(a, b ,c)=(2k+1,2k-1,k),\; (r^2+r-1,r+1,r)
$$
for all $k,r\ge 1$.
Equality of their products means
$$
4k^3-k=r^4+2r^3-r
$$
This Diophantine equation has the "trivial" solution $(k,r)=(2,2)$. In this case the triples coincide and are $(a, b,c)=(5,3,2)$ with product $abc=30$. With a computer one could try to find a non-trivial solution in positive integers, if it exists. This would yield two different $H$-triples with equal product. Of course one may use also different universal triples, like $(a,b,c)=(2l^2+4l+1,2l+3,2l+1)$ and others.
Comment: I did try this approach, but I didn't use the particular parametrised H-triples that you suggest, which seem to me to have a better chance of working than mine. Let me try this on the computer...
Comment: Tried this using VBA/Excel running k and r up to 5000 - no counterexample. An alternative approach; count the H-triples with all elements less than 1,000 say, then count their products.  Do the numbers match?
Comment: I generated the 418902 triples with $a<100000$, and none were found to have the same $abc$.

Uniqueness conjecture


Is it wrong to alter bar numbers after repeat endings so they reflect the performance progression rather than the last repeated measure +1?

Question: I'm part of a small group and we have our own pieces, which I'm not allowed to share. But I'll describe the situation and hopefully get the point across. In nearly all the songs in my group's repertoire, different instruments have repeated bits at different points, which means that usually there can be no volta brackets or other repeat signs.
However, we often need to have single-staff scores at hand so that we can actually read the music while rehearsing, otherwise it's impossible due to the sheer size it gets. That said, I can either:

write the entire piece without a single repeat, explicitly showing each phrase again and again; or
use volta brackets and segni etc. in different places, relying heavily on the fact that each score you look at contains a single staff for a single instrument.

For example:
When you're writing the flute part all by itself in a dedicated sheet of paper, there's no reason you couldn't put volta brackets around measures 11 through 20 rather than writing them twice, even if the other instruments do not repeat said measures. Right? No need to waste many pages on music that has already been written, read and understood. So let's say I choose to go with that. Now after the flutist plays measures 11 through 20 the second time, they would actually land on measure 31 rather than 21, big picture-wise. Think communication with the other musicians, especially considering they all have different repeats themselves. Also somebody watching the rehearsal and counting the measures would have counted 30 of them so far.
If I don't change the numbers in this way: "Let's play again from measure 21. I mean, it's 21 for me, but it should be 31 for somebody who doesn't have any repeats on their score up to this point. It should be measure 18 for the violinist. No, wait, that is… 17, I think…?"
vs.
If I do: "Let's play again from measure 31, everybody."
So in the end what I did is, I put a little 31 over the ending volta bracket (the one that closes measure 20), effectively changing the number of the following measure, which would otherwise be 21. I tweaked it and counted from 31 on, afterwards. By folding measures 21 through 30 into the repeat since they are 11 through 20 played again, I deliberately removed those numbers from the flute score.
A more visual example would be the following picture:

Note that the numbers are not actually printed every measure; this is just the rationale.
Is it something that should be avoided? If a pro saw this, would they feel inclined to undo everything and put the numbers as they were, leading to the need to remove the repeats altogether? I'm feeling a little insecure as I don't want my group to have poorly-organized sheet music for posterity.
Comment: If you don't want to leave "poorly-organized sheet music for posterity", the simplest plan would be to create a full score without any of these repeats. Any notation program will have a cut-and-paste option, so it's easy to do this. Any future problems understanding your parts can then be solved by referring to the full score.
Answer: As I understand bar numbers, they are intended to locate the correct position in the score, not the point in time. Note, that they often do not exist at all, and you will find rehearsal marks (squared or circled characters or numbers). I never encountered the "repetition-reflecting" numbering you propose, which has a set of drawbacks on its own: in your example "B" the player will have a hard time to arrive at bar 6, espcially if more than one bar is repeated (single bar repetition would anyway be typically represented by a bar repetition looking similar as ".//.").
So a conductor will typically state something like "We start with bar five, second repetition".
So summarized, perhaps your numbering is not wrong, but so unusual, that I would tend to avoid the necessary explanation for justifying it.
Comment: @guidot the usual English term for "exercise marks" is "rehearsal marks".
Comment: Good point on the repeated bars - // - which may also have 'by the way, there's 7 of them' somewhere.
Comment: Thank you for replying. The problem with "bar 5, 2nd repetition" is that bar 5 would be in a different place in every staff score when using numbers traditionally. That is, if A has a repetition of which bar 5 is a part while B does not, then the number 5 will be in different timestamps for them. A could be playing the 8th bar of the song as a consequence of looking for bar #5 on the page. I need to humbly clarify that my group is far less invested in sheet music than I am. They won't even bother trying to read if everybody has different bar numbers at any given time due to misaligned repeats.
Comment: @user3241796: I guess,  if you have differing numbers of repetitions depending on the voice you could consider to switch to use excercise marks instead (and possibly keep the bar numbers in standard way).
Comment: Thank you. I'll look into exercise marks. Judging by the context I have a hunch they work a little like a Segno—just without the Dal Segno command written in the score.
Answer: I agree with guidot, but a side discussion started in the comments that I wanted to address in a top-level reply.
user3241796 says:

The problem with "bar 5, 2nd repetition" is that bar 5 would be in a different place in every staff score when using numbers traditionally. That is, if A has a repetition of which bar 5 is a part while B does not, then the number 5 will be in different timestamps for them.

In making the parts, you should have each part be structurally identical in almost all cases.  That is, you shouldn't have one part have a repeat and another not.
I can imagine an exception: you might have a piece of music with long repeated sections, where only a subset of the ensemble does something different.  Maybe there's a very long "verse" with the same accompaniment but with a different melody/solo on top of it.  If the length were enough to take most of a page, then it might make practical sense (from a typesetting perspective) to write the accompanying instruments with a repeat, but write out both repetitions for the melody instruments.  In this case, I would recommend writing both sets of measure numbers in the accompaniment, as suggested in the question.
Comment: I agree with the guidelines you proposed, but I'm afraid it has fallen to me to transcribe other people's pieces, pieces that either have never been written or have been written only as an orchestra sheet music, where misaligned repetitions evidently need to be unfolded. It all comes down to preserving works that do not preserve the traditional conventions of Western music. We call the solos 'ouchi' and the acompaniments 'jiuchi'. We're a taiko ensemble, actually. Jiuchi is usually a constant sequence of a super-short loop, like augmented eigth + sixteenth (meaning a single-beat loop in 4/4).
Comment: This didn't fit in a single comment. I meant to add that, due to the overwhelming length of several kinds of jiuchi, there is no way not to fold the repeats into volta brackets when writing a single part score for a single part musician to read. Just imagine most of a page repeating that example above — augmented eighth + sixteenth. don ko don ko don ko don ko don ko don ko don ko don ko.......... Just writing this here in plain text feels like too much repetition of such short a phrase. See why I need to break down the structure of different parts at different times? There's no escaping this.
Answer: It sounds as if, in this case, writing 'true' bar numbers would be best.  Where a bar within a repeated section has two bar numbers, indicate them as e.g. 12(24).
You must not be using a computer scoring program.   This sort of independent looping is tricky to achieve, without breaking the connection between Full Score and Parts, with all the potential for error that encourages!
And only consider giving different parts different 'road maps' when there's a substantial reason, e'g' a jazz number where the rhythm section repeat the same 32-bar chorus several times, with varying solo and background arrangements in the front line. Don't do it capriciously.
Comment: I use Lilypond. I think I'll be able to tweak the bar number engraver with some research to include both numbers. Thank you for the suggestion.
Answer: At each 'new' part, maybe 16 or 24 bars in, where everyone's together again, or a different theme starts, use rehearsal letters, which would be the same for everyone. Then, if you said 'let's take it from 4 bars after C',or '6 bars before J', all would start in the same place.
Comment: It sounds as bar numbering may not be very appropriate or useful in your type of music.  Label sections instead.
Comment: Thank you for replying. I like your idea of labeling measures with something other than numbers so as not to override them. Truth is though, I'm not sure that would work out well because the structures of our pieces are packed with repeats, which puts a lot of those 'start 4 bars after C' occurrences inside repeats. At any point we often need to start at the 17th repetition of A's short phrase, in the middle of B's solo. We use 'performance-oriented' labels so much and 'page-oriented' numbers so little that I think we'd be better off without the traditional measure numbering system altogether.
Comment: Most solos are not that long. I can't understand why you'd want to start in the middle of a solo. It hardly is in context if that's the case.
Comment: I'm just writing songs we've learned across the years. Songs from masters that visited us to host a workshop, songs some of us composed without sheet music, etc. This group isn't classically trained, so this kind of thing tends to happen a lot in compositions. A lot of melodies with no pinpointable key due to lack of a tonic, etc. You said most solos aren't that long, and you're right. But in my group one person is often stuck in a loop for ages before another person begins their solo. That's why I planned on shifting the focus of the bar labels from the written music to the performed music.
Answer: As far as I remember, Guitar Techniques used nearly the same notation that you propose when they used to do songs. They had the bar number at start of each row, for example 47 51 55. And then, if the last row had a repeat, next row might start with bar 63 or 61.
I wasn't even aware some are numbering the bars as they appear on sheet not as they appear in song. "Fifth bar, second repetition" sounds quite wrong as that just depends on how the sheets are done not how the song goes. At least for a normal band it would seem quite ridiculous that the bass player would have sheets and sheets of the same notes just because the singer's part has some slight changes from verse to verse.
Answer: Notation is not right or wrong but good or bad.  Its function is to convey meaning to musicians.  The question is how good that notation is for that purpose, and how efficient.
With complex repeat structures (dal segno al coda), repeats may be traversed several times, requiring a stack of numbers.
You save redundancy for things like "let's start in measure 47 in the second repeat" but the question is whether this redundancy arrives at players with multiple numbers, and your principal goal is that every player may have individual repeat structures, so a decision like "ok, lets keep the repetitions in the da capo" is not possible to make.
Even without complex repeat structures, you'll need to put bar numbers (and where applicable, their ghost stacks) at the start of every repeat and at every alternate ending end at the exit.
There is a reason that generally, repeat structures are common to the whole orchestra.  Particularly for drummers, there are abbreviations like bar repeats (that look like percent signs with a variable number of oblique bars in the middle) that can significantly condense repetitive material without affecting the overall repeat structure or bar numbering.
So while at surface value, your proposal may have some merit, it does come with complications particularly of having problems scaling up.  There may be some cases where it appears worth the trouble, particularly in lesson books or other stuff where introducing your own conventions and benefitting from the savings covers a larger body of material under your control and you can evaluate the drawbacks and benefits specifically.
As a general practice for orchestral scores, having the same repeat (and bar numbering) structure for everyone in a manner where no extra bar numbers are required at start and end of repeats is very much the norm.
Answer: At least according to the Royal Conservatory of Music, obeying repeat signs is optional. This is supported by sources such as the 2022 RCM Piano Syllabus (https://rcmusic-kentico-cdn.s3.amazonaws.com/rcm/media/main/about%20us/rcm%20publishing/piano-syllabus-2022-edition.pdf) and https://www.olivermusicstudios.ca/RCM-Practical-Exam-Info---Piano-Levels-8---9. In fact, the 2022 RCM Piano Syllabus says this in its Page 4:

Repeat signs should ordinarily be ignored.

Repeat signs are indeed still not always followed in public and published performances of music. For example, this sheet music excerpt from the  Breitkopf und Härtel edition of Beethoven's Appassionata Sonata shows the first repeat ending, for the development and recapitulation, of that sonata's 3rd movement:

These two performances of the 3rd movement of Beethoven's Appassionata Sonata flagrantly skip that first repeat:

For another example, these sheet music excerpts of Mozart's Piano Sonata No. 16 in C Major, K.545 show the ending repeat sign, for the development and recapitulation, of that sonata's 1st movement:
Breitkopf und Härtel

Schirmer

These two performances flagrantly skip the repeat of the development and recapitulation of that Mozart piano sonata first movement:

The thread https://classicalmusicguide.com/viewtopic.php?t=15240 brings up even more examples of skipped repeats in published performances, including of Haydn symphony movements.
This jump measure numbering that assumes that repeats will always be followed therefore cannot be supported.
Comment: I don't understand the way in which you're using the RCM instructions. The RCM (and ABRSM) requests students ignore repeats when taking exams because it saves time. It has nothing to do with how the music would typically be performed. A performer not following the repeats — i.e., not following the composer's instructions — would be making an exception to the expected practice, and so also an exception to the measure numbering.
Comment: These guide lines are for a single performer taking an exam.  They don't really apply to OPs situation.
Comment: @Aaron - I have heard "exceptions to the expected practice" of following repeats often enough that I do not think the expected practice actually involves always following the notated repeats. Take performances of the 3rd movement of Beethoven's Appassionata Sonata, for example - these performances skip the first repeat of the development and recapitulation entirely: https://www.youtube.com/watch?v=LqIKv-42v1E, https://www.youtube.com/watch?v=xnqP6a9YDf0
Comment: @Dekkadeci In that regard we agree, but I don't think relying on the RCM exam procedure is enough to make your case. Adding your previous comment to your answer, plus another example or two, would strengthen your post considerably (especially if you could point to a numbered score of those pieces and show what the editorial practice is).
Comment: @Aaron - Added the comment above to my answer, then - it didn't take long - found another example of skipped repeats in performances, this time of Mozart.
Comment: Cool. To my mind, a much stronger case. So I'll bring up something else to consider. [Guidot's answer](https://music.stackexchange.com/a/46659/70803) uses the idea that measure numbers indicate position in the score, not position in the performance. If one accepts that, then measure numbering is (as an expression) arbitrary. One can count or not count repeated portions according to personal (i.e., editorial) preference, and there's no rule one way or the other. The strongest argument you could make here would be to address that score numbering vs. performance numbering idea.


Can't get SQL query results

Question: I used a PHP code to show results of this query:
<code>SELECT COUNT(*) FROM mytable
</code>
I want to get the number of rows in a specific table. This query works fine in phpMyAdmin, but it doesn't work when I place it in a template file.
I mean it doesn't return the number of rows.
Do you have any idea?
Comment: Could you post the code how you tried to retrieve the result?
Comment: Please post the complete code not only the SQL. and are you using db_query() or mysql_query ?
Comment: Realyl Thanks, specially kantu. I used db_query and it fixed my problem.
Answer: A template file should never contain code that executes a query; that should be done in a preprocess function, eventually.
The code to get the number of rows in a table is similar to the following one.
<code>$count = db_result(db_query("SELECT COUNT(*) FROM {mytable}"));
</code>
The table name should always be put between curly brackets, which will be replaced with the prefix currently set for database tables.

Can't get SQL query results