Why is composer deleting and reinstalling core?

Question: I am running Drupal 9.2.4 on Lando on Mac Big Sur.  When I use composer to install a module it first deletes core.
<code>Removing package drupal/core so that it can be re-installed and re-patched.
 - Removing drupal/core (9.2.4)
</code>
Then it reinstalls it.
<code> - Installing drupal/core (9.2.4): Extracting archive
</code>
If the module fails to install, no core!
I think these are the relevant lines from composer.json.
<code>"drupal/core": "^9.2.4",
"drupal/core-composer-scaffold": "@stable",
"drupal/core-project-message": "9.2.4",
"drupal/core-recommended": "@stable",
</code>
Any ideas as to why this is happening and how to prevent it from happening?
Comment: Composer tells you why it is happening: "Removing package drupal/core so that it can be **re-installed and re-patched.**"
Comment: Have you tried updating cweagans/composer-patches? See this issue. https://github.com/cweagans/composer-patches/issues/363
Comment: This is most likely the bug I mentioned and that is why I posted it as an answer, not a comment. I Don't appreciate that being changed.
Comment: @tonytheferg Answers are for answering the question, not asking questions to the OP or merely providing a link. Answers asking for information or merely providing a link are removed.
Comment: Core being deleted and not being re installed is the bug I mentioned. It's not designed behavior for composer patches. There's not much else to say about it.
Answer: When there is a patch set in your composer.json file or a composer.json file in one of your packages, composer will remove the package with a patch (in this case core) and reinstall it to apply all the patches. Look for a section that looks something like:
<code>"patches": {
            "drupal/core": {
                "3035113 - EntityAccessChecker": "https://www.drupal.org/files/issues/2019-10-21/LatestRevisionCheck-13092187-24.patch",
                "2856823 - header links": "https://www.drupal.org/files/issues/2020-11-24/2856823-48__core-9.1.x.patch",
                "2784233 - Allow multiple vocabularies in the taxonomy filter": "https://www.drupal.org/files/issues/2021-05-28/2784233-193.patch"
            }
}
</code>
If not your composer.json file, check for a composer file of your distribution or profile. That's the most likely place to find it.
Comment: I do, in fact, have a patches section in my composer file.  Thanks for pointing this out.  This composer file was generated my the Acquia Migrate Accelerator module.   I am wondering if I can safely remove this section?
Comment: Well, that depends. If you are still doing the migrations and need the Acquia Migrate Accelerator module, I would leave it alone. It is likely depending on those patches. Acquia does a good job of checking for updates to core and will remove patches from their module when they're not needed. So be sure to keep up-to-date. Also, be sure your `cweagans/composer-patches` is updated as mentioned by @tonytheferg


Crescendo and accelerando throughout, how?

Question: I hear this in most piano transcriptions and in all orchestras when I hear In the Hall of the Mountain King. It is as though Edvard Grieg wrote cresc. and accel. and pp and left it at that. I did hear once a piano transcription without that accelerando and it did not sound right to me. Of course, Edvard Grieg wrote all the dynamics but I still hear 1 smooth crescendo, even though in the sheet music there is no crescendo. Why is that? Why do I hear a crescendo and an accelerando if neither of these are written in the music?
I myself when I play this, try to play as quiet as possible in the first few measures. I also start at a bpm of 60. So I start at Larghetto. I end at Presto. It is like me going from Largo by Handel to Moonlight sonata 3rd movement in 2 minutes. That is how fast the tempo changes when I play it. But I see no signs of a tempo change. The only tempo I see is this:
Alla Marcia e Molto Marcato
Like a march with lots of accents is basically what that translates to. And then I see this:
sempre staccato e pp
In other words, every note is to be staccato, except where the slurs are. At super fast speeds though, I can't really achieve a true staccato. And staccato triplets at allegro is hard. If I even try to play staccato at Presto, I end up playing legato, even with the staccato technique because the notes are just so fast that the line between staccato and legato is blurred, Also staccato at those speeds causes me to be more tense than legato at those speeds. And I know this is because I build up tension and then release it with the staccato, more so if I am doing the staccato at forte.
But why is it that I hear a smooth accelerando and a smooth crescendo in that piece when neither one is written down?
Comment: They are without that h in my language. Its just I hear what sounds like an h when I hear those words and I quite often write those words with the h.
Comment: Caters - I edited for you. Remember you can edit your posts, as just putting an update in comments is not permanent.
Answer: Looking at the score:
The orchestration gets "fuller"; instruments are added (almost) each time the main phrase comes up. This results in a "natural" crescendo, because there are more playing. The range is also expanded, with the bassoons beginning (very low in pitch), and instruments being added "on top".
Plus, it is written "crescendo e stretto, poco a poco" when the violins play the main phrase for the first time (Peters 1888 edition, reprint), so it is actually in there as well.
As for "sounds wrong": You (well, we all) are so used to the cresc. + acc. version that everything else is at least "weird". Same with other pieces, like e.g. Dvořák's Symphony No. 9. I heard a recording conducted by, I believe, Srgiu Celebidache. It was incredibly slow for me, but one could appreciate other details than if people just rush through it...
Answer: The lateral answer is that the dynamics and tempi are always subject to the desire of the conductor.  All compositions are interpreted by the conductor, which is not only acceptable but is the reason we collect multiple recordings of a favorite piece.
As a side note, do not listen to Shostakovitch's 7th, with a 20 or 25-minute crescendo inside the Bolero movement.  I feel much pity for the snare drummer.
Comment: similar to Ravel's Bolero?
Comment: @JoeW  take a listen :-) .


"Page not found" with new content type

Question: I already have a custom content type (jobs). When I create jobs nodes, they are displayed. I have created a new content type (ideas). When I add an idea node, I get a Page not found error. Any new custom content type I create gives me the same error.
The nodes I created are published. I cleared the cache.
I tried re-building the node permissions here: https://www.foo.com/admin/reports/status
Which didn't work.
There does appear to be  Experimental modules found: Content Moderation. This would no longer be experimental in 8.6, currently the site is running 8.2. Not sure if that upgrade would help or create more problems.
There is this error which is interesting:
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions. Content
The node.field_recognition_date field needs to be uninstalled.
But I am not sure how to uninstall that or how to fix this issue. Any help would be appreciated.
Comment: Is there Rabbit Hole? Is there a global redirect of some sort? Is there an htaccess rule about `idea` it does not like?
Comment: No there isn't Rabbit Hole and no to the other aspects.
Answer: Sound like you have removed a dependency from the codebase that a field a certain field depends on, usually it's a module. If that's the case you will need to reinstate it, then uninstall it. But also, you might want to try drush entup and drush updb
Also, it's a good idea to check the error reports for a more detailed explanation of what has happened
Comment: I ran both of those commands and that didn't fix the issue. But I am guessing that you are right about the dependency, I just have to track that down.

"Page not found" with new content type


Oh-my-posh themes not working correctly with Powerline font and ConEmu

Question: I use PowerShell as my shell on Windows 7. I find that ConEmu is a really good terminal. Since I am not on Windows 10, I cannot use Windows Terminal but ConEmu is not bad at all. I found out about posh-git and oh-my-posh and how they can customize your PowerShell experience. I installed oh-my-posh and the Paradox theme looked nice. But I saw some empty boxes in random places in my Prompt.
And this is an issue that I face on all the themes. The colors and the design are beautiful and I want to use it but those weird boxes are keeping me from doing that. I would also like to tell that I am using Cascadia Code as my font and also this is the Powerline version of Cascadia Code. So, I think it should work as excepted. Next, trying to fix this, I went to nerdfont.com and I installed Cascadia Code from there as opposed to Microsoft's official GitHub repository. Then I set ConEmu's font to Cascadia which I installed from nerdfonts and this happened:

It's better in a way that I can see the Python symbol and some more symbols but still there is one box that cannot be rendered. But it does get worse if I change repository:

There is a weird question mark after "master". I think I have met all the prerequisites to use oh-my-posh like install posh-git and PSReadLine and having powerline Cascadia Code font and also using ConEmu as they officially suggest. I would absolutely appreciate it a lot if anyone can help me out of this mess and suggest what to do to fix my prompt.
P.S I am using PowerShell 7 Core.
Answer: When you see boxes, that means that the font doesn't have that specified character. e.g. there are a lot of specialized fonts that don't have every character location defined.
Right on the oh-my-posh GitHub page, Quote:

In case you notice weird glyphs after installing a font of choice,
make sure the glyphs are available (maybe they have a different
location in the font, if so, adjust the correct $ThemeSettings icon).
If it turns out the character you want is not supported, select a
different font.

Also on the oh-my-posh GitHub page, the font used is:

The fonts I use are Powerline fonts, there is a great repository
containing them. I use Meslo LG M Regular for Powerline Nerd Font

If using Meslo LG M Regular doesn't solve your problem, then you have to manually remap the icons to the correct unicode locations in your chosen font.
For Version 2 of Oh My Posh, you have to edit the $ThemeSettings variable. Follow the instructions on the GitHub on configuring Theme Settings. e.g.:
$ThemeSettings.GitSymbols.BranchSymbol = [char]::ConvertFromUtf32(0xE0A0)

For Version 3+ of Oh My Posh, you have to edit the JSON configuration file to make the changes, e.g.:
...
{
    "type": "git",
    "style": "powerline",
    "powerline_symbol": "\uE0B0",
....

Comment: Short answer yup. The PowerShell console doesn't render the same as VS Code terminal. Remember, VS Code is an Electron app, and so renders the PowerShell terminal using multiple `` elements, or can be changed to render with the [DOM](https://code.visualstudio.com/docs/editor/integrated-terminal#_changing-how-the-terminal-is-rendered). Trying to get any type of theming to work the same on both, is a hope and a prayer ;-).
Comment: Since ps1 profiles are only run at the start of the PowerShell session, when changing themes, you may have to re-run the `$ThemeSettings` commands for the changes to take effect. Personally I would keep the settings inside the profile as they are specifically "font" related. If you hard code them into the themes `.ps1` files, they may be overwritten by any updates.
Comment: @U.Savas `$ThemeSettings` is in [Version 2](https://ohmyposh.dev/docs/upgrading#enter-v3) of Oh My Posh. Oh My Posh V3 uses `.JSON` files for [configuration](https://ohmyposh.dev/docs/configure) so there is no longer a `$ThemeSettings` variable.
Comment: Thanks for you answer. It has certainly helped me.  But I need to know one more info. I have manually corrected the broken symbols (empty boxes) like git symbol, prompt indicator symbol, failed command symbol etc. to make sure that they are not weird glyphs but good symbols. I have used $ThemeSettings to do this and I placed all these in my .ps1 profile. But when setting a new theme, my customizations are overridden. The only way I see to fix this is to hardcode my settings in the themes' .ps1 files themselves. Is it a good idea or should I do something else?
Comment: Maybe I could write a function or something that I can call right after changing my theme that will update the boxed symbols correctly. Anyways, I was curious about if oh-my-posh themes work in the VS Code Terminal. And I saw the the VS Code Terminal is horribly unusable if a theme is set. My VS Code font is Cascadia Code Nerd Font as well. That is why I am using Git Bash as my shell in VS Code. So is this an expected behavior? Is oh-my-posh NOT supposed to work in VS Code Terminal?
Comment: Hey thanks for all these info and knowledge. Have a great day and I'll choose your answer as the correct one.
Comment: I currently have the same issue with seeing the red base settings. I tried changing fonts, but no luck. When I go to $ThemeSettings I see there is an ErrorCount of 1, is there a way t o view this error?
Comment: I cannot access the $ThemeSettings. Where is this located?
Answer: Posting this response because I followed @HAL9256 's response and it was extremely helpful but I had to take it one step further. If you are using windows terminal, you actually have to set the terminal to use the nerd font. This took me far too long to figure out so hopefully it helps the next person.
In windows terminal, open the settings, then the Defaults on the left blad, then the appearance tab, finally change the fontface to something nerd font
https://www.jondjones.com/media/rhzobluq/customise-your-powershell-prompt-like-a-boss-c.gif
source: https://www.jondjones.com/tactics/productivity/customise-your-powershell-prompt-like-a-boss/
Comment: As suggested in the oh-my-posh document,I was updating the default font family whereas I needed to update the font family of specific 'Windows Terminal'.
Answer: I faced the same issue and solved it by editing the following file: C:\Path\To\Your\WindowsPowerShell\Modules\oh-my-posh\2.0.496\defaults.ps1
Within PromptSymbols, there should be something called VirtualEnvSymbol. Just change the value from the current one to something from the above listed ones. For example,
VirtualEnvSymbol = [char]::ConvertFromUtf32(0x26A1)

Comment: This file no longer exists. I suspect that OMP 3.x versions changed this behavior to requiring setup in the theme JSON files.
Answer: I've encounter the same problem and was solved installing the fonts.

Download the fonts at https://github.com/microsoft/cascadia-code/releases
Unzip
Right click on the font and select "Install the font for all users"

Enjoy !

From : https://github.com/microsoft/cascadia-code
Answer: Just install this whole Cascadia Code font and it will work no need to modify the theme settings.
https://github.com/ryanoasis/nerd-fonts/tree/master/patched-fonts/CascadiaCode/Regular/complete
Comment: Can you include an explanation of why this is a better choice than installing the Microsoft font as detailed in [this previous answer](https://stackoverflow.com/a/66031848/2449857)?
Comment: Thats because I tried the cascade one but it didn't work, I tried many other fonts too but  this nerd one worked for both VS code and ubuntu(wsl) plus terminal/powershell.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31108765)
Comment: This should be the official answer. Everything else is brittle at best. This solves everything.

You need to set the the Font in Windows Terminal, by opening Settings, then look in the left bar for `Profiles` and under that `Defaults`. Set the Font Face to `CaskaydiaCove Nerd Font Mono.` Or, hold SHIFT while clicking `Settings` in Windows terminal and edit the JSON:
````
"profiles":
    {
        "defaults":
        {
            "font":
            {
                "face": "CaskaydiaCove Nerd Font Mono"
            },
            "useAtlasEngine": true
        }
````
Answer: I went round and round on this trying to remap codes that were missing in JSON per helpful answers.
What I learned is not all Fonts are as "complete" as you'd want, but if you find one, there's no hacking or alterations needed.
Just installing using this font Delugia this fixed all my issues with pwsh (PowerShell 7.x) and Windows. I've tested in Windows Terminal and VS Code.
https://github.com/adam7/delugia-code


How to get records between a timeframe

Question: I have a simple model called Event.
I'm trying to grab the Events that have a scheduled_at:datetime within the next 30 minutes.
I've tried this but it's not working like I need it do - I must be doing something wrong.
Event.where('scheduled_at > ?', Chronic.parse('now'))
     .where('scheduled_at < ?', Chronic.parse('30 minutes from now'))
     .find_each do |event|
  puts event.id
end

Answer: You can use:
 Event.where(scheduled_at: DateTime.now..(DateTime.now + 30.mins))

Answer: The below query will give you the data between the given dates and time. Better you just check the records inside the console.
Event.where('date(scheduled_at) > ?', Chronic.parse('now'))
     .where('date(scheduled_at) < ?', Chronic.parse('30 minutes from now'))

Answer: Event.where(scheduled_at: DateTime.now..(DateTime.now + 30.minutes))
Event.where(:scheduled_at => DateTime.now..(Time.zone.now + 30.minutes))
Event.where{'scheduled_at ? '> DateTime.now & 'scheduled_at ?' < DateTime.now + 30.mins}

How to get records between a timeframe


'Permission denied' error when I tried to use getUserMedia in teams desktop popup window

Question: I use microsoftTeams.authentication.authenticate to open our app(the sample code is https://github.com/Wajeed-msft/DevicePermissionsDemo/blob/master/DevicePermissionsDemo/Pages/Index.cshtml).
microsoftTeams.authentication.authenticate({
  url: <our app's url, use https policy>,
  width: 300,
  height: 520,
})

And when I try to use navigator.mediaDevices.getUserMedia({ audio: true }) to request user media permission, it always returns error "DOMException: Permission denied". Error is page shows

according to doc: https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/native-device-permissions?tabs=desktop
my teams app already get the permission:

Same is chrome settings in chrome://settings/content/siteDetails?site=https%3A%2F%2Fteams.microsoft.com%3A443
Answer: Could you please take a look at following device permission sample code which have getUserMedia() device permissions implemented for Tab.
Comment: Thanks, I tried. It shows Error 'Error name: NotAllowedError; Error message: Permission denied; Error constraintName: undefined'
Comment: Hi @joyvince, Could you please get permissions from your IT Admin.
Comment: Hi @Jagadeesh-MSFT, I  think I could get the permissions because I can get the microphone permissions on the Personal Tab page, I just cannot get the permissions in the popup window. Or how could I check if I can get permissions?


COUNT em multiplas tabelas do mysql

Question: Boa tarde, alguém sabe me informar oque á de errado no codigo abaixo ?
Pois ele apenas faz a verificação count em uma tabela as demais ele ignora.
o Insert está correto porem o "Select Count" nao verifica todas apenas o primeiro comando.
segue o codigo:
'inicia uma FOR para verificação e impedir inserts de duplicados.

For r As Integer = 0 To DataGridView1.Rows.Count - 1

Dim resultquery As String = "SELECT

(SELECT COUNT(cnpjcpf_cnpjcpf) FROM cnpjcpf WHERE cnpjcpf_cnpjcpf ='" & DataGridView1.Rows(r).Cells(7).Value & "'),

(SELECT COUNT(mov_identificacao) FROM movimento WHERE mov_identificacao ='" & DataGridView1.Rows(r).Cells(0).Value.ToString & "'),

(SELECT COUNT(imov_mov_identificacao) FROM imovimento WHERE imov_mov_identificacao ='" & DataGridView1.Rows(r).Cells(0).Value.ToString & "')"

 command = New MySqlCommand(resultquery, sqlcoon)
 resultquery = command.ExecuteScalar()

   If resultquery = 0 Then

' insere os dados do datagridview na tabela do banco de dados

  Dim Query As String = '"insert into cnpjcpf (cnpjcpf_cnpjcpf) values(@cnpjcpf_cnpjcpf);" +
                         "insert into movimento (mov_identificacao,mov_protocolo,mov_destinatario,mov_endereco,mov_bairro,mov_cep,mov_datadoc,mov_cnpj_cpf,mov_cli_codigo,mov_dataprocessa,mov_datavencimento) values(@mov_identificacao, @mov_protocolo, @mov_destinatario, @mov_endereco, @mov_bairro, @mov_cep, @mov_datadoc, @mov_cnpj_cpf, @mov_cli_codigo, @mov_dataprocessa, @mov_datavencimento);" +
                         "insert into imovimento (imov_mov_identificacao,imov_mov_protocolo,imov_dataprocessa) values(@imov_mov_identificacao,@imov_mov_protocolo,@imov_dataprocessa);"
                    Dim CmdSalvarItens As New MySqlCommand(Query, sqlcoon)

     'EXECUTA O INSERT NA TABELA CNPJ/CPF
      CmdSalvarItens.Parameters.Add("@cnpjcpf_cnpjcpf", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells(7).Value

       'EXECUTA O INSERT NA TABELA MOVIMENTOS
       CmdSalvarItens.Parameters.Add("@mov_identificacao", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Identificação").Value
       CmdSalvarItens.Parameters.Add("@mov_protocolo", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Protocolo").Value
       CmdSalvarItens.Parameters.Add("@mov_destinatario", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Destinatario").Value
       CmdSalvarItens.Parameters.Add("@mov_endereco", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Endereço").Value
       CmdSalvarItens.Parameters.Add("@mov_bairro", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Bairro").Value
       CmdSalvarItens.Parameters.Add("@mov_cep", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Cep").Value
       CmdSalvarItens.Parameters.Add("@mov_datadoc", MySqlDbType.Date).Value = dinicio
       CmdSalvarItens.Parameters.Add("@mov_cnpj_cpf", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("CNPF/CPF").Value
       CmdSalvarItens.Parameters.Add("@mov_cli_codigo", MySqlDbType.VarChar).Value = txtcod.Text
       CmdSalvarItens.Parameters.Add("@mov_dataprocessa", MySqlDbType.Date).Value = dfim
       CmdSalvarItens.Parameters.Add("@mov_datavencimento", MySqlDbType.Date).Value = ddata

       'EXECUTA O INSERT NA TABELA IMOVIMENTOS
       CmdSalvarItens.Parameters.Add("@imov_mov_identificacao", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Identificação").Value
       CmdSalvarItens.Parameters.Add("@imov_mov_protocolo", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Protocolo").Value
       CmdSalvarItens.Parameters.Add("@imov_dataprocessa", MySqlDbType.VarChar).Value = dfim

          CmdSalvarItens.ExecuteNonQuery()

        Else

        End If

       Next

Alguem pode me dizer oque esta errado no (string - ResultQuery) onde esta sendo feito os 3 select count??
Answer: Penso que isto resolve o seu problema:
Dim reader As MySqlDataReader
Dim CmdSalvarItens As MySqlCommand
Dim Query As String
Dim resultquery As String

Dim strCPF As String
Dim strMovimentos As String
Dim strImovimentos As String

'inicia uma FOR para verificação e impedir inserts de duplicados.
For r As Integer = 0 To DataGridView1.Rows.Count - 1
    strCPF = DataGridView1.Rows(r).Cells(7).Value.ToString
    strMovimentos = DataGridView1.Rows(r).Cells(0).Value.ToString
    strImovimentos = DataGridView1.Rows(r).Cells(0).Value.ToString

    resultquery = "SELECT
        (SELECT COUNT(cnpjcpf_cnpjcpf) FROM cnpjcpf WHERE cnpjcpf_cnpjcpf ='" & strCPF & "'),
        (SELECT COUNT(mov_identificacao) FROM movimento WHERE mov_identificacao ='" & strMovimentos & "'),
        (SELECT COUNT(imov_mov_identificacao) FROM imovimento WHERE imov_mov_identificacao ='" & strImovimentos & "')"

    command = New MySqlCommand(resultquery, sqlcoon)
    reader = command.ExecuteReader()
    reader.Read()

    Dim objs(3) As Object
    Dim quant As Integer = reader.GetValues(objs)

    'TABELA CNPJ/CPF
    If objs(0) = 0 Then
        'insere os dados do datagridview na tabela do banco de dados
        Query = "insert into cnpjcpf (cnpjcpf_cnpjcpf) values(@cnpjcpf_cnpjcpf);"

        CmdSalvarItens = New MySqlCommand(Query, sqlcoon)
        CmdSalvarItens.Parameters.Add("@cnpjcpf_cnpjcpf", MySqlDbType.VarChar).Value = strCPF

        CmdSalvarItens.ExecuteNonQuery()
    End If

    'TABELA MOVIMENTOS
    If objs(1) = 0 Then
        'insere os dados do datagridview na tabela do banco de dados
        Query = "insert into movimento (mov_identificacao,mov_protocolo,mov_destinatario,mov_endereco,mov_bairro,mov_cep,mov_datadoc,mov_cnpj_cpf,mov_cli_codigo,mov_dataprocessa,mov_datavencimento) values(@mov_identificacao, @mov_protocolo, @mov_destinatario, @mov_endereco, @mov_bairro, @mov_cep, @mov_datadoc, @mov_cnpj_cpf, @mov_cli_codigo, @mov_dataprocessa, @mov_datavencimento);"

        CmdSalvarItens = New MySqlCommand(Query, sqlcoon)
        CmdSalvarItens.Parameters.Add("@mov_identificacao", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Identificação").Value
        CmdSalvarItens.Parameters.Add("@mov_protocolo", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Protocolo").Value
        CmdSalvarItens.Parameters.Add("@mov_destinatario", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Destinatario").Value
        CmdSalvarItens.Parameters.Add("@mov_endereco", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Endereço").Value
        CmdSalvarItens.Parameters.Add("@mov_bairro", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Bairro").Value
        CmdSalvarItens.Parameters.Add("@mov_cep", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Cep").Value
        CmdSalvarItens.Parameters.Add("@mov_datadoc", MySqlDbType.Date).Value = dinicio
        CmdSalvarItens.Parameters.Add("@mov_cnpj_cpf", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("CNPF/CPF").Value
        CmdSalvarItens.Parameters.Add("@mov_cli_codigo", MySqlDbType.VarChar).Value = txtcod.Text
        CmdSalvarItens.Parameters.Add("@mov_dataprocessa", MySqlDbType.Date).Value = dfim
        CmdSalvarItens.Parameters.Add("@mov_datavencimento", MySqlDbType.Date).Value = ddata

        CmdSalvarItens.ExecuteNonQuery()
    End If

    'TABELA CNPJ/CPF
    If objs(2) = 0 Then
        'insere os dados do datagridview na tabela do banco de dados
        Query = "insert into imovimento (imov_mov_identificacao,imov_mov_protocolo,imov_dataprocessa) values(@imov_mov_identificacao,@imov_mov_protocolo,@imov_dataprocessa);"

        CmdSalvarItens = New MySqlCommand(Query, sqlcoon)
        CmdSalvarItens.Parameters.Add("@imov_mov_identificacao", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Identificação").Value
        CmdSalvarItens.Parameters.Add("@imov_mov_protocolo", MySqlDbType.VarChar).Value = DataGridView1.Rows(r).Cells("Protocolo").Value
        CmdSalvarItens.Parameters.Add("@imov_dataprocessa", MySqlDbType.VarChar).Value = dfim

        CmdSalvarItens.ExecuteNonQuery()
    End If

    reader.Close()
Next

O problema estava no facto de estar a utilizar ExecuteScalar(), que apenas lhe traz úm único valor, quando na verdade queremos trazer 3.
Posto isto, utilizamos o ExecuteReader() para ler todos os resultados (que neste caso é apenas uma linha com 3 colunas) e depois vamos um a um executar as queries.
Comment: obrigado pelo retorno João , mas ainda não deu certo o seu exemplo. mesmo eu modificando o código da maneira que me aconselhou. retorna o seguinte error : If myreader.GetInt32(1) = 0 Then --> "You have specified an invalid column ordinal." e tive que acrescentar um Reader.Close() posterior do Reader.read() senão apontava que jã tinha um Reader sendo utilizado.
Comment: Resposta editada, tinha alguns erros! Experimente de novo :)
Comment: João Permaneceu o error. eu fiz um teste. Comentei todas as linhas onde tem ' Tabela movimento e Imovimentos . e deixei apenas o IF da tabela cnpj/cpf. e entao acrescentei um reader.close() ficando assim ->  If reader.GetInt32(0) = 0 Then
                    reader.Close()  - Funcionou perfeitamente. descometei o IF da tabela Movimentos e tentei fazer o mesmo porém. deu error o mesmo error (""You have specified an invalid column ordinal." Acredito eu que falta apenas um detalhe para funcionar.
Comment: Se colocar a _query_ no SQL o que é que lhe devolve?
Comment: da maneira que vc me deu sem eu alterar devolve:
Já existe um DataReader aberto associado a esta conexão que deve ser fechado primeiro. - por isso acrescente reader.close() pra ver se funcionava. quando tem apenas um IF reader.close() resolve. quando eu acrescente mais um não funciona mais.
Comment: Não, não era isso. Se pegar na _query_ SQL resultante da variável `resultquery` e colocar diretamente no SQL, que resultado lhe dá? Devolve-lhe 3 colunas com números inteiros?
Comment: sim retorna 3 numero . porém por serem os primeiros dados a serem inseridos. retorna ( 0 , 0 , 0). Acredito que o error seja que Alguma parte do código antes ou depois do IF o Reader precisa ser fechado. tanto que se remover os comentarios dos 2 IF ' tabela movimentos e imovimentos e acrescenter Reader.close() o error só vem no terceiro if.
Comment: Resposta editada com código diferente.
Comment: João,reformulei o código de acordo com a alteração que você acabou de fazer. Retornou o error no  CmdSalvarItens.ExecuteNonQuery() do Primeiro IF ( If objs(0) = 0 Then) error : "There is already an open DataReader associated with this Connection which must be closed first "
Comment: joão conseguir resolver, acrescentando o Read.close()  Dim quant As Integer = reader.GetValues(objs) resolveu o problema , fiz a alteração no código que você editou. muito obrigado mesmo pela solução, pelo tempo e atenção.

COUNT em multiplas tabelas do mysql


Why Read_HTML from Python Pandas not working?

Question: I would like to use Python Pandas Read_HTML() function to scrape the information from Yahoo Finance table, seen in the screenshot, bordered in red.

However, I received a HTTPError: HTTP Error 404: Not Found
Here is my code output:
!pip install pandas
!pip install requests
!pip install bs4
!pip install requests_html
!pip install pytest-astropy
!pip install nest_asyncio
!pip install plotly

import pandas as pd
from bs4 import BeautifulSoup
import requests
import requests_html
import nest_asyncio
import lxml
import html5lib
nest_asyncio.apply()

url_link = "https://finance.yahoo.com/quote/NFLX/history?p=NFLX%27"
read_html_pandas_data = pd.read_html(url_link)

Answer: Try as follows:
import pandas as pd
import requests
url_link = 'https://finance.yahoo.com/quote/NFLX/history?p=NFLX%27'
r = requests.get(url_link,headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'})
read_html_pandas_data = pd.read_html(r.text)[0]
print(read_html_pandas_data)

Comment: just add User-Agent
Comment: Now you will get  data
Comment: If you want to access the site's  data , then it's requirement is to get your real identification that's why you have to inject user-agent as header. Thanks
Comment: Hi, thanks for the response! However, I received this output: [                                                   0
0  Will be right back...  Thank you for your pati...]
Comment: Brilliant, thanks! I got output, but how do I transpose the rows to columns?
Answer: Because an user-agent header is needed which can't be specified with read_html. You could grab table first with requests, specifying the appropriate header, then handover to pandas:
from pandas import read_html as rh
import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://finance.yahoo.com/quote/NFLX/history?p=NFLX%27', headers = {'User-Agent':'Mozilla/5.0'})
soup = bs(r.content, 'lxml')
table = rh(str(soup.select_one('[data-test="historical-prices"]')))[0]
print(table)

Comment: table is already a dataframe. That has a transpose() method. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transpose.html
Comment: Hi, thanks for the response! Is there a way to transpose the rows to columns and place them in a DataFrame? Here is the current output:                                                Date  \
0                                         Jul 02, 2021
1                                         Jul 01, 2021
2                                         Jun 30, 2021


Find all values of $c$ for which $(1+c)^k - c^k - kc^{k-1} \ge 0$

Question: For an integer $ k \ge 1$ and and a real number $c$, consider the polynomial function $f_{k,c}:\mathbb R \to \mathbb R$ by $f_{k,c}(z) = (z+c)^k$. Also define $r_{k,c} := f_{k,c}(1) - f_{k,c}(0) - f'_{k,c}(0)=(1+c)^k - c^k - kc^{k-1}$. I'm interested in the set of values of $c$ for which $r_{k,c} \ge 0$, i.e the set $S_k := \{c \in \mathbb R \mid r_{k,c} \ge 0\}$.
The case of even $k$
It is clear that if $k$ is even, then $f_{k,c}$ is convex and so $S_k = \mathbb R = (-\infty,\infty)$.
The case of odd $k$
Experiments seem to show that when $k$ is odd, $S_k$ is always an interval of the form $[c_k,\infty)$, for some $c_k \le 0$ with $r_{k,c_k} = 0$.

Question 1. Is it really true that for odd $k$, one has $S_k = [c_k,\infty)$ for some $c_k  \in (-\infty,0]$ with $r_{k,c_k} = 0$ ?

In case the answer to the above question is affirmative,

Question 2. For large $k$, what is a good estimate for $c_k$ ?
Answer: Consider the polynomials
$$
 p_k(x) = (1+x)^k - x^k - k x^{k-1} \, .
$$
The case $p_1(x) = 0$ is not interesting, therefore we will consider $k \ge 2$ only.
$p_k$ is a polynomial with the exact degree $k-2$, and
$$
 p_k'(x) = k p_{k-1}(x) \, .
$$
This property can be used to prove that

If $k\ge 2$ is even then $p_k(x) > 0$ for all $x \in \Bbb R$.
If $k \ge 3$ is odd then $p_k$ is strictly increasing and has exactly one zero $c_k$. Also $-1 < c_k < 0$.

Sketch of a proof via induction:

The claim surely holds for $p_2(x) = 1$ and $p_3(x) = 3x+1$.
If $k$ is even and $p_k(x) > 0$ for all $x$ then $p_{k+1}$ is strictly increasing. Also $p_k(-1) = 1-k < 0$ and $p_k(0) = 1 > 0$. It follows that $p_{k+1}$ has exactly one zero $c_k$, and that is in the interval $(-1, 0)$.
If $k$ is odd and $p_k$ is strictly increasing with exactly one zero $c_k$ then $p_{k+1}$ is decreasing on $(-\infty, c_k]$ and increasing on $[c_k, \infty)$. Also
$$
 p_{k+1}(c_k) = (1+c_k)^{k+1} - c_k^{k+1}-(k+1)c_k^k \\
 = (1+c_k)(c_k^k + kc_k^{k-1}) - c_k^{k+1}-(k+1)c_k^k \\
 = kc_k^{k-1} > 0
$$
shows that the minimum of $p_{k+1}$ is strictly positive.

Therefore, in your notation, $S_k = \Bbb R$ if $k$ is even, and $S_k = [c_k, \infty)$ with some $c_k \in(-1, 0)$ if $k$ is odd.
The following estimate holds for odd $k$:
$$
 -\frac 12 < c_k < d_k := - \frac 12 \cdot \frac{1}{(k2)^{1/(k-1)}} \, ,
$$
so that in particular $\lim_{n \to \infty} c_{2n+1} = -1/2$.
The lower bound follows from $g(-1/2) < 0$, and the upper bound follows from
$$
 g_k(x) > \frac{1}{2^k} - kx^{k-1}
$$
for $x > -1/2$ and determining $d_k$ as the solution of $\frac{1}{2^k} - kx^{k-1} = 0$.
Comment: A better estimate: $-1/2 < c_k < 0$ for odd $k$, since $g(-1/2) = (1-k)/2^{k-1} < 0$.
Comment: @dohmatob: The limit is $-1/2$, I have added that to the answer.
Comment: Ideally, there is a localization of $c_kk$ which depends on $k$. For example, one could wonder what is the limit of $c_{2n+1}$ as $n \to \infty$.


Module's optional field config not imported on install

Question: I've got a module which contains a config/optional folder which has the content:
paragraphs.paragraphs_type.my_paragraph_id.yml
field.field.paragraph.my_paragraph_id.field_my_field.yml
field.storage.paragraph.field_my_field.yml
core.entity_form_display.paragraph.my_paragraph_id.yml
core.entity_view_display.paragraph.my_paragraph_id.yml

These files have been exported from an existing installation without uuid's. When I enable the module, the config does not import since the module paragraphs has not yet been enabled. When I enable paragraphs the paragraph type my_paragraph_id is created as expected. The field storage for field_my_field is also created, since I can create a new field based on the existing field field_my_field. Though, the field is not created on the paragraph itself.
I've tried moving the config files to config/install and then it simply works as expected; the field gets created on the paragraph just fine. But the module paragraph should be optional and only then the config should be created, therefor, I want it to be optional.
Why does the config/optional not install the field?
Answer: Optional config is only installed if it has an explicit dependency on a module that is being installed right now. Otherwise that configuration would be re-installed every time you install a module, even if it is something you chose to delete on a specific site.
The downside of that is that there are some grey areas of config that depends on config that depends on a module being installed that isn't found by this. Although that should also work but apparently does not in this case.
As a workaround, you can add an enforced dependency on the paragraphs module on those configurations that aren't being imported, then it should work. See https://www.drupal.org/node/2404447
Comment: I knew about `enforced`, but I figured that that only made sure that dependencies in that property were made persistent and not auto-calculated. I did not know that it would have impact on optional config and the import of that on install. Thanks! It works now!


Python cancel raw_input/input via writing to stdin?

Question: For starters, I'm on python 2.7.5 and Windows x64, my app is targeted at those parameters.
I'm in need of a way to cancel a raw_input after a certain amount of time has passed.  Currently I have my main thread starting two child threads, one is the timer (threading.Timer) and the other fires the raw_input.  These both return a value to a Queue.queue that the main thread monitors.  It then acts on what is sent to the queue.
<code># snip...
q = Queue.queue()
# spawn user thread
user = threading.Thread(target=user_input, args=[q])
# spawn timer thread (20 minutes)
timer = threading.Timer(1200, q.put, ['y'])
# wait until we get a response from either
while q.empty():
    time.sleep(1)
timer.cancel()

# stop the user input thread here if it's still going

# process the queue value
i = q.get()
if i in 'yY':
    # do yes stuff here
elif i in 'nN':
    # do no stuff here

# ...snip

def user_input(q):
    i = raw_input(
        "Unable to connect in last {} tries, "
        "do you wish to continue trying to "
        "reconnect? (y/n)".format(connect_retries))
    q.put(i)
</code>
The research that I've done so far seems to say that it's not possible to "correctly" cancel a thread.  I feel that processes are too heavy for the task, though I'm not opposed to using them if that's what really needs to be done.  Instead, my thought is that if the timer finishes with no user input, I can write a value to stdin and close that thread gracefully.
So, how do I write to stdin from the main thread so that the child thread accepts the input and closes gracefully?
Thanks!
Answer: You can use the threading.Thread.join method to handle the timeout. The key to getting it working is to set the daemon attribute as shown below.
<code>import threading

response = None
def get_response():
    global response
    response = input("Do you wish to reconnect? ")

thread = threading.Thread(target=get_response, daemon=True)
thread.start()
thread.join(2)
if response is None:
    print()
    print('Exiting')
else:
    print('As you wish')
</code>
Comment: Amazing.  This is the only example that actually performs a proper timeout of `input` (for Python 3), without having to press `Enter` key again to have the code continue to run.
Comment: I do believe that will work as in my case (a CLI program), I won't care if the main thread blocks while we're waiting for input.  Thanks!


Direct calculation of flux in 3D

Question: Question;
What is the flux of the vector field $F=<x,-y,z>$ out through the surface of the cylinder which is $x^{2} + y^2 = a^2 , 0<z<b$.
I can easily find the answer by divergence theorem but when I try to direct calculation of the flux through the surface , I find 0.Am I doing some algebra mistakes or do I miss anything different ?
My path;
$$\int \int <x,-y,z>.\frac{<x,y,0>}{a} dS \\
x=a*cos\theta \\
y=a*sin\theta \\
\int_0^b \int_0^{2\pi} \frac{a^2 *cos2\theta}{a}*a*d\theta dz \\
$$
Comment: What is F? And you have given the equation of a circle and mentioned 3D flux.
Comment: Why don't you post your working for the direct calculation so we can _see_ where the mistake(s) lie.
Comment: @SchrodingersCat corrected.
Comment: @Mattos I added.
Answer: The integration over divergence is correct and it is $\pi b a^2$
The integration on surface is correct except for mission the top and the bottom of the cylinder!
$$\int \vec F .d \vec S= \text{flux around} + \text{flux top} + \text{flux bottom}=\\\iint (x,-y,z).(\frac x a,\frac y a,0) dS+\iint (x,-y,b).(0,0,1)dS+\iint (x,-y,0).(0,0,-1)dS\\ =\pi b a^2$$
Using divergence:
$$\vec \nabla . \vec F=1$$
$$\iiint (\vec \nabla . \vec F) dV=V=\pi b a^2$$
Comment: @Arasgium Thanks for your answer.By the way , for the bottom part $\vec{F}=$

Direct calculation of flux in 3D


Date Conversion in .net format "dd/mm/yyyy HH:mm:ss AM/PM"

Question: I'm trying to convert a date formatted like
dd/mm/yyyy HH:mm:ss AM/PM
into
YYYY-mm-dd hh:mm:ss.fffZ
but had no success.
This is what I've tried:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-CA");
string inputDate = "14/02/2008 1:55:11 PM";
DateTime newDate = Convert.ToDateTime(inputDate);
DateTime.TryParseExact(inputDate, "dd/MM/yyyy HH:mm:ss", enUS, System.Globalization.DateTimeStyles.None, out newDate);

and also:
string inputDate = "14/02/2008 1:55:11 PM";
string nw = String.Format("{0:u}", Convert.ToDateTime(inputDate));

apart from a few other tricks but nothing seems to work. Please help.
My input string is: "14/02/2008 1:55:11 PM"and my output should be "2008-02-14 1:55:11.000Z".
Answer: Hope this helps:
string inputdate = "14/02/2008 1:55:11 PM";
DateTime date = DateTime.Parse(inputdate);
string newDate = date.ToString("yyyy-MM-dd h:m:s.fffZ");

I changed "YYYY-mm-dd hh:mm:ss.fffZ" to "yyyy-MM-dd h:m:s.fffZ" because you said:

my output should be 2008-02-14 1:55:11.000Z

Using hh:mm:ss would add leading zeros:
2008-02-14 01:55:11.000Z


Significance testing of categorical variables - is chi squared as good as it gets?

Question: I am testing categorical variables for significant relationships, 5 age groups and 3 answer options (yes/no/don't know). Is there a test which will specifically tell me if e.g. age group 1 is significantly more likely to answer 'yes' than age group 2?
I have been using chi-squared but this only tells me if there is a difference in the pattern and not specifically where the difference comes from.
Is looking at indexed values and percentages in the chi-squared table really the only way to find out where the difference came from? I find this method could be fairly inaccurate if a variable has many categories?
Comment: It may be the case that age should not be understood *categorically* but ordinally, or even continuously (e.g. increasing age increases probability of such-and-such answer). Just a thought.
Comment: These are commonly known as *contrasts*. After running a regression/ANOVA, one can can test linear combinations of the coefficients (for example, Age 1 vs Age 2, or something more complex such as Age 1 and 2 vs Age 3). However, your case is a bit more complicated since your outcome variable (answer options) is multinomial.
Comment: @Julia: Contrasts are on parameters, so, yes.
Comment: Can contrasts be used for categorical variables?
Comment: You could look at log-linear models, simply said they try to predict the counts in the cells of you contingency table.  But if you google it you will find several links.
Answer: With three answer options, yes/no/don't know, you might look into multinomial logistic regression.  Or, maybe, if in your context you can justify an ordering like yes/don't know/no, you can use ordinal logistic regression.  If the predictor variable is age, that can be coded as an ordered variable, maybe with only linear and quadratic effects.
If this is more efficient than chi square tests? You could try some simulations to find out ...


Any way to exploit relations between examples in dataset?

Question: Suppose I have a dataset with k examples:
<code>
id1, feature1, feature2 .. featuren
...
idk, feature1, feature2 .. featuren
</code>
For which I can label a training set and feed it to some classification algorithm, getting predictions.
Suppose my examples are also vertices in a sparse undirected graph.
Is this possible to come up with some reasonable model that ensures predictions for neighbouring vertices tend to be the same?
Comment: Have you looked at the k nearest neighbors method?
Comment: @TrynnaDoStat Yes, thank you I've been thinking about it, though never gave it a try. How do I incorporate graph distance into a euclidean (or any other mertic) in the feature space?
Answer: In general, if you want to feed extra information about the examples to the classifier, you add this information as a feature. In your case, you would add some notion of the position of the example in the graph as a feature, so that examples that are close together have close values.
Comment: Yes this is probably the way to go.
But I seriously lack options here. I can think of some graph visualization technique mapping vertices into a [probably multidimensional] plane. But for my graph [and I should have mentioned that], there could be connected components as small as just two vertices yet with really informative edge between them. So, even I map the entire graph on a plane, I'd hardly grasp any correlations unless I use an extremely complex model and overfit terribly.
Any other way to map the graph into a feature space?


What is the probability of having both girls given that at least one of them is girl?

Question: I'm reading the textbook entitled Harvard Statistics by Joseph K. Blitskein. In conditional probability context, I'm a little bit confused of calculating the intersection of event A and B $P(A\cap B)$. The problem is given below;

Example 2.2.5 (Elder is a girl vs. at least one girl). A family has two children, and it is known that at least one is a girl. What is the probability that both are girls, given this information? What if it is known that the elder child is a girl?

For the solution (based on textbook):
First, let the following events equal to A and B (just to keep it short):
A = event of having both girls, B = event of at least one girl
$$P(A|B)=\frac{P(A∩B)}{P(B)}=\frac{1/4}{3/4}=1/3$$
Intuitively, the answer is correct but I was wondering on why $P(A∩B)=1/4$. Since $P(A∩B)=P(A)P(B)$, which in this case $P(A)=1/4$ and $P(B)=3/4$. Just to give you a reference, the possible combinations of having two children are ${\{GG, BG, GB, BB}\}$.
Anyone can shed me a light regarding with my problem?
Comment: Probabilty both girls and probability at least one girl are not independent.  It is *impossible* to have two girls if there is not at least one girl and if you have two girls it is impossible *not* to have at least one girl.  Common sense: $A\subset B$ and   $A\cap B = A$ and $P(A\cap B) = P(A)$
Comment: Thing to realize is when $A \subset B$ then $A\cap B = A$ and $P(A\cap B) = P(A)$.
Comment: related https://math.stackexchange.com/questions/1266043/boy-and-girl-paradox-is-driving-me-crazy
Answer: $A$ and $B$ should be defined as events and not probabilities. $A$ is the event of having both girls and $B$ is the event of having at least one girl. By definition, you can see that they are not independent events. Hence $P(A,B) = P(A)P(B)$ does not hold. When we estimate $P(A,B)$, only one combination works $(GG)$ out of the four possible combinations. Hence the probability of both having both girls and having at least one girl is $P(A,B)=1/4$.
Comment: @King $P(A,B)=P(A)P(B)$ only for ***in***dependent events.
Comment: Oh I see! thanks for the correction. I misunderstood the definition of $P(A,B)$ that's the reason why I'm having a trouble on calculating the intersection of two events. This rule $P(A,B) =  P(A)P(B)$ is only applicable for dependent events?
Comment: Thanks I got it now :) sorry for noob question.


How do you give the content of a node a margin/padding without using html within the node?

Question: How would you go about giving an entire node (the content) a margin or padding to the edge of the node - without using html within the node - in drupal?

Is there a module for this?
If not - how do you do so using CSS?
Comment: it varies per whatever theme you use. it's typically something like `div.node` or `div.node div.content` as an example. tools like Firebug and Chrome developer tools can show you what classes a piece of content has in your HTML page. Using DisplaySuite for example you could provide additional classe(s) to any piece of view_mode -- but the basic markup exists per theme to target a nodes output on the screen.
Comment: Have you ever heard of css? It requires 0 html and 0 php.
Comment: Why yes of course - but what is the css class/tag for the entire content of a node?
I thought people might answer with a module that did it or otherwise explain the CSS needed
Answer: it varies per whatever theme you use. it's typically something like div.node or div.node div.content as an example. tools like Firebug and Chrome developer tools can show you what classes a piece of content has in your HTML page. Using DisplaySuite for example you could provide additional classe(s) to any piece of content within view_mode -- but the basic markup exists per theme to target a nodes output on the screen.
It not only varies per whatever theme your using, but if your theme is HTML5 vs HTML4 (why in this day in age, i dunno) it may be article.node as a CSS selector because article is a new HTML5 element type, vs say a plain old div.node in older versions of HTML.


Button inside a table does not work clicking at all

Question: I have a button that when clicked changes its status within a table, when I load the page and click on any one, it only activates the first one from above and the others do not, and also it does not return to the previous status, I would like to know the that I'm doing wrong.

In the image above, when I click on any one, it activates only the first one and does not deactivate it back,
And the 3rd has already been activated and I can't move it, I think there's something wrong with the map or something...
{
    this.state.dataSource.map((data) => {
        function ChangeIcon(e) {
            e.preventDefault();
            if (data.statusPedido === "Em aberto") {
                var btn = document.getElementById("btn-times");
                btn.style.display = "none";

                var btn2 = document.getElementById("btn-check");
                btn2.style.display = "block";
            }
        }
        return (

                {data.nrPedido}
                {data.dataPedido}
                {data.dtEntrega}
                {data.totalDoses}
                {data.totalDosesConvencionais}
                {data.totalDosesCervicais}
                {data.rota}
                {data.periodoLactacao}
                {data.plantelMatrizes}
                {data.porcentagemReposicaoLeitoas}

                    {data.statusPedido === "Em aberto" ? (

                            <button
                                className="btn"
                                onClick={ChangeIcon}
                                style={{ backgroundColor: "transparent" }}
                                id="btn-times"
                            >
                                <FontAwesome name="times" />
                            </button>
                            <button
                                className="btn"
                                id="btn-check"
                                style={{ display: "none", backgroundColor: "transparent" }}
                            >
                                <FontAwesome name="check" />
                            </button>

                    ) : (
                        <button
                            className="btn"
                            style={{ backgroundColor: "transparent" }}
                            id="btn-check"
                        >
                            <FontAwesome name="check" />{" "}
                        </button>
                    )}

        );
    });
}

Comment: You had a missing closing  tag, I fixed it in the format edit.
Comment: I didn't copy the tag in the example, but it is closed hehe
Answer: In your example, you render a list of elements produced by a map function, but you forgot to assign keys to the elements (tr's in your case). Keys help React identify which items have changed, are added, or are removed. Without keys, you can get a lot of hard to catch bugs because React does not understand which row to update. The best choice for a key would be an ID or other unique string to identify each row in this table.
Comment: I'm trying to do it, but I'm not getting it to work.
Answer: You are right! The problem is with the map method. The reason is that you're not providing a unique key property for each returned element.
You can fix it this way:

{
    // Add an index argument
    this.state.dataSource.map((data, index) => {
        function ChangeIcon(e) {
            e.preventDefault();
            if (data.statusPedido === "Em aberto") {
                var btn = document.getElementById("btn-times");
                btn.style.display = "none";

                var btn2 = document.getElementById("btn-check");
                btn2.style.display = "block";
            }
        }
        return (
        // Use that index here as key property

                {data.nrPedido}
                {data.dataPedido}
                {data.dtEntrega}
                {data.totalDoses}
                {data.totalDosesConvencionais}
                {data.totalDosesCervicais}
                {data.rota}
                {data.periodoLactacao}
                {data.plantelMatrizes}
                {data.porcentagemReposicaoLeitoas}

                    {data.statusPedido === "Em aberto" ? (

                            <button
                                className="btn"
                                onClick={ChangeIcon}
                                style={{ backgroundColor: "transparent" }}
                                id="btn-times"
                            >
                                <FontAwesome name="times" />
                            </button>
                            <button
                                className="btn"
                                id="btn-check"
                                style={{ display: "none", backgroundColor: "transparent" }}
                            >
                                <FontAwesome name="check" />
                            </button>

                    ) : (
                        <button
                            className="btn"
                            style={{ backgroundColor: "transparent" }}
                            id="btn-check"
                        >
                            <FontAwesome name="check" />{" "}
                        </button>
                    )}

        );
    });
}

To know more about Lists and Keys in React, you can check the The official documentation
Comment: I added this same code and it didn't work, it was the same format
Answer: I think it has something to do with the conditional rendering you are doing. In that case, try this:
{data.statusPedido === "Em aberto" ? (
                        <button
                            className="btn"
                            onClick={ChangeIcon}
                            style={{ backgroundColor: "transparent" }}
                            id="btn-times"
                        >
                            <FontAwesome name="times" />
                        </button>
                ) : (
                   <button
                            className="btn"
                            id="btn-check"
                            style={{ display: "none", backgroundColor: "transparent" }}
                        >
                            <FontAwesome name="check" />
                        </button>
                )}

Now, it will return either a "check" button or an "X" button. Also:

Avoid to name functions with capital cases, that's reserved for classes. Your code will still work, but it's not respecting the standard.
You don't even need to call event.preventDefault() since a button doesn't have a default behaviour like a "submit' or "clear" input.


Prevent Templates From Discarding DOM Elements

Question: I am attempting to integrate a D3.js visualization into a Meteor app. After the page has loaded, a D3 function injects DOM elements into a
 in my template, based on available data.
Whenever there is a reactive update anywhere on the page, however, Meteor dumps the contents of the template that were injected by my D3.js function. I can re-insert the elements, but this leads to an undesirable flicker and decrease in performance.
Any idea on how to suppress this dropping of externally injected elements? I gather that since these elements were not part of the template originally, they are discarded as part of Meteor's 'cleanup' process.
Comment: We need to add a good way to preserve programmatically embedded elements.  The problem is that when a template is re-rendered it replaces whatever is in the DOM with whatever it rendered to -- it doesn't know what elements were added by other means.
Comment: @dgreensp - that's a feature, not a flaw.  ;)
Answer: Have you tried giving unique ids to the D3 injected elements (or at least a parent element)? From the doc (http://docs.meteor.com/#livehtml):

Just make sure that each of your focusable elements either has a unique id, or has a name that is unique within the closest parent that has an id. Meteor will preserve these elements even when their enclosing template is rerendered, but will still update their children and copy over any attribute changes.
Comment: I agree that the documentation seems to imply that having a unique ID attached to an element would prevent it from being dropped, but this does not seem to be the case. In my application, each element inserted had a unique ID, but they were removed on a reactive update nevertheless.
Answer: With the introduction of the Spark templating engine in version 0.4.0, they've introduced the {{#constant}} block helpers to address this issue.
http://meteor.com/blog/2012/08/31/introducing-spark-a-new-live-page-update-engine
Your html template should look something like this....
<template name="samplePageTemplate">

        {{#constant}}

        {{/constant}}

</template>

And the javascript should look something like this...
Template.samplePageTemplate.destroyed = function () {
    this.handle && this.handle.stop();
};
Template.samplePageTemplate.rendered = function () {
    self.node = self.find("svg");
    if (!self.handle) {
        self.handle = Meteor.autorun(function(){

            $('#sampleGraph').html('');
            renderChart();

        });
    };
};

function renderChart(){

    // lots of d3 chart specific stuff

    var vis = d3.select("#sampleGraph").append("svg:svg")
        .attr("width", window.innerWidth)
        .attr("height", window.innerHeight)
        .append("svg:g")
        .attr("transform", "translate(" + m[3] + "," + m[0] + ")");

    // more d3 chart specific stuff

    });
};

I've sometimes had to use self.node instead of self.handle, but otherwise it should be fairly straight forward.


How to remove "display name" from edit user

Question: I'm building a site that leverages the user email address for the user login instead of a username (via modules Logintoboggan  & Email Registration). I'm also using Real Name to display the "first name" field of the user instead of the username.
My solution is working perfectly apart from when the user is on the edit user account page (and some native drupal system notification message), which displays a "Display Name" field instead of the desired "first name" field.
Question: How can I remove/delete the "Display Name" field from the edit profile page and Drupal system messages/notification fields?
Comment: Where do the First Name, Last Name, Display name fields come from? Did you create them? Or are they brought by any module you mentioned?
Comment: I defined them.
Answer: The first one was easy. To hide any field from the user edit form simply set the '#access' to this field to FALSE or any other logic you desire. The second one was more difficult. Turned out the display name was still used on the password reset page. That's how we finally solved it:
/**
 * Implements hook_form__alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    $form['account']['name']['#access'] = FALSE;
  }

  if ($form_id == 'user_pass_reset') {
    // Here we take the corresponding user ID from the URL, second argument
    $user_id = arg(2);
    // Then we load the user
    $user = user_load($user_id);
    // Now we have the mail
    $user_mail = $user->mail;

    // extracting the date string with a helper function
    $sub_text = getContents($form['message']['#markup'], '', '');
    $expiration_date = $sub_text[1];

    // Now we alter the existing form
    $form['message']['#markup'] = '
This is a one-time login for '.$user_mail.' and will expire on '.$expiration_date.'.

Click on this button to log in to the site and change your password.
';
  }
}

/**
 * Helper function to extract a string between two given delimiters
 * Credit: http://stackoverflow.com/a/27078384/2199525
 */
function getContents($str, $startDelimiter, $endDelimiter) {
  $contents = array();
  $startDelimiterLength = strlen($startDelimiter);
  $endDelimiterLength = strlen($endDelimiter);
  $startFrom = $contentStart = $contentEnd = 0;
  while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
    $contentStart += $startDelimiterLength;
    $contentEnd = strpos($str, $endDelimiter, $contentStart);
    if (false === $contentEnd) {
      break;
    }
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;
  }
  return $contents;
}

Comment: Thank you but where do I specifically add this code? I am a front end developer with zero experience in this area of Drupal ☺
Comment: What about tokens or string overrides? Could I leverage any of these modules to assist?
Comment: @Andy - Tokens or String Overrides. You have to find out. Don't know any of these modules. The code I have in my answer needs to be put into a very simple custom module. All it needs is a `.info` and a `.module` file. Inside the `.module` file you have to place that code. Look for tutorials about creating custom modules in Drupal. There are plenty. Believe me, it's worth learning and it's not so difficult as it sounds first.
Comment: Thank you so much for taking the time to help me. I really appreciate it.
Comment: @Andy - If you have a custom backend theme you could also paste that code in this theme's `template.php` and name it `function MYTHEME_form_user_profile_form_alter(...)`. But if not, go with the module approach. You then later also can put other custom code inside there. Also have a look at the [Devel](https://www.drupal.org/project/devel) module. After installation you have a function `dpm()`. Calling `dpm($form)` inside the code of my answer will output you the correct name of your field and much more. You're welcome!
Comment: I have added the following code to my custom template's template.php file'
Comment: I have added the following code to my custom template's template.php file.

<?php

/**
 * Implements hook_form_FORM_ID_alter().
 */
function wannalift_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['field_display_name']['#access'] = FALSE;
}

I have the Devel module installed but I'm not familiar with how/where to call a function as you described. I assume I need to do this to update the function you showed me with the specific form id of the form field that I wish to remove?
Comment: @Andy – If you'ld simply use `function THEMENAME_form_alter(&$form, &$form_state, $form_id)
  dpm($form_id);
}` you'll get the form's ID. As your problem is on the user profile page it very likely will be `form_user_profile`. So you already should be at the right place. Now you need to clear the cache to make Drupal detect your new function. With `dpm($form)` you'll get a clickable field on the user profile page with lots of info inside. Replace `field_display_name` with your correct field name. You maybe named it differently.
Comment: ok so I've added this exact code:

function THEMENAME_form_alter(&$form, &$form_state, $form_id) dpm($form_id); }

But I get a error when browsing to the site:

Parse error: syntax error, unexpected 'dpm' (T_STRING), expecting '{' in /site/sites/all/themes/wanna-lift/template.php on line 7

Does "THEMENAME" need to be the exact name of my custom theme?

When you say "you'll get the form's ID" where will I see the form's id exactly when the above works correctly?
Comment: @Andy - At least something is happen. 'Though it's just an error for now. You are on the right track. You do this in the backend theme's template.php, right? Yes, THEMENAME needs to be the machine name (folder name) of your backend theme. The code you provided is missing a curly bracket like the error message states. It should look like `function functioname(arguments) { code; }`. You'll see the form ID on the edit user profile page or on any other backend page that displays a form.
Comment: it is in my themes's template.php. I figured out that my theme name "wanna-lift" had a hiphen in the name which Drupal didn't like. So I deactivated the theme, renamed it, then added: <?php

/**
 * Implements hook_form_FORM_ID_alter().
 */

function wannalift_form_alter(&$form, &$form_state, $form_id) dpm($form_id); }

Now seeing the following error: Parse error: syntax error, unexpected 'dpm' (T_STRING), expecting '{' in /Users/Andrew/Sites/_freelance/wanna-lift/site/sites/all/themes/wannalift/template.php on line 7
Comment: @Andy - Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/29663/discussion-between-leymannx-and-andy).


MySQL SSL: SSL_CTX_set_default_verify_paths failed


Guitar build — Will the wrong neck work?

Question: I am building a Les Paul style guitar from parts I bought online.
Unfortunately, I noticed that I've got the wrong neck, the body is cut for a set-in neck with a tab at the end of the heel which goes into the bottom of the neck pickup cavity. The neck I have does not have this tab.
Can I still use it, because it fits into the body quite nicely? Or will this create a weak spot in the back of the body itself?
Comment: Maybe you could give some pictures?
Comment: I'm not a big LP guy, but I think what your body wants and your neck doesn't have is called a "long neck tennon". I have no opinion about whether that'll lead to problems to your build. Maybe look into luthier forums elsewhere?
Answer: Bear in mind that Les Paul style guitars have set necks. Their necks aren't bolt/screw on, like, say, Strats. 'Fits the body quite nicely' - I'd want it to be such a fit that it'd need a vice or such-like to press the two together. There's also the neck angle to work out - that's pretty well dictated by the pocket and the shape of the neck heel. May/may not work.
If it was mine, I'd expect to glue and screw. Consider also where fret 12 will sit once it's in place - there's only so much adjustment in saddles, or where the bridge will go, for good intonation. Once glued and screwed, properly, it will be strong enough but use a good quality 2 part epoxy, and remember once it's fixed, it's fixed.
Comment: "once it's fixed, it's fixed" … not if you do it the guitar builder's way and use hide glue. Resetting the neck on old guitars is not that uncommon. Won't probably work out with epoxy though.


Is a symmetric positive definite matrix always diagonally dominant?

Question: A Hermitian diagonally dominant matrix $A$ with real non-negative diagonal entries is positive semidefinite.
Is it possible to have a Hermitian matrix be positive semidefinite/definite and not be diagonally dominant?
In other words, if I know that a matrix $M$ is symmetric positive definite then can I ensure  $M - dI$, for a real number $d$, is positive definite only by ensuring $M - dI$ is diagonally dominant with non-negative diagonal entries?
I am aware that $d \le \lambda_{min}$, $\lambda$ being eigenvalue, for the matrix to remain semidefinite, but I need to avoid eigenvalue computation.
Thanks!
Comment: The matrix $\left(\begin{matrix} 1&-2 \\ -2&4\end{matrix}\right)$ is symmetric and positive semidefinite, but not diagonally dominant. You can change the "positive semidefinite" into "positive definite" by changing the $-2$'s to $-3/2$'s. Does this answer your question? (I am not totally sure what you are asking.)
Comment: Note: The converse direction holds. A symmetric matrix which is diagonally dominant is positive definite. I guess the same holds with "Hermitian" (no guarantees).
Comment: @Hjan: thanks for catching this. I was using a nonstandard definition of diagonal dominance, in which the diagonal entries were required to be positive.
Comment: @darijgrinberg you wrote: 'A symmetric matrix which is diagonally dominant is positive definite.' This is only true if the values in the diagonal are positive. Diagonal dominance looks at the magnitude. For example $\begin{bmatrix}
-3 & 1\\
1 & 2
\end{bmatrix}$ is symmetric diagonally dominant but not positive definite.
Comment: Thanks that answers my question
Answer: This was answered in the comments.

The matrix $\left(\begin{matrix} 1&-2 \\ -2&4\end{matrix}\right)$ is
symmetric and positive semidefinite, but not diagonally dominant. You
can change the "positive semidefinite" into "positive definite" by
changing the $−2$'s to $−3/2$'s. Does this answer your question? (I am
not totally sure what you are asking.) – darij grinberg Sep 30 '15 at
22:54


Initialize atk4 js after loading a page via ajax

Question: I'm trying to use atk4 in a project started some months ago. This project is a app that has a menu and load pages in a div via ajax. Menu is fixed and never reloaded.
I want to use atk4 to generate new pages and do the database work, leaving what is done as is by the moment.
Pages are generated and loaded ok, but components loaded via ajax are not enhaced, because the document ready event is not fired.
We have an event fired every time an ajax page is loaded in the corresponding div ¿can we call a function or functions from this event to have atk4 js system initialized and new components enhaced?
Our function:
$(document).bind('afterajaxload', function(){
    //here we need to call atk4 js initialization to enhace the ajax loaded page.
})

Thanks (and sorry for my bad english)!!
Answer: If you are writing JavaScript function directly into the template, you shouldn't use standard jQuery construct $(function(){ .. }). This function is only fired once per page.
Agile Toolkit achieves a proper functionality by introducing alternative function $.atk4(function(){ ... }) which is properly triggered after AJAX code is loaded. Any  which happens to be loaded through AJAX will automatically be fired, so you don't even need to wrap it.
For developers comfort, if you are writing your code in JavaScript, it's super easy:
$object->js(true, 'your js here');

here is important note. The "$object" must be directly or indirectly reloaded, otherwise it's JS code will not be re-executed automatically. You can always see script sequences through inspector/console in your browser.
It's always suggested to create a library for your JavaScript routine instead of dumping functions into global namespace, but you can read that in JavaScript documentation.
Comment: ok, I think the problem is that ajax calls are managed by another library, not by atk4, and $.atk4(function(){...}) is not triggered after load. Example: i have a form with a mandatory field. Loading the page in browser makes the error text appear below the field when submitting as it must be. When the form is loaded via ajax "$('#sample_project_login_form_2').atk4_form('fieldError','user','User is a mandatory field')" is returned ok but nothing happens. I think I'm going to try to redo this project from scratch. More time now but few problems in future...
Comment: might also happen because of some javascript parse error. If atk4_form is not initialized, the errors will not show too.
Answer: Im using $object->js(true, 'your js here');, but have a problem:
If certain conditions are met, i redirect page to something else, with js function like this:
top.location = "http://some-url.com?param1=AAA&param2=BBBB"

but & character converts to: &
I know i can use $this->api->redirect('some-url', array('param1'=>AAA, 'param2'=>BBB));

But for some reasons i have to use js function, but only to read html characters properly.. How to acomplish this?


If $\det(AB-BA) = 0$ and $A^2 + B^2 = 0_n$, then show that $n$ is even.

Question: Let $A,B ∈ M_n(\Bbb R)$. Suppose that
$A^2 + B^2 = 0_n$ and $\det( AB - BA ) =0$. Show that $n$ is even.
Comment: If the statement holds and if $A$ and $B$ are matrices satisfying the conditions, then so are $A'=\begin{bmatrix}A &0 \\ 0 & 0\end{bmatrix}$ and $B'=\begin{bmatrix}B & 0 \\ 0 & 0\end{bmatrix}$, but they are in odd dimension. So you're likely missing a hypothesis, eg that $A$ and $B$ are invertible.
Comment: What have you tried?
Comment: Sorry, i'm newbie. So i don't know how to code. I tried : $A^2 + B^2 = (A-iB)(A+iB)$ . But seem like it not work
Comment: That's ok. For next time, [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a quick reference on how to format mathematics on this site. But back to the question: What have you tried? What do you know about determinants that you think may come in handy?
Comment: Det =0 so AB-BA is not invertible. Am i miss understanding your question? Cause my English also very bad ,hi!
Answer: A simple counterexample is $A=B=0$ for any odd value of $n$.
On the other hand, if either $A$ or $B$ is invertible, then there is a very simple proof.
$A^2=-B^2$ therefore
$|A^2|=|-B^2|$ and so
$|A|^2=(-1)^n|B|^2$.
Then $(-1)^n$ is positive and so $n$ is even.
Comment: Since $A=B=0$ is a simple counterexample there has to be some other condition.
Comment: Sorry but i'm pretty sure that my example not mention to A,B is invertible or not, can you help me furthermore? (Sorry my english quiet bad ☹ )


how can i add links using java script

Question: I have been trying to find the marquee option in javascript. and i would like to know how can i add hyperlink to this code?Can you please guide me..I am pasting the code below.

Answer: you can code like this...var str = path + 'mypage.aspx?;
        javascript: window.open(str, 'SplPopup', 'scrollbars=yes,width=800,height=600,top=75,left=150,resizable=yes,status=yes,toolbar=no');
Comment: Could you please edit in the above code and share to me? thanks

how can i add links using java script


Qt: how to set the background color of QPushButton to System-color?

Question: I have a QPushbutton on a parent-Widget. I want now to give the parent-Widget a new Background (color, image eg.) this works fine (using QPalette). However, as I am using Unix, the color from the parent-Window is propagated to the Button. Like the button has transparent background. This is fine for some cases, but sometimes I just want the parent-Widget's background to change an not the children. So that the Buttons will keep their original "system"appearance. How to achieve this? I tried a lot...but nothing gave me the desired result. Any ideas on how to achieve that?
Thx
Answer: Have you tried using setBackgroundRole for the button? Maybe your button has QPalette::NoRole and therefore inherits its role from its parent.
Comment: no this doesn't work. The button inherits the Roles from its parent...and the parent has colors set on Role::Window, Role::Button. Changing the background role of the button doesn't change anything therefore.
Comment: Ok, I found a solution...one has to use standardPalette() (can be retrieved by QApplication::style() oder widget->style())and overwrite the whole palette of the childwidget or just single roles with the values of the standard palette.
Answer: if your Button seems to inherit the background from the MainWindow, try setting stylesheet in this format.
this->setStyleSheet("MainWindow{background-color:red}");

Now, the background will not be inherited by your button.


Determining all the positive integers $n$ such that $n^4+n^3+n^2+n+1$ is a perfect square.

Question: I successfully thought of bounding our expression examining consecutive squares that attain values close to it, and this led to the solution I'll post as an answer, which was the one reported. However, before that, I had briefly tried manipulating $$n^4+n^3+n^2+n+1=m^2.$$Since $n=1$ is not a solution, I rewrote this as $$\frac{n^5-1}{n-1}=m^2 \\ n^5-1=nm^2-m^2 \\ m^2-1=n(m^2-n^4) \\ (m-1)(m+1)=n(m-n^2)(m+n^2),$$ but in vain. Does manipulation lead somewhere? Is there a different approach from both of mine?
Comment: @ByronSchmuland: Thank you for your comment and your answer. However none of those answers provides an alternative approach with the degree of the polynomial being $4$ and the value of $x$ varying.
Comment: As a reference: this exercise was proposed in the admission test of SNS (*Scuola Normale Superiore*, Italy), 2015 (If I recall it correctly).
Answer: Hint: notice that
$$ (2n^2+n)^2 = 4n^4+4n^3+n^2, $$
$$ (2n^2+n+1)^2 = 4n^4+4n^3+5n^2+2n+1 $$
are two consecutive squares and $4(n^4+n^3+n^2+n+1)$ is just between them, with very few exceptions. An old motto says "too close to a square to be a square, it is not a square".
Answer: For all positive $n$ we have $$\require\cancel \left(n^2+\frac{n}{2}\right)^2=\cancel{n^4+n^3}+\frac{n^2}{4}<\cancel{n^4+n^3}+n^2+n+1 \\ \frac{n^2}{4}<n^2+n+1 $$ and on the other hand $$\require\cancel \left(n^2+\frac{n+2}{2}\right)^2=n^4+n^3+2n^2+\frac{n^2+4n+4}{4}>n^4+n^3+n^2+n+1 \\ \cancel{n^4+n^3}+\frac{9}{4}n^2\cancel{+n+1}>\cancel{n^4+n^3}+n^2\cancel{+n+1} \\ \frac{9}{4}n^2>n^2.$$ As a consequence, $n$ cannot be even, and for some odd $n$ we must have $$\left(n^2+\frac{n+1}{2}\right)^2=\cancel{n^4+n^3+n^2}+\frac{n^2+2n+1}{4}=\cancel{n^4+n^3+n^2}+n+1 \\ n^2+2n+1=4n+4 \\ n^2-2n-3=(n-3)(n+1)=0,$$ whence $n=3$. In particular, $$3^4+3^3+3^2+3+1=11^2.$$
Comment: I used a similar techniques here: http://math.stackexchange.com/questions/493162/show-that-xx1-y4y3ay2byc-has-a-finite-number-of-positive-integral to show that if $a$, $b$, and $c$
are integers,
there are only a finite number
of positive integers $x$ and $y$
such that
$x(x+1) = y^4+y^3+ay^2+by+c$.
Comment: @martycohen Nice, (+1). Sooner or later I'll try to deal with your problem.
Answer: There are only two additional non-positives that also give perfect squares.

Case 1: $\boldsymbol{n}$ odd
$$
\begin{align}
\left(n^2+\frac{n-1}2\right)^2
&=n^4+n^2(n-1)+\frac{n^2-2n+1}4\\
&=n^4+n^3-\frac34n^2-\frac12n+\frac14
\end{align}
$$
smaller than $n^4+n^3+n^2+n+1$ if $\frac74n^2+\frac32n+\frac34\gt0$
$$
\begin{align}
\left(n^2+\frac{n+1}2\right)^2
&=n^4+n^2(n+1)+\frac{n^2+2n+1}4\\
&=n^4+n^3+\frac54n^2+\frac12n+\frac14
\end{align}
$$
bigger than $n^4+n^3+n^2+n+1$ if $\frac14n^2-\frac12n-\frac34\gt0$.
Only leaves $n=-1,1,3$. Only $-1,3$ give squares.

Case 2: $\boldsymbol{n}$ even
$$
\begin{align}
\left(n^2+\frac{n}2\right)^2
&=n^4+n^2n+\frac{n^2}4\\
&=n^4+n^3+\frac14n^2
\end{align}
$$
smaller than $n^4+n^3+n^2+n+1$ if $\frac34n^2+n+1\gt0$
$$
\begin{align}
\left(n^2+\frac{n+2}2\right)^2
&=n^4+n^2(n+2)+\frac{(n+2)^2}4\\
&=n^4+n^3+\frac94n^2+n+1
\end{align}
$$
bigger than $n^4+n^3+n^2+n+1$ if $\frac54n^2\gt0$.
Only leaves $n=0$, which gives a square.

Thus, only $n\in\{-1,0,3\}$ give squares.


Multi-variable indexes in postgres

Question: Im looking at an application where I will be doing quite a few SELECTs where I am trying to find column_a = x AND column_b = y.
Is the correct to create that index that something like the following?
CREATE INDEX index_name ON table (column_a, column_b)

Answer: Yes.
Comment: Great, thanks. I searched the postgres documentation but didnt find anything like that.

Multi-variable indexes in postgres


Form API Ajax trigger callback with size of input

Question: I use the API Form of Drupal 8 to create my form.
I had an ajax callback on a field:
$form['association']['numero'] = array(
        '#type' => 'textfield',
        '#title' => t('foo'),
        '#size' => 10,
        '#maxlength' => 10,
        '#suffix' => '

',
        '#ajax' => [
            'callback' => '::fetchApiData',
            'event' => 'change',
            'prevent' => 'click',
        ],
    );

with my callback function :
public function fetchApiData(array $form, FormStateInterface $form_state)
{
    return 'foo';
}

It's all working fine, but i want to trigger the callback when the user writes 10 characters precisely. Does anyone has a solution for that?
Answer: You can do this:
1) Decide on an event name. In this code, the event name will be 'overminlength'
2) In the form element being defined using the Form API, set your #ajax as normal, but set the #ajax 'event' to the event name chosen in step 1:
'#ajax' => [
  'wrapper' => 'some_wrapper',
  'callback' => 'some_callback',
  // Set the custom event here:
  'event' => 'overminlength',
],

3) Create a custom JS file and attach it to the field
'#attached' => [
  'library' => ['mymdodule/mylibrary'],
],

4) Add a $.keyup() listener to the field.

In the callback, count the number of characters in the field
If it's more than X characters, call $.trigger(), and trigger the event from step 1
(function($, Drupal) {

  "use strict";

  function fieldwatcher(context) {
    $(context).find("#edit-myfield").once("fieldwatcher").each(function() {
      $(this).keyup(function() {
        // Change '3' to the number of characters after which you want to
        // trigger the ajax.
        if ($(this).val().length > 3) {
          $(this).trigger("overminlength");
        }
      });
    });
  }

  Drupal.behaviors.testScript = {
    attach: function(context) {
      fieldwatcher(context);
    }
  };

}(jQuery, Drupal));

Comment: That's correct. The Form API is great, but this is not functionality it provides by default. It may make for an interesting add-on however.
Comment: Hello Jaypan and thank you for your response.
I don't really understand your point, can you please explain me more ?
Regards,
Comment: Well, my answer is all jQuery and JavaScript based. If you don't understand how to work with those, the answer I gave above isn't going to help you, and I can't really teach JS and jQuery on Drupal answers. If you are looking for a method of doing what you want purely through the Form API, the answer is that it cannot be done. The solution I gave above would be a custom one that requires custom JS coding.
Comment: Ho okay, yes i can do that with javascript but my question was more about using the Form API, but it seems we actually can't.
Comment: I've actually tested my theory, and it works. I've re-written my post above to show specific instructions.
Comment: Hello, thank for your theory and code, it works well !


Form shrinks on smaller screen in VS. How do I get groupboxes that are now outside the form's border?

Question: I'm on the road at the moment and I've opened a WinForms project in VS.
The form was designed to run on a full hd display, so VS has shrunk it for my laptop display. I'm trying to put all the groupboxes in a panel so I can run it on my laptop, but some of them are now outside the form's border. How can I grab them?
Comment: [How to find the Control that I added to Form?](https://stackoverflow.com/questions/32331696/how-to-find-the-control-that-i-added-to-form)
Comment: Also temporarily you can set `AutoScroll` property of form to `true`, then you can find those lost controls.
Answer: Use  TableLayoutPanel Control  Because i have also face same issue but when you design winform using TableLayoutPanel  then the size of the form increase or decrease then don't affect on winform. it's resize the every control on form as per screen size.
Hope it will help you thank you.
Comment: I'm not the downvoter, but I think setting `AutoScroll` to `true` is a better option. When the controls go beyond form's boundary, `TableLayoutPanel` will not help much.
Comment: @RezaAghaei thank you so much but when the size of screen is BiG and if you don't wan't  the scrolling form then you have only single option that is use TableLayoutPanel Control beacuse it's able to resize all control as per form size.
Comment: I understand what you mean. When you want to size controls by *percentage* you can use `TableLayoutPanel`. This way, you should have a docked `TableLayoutPanel` with *percent* row and column styles and put some docked controls in cells. You can make the answer more useful by adding more details.
Comment: @RezaAghaei is's depend on UX team you are also right  AutoScroll true is one also solution of this but it's not proper way to solving problem.


How to display an HTML table after the form submission on the same page as the form?

Question: I am trying to build a form which takes the food item and the no. of servings and calculates the total calories for that particular food and displays it to the user.
User, can add another food by filling out the form again and the calculated calories for the second food is added to the first and the total calories are also displayed. He can add as many food items as he wants and the form shows the total calories of all those food items.
I want to display this information to user in a table. table will have the following columns.. food item, servings, calories and in the last row the total calories of all those food items. I also want to have a another column with a "delete" button to delete that particular food item from the table and refresh the table without that particular food item.
The main problem am facing is, How can I show this table on the same page as that of the form ?
I have been saving all the user submitted info in session variables and I am being able to create and show such table on another page (for example, when user adds many food items and clicks "Done" button, its redirected to another page and the table is shown there.) But I dont want the user to be redirected. I mean if he wants to add another food item to the table, he has to navigate to the form page again and that's not convenient to the user.
To learn how to write forms, I followed this guide, http://drupal.org/node/262422. So my form is in a file, say..myform.module. Now, I have all the data to create an HTML table (Am saving all the food details given by the user in session variables), but how can I make it displayed on the same page as that of the form ?
or in other words, path to my form is, http://localhost/d7/?q=calorie_consume , I also want the table to be showed on the same path or page. How can I do it?
Where should I put the code for creating the table inside myform.module file ?
So how can I achieve this ? Or is there some other approach to creating such calculators that am not aware of ?
Thanks in advance.
Answer: If you're saving your data in $_SESSION vars, I think the easiest way would be to check for the existence of your session data when you build up the form. Then you can show the table at the top of the form if the user has already submitted data, and the normal part of the input form directly underneath. A basic example:
function my_form($form, &$form_state) {
  if (isset($_SESSION['my_var'])) {
    $form['table'] = array(
      '#markup' => 'Your table markup based on session data here'
    );
  }

  $form['input'] = array(
    '#type' => 'textfield',
    '#title' => 'Title'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );
}

function my_form_submit($form, &$form_state) {
  $_SESSION['my_var'][] = $form_state['values']['input'];

  $form_state['rebuild'] = TRUE;
}

You'll probably need to put some sort of mechanism to clear that session var at some point, if you want users to be able to reset their submission.
A more complete example with functionality to remove items:
function MYMODULE_form($form, &$form_state) {
  // If we have some session data set, build a table
  if (isset($_SESSION['MYMODULE_data'])) {
    $header = array('Food', 'Calories');
    $options = array();
    $total = 0;
    foreach ($_SESSION['MYMODULE_data'] as $item) {
      $options[$item['identifier']] = array(
        $item['food'],
        $item['calories']
      );

      // Keep a running total
      $total += $item['calories'];
    }

    // Add the total row
    $options[] = array('Total calories', $total);

    $form['existing_data'] = array(
      '#type' => 'tableselect',
      '#options' => $options,
      '#header' => $header
    );

    $form['remove_item'] = array(
      '#type' => 'submit',
      '#value' => 'Remove Selected',
      '#submit' => 'MYMODULE_form_remove_item'
    );
  }

  $form['food'] = array(
    '#type' => 'textfield',
    '#title' => 'Food'
  );

  $form['calories'] = array(
    '#type' => 'textfield',
    '#title' => 'Calories'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );

  return $form;
}

function MYMODULE_form_remove_item($form, &$form_state) {
  $remove = array_filter($form_state['values']['existing_data']);
  foreach ($remove as $key) {
    unset($_SESSION['MYMODULE_data'][$key]);
  }
  $form_state['rebuild'] = TRUE;
}

function my_form_submit($form, &$form_state) {
  // this example will just use the food name as the identifier
  $_SESSION['MYMODULE_data'][] = array(
    'identifier' => $form_state['values']['food'],
    'food' => $form_state['values']['food'],
    'calories' => $form_state['values']['calories']
  );

  $form_state['rebuild'] = TRUE;
}

I haven't tested that but it should give you a good starting point even if there are a few bugs.
Comment: Thank you so much for the answer. Is there a way to add that "delete" button to each row of the table as I mentioned in my question ?
Comment: Rather than a delete button on each row (which would require a fair bit more coding), why not use a tableselect type instead? Then your users can choose multiple items in the table to delete in a single go. I'll whip some example code up and put it in the answer
Comment: @akshaynhegde I've added an example with a tableselect, hope it helps


Direct downloading a csv file without writing it to the directory

Question: I am using rails 2.3.14 with ruby 1.8.7 and I want to download a csv file without writing it to any directory.
My code:
<code>  def export
    @news = News.find(:all, :conditions => ["updated_at >= ? and news_source_id != 1 and ready = 1", 1.week.ago])
    file_name = "Non_linksv_news_#{1.week.ago.strftime('%b-%d-%Y')}_to_#{Time.now.strftime('%b-%d-%Y')}.csv"
    File.open(file_name, "w") do |file|
      file_name << %w(Source Headline).to_csv
      @news.each { |news| file_name << [news.news_source.name, news.news_headline].to_csv }
    end
    send_file file_name
  end
</code>
It creates a file in directory then downloads. I don't want to create file.
Answer: Solved
<code>  def export
    ns = NewsSource.find_by_name 'Linksv', :select => :id
    @news = News.find(:all, :conditions => ["updated_at >= ? and news_source_id != ? and ready = 1", 1.week.ago, ns.id])
    file_name = "linksv_news_#{1.week.ago.strftime('%b-%d-%Y')}_to_#{Time.now.strftime('%b-%d-%Y')}.csv"
    csv = %w(Source Headline).to_csv
    @news.each { |news| csv << [news.news_source.name, news.news_headline].to_csv }

    send_data csv, :filename => file_name, :type => "text/csv"
  end
</code>
It will generate csv file in proper way, with rows and columns
Answer: We use this approach
<code>def export
  output = [["Source", "Headline"]]
  @news.each do |a_new|
    output << [a_new,news_source.name.to_s, a_new.news_headline.to_s]
  end
  respond_to do |format|
    format.csv {
      send_data output.to_csv, :type => "text/csv", :filename => "My news csv.csv"
    }
  end
end
</code>
Comment: thanks for reply but Its showing me everything in single line but I need it like a table cols and rows
Comment: Isnt it adding \n? Show me an example of that output, please


debug apache beam / dataflow in a debugger?

Question: This is highly related to this post first -> How to do this type of testing in Dataflow(called feature testing at twitter)?
We have some code like this in production
@Override
public PDone expand(PCollectionTuple in) {
    final RosterPipelineOptions options = (RosterPipelineOptions) in.getPipeline().getOptions();
    try {
        final Schema schema = new Schema.Parser().parse(PractitionerStandardAvroWriter.class.getResourceAsStream("/standardFormat.avsc"));
        final String schemaStr = new BufferedReader(new InputStreamReader(PractitionerStandardAvroWriter.class.getResourceAsStream("/standardFormat.avsc")))
            .lines().collect(Collectors.joining("\n"));

        final PCollection<Validated<PractitionerStandardOutputDto>> validOutputs = in.get(PractitionerStandardOutputConverter.VALID_OUTPUTS_TAG);
        final PCollection<Validated<PractitionerStandardOutputDto>> invalidOutputs = in.get(PractitionerStandardOutputConverter.INVALID_OUTPUTS_TAG);

        final PCollection<GenericRecord> validRecords = validOutputs.apply(
            "Transform Valid Standard Output into Generic Rows", ParDo.of(new GenericRecordConverter(schemaStr)));
        final PCollection<GenericRecord> invalidRecords = invalidOutputs.apply(
            "Transform Invalid Standard Output into Generic Rows", ParDo.of(new GenericRecordConverter(schemaStr)));

        validRecords
            .setCoder(AvroCoder.of(GenericRecord.class, schema))
            .apply("Write Records", AvroIO.writeGenericRecords(schema)
                .to(options.getValidOutput())
                .withoutSharding());

        final PCollection<String> invalidRows = invalidRecords
            .setCoder(AvroCoder.of(GenericRecord.class, schema))
            .apply("Convert Error Avro to Csv", ParDo.of(new AvroToCsvConvertFn(schemaStr, ",")));
        invalidRows.apply("Write Error Records to Csv",
            TextIO.write().to(options.getInvalidOutput()).withoutSharding());

        return PDone.in(in.getPipeline());
    }
    catch (IOException e) {
        SneakyThrow.sneak(e); return null;
    }
}

but when we debug it in a test, we have no visibility into the bugs.  It's insanely hard to step through this code to see what is going on since I think it is run AFTER this code to morph the data and this code is only the definition of how to deal with incoming data.  Correct me if I am wrong here?
Two questions

Is this the best way to write debuggable apache-beam/dataflow code that we can step through and easily see where our bug is?
Is there some other way to easily debug it since I suspect the 'real execution' happens after that method when stuff is applied?

thanks,
Dean
Answer: In general, like in your other question, my advice would be the following:

To step through your pipeline, you can write a unit test that you run with your IDE, and it will run in the DirectRunner. This allows you to step through your pipeline easily. This is not running in Dataflow, but rather locally - it's still valuable.

You can set breakpoints in expand, which will be hit at pipeline construction time. You can set breakpoints in the process of a DoFn, or split, read for Sources - these will be hit at pipeline execution time.

Advice on writing pipelines that are debuggable - well, in this case, my advice would be to write composable transforms that can be tested individually. You can use various test utilities that Beam has to write tests for your pipelines. See: https://beam.apache.org/documentation/pipelines/test-your-pipeline/

Some of the most valuable test uitilities are PAssert, TestStream, and TestPipeline. I recommend you review the page I shared, and see if these utilities will help.

For your particular pipeline, I might think that you can separate the PTransform into smaller sections, and write simple unit tests for each section.
Comment: thank you for the advice.  yes, the person on the team said this one -> "well, in this case, my advice would be to write composable transforms that can be tested individually".    My only issue with that statement is on past projects, we have a huge influx of bugs so writing a unit test is a bit hard UNTIL you know where the bug is.  I am trying to optimize for maintenance but dataflow seems optimized in a different direction making it hard on the support engineers.  I do like the breakpoints on process/split/read and will try that path
Comment: it's too bad dataflow(apache beam) doesn't do something like guice with constructor stack traces (fake stack traces about the real problem showing you exactly how it happened).  that would be slick in dataflow.