Taking the derivative of the SPH density estimator

Question: I am taking a course in Smooth Particle Hydrodynamics but I am struggling with some of the steps involved in deriving the method.
I have written out the steps in my notebook I hope that is ok.
I have numbered the steps and asked questions about each step. If someone is able to explain I would greatly appreciate it, Thank you.
The derivation and more details are done here on page 16 https://arxiv.org/pdf/1007.1245.pdf
Sorry if this isnt a good post, I just really need some help
Answer:
From (3.39) you have $\rho_i=\sum_km_kW_{ik}$, so then
$$ \frac{\partial\rho_i}{\partial\mathbf r_j}=\sum_km_k\frac{\partial W_{ik}}{\partial\mathbf r_j} $$
since $m_k$ is constant.
Because it leads to a useful result. Actually there are two reasons why it's useful. Firstly, SPH uses the derivative of the kernel function to interpolate the derivative of the function. The kernel function is a function of one variable ($r$, the distance between the two points) so to differentiate the kernel function in some direction at a point using the chain rule you can always use the 1D derivative of the kernel function and then multiply by the derivative of the distance between the two points. This means you don't have to differentiate the kernel in lots of different ways all the time.
$\mathbf r_{ik}=\mathbf r_{i}-\mathbf r_k$, and $r_{ik}$ is the length of $\mathbf r_{ik}$. So
$$ \frac{\partial r_{ik}}{\partial \mathbf r_j} = \frac{1}{r_{ik}}(\mathbf r_{i}-\mathbf r_{k})\frac{\partial}{\partial \mathbf r_j}(\mathbf r_i-\mathbf r_k)=(\delta_{ij}-\delta_{kj})\hat{\mathbf r}_{ik}.$$
Since $\frac{\partial\mathbf r_i}{\partial\mathbf r_j}$ is $0$ if $i\neq j$ and $1$ if $i=j$, we have $\frac{\partial\mathbf r_i}{\partial\mathbf r_j}=\delta_{ij}$.
The derivation is strange here, if it was the case that $\partial/\partial\mathbf r_j\equiv\nabla_j$ then $$\frac{\partial\rho_i}{\partial\mathbf r_j}=\sum_km_k\frac{\partial W_{ik}}{\partial\mathbf r_j}=\sum_km_k\nabla_jW_{ik}, $$ so it's not clear to me.

There is another way to obtain (3.61) though which is simpler. We are looking for the SPH interpolant of the Euler equation (ignoring body forces, which can be applied to each computational particle individually),
$$ \frac{\mathrm d\mathbf v_i}{\mathrm dt} = -\frac{\nabla p_i}{\rho_i}. $$
First rewrite
$$\frac{\nabla p_i}{\rho_i}=\nabla\left(\frac{p_i}{\rho_i}\right)+\frac{p_i\nabla\rho_i}{\rho_i^2}$$ and then find the SPH interpolant, using the standard SPH approximation of a derivative,
$$ \nabla F_i=\sum_j\frac{m_j}{\rho_j}F_j\nabla_iW_{ij}. $$
We get
$$\frac{\mathrm d\mathbf v_i}{\mathrm dt}=-\sum_j\frac{m_j}{\rho_j}\frac{p_j}{\rho_j}\nabla_iW_{ij}-\frac{p_i}{\rho_i^2}\sum_j\frac{m_j}{\rho_j}\rho_j\nabla_iW_{ij}=-\sum_jm_j\left(\frac{p_j}{\rho_j^2}+\frac{p_i}{\rho_i^2}\right)\nabla_iW_{ij}, $$
exactly as (3.61) (with $I$ and $j$ swapped).
Comment: Hi David, thank you for your very in depth reply, you have answered all of my questions clearly and your added working using the standard SPH approximation has been extremely useful.
Comment: No worries. I just tried to expand a bit on point 2, hopefully it makes sense.


Showing $\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}/(1,-1,0)\mathbb{Z}+(0,1,1)\mathbb{Z}+(1,0,-1)\mathbb{Z}\cong \mathbb{Z}$

Question: I have to prove that if $V_K = \{v_0, v_1, v_2\}$ and $K = \{\{v_0\}, \{v_1\}, \{v_2\}, \{v_0, v_1\}, \{v_0, v_2\}, \{v_1, v_2\}\}$ then $H_q(K, \mathbb{Z})\cong  \mathbb{Z}$ for $q = 0, 1$.
Already I proved that for $q=1$. For $H_0(K, \mathbb{Z})=\ker\delta_0/\operatorname{Im}\delta_1$, $\delta_0 : C_0(K)\to 0$, so it is obvious that $\ker\delta_0 = C_0(K)$. Also,
$$\operatorname{Im}\delta_1 = \{(a + c)v_0 + (-a + b)v_1 + (b - c)v_2 \mid  a, b, c \in \mathbb{Z}\}$$
according to the definition of $\delta_1$.
Finally, this set can be written as follows:
$$\operatorname{Im}\delta_1 = (1, -1, 0)\mathbb{Z} + (0, 1, 1)\mathbb{Z} + (1, 0, -1)\mathbb{Z}$$
so the only thing I have to prove is that
$$\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}/(1,-1,0)\mathbb{Z}+(0,1,1)\mathbb{Z}+(1,0,-1)\mathbb{Z}\cong \mathbb{Z}.$$
All I can say is that the vectors $e_i$ don't belongs to this subset.
Comment: The first homology group is trivial, unless I'm reading things incorrectly.
Comment: Suppose $f\colon Z+Z+Z\rightarrow Z$ is a homomorphism with kernel equal to subgroup in question. Then $f$ is of the form $f(x,y,z)=ax+by+cz$, for some $a,b,c\in Z$. Then $f(1,-1,0)=0$ implies $a-b=0$. Similarly $b+c=0$ and $a-c=0$. This gives that $a=b=c=0$; $f$ is zero map!!! Is something missing in your or my argument?
Comment: Use the Smith normal form.
Comment: Sorry, the 3-simplex in K should not be, I edited the question
Answer: The quotient is not equal to $\Bbb Z$: it is equal to $\Bbb Z/2$.  In particular, to correct the comment by p Groups:
$f(1, -1, 0)=0$ implies $a-b=0$, so $a=b$.  Similarly, $a-c=0$ implies $a=c$.  Finally, $b+c=0$ implies $2a=0$.  So the quotient is just $a\Bbb Z/2a\Bbb Z$, for example with representatives $\{(0, 0, 0), (1, 0, 0)\}$.
In particular, $(0, 0, 1) = (1, 0, 0) - (1, 0, -1)$, and $(0, 1, 0) = (1, 0, 0) - (1, -1, 0)$.
Answer: I believe you got a sign wrong in you expression for $\operatorname{Im}\delta_1$. You should have
$$\operatorname{Im}\delta_1 = \{(a + c)v_0 + (-a + b)v_1 + (\color{red}{-b} - c)v_2 \mid a, b, c \in \mathbb{Z}\}$$
as $\delta_1\{v_0, v_2\} = 1\{v_0\} \color{red}{- 1}\{v_2\}$, so $\operatorname{Im}\delta = (1, -1, 0)\mathbb{Z} + (1, 0, -1)\mathbb{Z} + (0, 1, -1)\mathbb{Z}$.
Now note that the group homomorphism $\varphi : \mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z} \to \mathbb{Z}$ given by $\varphi(x, y, z) = x + y + z$ is surjective and $\operatorname{Im}\delta_1 \subseteq \ker\varphi$. If $(x, y, z) \in \ker\varphi$, then $x + y + z = 0$ so $z = -x - y$. As
$$(x, y, z) = (x, y, -x - y) = x(1, 0, -1) + y(0, 1, -1) \in \operatorname{Im}\delta_1,$$
we see that $\ker\varphi \subseteq\operatorname{Im}\delta_1$, and therefore $\ker\varphi = \operatorname{Im}\delta_1$.
So by the first isomorphism theorem,
$$\frac{\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}}{(1, -1, 0)\mathbb{Z} + (1, 0, -1)\mathbb{Z} + (0, 1, -1)\mathbb{Z}} \cong \mathbb{Z}.$$
Answer: Performing elementary row and column operations you can bring your matrix of vectors to the form $$\begin{pmatrix}2&0&0\\0&1&0\\0&0&1\end{pmatrix}$$ so the quotient is $\Bbb Z_2$. In the corrected answer by Michael Albanese, you would end up with a $0$ instead of a $2$ (carry out the calculation yourself), so the quotient is indeed $\Bbb Z$. Note that the first homology group is zero, not $\Bbb Z$, unless the 2-simplex is not supposed to be there.


WYSIWYG editor on Paragraphs text field?

Question: How do I enable the WYSIWYG editor on a paragraphs text field in Drupal 8?
Currently, adding a text field (of any type) displays a single line input box.  I'd like this field to be at least a multi line textarea, with preferably, a WYSIWYG editor.  Is there a setting or module I can use to change this ?
EDIT: I should add that the editor works fine in a field on a content type or block.  It does not load for any text type in a paragraphs field.
Comment: It doesn't matter where you add the field, this has nothing to do with paragraphs. In D8 WYSIWYG is included in the standard installation. Did you try this on a fresh install and can you be more specific what is different in your case?
Comment: Try to install https://www.drupal.org/project/bootstrap_paragraphs module(not a solution for your case), This module define a lot of paragraphs types with WYSIWYG.
Comment: @4k4 I understand that the WYSIWYG editor is part of core.  What I don't get is how I can use that editor on a textfield in a paragraphs entity.  All text types don't seem to use it.
Comment: @4k4 If it isn't clear in my post and my comment, the WYSIWYG editor works fine on a field in a content type or block. It does not load for any of the text types in a paragraph field. That is why I am implying its related to paragraphs.
Comment: I don't know if it helps, but to be precise, you don't add fields to a paragraph field, but to a paragraphs type the same way as to a content type.
Comment: $k4k Unfortunately no. Not sure why I'm having an issue with this but the WYSIWYG editor will not load no matter which type and format are selected   for the field.
Answer: If you want to have a multi line textarea with an WYSIWYG editor, you'll have to create, for your paragraph type, a field of type "Text (formatted, long)" and while editing your field, you should choose "Full HTML" as "Text format". Hope this works for you.
Comment: That doesn't work for me.  The field is of type text (formatted, long) and field format is Full HTML. Still a single line input textbox. :(
Comment: @AyexeM Could you check the form display of your paragraph type? There, you can define the widget type and the number of rows.

_Home >> Administration >> Structure >> Paragraphs types >> My paragraph >> Manage form display_

(../en/admin/structure/paragraphs_type/my_paragraph/form-display)
Comment: In the form display, I only see an option to change textfield size, which I believe is number of characters in the field. Also, the only option under "widget" is textfield, which I guess is a root cause.  Is there a way to enable another widget type that will load the editor?
Comment: If that's what you see then your widget type is "Text (plain)".
Comment: A very interesting setting that you might want to check is "Text formats and editors": _Home >> Administration >> Configuration >> Content authoring_ (../en/admin/config/content/formats).

You could put "Full HTML" on top on the list + verify that the "Anonymous user" does not have access to this format. You could as well define the behavior of your editor per "Text format".
Answer: The field type needs to be "Textarea (formatted, long) with summary" when creating the paragraph type.
Comment: Any formatted text field works, because WYSIWYG depends on text formats, not on paragraphs and not on a field with summary.
Comment: @4x4 That is not consistent with my experience. I've even checked with a fresh install of Drupal 8.3.7 with Paragraphs 8.x-1.2. "Textarea (formatted, long) with summary" is the only field type within a paragraphs entity that loads the WYSIWYG.

A text field directly in a node works as you describe, but not within a paragraphs entity.

Maybe there is a config setting to change this, but I'm not aware of it and that's kinda the entire point of my question.


Drush command needs higher bootstrap level - Pantheon Drush Alias Setup

Question: I just setup pantheon for one of my websites. So far I've done the following and the site works fine:
Version Drush: 5.3
Local Dev: Ubuntu 12.04

Git clone the repo to my local desktop
Copy the pantheon.aliases.php file to the .drush directory at ~/home

Now when i do a drush @pan.chouse.dev pm-list I get the following error.

<code>~/websites/pan-chouse$ drush @pan.chouse.dev pm-list

Command pm-list needs a higher bootstrap level to run - you will need    [error]
to invoke drush from a more functional Drupal environment to run thiscommand.

The drush command 'pm-list' could not be executed.                       [error]
The directory /home/drupalpro/websites/pan-chouse does not contain a     [error]
valid Drupal installation
</code>

I also did a drush @pan.chouse.dev status and I get this:

~/websites/pan-chouse$ drush @pan.chouse.dev status  PHP
  configuration   :
  /srv/bindings/a59cd0c1631747ef8cda2b5e88fc5124/php.ini
                          /srv/bindings/a59cef8cda2b5e88fc5124/php.ini    Drush
  version       :  5.10.0
  Drush               :
  /srv/bindings/a59cd8cda2b5e88fc5124/drushrc.
  configuration          php

I'm not exactly sure what I'm doing wrong as it should technically work.
Comment: Do you have settings.php in place ?
Comment: Does your alias specify a bunch of additional params? Here's one of my Pantheon aliases:
`$aliases['mysite.test'] = array(
'root' => '.',
'uri' => 'test.mysite.gotpantheon.com',
'remote-host' => 'appserver.test.long-id.drush.in',
'remote-user' => 'test.long-id,
'ssh-options' => '-p 2222 -o "AddressFamily inet"',`
Comment: What does `drush sa @pan.chouse.dev` say?  It looks like your alias is empty.
Comment: nvm it works.. it shows this... http://prntscr.com/4u81at
Comment: yea i just copied another settings.php files into the default folder... it still doesnt show any response. but when i go outside of the drupal folder.. i get a response from pantheon, but it shows that the default theme is "garland", but i have "omega" as the default theme... see here: http://prntscr.com/4u9yzt
Comment: yea i have all of that.. see: http://prntscr.com/4ui6m7
Answer: While sites on Pantheon don't require a settings.php file in order to serve web requests, due to the fact that database credentials are dynamically injected, they will still need a settings.php configuration file present in order to enable the remote execution of Drush commands. With Drush 5 installed locally, there is unexpected behavior with Pantheon aliases run from inside a local Drupal docroot. In addition, the <code>--strict=0</code> option needs to be appended to most commands when using Drupal 6 on your local dev environment.
Source: Drush error "Could not find a Drupal settings.php file" or missing system information from status
Comment: You need to put the settings.php file in your code directory on Pantheon.
Comment: that didnt work.. did it outside of the drupal folder too. see here: http://prntscr.com/4ui78a
Comment: It didn't work because you need a `settings.php` file in your `/code/sites/default/` directory in order to run drush commands on Pantheon aliases. Make a copy of `default.settings.php` and call it `settings.php` and you will have great success.
Comment: nope that didnt work, see here: http://prntscr.com/4uvc4c
Comment: but wouldnt that overwrite the existing one on the pantheon servers? how would i go about doing that?
Comment: ok just uploaded by switching to sftp mode on the dashboard. it was git mode previously. I then sftp into the server and uploaded a settings.php file to code/sites/default --- http://prntscr.com/4uxcnk   ---- and i tried it again ... http://prntscr.com/4uxdjq --- Still doesnt work... now i can't even delete the file. what can i be doing wrong?
Comment: ok got it! had to do it thru the cli
Answer: Ok so this is how i solved it after 4 days of trying... the docs and support techs on pantheon are not clear which has lead to this confusion and im sure many others too.
To get Drush aliases to work you have to have a settings.php file in the sites/default folder. BUT! when we use pantheon, we all git clone the codebase to our local. So we all assume that we needed it in our local drupal setup that we cloned which is not the case.
You have to have the EMPTY settings.php file on the PANTHEON servers! In order to get it there, you have to switch your account to SFTP mode from GIT. I then logged in to the server via the terminal. Just copy and paste the cli command they give you on the info box.
Once you get inside, you need to goto this folder:
code/sites/default
Then I upload an empty settings.php file taken from default.settings.php.
This is what you should see once setup properly:
Comment: The need for a settings.php in order to enable Drush aliases to work is fully documented in the Pantheon helpdesk article located here: http://helpdesk.getpantheon.com/customer/portal/articles/411388


using (windows) PowerShell to perform a dynamic DNS update with TSIG to a BIND9 server

Question: I run BIND9 DNS servers and allow Dynamic DNS updates from my customers by using a TSIG key.
One of my customers uses only a Windows environment, and therefore PowerShell to run scripts. He wants to use PowerShell to send dynamic updates to my servers.
Doing this from a Linux shell for testing is easy: use nsupdate.
from: https://www.freeipa.org/page/Howto/DNS_updates_and_zone_transfers_with_TSIG

Client
For nsupdate from bind-utils package you have to either use
  option -y algorithm:keyname:keyvalue or -k keyfilename option. E.g.
$ nsupdate -y hmac-sha512:keyname:keyvalue
or
$ nsupdate -k Kkeyname.+165+0316.private

then do your update:
from https://linux.die.net/man/8/nsupdate:

# nsupdate
> update delete oldhost.example.com A
> update add newhost.example.com 86400 A 172.16.1.1
> send

To do an update from Powershell without TSIG is ... kinda easy... I think?: use a cmdlet (for example) Add-DnsServerResourceRecordA

Add-DnsServerResourceRecordA -Name "host23" -ZoneName "contoso.com" - AllowUpdateAny -IPv4Address "172.18.99.23" -TimeToLive 01:00:00

After scouring the documentation, I don't see any references to Transaction Signatures or somehow using a TSIG key.
How do I send a dynamic update using a TISG key to a BIND9 server from Powershell?
This is frustratingly hard to find an example of. Most examples I can find are using PowerShell to send updates via an API which then (probably) does some kind of deploy or dynamic update inside a black box. I want to just build a DDNS update and send it off using PowerShell.
Comment: There are several programming languages (other then powershell) that support it (eg python w/dnspython). You could also use nsupdate from WSL.
Comment: I have created a powershell script last night that does exactly what you are looking for. I will be answering with the first version of the script later tonight when I can get back to my lab network.
1. get interfaces, dns servers and connection specific DNS domains. 2. digest the output for processing 4. tests if records match existing DNS on connection DNS servers 3. generate an nsupdate script file which deletes the record and creates A and AAAA records as well as PTR records 5. saves to a temp file and calls nsupdate.exe with the script file
Comment: I'm not sure you understand the question... The problem is that nsupdate isn't in Powershell. I am looking for the Microsoft comparable product, usable in Powershell. It appears not to exist. Unless your script constructs packets like nsupdate does, it does not answer my question.
Answer: They will have to download nsupdate from BIND (https://www.isc.org/downloads/).  It is possible to call nsupdate from a PowerShell host.
Answer: Here is a script that will create and submit DDNS requests if a tsig file is provided. Ensure NTFS permissions are set to prevent unauthorized users (including other admins) from accessing this file.
This does assume that you have installed nsupdate.exe and the associated dll's in C:\windows\system32 but it can be modified for other paths.
I welcome any pull requests.
https://github.com/ACiDGRiM/UsefulScripts/blob/master/Update-DNS.ps1
Param (
    [String]$KeyPath = "C:\Windows\System32\drivers\etc\windows-update-client.txt",
    [String]$NSScriptPath = "$env:Temp\nsupdate.txt",
    [String]$NSUpdatePath = "$env:SystemRoot\System32"
)

begin {
    #Gather status of system IP Addresses, DNS Servers, and domains
    $IPAddresses = Get-NetIPAddress | Where-Object -FilterScript { ($_.InterfaceAlias -like "Ethernet*" -or $_.InterfaceAlias -like "Wi-Fi*") -and $_.IPAddress -notlike "fe*"}
    $DNSServers = Get-DnsClientServerAddress | Where-Object -FilterScript { $_.InterfaceAlias -like "Ethernet*" -or $_.InterfaceAlias -like "Wi-Fi*"}
    $DNSClient = Get-DnsClient | Where-Object -FilterScript { $_.InterfaceAlias -like "Ethernet*" -or $_.InterfaceAlias -like "Wi-Fi*"}
}

process {
    [array]$RequestOutput = @()
    #Parse network status into simplified objects
    foreach ( $if in $IPAddresses ) {
        $requesthash = @{
            IPAddress = @{Address = $if.IPAddress;AddressFamily = $if.AddressFamily}
            Zone = $DNSClient | Where-Object -FilterScript { $_.InterfaceAlias -eq $if.InterfaceAlias } | Select-Object -ExpandProperty "ConnectionSpecificSuffix" -First 1
            Servers = $DnsServers | Where-Object -FilterScript { $_.InterfaceAlias -eq $if.InterfaceAlias } | Select-Object -ExpandProperty "ServerAddresses"
        }
        $RequestObj = New-Object -TypeName psobject -Property $requesthash
        $RequestOutput += $RequestObj

    }

    #Condense zones from multiple interfaces
    [array]$UniqueZones = ($RequestOutput.Zone|Sort-Object -Unique)
    #Combine IPv6 and IPv4 addresses into a single object property for each zone
    [array]$CombinedOutput = @()
    for ($i=0;$i -lt $UniqueZones.count;$i++) {
        $Combinedhash = @{
            Addresses = $RequestOutput | Where-Object -FilterScript {$_.Zone -eq $UniqueZones[$i]} | Select-Object -ExpandProperty "IPAddress"
            Servers = $RequestOutput | Where-Object -FilterScript {$_.Zone -eq $UniqueZones[$i]} | Select-Object -ExpandProperty "Servers" | Sort-Object -Unique
            Zone = $UniqueZones[$i]
        }
        $CombinedObj = New-Object -TypeName psobject -Property $Combinedhash
        $CombinedOutput += $CombinedObj
    }

    foreach ( $o in $CombinedOutput ) {
        foreach ( $s in $o.Servers ) {
            $CurrentRecords = Resolve-DnsName $env:COMPUTERNAME`.$($o.Zone) -Server $s -Type "A_AAAA" -DnsOnly -DnssecOK -QuickTimeout -ErrorAction "SilentlyContinue" | Select-Object -ExpandProperty "IPAddress" -ErrorAction "SilentlyContinue"
            if ( $CurrentRecords ) {
                $CurrentState = Compare-Object $IPAddresses.IPAddress $CurrentRecords -ErrorAction "SilentlyContinue"
            } else {
                $CurrentState = $true
            }

            if ( $CurrentState ) {
                $script += "server $s
"
                foreach ( $a in $o.Addresses ) {
                    if ( $a.AddressFamily -eq "IPv4" ) {
                        $PTR = $a.Address -replace '^(\d+)\.(\d+)\.\d+\.(\d+)$','$3.$2.$1.in-addr.arpa.'
                    } else {
                        $PTR = (([char[]][BitConverter]::ToString(([IPAddress]$a.Address).GetAddressBytes())-ne'-')[31..0]-join".")+'.ip6.arpa.'
                    }
                    $script += "update delete $env:COMPUTERNAME.$($o.Zone). $(if($a.AddressFamily -eq "IPv4"){"A"}else{"AAAA"})

update add $env:COMPUTERNAME.$($o.Zone). 60 $(if($a.AddressFamily -eq "IPv4"){"A"}else{"AAAA"}) $($a.Address)

update delete $PTR PTR

update add $PTR 60 PTR $env:COMPUTERNAME.$($o.Zone).

"
                }
            }

        }
    }
}

end {
    $script | Out-File -FilePath $NSScriptPath -Encoding "ascii" -Force
    Start-Process -FilePath (Join-Path -Path $NSUpdatePath -ChildPath "nsupdate.exe") -ArgumentList "-d -k `"$KeyPath`" `"$NSScriptPath`"" -Wait -NoNewWindow -RedirectStandardError "$env:TEMP\nsstderr" -RedirectStandardOutput "$env:TEMP\nsstdout" -WorkingDirectory $NSUpdatePath | Out-Null

}

Comment: I'm not sure you understand the question... The problem is that nsupdate isn't in Powershell. I am looking for the Microsoft comparable product, usable in Powershell. It appears not to exist. Unless your script constructs packets like nsupdate does, it does not answer my question... and it appears to *rely on* nsupdate being installed - missing the point.
Answer: Solution for those Who don't have Static IP Address and Need to Update IP Dynamically for DNS zone and reverse DNS PTR records too
            $Server = "your server"; $Hostname = "mail"; $Zonename = "your zone";
            $MZone = $Hostname + "." + $Zonename
            <# No need to edit below unless you have to change some internal component #>

            $oldobj = get-dnsserverresourcerecord -ComputerName $Server -name $Hostname -zonename $zonename -rrtype "A"
            $newobj = get-dnsserverresourcerecord -ComputerName $Server -name $Hostname -zonename $zonename -rrtype "A"
            $ip =  (Invoke-WebRequest ifconfig.me/ip).Content.Trim()
            $oip = $oldobj.recorddata.Ipv4address.IpAddressToString
            $oipSplit = $oip.Split("."); $oipr = $oipSplit[2] + "." + $oipSplit[1] + "." + $oipSplit[0] + ".in-addr.arpa"
            $ipSplit = $ip.Split("."); $ipr = $ipSplit[2] + "." + $ipSplit[1] + "." + $ipSplit[0] + ".in-addr.arpa"
            $newobj.recorddata.ipv4address=[System.Net.IPAddress]::parse($ip)
            if ($oip -ne $ip) {
                Set-dnsserverresourcerecord -ComputerName $Server -newinputobject $newobj -oldinputobject $oldobj -zonename $zonename -passthru
                echo "updated A record"
            }
            $oiprZ = Resolve-DnsName -Name $oipr -Server $Server; $oiprR = 0;
            if ($oiprZ.count -gt 0) {
                $oiprR = get-dnsserverresourcerecord -ComputerName $Server -ZoneName $oipr -rrtype "PTR"  -Name $oipSplit[3] | Select-Object HostName, @{Name='RecordData';Expression={$MZone}}
                if ($oiprR -ne 0 -And $oiprR -ne $null -and -not ($oiprR[0].HostName -eq $ipSplit[3] -and $oiprR[0].RecordData -eq $MZone -and  $oipr -eq $ipr )  ){
                    Remove-DnsServerResourceRecord -ComputerName $Server -ZoneName $oipr -rrtype "PTR" -Name $oipSplit[3] -RecordData $MZone -Force
                    echo "removing existing ptr record"
                    echo $oiprR
                    echo "removed existing ptr record"
                }
                $oiprR =get-dnsserverresourcerecord -ComputerName $Server -ZoneName $oipr -rrtype "PTR"
                if (((($oiprR) -eq $null) -or (($oiprR).Count  -eq 0)) -And $oipr -ne $ipr )  {
                    Remove-DnsServerZone  -ComputerName $Server $oipr -PassThru -Verbose -Force
                    echo "Removing RDNS Zone"
                    echo $oiprZ
                    echo "Removing RDNS Zone"

                }
            }

            $ipNID = $ipSplit[0] + "." + $ipSplit[1] + "." + $ipSplit[2] + ".0/24"
            $iprZ = Resolve-DnsName -Name $ipr -Server $Server; $iprR = 0;
            if ($iprZ.count -gt 0) {
                $iprR = get-dnsserverresourcerecord -ComputerName $Server -ZoneName $ipr -rrtype "PTR"  -Name $ipSplit[3] | Select-Object HostName, @{Name='RecordData';Expression={$MZone}}
                if ($iprR -eq $null ){
                Add-DnsServerResourceRecordPtr  -ComputerName $Server  -Name $ipSplit[3] -ZoneName $ipr -AllowUpdateAny -TimeToLive 01:00:00 -AgeRecord -PtrDomainName $MZone
                    echo "adding ptr record"
                    echo $iprR
                    echo "added ptr record"
                }
                else
                {

                }
            }
            if ($iprZ.count -eq 0) {
                Add-DnsServerPrimaryZone  -ComputerName $Server -DynamicUpdate Secure -NetworkId $ipNID -ReplicationScope Domain
                Add-DnsServerResourceRecordPtr  -ComputerName $Server  -Name $ipSplit[3] -ZoneName $ipr -AllowUpdateAny -TimeToLive 01:00:00 -AgeRecord -PtrDomainName $MZone
            }


Hibernate mapping with ID generated by DB trigger + sequence

Question: everyone.
I've a LOG table with a combination of trigger and sequence to create the id, so when I insert the line I do not have to specify the id, otherwise the database returns error. However Hibernate claims (rightly) that was specified primary key.
What kind of "generator" property should I use in this case?
I already tried "assigned" it says:
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save (): it.m2sc.simulator.beans.Log

With "select" hib ask me the natural key, but there is no natural key in this table, but the primary.
org.hibernate.id.IdentifierGenerationException: no natural-id property defined; need to specify [key] in generator parameters

That's my hbm
<hibernate-mapping>
    <class name="it.m2sc.simulator.beans.Log" table="LOG">
        <id name="id" type="integer" column="LOG_ID" access="field">
            <generator class="select" />
        </id>
        <property name="date" type="date" column="LOG_DATE" access="field" />
        <property name="user" type="string" column="LOG_USER" access="field" />
        <property name="evtId" type="integer" column="EVT_ID" access="field" />
        <property name="detail" type="string" column="LOG_DETAIL" access="field" />
        <property name="deleted" type="character" column="LOG_DELETED" access="field" />
        <property name="codiceRaggruppamento" column="LOG_CODICE_RAGGRUPPAMENTO" type="string" access="field" />
    </class>
</hibernate-mapping>

The Class
public class Log {
    private Integer id;
    private Date date;
    private String user;
    private Integer evtId;
    private String detail;
    private Character deleted = '0';
    private String codiceRaggruppamento;

    ... ( getter & setter )
}

DDL of table/trigger/sequence
CREATE TABLE
    LOG
    (
        LOG_ID NUMBER(12) NOT NULL,
        LOG_DATE TIMESTAMP(6),
        LOG_USER VARCHAR2(50),
        EVT_ID NUMBER(12),
        LOG_DETAIL VARCHAR2(100),
        LOG_DELETED CHAR(1) DEFAULT '0 ' NOT NULL,
        LOG_CODICE_RAGGRUPPAMENTO NCHAR(2) NOT NULL,
        CONSTRAINT LOG_PK PRIMARY KEY (LOG_ID),
        CONSTRAINT LOG_CFG_EVENT_TYPE_FK1 FOREIGN KEY (EVT_ID)
        REFERENCES CFG_EVENT_TYPE (EVT_ID)
    );

   CREATE SEQUENCE  LOG_SEQ  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 358 CACHE 20 NOORDER  NOCYCLE;

CREATE OR REPLACE TRIGGER "DTCUSR"."LOG_TRG" BEFORE INSERT ON LOG
FOR EACH ROW
BEGIN
  <<COLUMN_SEQUENCES>>
  BEGIN
    IF :NEW.LOG_ID IS NULL THEN
      SELECT LOG_SEQ.NEXTVAL INTO :NEW.LOG_ID FROM DUAL;
    END IF;
  END COLUMN_SEQUENCES;
END;

Ah, just fyi: db is Oracle11
Ty in advice
Comment: Tried with "**native**" too, it says: 'select hibernate_sequence.nextval from dual' :(
Comment: Have you found any solution? I'm facing the same problem and I cannot use the sequence value generation in oracle. I need to use a trigger.
Answer: To achieve the goal you need to use GenerationType.IDENTITY

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "LOG_ID", updatable = false, nullable = false)
private Integer id;

See more on https://www.thoughts-on-java.org/jpa-generate-primary-keys/
Comment: that used to work for me too. after I upgraded my ojdbc.jar, it got messed up
Comment: GenerationType.IDENTITY creates "generated as identity" (in Oracle) and this does not allow you to enter the ID manually (and thus use the trigger) as required in the question.
Answer: sequence-identity id generation strategy embeds sequence call directly in the insert statement:
insert into log (log_id, log_date, log_user, ...)
values (LOG_SEQ.nextval, ?, ?, ...)

This way you can get rid of the trigger because it's not needed.
Also, you have to set hibernate.jdbc.use_get_generated_keys property to true, so that Hibernate reads the generated keys after executing insert statements.
In hbm.xml:
<id name="id" type="integer" column="LOG_ID" access="field">
  <generator class="sequence-identity" >
    <param name="sequence">LOG_SEQ</param>
  </generator>
</id>

With annotations:
@Entity
@Table(name = "LOG")
public class Log {
  @Id
  @org.hibernate.annotations.GenericGenerator(name="logSequenceGenerator", strategy = "sequence-identity",
    parameters = {@org.hibernate.annotations.Parameter(name="sequence", value="LOG_SEQ")})
  @GeneratedValue(generator = "logSequenceGenerator")
  @Column(name = "LOG_ID")
  private Integer id;
  ...
}

Comment: the problem is that I can't rid of the trigger, this DB is made by another co-worker and I have to work with what I have
Answer: Take a look at this link explaining how to use a trigger based generator.
Additionaly, remember to use the hibernate.jdbc.use_get_generated_keys property in your Hibernate persistence configuration
<property name="hibernate.jdbc.use_get_generated_keys" value="true" />

Probably you will get an NullPointerException while inserting using the class described on the link. Change the method executeAndExtract(PreparedStatement insert, SessionImplementor session) to anything like this
    @Override
    protected Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session)  throws SQLException {

        insert.executeUpdate();

        try {

            ResultSet rs = insert.getGeneratedKeys();
            rs.next();

            return rs.getLong(1);

        } catch (RuntimeException rt) {
            throw new SQLException("Error while attempt to use the CustomTriggerGenerator. Check the <property name=\"hibernate.jdbc.use_get_generated_keys\" value=\"true\" /> in your persistence.xml");
        }

    }

Answer: Hibernate doc is really clear on different generation mechanism available. Depending on how data will be written one should make a call:
For simple use cases you might use sequence, but there are several more options available.
Refer: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-id
Comment: I read that refer, because it is referenced by other topics here on StackOverflow, but unfortunately I have not found the answer to my question. I wrote this post very detailed to find additional help.
Answer: If you want your ID to be generated only in database and just read by hibernate you can use parameters 'insertable' and 'updatable' in @Column annotation:
@Column(name = "LOG_ID", insertable=false, updatable=false)
private Integer id;

With this parameters hibernate will not add the id column to inserts and updates.
Comment: Wrong. With @Id this doesn't work. I've got ``@Id @Column(name = "ADH_ID", insertable = false, updatable = false)
 private Long id;`` and still get the exception: ``org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save()``


Return matching posts based on postmeta meta_key

Question: So I have the following SQL tables and their all matching:
wp_postmeta
wp_posts
wp_1_postmeta
wp_1_posts
wp_2_postmeta
wp_2_posts

Then I'm using the following SQL query to search and return all meta_key matching "_taleo_id" inside the `wp_..._postmeta tables.
SELECT *
FROM wp_postmeta
WHERE meta_key = '_taleo_id'
union all
SELECT *
FROM wp_1_postmeta
WHERE meta_key = '_taleo_id'
union all
SELECT *
FROM wp_2_postmeta
WHERE meta_key = '_taleo_id'

I get the following results back:

So now since I have the matching post_id based on the meta_key, how can I look inside the wp_posts or wp_1_posts table and return the post matching the post_id?
Example:
In the above screenshot, we have a matching meta_key that has a post_id of 252, now if I jump into the wp_posts table, I'll see the following result shown below - So I'm basically wanting to print out all the posts that have a matching meta_key of taleo id all in one view.
Comment: Why do you have multiple post and meta tables?
Comment: @GordonLinoff, this is how WordPress multi-sites work, it's multiple websites so it uses a `wp_1_posts, or wp_2_postmeta` prefix, I'm basically wanting to print out all the posts from all of our websites in a view that have a matching taleo_id.
Comment: You can't use a central database for all the sites?  In any case, I've answered below, but it seems strange to divide the data into three -- particularly if you want to analyze it as a single source.
Answer: You can use join:
SELECT p.*
FROM wp_postmeta pm join
     wp_posts p
     on p.id = pm.post_id
WHERE pm.meta_key = '_taleo_id'
UNION ALL
SELECT p.*
FROM wp_1_postmeta pm join
     wp_1_posts p
     on p.id = pm.post_id
WHERE pm.meta_key = '_taleo_id'
UNION ALL
SELECT p.*
FROM wp_2_postmeta pm join
     wp_2_posts p
     on p.id = pm.post_id
WHERE pm.meta_key = '_taleo_id';

I don't understand why you have multiple posts and metadata tables.  It seems unusual.


NullPointerException ao eliminar registo

Question: Bom dia. Estou com problema que não consigo resolver.
Estou desenvolvendo meu primeiro app Android e esbarei com este erro, o SQLite não consegue trabalhar com Context. Fiz algumas pesquisas e não achei solução.
Espero que alguma alma caridosa me ajuda a dar fim.
Desde já agradeço.
Vamos ao código.
O Erro só aparece quando tento excluir o item.
DBHelper - método: itemDelete
    public class DBHelper extends SQLiteOpenHelper {
        private static final String DATABASE = "ListaDeCompras";
        private static final String TABLE = "Produtos";
        private static final String NOME = "name";
        private static final String MARCA = "marca";
        private static final String PRECO = "preco";
        private static final String TOTAL = "total";
        private static final String QUANTIDADE = "quantidade";

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE + "(id INTEGER PRIMARY         KEY AUTOINCREMENT, "
               + NOME + " TEXT,"
               + MARCA + " TEXT NULL,"
               + PRECO + " TEXT,"
               + TOTAL + " TEXT,"
               + QUANTIDADE + " TEXT)");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF NOT EXISTS " + TABLE);
            onCreate(db);
        }

        public boolean insertProduto(String name, String marca, String preco, String total, String quantidade) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues content = new ContentValues();
            content.put(NOME, name);
            content.put(MARCA, marca);
            content.put(PRECO, preco);
            content.put(TOTAL, total);
            content.put(QUANTIDADE, quantidade);
            db.insert(TABLE, null, content);

            return true;
        }

        public ArrayList<Produto> getAllProdutos() {
            ArrayList<Produto> array = new ArrayList<Produto>();
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE + " ORDER BY " + NOME, null);
            cursor.moveToFirst();
            while (cursor.isAfterLast() == false) {
                Produto produto = new Produto();
                produto.setId(cursor.getInt(cursor.getColumnIndex("id")));
                produto.setNome(cursor.getString(cursor.getColumnIndex(NOME)));
                produto.setMarca(cursor.getString(cursor.getColumnIndex(MARCA)));
                produto.setPreco(cursor.getString(cursor.getColumnIndex(PRECO)));
                produto.setTotal(cursor.getString(cursor.getColumnIndex(TOTAL)));        produto.setQuantidade(cursor.getString(cursor.getColumnIndex(QUANTIDADE)));
                array.add(produto);
                cursor.moveToNext();
            }
            return array;
        }

        public boolean updatePtoduto(int id, String marca, String preco, String total, String quantidade) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues content = new ContentValues();
            content.put("id", id);
            content.put(MARCA, marca);
            content.put(PRECO, preco);
            content.put(TOTAL, total);
            content.put(QUANTIDADE, quantidade);
            db.update(TABLE, content, "id = ?", new String[]{String.valueOf(id)});
            db.close();
            return true;
        }

        public boolean listDelete() {
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(TABLE, null, null);
            db.close();
            return true;
        }

        public void itemDelete(int id) {
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(TABLE, "id = " + id, null);
            db.close();
        }

        public DBHelper(Context context) {
            super(context, DATABASE, null, 1);
        }
    }

Adapter:
    public class AdapterProduto extends RecyclerView.Adapter<AdapterProduto.ProdutoViewHolder> {
        private Context context;
        private ArrayList<Produto> produtos = new ArrayList<Produto>();

        public AdapterProduto(MainActivity mainActivity, Context context, ArrayList<Produto> produtos) {
            this.context = context;
            this.produtos = produtos;
        }

        @Override
        public ProdutoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
            ProdutoViewHolder produtoViewHolder = new ProdutoViewHolder(view, context, produtos);
            return produtoViewHolder;
        }

        @Override
        public void onBindViewHolder(ProdutoViewHolder holder, int position) {
            Produto produto = produtos.get(position);
            holder.tv_nome.setText(produto.getNome());
            holder.tv_marca.setText(" " + produto.getMarca());
            holder.tv_preco.setText("R$ " + produto.getPreco());
            holder.tv_quantidade.setText(produto.getQuantidade() + " unid.");
            holder.tv_total.setText("R$ " + produto.getTotal());
}

        @Override
        public int getItemCount() {
            return produtos.size();
        }

        public class ProdutoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
            public TextView tv_nome;
            public TextView tv_marca;
            public TextView tv_preco;
            public TextView tv_quantidade;
            public TextView tv_total;

            Produto produto;
            Context context;
            ArrayList<Produto> produtos = new ArrayList<Produto>();

            DBHelper dbHelper = new DBHelper(context);

            public ProdutoViewHolder(View view, Context context, ArrayList<Produto> produtos) {
                super(view);
                this.produtos = produtos;
                this.context = context;

                view.setOnClickListener(this);
                view.setOnLongClickListener(this);

                tv_nome = (TextView) view.findViewById(R.id.tv_nome);
                tv_marca = (TextView) view.findViewById(R.id.tv_marca);
                tv_preco = (TextView) view.findViewById(R.id.tv_preco);
                tv_quantidade = (TextView) view.findViewById(R.id.tv_quantidade);
                tv_total = (TextView) view.findViewById(R.id.tv_total);
            }

            @Override
            public void onClick(View view) {
                int position = getAdapterPosition();
                produto = this.produtos.get(position);

                //passando os dados pra EditActivity
                Intent intent = new Intent(this.context, EditActivity.class);
                intent.putExtra("id", produto.getId());
                intent.putExtra("nome", produto.getNome());
                intent.putExtra("marca", produto.getMarca());
                intent.putExtra("preco", produto.getPreco());
                intent.putExtra("total", produto.getTotal());
                intent.putExtra("quantidade", produto.getQuantidade());
                this.context.startActivity(intent);
            }

            @Override
            public boolean onLongClick(View view) {
                final int position = getAdapterPosition();
                final int id = produtos.get(position).getId();

                //AlertDialog - mensagem
                AlertDialog.Builder alert = new AlertDialog.Builder(context);
                alert
                        .setTitle("Excluir item")
                        .setMessage("Deseja excluir o item " + tv_nome.getText().toString() + " permanentemente?")
                        .setCancelable(true)
                        .setNegativeButton(R.string.title_no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .setPositiveButton(R.string.title_yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dbHelper.itemDelete(id);
                                Toast.makeText(context, getPosition(), Toast.LENGTH_SHORT).show();
                            }
                        });
                AlertDialog alertDialog = alert.create();
                alertDialog.show();
                return true;
            }
        }
    }

Android Monitor:
    07-12 09:59:30.962 29172-29172/com.charlespresidente.listadecompras E/AndroidRuntime: FATAL EXCEPTION: main
            Process: com.charlespresidente.listadecompras, PID: 29172
            java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at com.charlespresidente.listadecompras.database.DBHelper.itemDelete(DBHelper.java:93)
            at com.charlespresidente.listadecompras.adapter.AdapterProduto$ProdutoViewHolder$1.onClick(AdapterProduto.java:116)
            at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5527)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Answer: Acho melhor passar a própria activity como context:
public AdapterProduto(Activity activity, ArrayList<Produto> produtos) {
  this.context  = activity;
  this.produtos = produtos;
}

Desta maneira seu context estará inicializado.
Comment: Obrigado Sergio, mas não funcionou.
Answer: Quando você instancia o Objeto DBHelper o Context ainda está nulo!
Tente da seguinte forma:
DBHelper dbHelper = null;

public ProdutoViewHolder(View view, Context context, ArrayList<Produto> produtos) {
    super(view);
    this.produtos = produtos;
    this.context = context;

     // AQUI SEU CONTEXT NAO ESTARÁ NULO!
    this.dbHelper= DBHelper(context);
    view.setOnClickListener(this);
    view.setOnLongClickListener(this);

    tv_nome = (TextView) view.findViewById(R.id.tv_nome);
    tv_marca = (TextView) view.findViewById(R.id.tv_marca);
    tv_preco = (TextView) view.findViewById(R.id.tv_preco);
    tv_quantidade = (TextView) view.findViewById(R.id.tv_quantidade);
    tv_total = (TextView) view.findViewById(R.id.tv_total);
}

Comment: Obrigado Thiago, funcionou!


Semver policy to exclude offending versions

Question: Consider a package with running versions:

1.0.0
1.0.1
1.0.2

given the semver policy ~1.0.0 - we'll get the latest patch - and life is great.
Now consider that version 1.0.3 has landed and is an offending version, so we expect 1.0.4 to correct the offense.
I don't want to wait for the authors to depricate 1.0.3, and it's anyway on my builder cache. I hope to handle this using the semver policy.
Is there a way I can phrase my semver policy to exclude that offending version, so that until a fix is released I'll get 1.0.2, and after its released I'll get 1.0.4?
And - if 1.0.4 is also offending, what will be the way to exclude both 1.0.3 and 1.0.4 so I'll get 1.0.5 as soon as it's published?
Thanks
Answer: Ah.. found it. I was looking in the wrong place for that...
The way to do that is:
 "dependencies": {
   "the-package" : "~1.0.0 < 1.0.3 || ~1.0.4",

and if 1.0.4 is found offensive, then
   "the-package" : "~1.0 < 1.0.3 || ~1.0.5",

It works with ^ as well, if you like, not just ~.
I expected to find it on the https://semver.org site, but the examples are found with an interactive playground here:

https://semver.npmjs.com/#syntax-examples


Draw customized (calculus) graphs like these?

Question: Can you please suggest some good software to draw customized graphs like these?
PS:I am studying calculus (engineering degree) and would like to take notes on my pc, including customized graphs, about all the theorems I am learning (bolzano-weierstrass, Rolle, etc...).
Hope you can help.
Thanks.
NB: I am on windows, but can use linux software as well.
Comment: this is not actually graph theory. (I wasn't sure whether to flag this for moderator attention; if a mod sees this, can you let me know?)
Comment: Not sure whether to flag it, but I have enough rep to retag stuff so I got rid of the graph-theory tag.
Comment: I do not understand how we can have 4 different questions on graphing software, and none of them have mentioned the same ones. See also (http://math.stackexchange.com/questions/26903/what-is-a-good-graphing-software) and (http://math.stackexchange.com/questions/55570/software-for-plotting-a-graph).
Answer: GeoGebra is easy to use, free, and the graphs look good.
Comment: +1 What an excellent piece of software.  Wish that had been around long ago when I was studying.
Comment: @iAsk: At the bottom of the window, there is a line where you can write your function, for example $y=\cos (x)$.
Comment: @Eivind: I tried inputing this: $(x^2+y^2+z^2)^2=2z(x^2+y^2)$. Does it more than 3d graphing?
Comment: @Cplayer: I have only used it for simple 2D graphing (for functions of one variable), and I don't think it can draw graphs of higher dimension. At least not the version I'm using.
Comment: thanks for the suggestion, Eiving. so how can I draw the green curve, in my figure no.1 ? I can't find the right tool in geogebra.
Comment: Thanks Eiving, but i don't know the equation of the green line/curve in my fig.1 . so how can i draw it manually? I can't find a way...thank you :)
Comment: @iAsk: If that was what you wanted (to draw it manually), I misunderstood your question, and I don't know any way to do this in geogebra. In any case, it is not usually that hard to find expressions for functions that looks similar to the ones you want, and which is good enough for your use, if I understand you correctly.
Comment: For example: For the first (and the third, i guess) you can use a part of a sine/cosine function, and for the second there are plenty of functions to choose from (for instance $-x^2$).
Answer: Try http://www.onlinefunctiongrapher.com/. You can customize your graphs there. Easy to use and free! unlike Mathematica or Mathlab. It is online so you don't have to worry about linux/windows shift.
Comment: Look at the [section of the FAQ on self-promotion](http://math.stackexchange.com/faq#promotion). All three of your posts on this site so far have been to promote your website, and none have disclosed your affiliation. If this continues the moderators may have to take action.
Answer: If you've got a Mac or iPad, this might help:
  http://www.omnigroup.com/products/omnigraphsketcher/
Answer: This question comes up from time to time in different forms. In an effort to consolidate all this information, check out the following.
See also What is a good graphing software? and Software for plotting a graph
Perhaps also A good, free, graphics package for mathematics? and Educational Math Software


Ruby - alias for object class

Question: sorry for my english.
My code ...
class MyClass

  NewFood = Food

  def index
    @items = NewFood.all
  end
end

@items.first is a Food object, but I want to get a NewFood object
Some help?
Answer: It doesn't make sense to say you want a NewFood object.  There are only two classes: MyClass and Food.  The constant MyClass::NewFood just points to Food; just because you defined that constant doesn't mean you can expect the instances of the Food class to start behaving differently and saying that their class is NewFood.
Could you zoom out and tell us what the big picture is?  What are you trying to accomplish?  What real life problem are you trying to solve?  We can probably offer a better way of solving it.
Answer: Take this example:
class Foo
  @@instances = []

  def initialize(value)
    @value = value
    @@instances << self
  end

  def self.all
    @@instances
  end
end

class Bar
  NewFoo = Foo.dup

  def index
    @items = NewFoo.all
  end
end

# Now Bar::NewFoo will instantiate it's own objects
Bar::NewFoo.new(5)
Bar::NewFoo.new('fish')
Bar.new.index
=>  [#<Bar::NewFoo:0x00000002f33cf0 @value=5>,
     #<Bar::NewFoo:0x00000002f65958 @value="fish">]

However I fail to see the need for this kind of metaprogramming hack.
Edit: crap, I forgot class variables (@@var) are shared along it's childs, so this example could turn messy.

Ruby - alias for object class


{{ directory }} not available in parts of menu--main.html.twig

Question: Printing {{ directory }} at the start of the file works fine. But a bit further it's no longer availble:
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
    **{{ directory }} {# THIS WORKS #}**
    {% import _self as menus %}
    {% if items %}
        {% if menu_level == 0 %}

        {% else %}

        {% endif %}
        {% for item in items %}

                **{{ directory }} {# THIS DOESN'T WORK #}**

                {{ item.title }}

        {% endfor %}

    {% endif %}
{% endmacro %}

Any idea why this happens and how to fix it?
Comment: Be careful about using `{{ directory }}` twig variable in a theme that you intend to use as a base theme and create sub-themes for:  https://drupal.stackexchange.com/questions/277278
Answer: The second occurrence of {{ directory }} is within a Twig macro. As the Twig documentation mentions, you cannot access the outer variables in a macro:

But as with PHP functions, macros don't have access to the current template variables.

You can however pass _context through a macro parameter and access directory that way, or pass it explicitly.


What does this chord/number means?

Question: Being a complete newbie at playing guitar( Got it on last weekend), I'm trying to learn a simple christmas song. From this site:

I do not know what does 7 means, is it referring to 7 string guitars or something else? Would be love to have some advice here!
Comment: The notation you posted is for single notes played on the high e string and has nothing to do with chords.  The numbers indicate the frets the note is played on.
Comment: @RockinCowboy yeah , i figured. My apologies for such a silly question.
Answer: It's talking about fret numbers, in this case on an E string. The top and bottom strings are both E strings, but if you play on these fret numbers with the right rhythms on either one, the melody will be Jingle Bells. More often than not, a melody like this would be played on the higher-pitched E string, not the lower one.
Actually, more often than not a melody wouldn't be played on a single string, but that's the point of this particular version...
Comment: @Gene Understood, but I'm not at all sure that playing on one string with lots of shifting (meaning, moving your hand up and down the fretboard) is actually any easier than playing on 2 or 3 strings without shifting. At least the normal way that beginners learn melodies is playing them in "first position," which is the point on the fretboard where your four fingers are on the first four frets without shifting.
Comment: I know. But as a total beginner, I'm still getting the hang on playing G major and C and etc properly. So yeah, at least I can get something out for now. Thanks!
Comment: Ahh!! In that case, would you give me any tips on any songs I could try out without shifting?
Comment: @Gene Any song could be, including Jingle Bells. Take the transcription you currently have, except convert the numbers like this: 7 –> 3 on E string, 5–>1 on E string 4–>0 also known as open E. The rest of the notes are on the B string; 2–>3 and 0–>1. That will be the same melody but in first position on the E and B strings. I'm sure the site you found has melodies transcribed that aren't single-string like this.

What does this chord/number means?


Quantile of a non standardized t distribution?

Question: I have a non standardized t distribution with parameters $\nu$,$\beta$ (or sometimes also denoted by $\sigma^2$) and $\nu$. Now I want to get the quantiles of it. qt just calculates the quantile of a standardized t distribution, I know there exist a monotonic transformation, BUT I do not want to use this, so I want to calculate the quantile of a non-standardized t distribution. Is there any preimplemented function in R?
If there is no function, the quantile is the inverse of the cdf, how can I implement this in R?
Comment: Then why not explain your actual problem?
Comment: Can you explain _why_ you don't want to use a monotonic transformation?
Comment: @Dason because I need this also for other distributions, in which case the monotonic transformation does not work and I want to have a solution for all distributions.
Answer: If you can calculate the quantiles of a standardised distribution $F(\cdot;\theta)$, where $\theta \in \Theta$ is a shape parameter, then the quantile function of the corresponding distribution with location and scale parameters $(\mu,\sigma)$ is simply
$$Q(p;\mu,\sigma,\theta)=\mu+\sigma F^{-1}(p;\theta).$$
In R, this can implemented for the Student-$t$ as follows
<code>qnst <- function(p,mu,sigma,nu) return(mu + sigma*qt(p,df=nu))

# Quantile 0.25, mu = 10, sigma = 1, nu = 2
qnst(0.25,10,1,2)
</code>
Comment: Good luck then :). Note that this method works for ANY distribution ;)
Comment: as I said: I DO NOT WANT TO USE the monotic transformation!


Can the field type of a foreign key be different to the referenced primary key?

Question: I get a E-R model which is not designed by me. But I have no way to contact the author.
There are something confusing me in this model.
In Table A, the Primary Key is an integer field. Table B has a Foreign Key referenced to the PK of A. But this FK of B is a varchar field.
I just start learning the database dedign, and never see or do that in my jobs.
Is it reasonable and realizable?
Note that the model is for mysql.
Comment: A foreign key doesn't have to reference the primary key of the parent table. A foreign key can reference any key in a table. Could it be that the foreign key in B is really referencing a varchar column in A and not the primary key of A?
Answer: That can't be implemented as a FOREIGN KEY constraint in InnoDB; the datatype of the foreign key column(s) must match the datatypes of the referenced column(s) EXACTLY.
You can perform a join operation on the columns, although there's going to need to be datatype conversion on one side or the other... e.g.
ON c.character_col + 0 = p.numeric_col

It's permissible to do that in SQL; we don't have to have a FOREIGN KEY constraint defined in order to perform join operations.
This design is not one we like to see; one of the big issues is performance, in that MySQL can't make effective use of an index on character_col.


Update time zone when user travels

Question: I am creating a site that increments a "day" session at midnight. Is there a way to update the timezone set for that user when they travel between time zones?
Would using javascript to pull the value from the calendar on their computer be an option? Right now we are storing timezone values in the DB so this would be a major code change, but would it work? Is there any Drupal module that could help with this?
Answer: You can use javascript to get the browser timezone. Assuming their computer timezone is updated, their browser timezone will change.
<code>var offset = new Date().getTimezoneOffset();
</code>
Or if you want the name you'll have to do something like https://stackoverflow.com/questions/2853474/can-i-get-the-browser-time-zone-in-asp-net-or-do-i-have-to-rely-on-js-operations
Sadly there is no way to do this without Javascript.

Update time zone when user travels


Shell Script para copiar estrutura de arquivos renomeando no destino

Question: Gostaria de copiar uma estrutura de pastas já renomeando os arquivos para o seu destino colocando na frente do nome um texto informado previamente pelo usuário.
Mas estou com dificuldades para copiar renomeando os arquivos.
No script estou executando um rsync. Gostaria de executar um find para listar e copiar a estrutura e os arquivos criando um array, com isso poderia manipular o destino individualmente dentro de um loop for ou while.
Abaixo segue a estrutura de pasta e o script.
Pastas e arquivos de origem:
Template
    00 - Criação
        Arq de Criação.docx
        Arq de Informações.docx
    01 - Iniciação
        Arq de Iniciação.docx
        Arq de Coleta.docx
    02 - Planejamento
        Arq de Planejamento.docx
        Arq de Informações.docx
    03 - Execução
        Arq de Cronograma.docx
        Arq de Mudança.docx
    04 - Controle
        Arq de Entrega Parcial.docx
    05 - Encerramento
        Arq de AS Bult.docx
        Arq de Encerramento.docx

Pastas e arquivos de destino:
P20190103.0001 - Estrutura nova cliente
    00 - Criação
        P20190103.0001 - Arq de Criação.docx
        P20190103.0001 - Arq de Informações.docx
    01 - Iniciação
        P20190103.0001 - Arq de Iniciação.docx
        P20190103.0001 - Arq de Coleta.docx
    02 - Planejamento
        P20190103.0001 - Arq de Planejamento.docx
        P20190103.0001 - Arq de Informações.docx
    03 - Execução
        P20190103.0001 - Arq de Cronograma.docx
        P20190103.0001 - Arq de Mudança.docx
    04 - Controle
        P20190103.0001 - Arq de Entrega Parcial.docx
    05 - Encerramento
        P20190103.0001 - Arq de AS Bult.docx
        P20190103.0001 - Arq de Encerramento.docx

O código P20190103.0001 é variável e inserido pelo usuário na execução do script.
#!/bin/bash
clear

LOCALMOUNTPOINT="/Volumes/Server01"

if mount | grep "on $LOCALMOUNTPOINT" > /dev/null; then
    echo ""
    echo ""
    echo ""
    echo "       Verificando se o volume esta montado.... OK"
    echo ""
    echo ""
    echo ""
    echo "       Informe o nome do projeto...: "
    read PROJETO
    FULLPATHSRC="/Users/xxx/Downloads/Templates/"
    FULLPATHDST="/Users/xxx/Downloads/teste/"$PROJETO"/"
    echo "       Criando estrutura do projeto: " $FULLPATHDST
    if [ -d "$FULLPATHDST" ]
    then
       echo ""
       echo ""
       echo "      ERROR    "
       echo "     -------   "
       echo ""
       echo "Diretório de destino já existe...:"
       echo "  ---> $FULLPATHDST  <---"
       echo ""
       echo ""
       echo ""
    else
       mkdir "$FULLPATHDST" > /dev/null;
       rsync -av --progress "$FULLPATHSRC" "$FULLPATHDST"
    fi
else
    echo ""
    echo ""
    echo "                            ERROR                         "
    echo "                           -------                        "
    echo ""
    echo "     Conecte-se ao servidor "Server01.dominio.local/Clientes""
    echo ""
    echo "            .....O volume não esta montado.....           "
    echo ""
    echo ""
    echo ""
fi

Answer: Após a execução do rsync você poderia rodar o find para listar todos arquivos copiados e renomear cada arquivo individualmente assim:
# lista todos os arquivos copiados para $FULLPATHDST
find "$FULLPATHDST" -type f > /tmp/files.txt

# manipula cada arquivo indivualmente
while IFS='' read filepath; do
    # obtém o diretório do arquivo
    filedir="${filepath%/*}"
    # obtém o nome do arquivo (sem o diretório)
    filename="${filepath##*/}"
    # renomeia o arquivo conforme a necessidade - adiciona o prefixo
    mv -v "$filepath" "$filedir/P20190103.0001 - $filename"
done < /tmp/files.txt

rm -f /tmp/files.txt

O único problema é que o rsync não seria muito eficiente na segunda vez que seu script rodar, pois todos os arquivos estariam renomeados e o rsync iria copiá-los todos novamente.


Get default value of a node field

Question: I have a field on a node which has a default value set, I need to access the default value of that field. But, I don't want to load any nodes of that type and access the field definitions, nor do I want to manually write a db_query and fetch the value directly from the db, I know there is a proper way to do it I just don't know of it.
Drupal 8.6.x
Answer: Use FieldDefinitionInterface::getDefaultValueLiteral:
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
if (isset($definitions['field_example'])) {
  $default_value = $definitions['field_example']->getDefaultValueLiteral();
}

Get default value of a node field


What is the purpose of signing a smart contract from the backend API? Is it secure?

Question: Since the transaction needs to be signed, it requires a private key, so how can the users interact with the backend API and send the private key securely.
I wonder what is the purpose of signing a smart contract from the backend API? Is there any solid real-world use case where a number of users need to interact through the backend to smart contract instead of frontend metamask to smart contract?
Answer: Mostly automated actions from your own wallet, so that you don't have to sign the transactions manually.

Trading bot sending automated buy and sell orders to a DEX contract from your own wallet based on some off-chain analysis. The script can run 24/7 not having to prompt you to sign the transaction each time.
Oracle pattern. Your own wallet is an authorized address on your sports bets contract, feeding it off-chain data who won a match. This way you can automate the process and not have to sign the transaction manually after each match.

As always in IT security, a chain is as strong as its weakest link. There are ways to securely store and use private keys. For example use a secrets management system, exclude sensitive values from logs, set up and review access to sensitive data (only certain users or apps are able to access it), ... Specifics depend on your implementation and how much value is at stake.
Comment: What if I want to build an API endpoint where users can transfer tokens to each other, is it possible in practice?
Comment: Is there a way of sending a user transaction, let them sign, and sending back to backend to process?  What is the approach that suit this kind of task?
Comment: @KrittamookAksornchindarat MetaMask and WalletConnect currently do not support "just" signing the transaction without broadcasting it (that you could broadcast later from your backend app) - they always broadcast the signed transaction. They do support signing a message (that is not broadcasted by design) but that's not the same thing... So unless the users give you their private key (so that you could sign the transaction with their key), they'll need to use a software wallet (and not an API) to sign the transaction and broadcast it.
Comment: So, if I want to save their transaction on the database, the only way, without touching their private keys, is to listen to their broadcast of the signed transaction right?
Comment: @KrittamookAksornchindarat Browser wallets usually return just the transaction hash (but not its other details). So you can wait until the tx is mined ([tx receipt](https://web3js.readthedocs.io/en/v1.7.3/web3-eth.html#gettransactionreceipt) has a non-null value after it's mined) and then process the tx receipt data on your backend app for example.


csharp flat file database for a standalone windows application

Question: A question like this has been asked differently several times.
Yet here i am.
I am writing a standalone windows program which will get user input like three fields and have to store it in the disk.
Also i need to delete them, edit them and so on.
It should be UTF8.
Besides here is the actual need.
I have hosted this application in my server and users can download it.
I want the db automatically created when the program is executed for the first time.
What i mean is user can or should download only one file and that is the program.
The program will be one exe file and it will not have any dependencies.
meanwhile asking this question i tried sqllite for .net 2.0 and i got an installer from sourceforge and installed it.
I included in my application and it showed an error like there is a problem in that.
So, if people suggest sqlite then please give me reference of how to include in c#.net v2.0
I am new to .net so it is taking a very long time to fit things together so thought of posting this question.
any comments, suggestions, advices and references would do good.
EDIT
I have attached the error what i got

Edit after first reply
A user can save as many as set of three fields.
I mentioned three fields for an example.
They will save as many as records as they want.
It could 100 to infinity.
Comment: SQLite works fine for me. I don't know why you're getting it from SourceForge: get it from the [System.Data.SQLite download page](http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki) at http://sqlite.org :) If you do settle on SQLite (it sounds like a prime candidate, although there are others) and still have problems, ask a *specific question* about those issues -- after searching, of course :)
Comment: If you want that error solved then better give some more details.
Comment: i could see versions like 3.5 or 4.0 but i am using 2.0 .net2005
Comment: Err... I don't use a VS package for SQLite. Is that an "extra"? All that's needed is the "System.Data.Sqlite.dll" and "sqlite3.dll" files -- just add a reference to the former in the project, and make sure the latter is in the load path. Then use ADO "like normal" :)
Answer: If that's only 3 fields to store - forget about databases and store the data in an XML file.
You can create a class that has these 3 properties, and then serialize/deserialize it on demand.
Here's a nice tutorial from Microsoft about XML serialization: http://support.microsoft.com/kb/815813
Deserialization is done in a very similar fashion.
Comment: A user can save as many as set of three fields.
I mentioned three fields for an example.
They will save as many as records as they want.
It could 100 to infinity.
Comment: and... i hate to use xml with .net because it is clustered so much with all the inheritances. I was thinking that xml would be so easy like in PHP. neither xml nor json in .net are as simple as PHP. I still wonder why it is so complicated to use xml in .net. i was hoping for a DOM traversal in .net
Comment: First - XML is really easy to use in .NET, just not the same way as in PHP. But it doesn't matter, with Xml Serialization you don't touch the XML itself, all is done for you. Instead, you manipulate objects. I suggest you read the link I've given you.


Interpretation of the p-values produced by Levene's or Bartlett's test for homogeneity of variances

Question: I have run Levene's and Bartlett's test on groups of data from one of my experiments to validate that I am not violating ANOVA's assumption of homogeneity of variances. I'd like to check with you guys that I'm not making any wrong assumptions, if you don't mind :D
The p-value returned by both of those tests is the probability that my data, if it were generated again using equal variances, would be the same. Thus, using those tests, to be able to say that I do not violate ANOVA's assumption of homogeneity of variances, I would only need a p-value that is higher than a chosen alpha level (say 0.05)?
E.g., with the data I am currently using, the Bartlett's test returns p=0.57, while the Levene's test (well they call it a Brown-Forsythe Levene-type test) gives a p=0.95. That means, no matter which test I use, I can say that the data I meet the assumption. Am I making any mistake?
Thanks.
Answer: The p-value of your significance test can be interpreted as the probability of observing the value of the relevant statistic as or more extreme than the value you actually observed, given that the null hypothesis is true.  (note that the p-value makes no reference to what values of the statistic are likely under the alternative hypothesis)
EDIT: in mathematical terminology, this can be written as:
$$p-value = Pr(T > T_{obs} | H_{0})$$
where $T$ is some function of the data (the "statistic") and $T_{obs}$ is the actual value of $T$ observed; $H_{0}$ denotes the conditions implied by the null hypothesis on the sampling distribution of $T$.
You can never be sure that you're assumptions hold true, only whether or not the data you observed is consistent with your assumptions.  A p-value gives a rough measure of this consistency.
A p-value does not give the probability that the same data will be observed, only the probability that the value of the statistic is as or more extreme to the value observed, given the null hypothesis.
Comment: Just one note on p-values (in relation to my bracketed comment), it could very well be that in the case that you have "unusual" data (say p-value of 0.0001).  BUT it may also be the case that it is *even more unusual* under the alternative hypothesis (say a p-value of $10^{-30}$ when you switch the null and alternative hypothesis around).  I believe this can happen when the statistic $T$ is not a sufficient statistic for the  hypothesis test.
Comment: ..continuing...It may also be the case that you have very "good" data (say p-value of 0.5).  BUT the alternative hypothesis may be *better* (or more consistent) with this data (say p-value of 0.99999 when the null and alternative hypothesis are switched around).
Answer: You're on "the right side of the p-value."  I'd just adjust your statement slightly to say that, IF the groups had equal variances in their populations, this result of p=0.95 indicates that random sampling using these n-sizes would produce variances this far apart or farther 95% of the time.  In other words, strictly speaking it's correct to phrase the result in terms of what it says about the null hypothersis, but not in terms of what it says about the future.
Comment: I remember the interpretation of the p-value as (in this case): when assuming that the null-hypotheses (i.e., homogeneity of variances) is correct, then the probability of obtaining this or a more extreme result (i.e., contrary the null) is 57% or 95%. But whatsoever, the conclusion is the same and correct.
Answer: While the previous comments are 100% correct, the plots produced for model objects in R provide a graphic summary of this question. Personally, i always find the plots much more useful than the p value, as one can transform the data afterward and spot the changes immediately in the plot.
Comment: Well said, another thing is that a p-value tells you nothing about *what to do* if the null hypothesis is "rejected", but a plot of the data gives you a clue as to the problem


How to output debugging information from intern functional tests?

Question: When I run a unit test using intern, it writes console.log to the standard output, which is useful when developing the tests.
However, functional tests apparently suppress output - writing to console.log does not do anything, and I can not find any way to output text to the console. Which means when something goes wrong, it is very difficult to find out why.
Answer: Where console.log outputs text depends on what environment the tests are running in. When you run intern-client, which only runs unit tests, the test code always runs in the Node.js environment and console.log writes to stdout in the terminal.
When you run intern-runner, unit tests run in the browser while functional tests run in Node.js. This means that console.log statements in the unit tests (those specified in the suites property of the intern config) will not print to stdout in the terminal, but instead will be output in the browser's console. Log statements in functional tests (those specified in functionalSuites) will be output to the terminal's stdout. The exception is log statements in execute or executeAsync blocks, which will be output to the browser's console since code in those blocks will actually be executed in the browser.


IQueryable for Subsonic Stored Procedure

Question: I need to use stored procedure to get data from DB, but I would also like to use IQueryable to add some filtering to results. I'm using subsonic and for now can't see a way to use subsonic sp and IQueryable. The only idea I have is to make a view that will perform all required joins. Then perform call to view like to table with subsonic:
MyView.All()

Subsonic All returns IQueryable and instead of adding where in sp I can add filter clauses in code. Not sure if this is viable solution or not?
Answer: IQueryable allows translating LINQ queries into SQL statements. Using IQueryable in conjunction with stored procedures is the same as mixing a SQL statement with a stored procedure, such as SELECT * FROM dbo.MyStoredProc WHERE x > 100. Since this won't work, mixing IQueryable with a stored procedure is useless, because there is no way to filter the results of the SP before they return.
What you are looking for is client-side (.NET side) filtering. For this you can simply use IEnumerable. When your stored procedure returns a collection of items, you can still use LINQ queries over that collection.
Comment: Steven, but what do you think about view and queries to them? No need to use stored procedure in this case. Joining is into view and filtering is done using IQueryable.
Comment: LINQ queries over database views are fine.
Answer: Ok, I`ve finished with this solution to add views to my SubSonic objects and IQueryable to add filtering.


Akka Actor Setup: In Main method or in 'Manager' class?

Question: Does anyone have any advice about how the creation of a large number of akka actors should be managed?
My new middleware project currently contains about 10 actors, but over time this will inevitably grow to a high number. I'm creating all my actors in my main function, but this could potentially get out of control as the system grows, with the function spanning an entire screen.
I could of course move all the actor creation into a function in a separate class, though this doesn't really solve the problem as such.
I'm not sure if there are any patterns available to help manage this setup procedure?
Answer: Normally one should have but a few top-level Actors (i.e. ones that are created by using system.actorOf). This is because you get a very poor fault-tolerance if all Actors are just as likely to ruin things for the others. So what you should do is to think about how you want failure to be contained in your application and then create actors as children of other actors using context.actorOf.
Comment: Does using context.actorOf directly make it difficult to mock these actors when writing unit tests? I've got a couple of unit tests where I use TestProbes to ensure messages are forwarded correctly. To facilitate this I have actorRef arguments in the constructor.
Answer: It really depends on the relationship of the actors. If they have no parent/child relationship to each other it doen't really matter where you start them. If they have such a relationship, you should start your actors inside their parents, because you have to use the context of the parent actor to create another actor as its child.
Answer: It is difficult to answer your question without knowing more about the nature of the actors you are creating. For example, if you can logically group your actors, I'd do something like this:
def initialize() = {

    // Initialize Misc actors
    val foo = FooActor()
    val bar = BarActor()

    initializeActorsThatDoStuff()
    initializeActorsThatDoOtherStuff()

}

If they have a parent/child relationship you should do as @drexin suggests.

Edit: Almost forgot: I you are creating multiple actors of the same type with different parameters, I'd of course use a loop and not copy and paste, e.g.
def initializeLotsOfActors(num:Int) =
    for(i <- 0 to num) new ActorThatTakesAnInt(i);

(because nobody likes copy and paste :D)
Comment: Note, that in Akka actors are not created with `new`.
Comment: Shame on me :) haven't really written Scala in some time.
Comment: My use case is described in general terms in this question:
http://stackoverflow.com/questions/11419335/managing-2-connections-in-scala-esque-fashion

I have actors which help to manage connections with a vendor API. I imagine I will also have a series of actors which will deal with individual message types received from the API, and pub/sub actors which relay information to different IT systems within our organisation.

Let me know if I still need to be a bit clearer with the context.


Why does text appear in the legend?

Question: library(ggplot2)
library(ggrepel)
set.seed(1234)
ss <- sample(1:32, 10)
df <- mtcars[ss, ]

ggplot(df, aes(wt, mpg))+ geom_point(col = "red") +
  geom_label_repel(aes(label = rownames(df), fill = factor(cyl)), size = 5,
                   hjust = 1,fontface = 3)

In the legend, why does 'a' appear alongside, 4,6,8?
Comment: Related: [Remove 'a' from legend when using aesthetics and geom_text](https://stackoverflow.com/questions/18337653/remove-a-from-legend-when-using-aesthetics-and-geom-text)
Comment: this may also be useful: https://stackoverflow.com/questions/49989158/how-to-have-a-removed-from-a-ggraph-plot-legend
Comment: @Henrik true. Of note though (even if that was not in the OP's question), the solutions offered there do not work to remove the `a` with `ggrepel` (they remove the legend altogether). @user20650's link might offer a way to remove it (works with `ggraph` but I did not test it with `ggrepel`)
Comment: @Henrik, this removes the legend altogether
Answer: a symbolizes the text added by geom_label_repel() and it matches the font, colour, etc. of your labels.
The picture below shows one of the demo examples of the ggrepel package shown in the package examples vignette:

You can see the same thing, but with different options passed as arguments to geom_label_repel().
If you actually want to remove the letter "a" from the legend you can redefine the legend key as shown here:
# save original legend key for later
oldK <- GeomLabelRepel$draw_key

# define new key without the text label
library(grid)
GeomLabelRepel$draw_key <- function (data, params, size) { draw_key_rect(data) }

# plot
ggplot(df, aes(wt, mpg))+ geom_point(col = "red") +
  geom_label_repel(aes(label = rownames(df), fill = factor(cyl)), size = 5,
                  fontface = 3)

# reset key
GeomLabelRepel$draw_key <- oldK

Comment: prosoitos : I hope its okay including the edit to your answer -- if not, please roll back
Comment: Fine by me. The OP was not asking how to remove those `a`, but I am sure that it will be useful, either to them or to others and thus makes for a better answer. Thank you for checking :)

Why does text appear in the legend?


How to get last emitted value of on Observable in the subscription when next is called after the subscription?

Question: How can I subscribe and log the last value when next is called after subscription ?
Here is the working demo stackblitz, how or is it possible to get value only the last value i.e.123 that is emitted after the subscription inside the subscribe method or any other alternative ? I used last() but it doesn't logs any value at all. I want the subscription to run only once and use the last value
    import { Component, Input, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { last } from 'rxjs/operators';

@Component({
  selector: 'hello',
  template: `

Hello {{ name }}!

  `
})
export class HelloComponent implements OnInit {
  @Input() name: string;
  subject = new BehaviorSubject<any>({});

  ngOnInit() {
    this.subject.next(456);

    this.getData()
      // .pipe(last())
      .subscribe(console.log);

      // this next is being done in another component after subscription so putting it here to mimic the behavior
     this.subject.next(123);

  }

  getData(): Observable<any> {
    return this.subject.asObservable();
  }
}

Comment: @MrkSef no `take(1)` logs only the initial value https://stackblitz.com/edit/angular-ivy-n25kys?file=src%2Fapp%2Fhello.component.ts
Comment: your example already logs `123`, it is not clear what you're trying to achieve here.
Comment: Sorry about that edit my question, I want to print only `123` subscribe to only last emitted value, thats why I am trying  to use `last()`
Comment: If I understand you properly, `take(1)` should do it
Answer: You cannot use last() as the subject does not currently complete. You need to call complete() on the subject to be able to use it:
ngOnInit() {
  this.subject.next(456);

  this.getData()
    .pipe(last())
    .subscribe(console.log);

  this.subject.next(123);
  this.subject.complete();
}

Your StackBlitz


Relationship between chi-squared and the normal distribution

Question: I am trying to understand the logic and application of the $\chi^2$ distribution. As far as I understand it,  if we take a random variable $X$, which is normally distributed, then the random variable $X^2$ follows a $\chi^2$ distribution. So my intuitive understanding of the $\chi^2$ distribution is that it shows the probability of drawing some $X$ from a normal distribution, given $K$ trials. From the above understanding, it follows that the $\chi^2$ test is only applicable, if the random variable is normally distributed.
However my textbook and various other examples use the distribution to estimate the probability of the random variable, $X$, from other distributions, with the most common example being to test whether a die is loaded. The values obtained by rolling a die, however would follow a uniform distribution (given that the die is fair).
Can someone please explain why using the $\chi^2$ test is this context is still valid, even though the data is not normally distributed.
Answer: Suppose we have a die that we think might not be fair.
We roll it 600 times and get the following table.
Face   1   2   3   4   5   6
Freq  44  97 102  99 105 153

So we have observed frequencies $X: 44,\, 97,\, 102,\, 99,\ 105,\ 153$ for
the respective faces. If the die is fair, we'd  expect frequency
$E = 100$ for each face.
If the die is fair, then the statistic
$$Q - \sum_{i = 1}^6 \frac{(X_i - E)^2}{E} \stackrel{aprx}{\sim}
\mathsf{Chisq}(\text{DF} = 5).$$
Very roughly, the rationale for the approximate chi-squared distribution
is that we could look at the $X_i$ as being Poisson events each with mean
$\mu = \lambda = 100$ and variance $\sigma^2= \lambda = 100.$
Standarizing,
we have $Z_i = \frac{X_i - \mu}{\sigma} \stackrel{aprx}{\sim} \mathsf{Norm}(0,1).$ If the $Z_i$ were independent, then $Q = \sum_{i=1}^6 Z_i^2$ would be approximately chi-squared with $6$ degrees of freedom.
But the
$Z_i$ aren't independent because the $X_i$ are constrained to add to $600$ rolls of the die. With some hand-waving we 'correct' for this by reducing
the degrees of freedom for $Q$ from $6$ to $5.$ The language of the hand-waving is that we have 'lost' a degree of freedom due to a linear constraint.
[Hand-waving aside, many simulation experiments have shown that, for a fair die, such values $Q$ are very nearly distributed as chi-squared with 5 degrees of freedom, provided that $E > 5.$ Because our $E = 100$ the approximation is quite good. One such simulation is shown in the Addendum.]
For the data above, one can show that $Q = 59.84.$ However, if we actually have
$Q \sim \mathsf{Chisq}(5),$ then this observed value of $Q$ seems very unlikely, because only 5% of values from $\mathsf{Chisq}(5)$ should
exceed the critical value $c =11.07.$ Put another way the probability
that a value from this distribution exceeds $59.84$ is the P-value of
the chi-squared test, which is much smaller than $0.0001.$
x = c(44, 97, 102, 99, 105, 153)
q = sum((x-100)^2/1  0 0); q
[1] 59.84

qchisq(.95, 5)
[1] 11.0705          # critical value
1-pchisq(59.84, 5)
[1] 1.311595e-11     # P-value

The conclusion is that the data provide strong evidence that our die
is unfair. [In fact, the values $X_i$ were simulated using
probabilities $(\frac 1{12}, \frac 1 6, \frac 1 6, \frac 1 6,\frac 1 6,\frac 1 4),$ respectively, for
the faces, instead of $\frac 1 6$ for each face, as for a truly fair die.
So the chi-squared test has been able to detect that the die is unfair.]

Addendum: Shown below is a simulation of 100,000 values of $Q,$ each based on $600$ rolls of a fair die.
Their histogram is plotted along with the density of
$\mathsf{Chisq}(5)$ in order to illustrate that is the the approximate
distribution of such values of $Q.$
By way of explaining the code, one experiment with $600$ rolls of a
fair die is simulated and tallied using rle in the first three lines below.
set.seed(413)
rle(sort(sample(1:6, 600, rep=T)))$len
[1]  83 103 114  96 106  98

set.seed(2019);  E = 100
q = replicate(10^5,
      sum((rle(sort(sample(1:6,600,rep=T)))$len - E)^2/E))
hdr = "Simulated Values of Q with Density of CHISQ(5)"
hist(q, prob=T, br=30, col="skyblue2", main=hdr)
  curve(dchisq(x, 5), add=T, lwd=2, col="red")

Answer: Let $X_1,\ldots,X_k$ be independent standard normal random variables.
("Standard normal" means normal with expectation $0$ and variance $1.$)
Then $X_1^2 + \cdots + X_k^2$ has a chi-square distribution with $k$ degrees of freedom.


Mysql UPDATE com JOIN e WHERE

Question: Minhas tabelas
EMPREGADO   Cod_Emp, Nome_Emp
COMPANHIA   Cod_Comp, Nome_Comp
TRABALHA    Cod_Emp, Cod_Comp, Salário, Cod_Emp_Supervisor

Quero dar um aumento de 10% a todos os supervisores da empresa 'teste'.
UPDATE trabalha
INNER JOIN companhia ON trabalha.Cod_Comp = companhia.Cod_Comp AND companhia.Nome_comp = 'teste'
SET salario = salario + (salario*0.10)
WHERE Cod_Emp IN (SELECT Cod_Emp_Supervisor FROM trabalha)

Answer:
UPDATE
    TRABALHA T
INNER JOIN
    COMPANHIA C ON
    (
        C.Cod_Comp = T.Cod_Comp
        AND
        C.Nome_comp = 'Teste'
        AND
        T.Cod_Emp = T.Cod_Emp_Supervisor
    )
SET
    T.Salario = T.Salario + (T.Salario * 0.10)

Pelo que entendi a coluna Cod_Emp_Supervisor na tabela TRABALHA indica quem é o supervisor de cada funcionário dentro da COMPANHIA.
Como não conheço a base ou o sistema que da carga na mesma. Imagino que o campo Cod_Emp_Supervisor será preenchido com o próprio código do supervisor. Ou caso não seja preenchido fique nulo, basta substituir a cláusula T.Cod_Emp = T.Cod_Emp_Supervisor para  T.Cod_Emp_Supervisor IS NULL.
Comment: Fiz desse jeito, mas não é bem o que eu queria. Eu estava tentando verificar com o *WHERE* os **Cod_Emp** com os **Cod_Emp_Supervisor**, assim eu saberia que aquele funcionário é um supervisor. E depois verificar as a empresa que ele trabalha com o *JOIN*.
Comment: @vdschuck Na tabela TRABALHA o empregado do tipo supervisor o campo Cod_Emp_Supervisor fica nulo ou com o mesmo código do campo Cod_Emp?
Comment: Por isso coloquei no JOIN a cláusula _T.Cod_Emp = T.Cod_Emp_Supervisor_ para obter somente os supervisores.

Mysql UPDATE com JOIN e WHERE


respond_to :json behaving very oddly

Question: I have a Controller:
class ThingController < ActionController
  respond_to :json

  def create
    puts "CREATE " + params.inspect
  end
end

and a test:
require "spec_helper"

describe "/thing" do
  context "create" do
    it "should get params" do
      params = {"a" => "b", "c" => ["d"], "e" => [], "f"=>"",
                "g"=>nil, , "controller" => "NOPE", "action" => "NOPE"}
      post uri, params
    end
  end
end

When I run this, the following is logged:
CREATE {"a"=>"b", "c"=>["d"], "action"=>"create", "controller"=>"thing"}

My questions are:

where did e go? I would expect it to deserialize to an empty array, not to nothing at all.
why are the action and controller params being mixed into this? Aren't the body and the rails internals completely separate concerns?
Because of this, my action and controller JSON fields were over-written. How would I access these?
Is this therefore not the right way to accept JSON?

I'm new to Rails, but I have done a lot of Django.
Answer: The rails middleware will add the action and controller params so you'll have to put those in a nested hash if you still want to access your custom values.
Try adding format: 'json' to the params in your test. This will send a different content-type header and might help serialize the params correctly in order to keep the e param.
Answer: There are two parts to this problem: you need to ensure that your parameters are being sent as JSON, and also that they are being interpreted as JSON.
Essentially, you have to

encode your parameters as JSON
set appropriate content-type and accepts headers

See POSTing raw JSON data with Rails 3.2.11 and RSpec for the way.
Comment: Great, thanks. I was following an example which must be slightly broken.

respond_to :json behaving very oddly


Where can I download english to chinese dictionary database?

Question: Where can I download english to chinese dictionary database?
Comment: if you do not have to do it offline. You may try Google translate API https://developers.google.com/translate/v2/libraries It's paid service AFAIK.
Answer: The CEDict is a sizeable Chinese-English dictionary database... depending on what you are doing, it might be enough to use it in reverse.
Answer: Just google it... , here is one http://www.mdbg.net/chindict/chindict.php?page=cedict
another one : http://hua.umf.maine.edu/China/database.html


Xpath - unable to find attribute

Question: I am trying to access the Language attribute in the following xml using Xpath. I get an empty string. Can anyone tell me why?
<?xml version="1.0" encoding="UTF-8"?> <soa:Request xmlns:soa=\"http://www.site.coom/soa\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <BookingPriceRequest Client=\"5000000\" SiteID=\"500\" Currency=\"AAA\" Language=\"ar\"> <BookingItems> </BookingItems> </BookingPriceRequest> </soa:Request>

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(requestXml)));
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
String language = (String) xpath.compile("//Request/BookingPriceRequest/@Language").evaluate(doc, XPathConstants.STRING);

Comment: The `Request` element has a namespace. `Request` is not the same as `soa:Request`. You even set `NamespaceAware` to "true", but the ignore the namespace.
Comment: possible duplicate of [Parsing xml that has different namespaces using XPath in JAVA](http://stackoverflow.com/questions/14392200/parsing-xml-that-has-different-namespaces-using-xpath-in-java)
Comment: See also: http://stackoverflow.com/questions/23203421/javax-xml-xpath-is-not-extracted-from-xml-with-namespaces
Answer: Try using the namespace for Request as well:
//soa:Request/BookingPriceRequest/@Language

Answer: "The Request element has a namespace. Request is not the same as soa:Request. You even set NamespaceAware to "true", but the ignore the namespace" this worked.
Answered by Mathias Müller.

Xpath - unable to find attribute


Cannot get string param in POST method from jQuery

Question: I have POST method like this
    public void PostMethod([FromBody]string param)
    {
        var test = param;
    }

And simple JS script

Ot work great. Ajax call is invoking the method BUT the param is null :/ always. I don`t know why. I can't get it running. Can someone pls help me and show me the correct direction ?
// update
too check something i`ve created new project to be sure that i didn't break something. Even in new project in default config I always get null
Answer: Because param is a simple type, so to make it work for simple type, you just:

If you still want to make POST request like yours, define you own strong type model:
class YourModel
{
    public string Param {get; set;}
}

So your action:
public void PostMethod(YourModel param)
{
    var test = param;
}

Or use JObject:
public void PostMethod(JObject param)
{
    var test = param;
}

More information:
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1
Comment: Thank you for help. I'm testing in on simple type. What if I want to use a more complex type. What do I need to change ? The second thing I'll be trying to achive is sending this from C# not with JS
Comment: ok last question. Do you know some good samples of sending same post request but with c# ?
Comment: @Fixus: You should ask another question instead of using comment, anyway you can use HttpClient for this, lot of questions on stackoverflow. For sample: http://blogs.msdn.com/b/webdev/archive/2012/08/26/asp-net-web-api-and-httpclient-samples.aspx