What are all possiblities for Galois group $G(L(\sqrt[5]{3})/L)$?

Question: If $L$ is a subfield of $\mathbb C$ (which implies it has characteristic 0 and $\mathbb Q$ as its prime subfield) , what can Galois group $G(L(\sqrt[5]{3})/L)$ be? I start to solve this problem by considering $\sqrt[5]{3}$ in $\mathbb C$. The polynomial of $\sqrt[5]{3}$ is $$f(x)=x^5-3$$ and all its roots are $\sqrt[5]{3}$,$\sqrt[5]{3} \zeta_5$,$\sqrt[5]{3} \zeta_5^2$,$\sqrt[5]{3} \zeta_5^3$, $\sqrt[5]{3} \zeta_5^4$. Then I think there are 2 cases for L, which are
(1) $L$ does not contain $\zeta_5$. Then the Galois group is trivial since $\sqrt[5]{3}$ can only be sent to itself.
(2) $L$ does not contain $\zeta_5$. This is the part where I get confused. Since $G(L(\sqrt[5]{3})/L)$? fixes $\zeta_5$, there will still be only one automorphism. Then in conclusion $G(L(\sqrt[5]{3})/L)$ can only be trivial.
Am I right about this? I feel that this problem is not that easy and there should be more case for $L$.
Comment: Just because in part (2) it fixes $\zeta_5$ doesn't mean it can't send $\sqrt[5]{3} \mapsto \sqrt[5]{3}\zeta_5$.
Answer: Firstly, you need to define what you mean by $\sqrt[5]{3}\in\mathbb{C}$. I will assume that $\sqrt[5]{3}$ is the unique real 5th root of 3 in $\mathbb{C}$. Let $S$ be a transcendence basis of $L$ over $\mathbb{Q}$, and let $K := \mathbb{Q}(S)$. Let $K'$ be the splitting field of $x^5-3$ over $K$. Then $K'/K$ is Galois with Galois group the semididirect product $C_5\rtimes C_4$, and $L(\sqrt[5]{3})$ is a subfield of the compositum $LK'$. Your job is to classify the intermediate extensions of $LK'/L$ of the form $L(\sqrt[5]{3})$. By the "Diamond theorem", there is a bijection between intermediate extensions of $LK'/L$ and those of $K'/K'\cap L$, obtained by "intersecting with $K'$". Thus, in terms of Galois theory, $L\cap K'$ (and hence $L$) corresponds to a subgroup $H_1$ of $C_5\rtimes C_4$, and $L(\sqrt[5]{3})\cap K'$ (and hence $L(\sqrt[5]{3})$) corresponds to a subgroup $H_2\le H_1$ of index at most 5 inside $H_1$. Note that $[L(\sqrt[5]{3}):L] = [H_1:H_2]\le 5$, but does not have to divide 5. I believe the following is a complete classification, but I'll let you work out the details and check to see if there are any cases I missed.

If $L$ contains $\zeta_5$, then $H_1$ is contained in the unique cyclic normal subgroup $C_5\lhd C_5\rtimes C_4$ (which is the Sylow-5 subgroup of $C_5\rtimes C_4$), and $H_2 = 1$. If $L$ doesn't contain any 5th roots of 3, then $H_1 = C_5\lhd C_5\rtimes C_4$, and so the the extension is Galois with group isomorphic to the cyclic group $C_5$ of order 5, generated by the automorphism sending $\sqrt[5]{3}\mapsto \zeta_5\sqrt[5]{3}$.
If $L$ contains $\zeta_5$, and contains a 5th root of 3, then it must contain all 5th roots of 3, so it contains $\sqrt[5]{3}$ and the Galois group is trivial (the extension is trivial). This corresponds to the case where $H_1 = H_2 = 1$.
If $L$ doesn't contain $\zeta_5$, and doesn't contain any 5th roots of 3, then the extension is of degree 5, but not Galois. This corresponds to the case $H_1 = C_5\rtimes C_4$ or an index 2 subgroup of $C_5\rtimes C_4$.
If $L$ doesn't contain $\zeta_5$ or $\zeta_5+\zeta_5^{-1}$, and contains a 5th root of 3, but doesn't contain $\sqrt[5]{3}$, then the extension is of degree 4 and we have $L(\sqrt[5]{3})\cong L(\zeta_5)$, which is Galois over $L$ with cyclic Galois group isomorphic to $(\mathbb{Z}/5\mathbb{Z})^\times\cong C_4$. This corresponds to the case where $H_1$ is precisely the Sylow-4 subgroup of $C_5\rtimes C_4$.
If $L$ doesn't contain $\zeta_5$, but does contain $\zeta_5+\zeta_5^{-1}$ and contains a 5th root of 3 but not $\sqrt[5]{3}$, then the extension is quadratic and is isomorphic to $L(\zeta_5+\zeta_5^{-1})$. This corresponds to the case where $H_1$ is the unique nontrivial proper subgroup of the Sylow 4-subgroup.
If $L$ doesn't contain $\zeta_5$ and contains $\sqrt[5]{3}$, then the extension is trivial.
Comment: Very clear picture! Thanks a lot!.
Comment: @RSBST I was actually wrong. I've edited the answer and now I believe it's correct.
Comment: Thanks! I have only one question. How do you come up with step 4,5,6. It is clear after you wrote it down but how can one come up with these in a systematic approach?
Comment: @RSBST Well I didn't do it systematically. I just thought about it, which is why there may be errors! However, I've added a bit in the first paragraph to help you see how you could do this systematically.
Comment: @RSBST Added some additional points
Comment: Thanks so much! I have read your answer closely and it really helps me.
Comment: @RSBST Had a mistake, corrected it, now I think it's pretty final, though there are still details to work out which I will leave to you. Have fun!


Can't get to Dell OMSA webpage on my server

Question: I'm running CentOS 6.3 x64 on a Dell PowerEdge R520. I have run the following two commands as per This Wiki
sudo wget -q -O - http://linux.dell.com/repo/hardware/latest/bootstrap.cgi | bash
sudo yum install srvadmin-all

All the related services appear to be running. But, when I try to access
http://myserver:1311

the page doesn't resolve.
When I try to access the webpage from the physical server, I am presented with a page that has 4 boxes and a question mark.
Any Help Is Much Appreciated.
EDIT: Apparently I suck a QA-ing.
The problem was what when I tried to access the OMSA webpage for my server from another machine, the page would be "unable to load". But, if I open a web browser while I'm at the server that I have OMSA installed on, then I am presented with a page containing four boxes and a question mark. Turns out that I just didn't have the appropriate ports open. My apologies to you all for not being clear and thank you all for your help.
Comment: Fixed the description
Comment: You might want to spell out exactly what "doesnt resolve" mean. Do you mean the hostname or is there a 404 or connection refused? You might also want to explain what "physical server" means. Is there some virtualisation invoved, do you mean different server or what?
Answer: It sounds like you need to open port 1311 in your firewall. (You may also want to restrict it to specific IP address ranges or other criteria, but this should get you going.)
Comment: That did it! I had to explicitly allow port 1311 and http and https. Thanks for the help!
Answer: That link is an https link by default. Have you tried using https:// instead of http://? Also, do you have an iptables rule that would block an inbound connection on port 1311?
Comment: Accessing the page at https:// also does not yield anything. I do not have an iptables block for port 1311.
Comment: My only reject line reads:
REJECT    all  --  0.0.0.0/0        0.0.0.0/0        reject-with icmp-host-prohibited
Comment: That is going to drop all traffic...
Answer: If you just installed omsa, be sure the service is started
On my CentOS 6 box, the script to call is:
/opt/dell/srvadmin/sbin/srvadmin-services.sh start


If $X \sim a\chi_1^2$, and $Y \sim b\chi_1^2$, what's the distribution of $Z = X/Y$?

Question: Assume that $X$ and $Y$ are independent. $Z = \frac{X}{Y}$ a ratio of independent $\chi^2$ random variables with 1 degree of freedom. If $X \sim a\chi_1^2$, and $Y \sim b\chi_1^2$, what's the distribution of $Z = X/Y$? Is it a $\frac{a}{b}F_{1,1}$ distribution? Note that $a, b$ are real number constants.
Comment: Seems to be a duplicate (with extension) of: https://stats.stackexchange.com/questions/140876/distribution-of-ratio-of-2-chi-squared
Comment: @compbiostats They're similar questions but I don't think it can be a duplicate if it's an extension of another question. Or can it?
Answer: Yes, exactly. $Z$ is $a/b$ times a random variable following an $F_{1,1}$ distribution or, in other words,
$$ \frac{b}{a} Z \sim F_{1,1}.$$
This follows immediately from the characterization of the $F$ distribution as the distribution of the ratio of two independent chisquare random variables, each divided by their degrees of freedom.
Also note that $$\frac{b}{a} Z = T^2$$ where $T\sim t_1$ or $T\sim$ Cauchy(0,1).
Answer: You have two random variables, which are equivalent to Gamma random variables
$$X\sim a\chi^{2}_{1}\equiv\text{Gamma}(1/2,2a)$$
and
$$Y\sim b\chi^{2}_{1}\equiv\text{Gamma}(1/2,2b)$$
Then we define
$$Z=\frac{X}{Y}\sim B'\Big(\tfrac{1}{2},\tfrac{1}{2},1,\tfrac{b}{a}\Big)$$
where $B'()$ denotes the generalized beta prime distribution.


Defining path to executable for a custom control

Question: I have created a custom control using VB.NET in Visual Studio 2008 that gives extensive mapping and tracking functionality to a search and rescue app.  The problem I am having is that in a number of places I need to define the path to the main applications executable in order to find a number of directories the control needs to function properly.  Everything works fine when I am using it in VS but when I try to embed the control in a form in a separate solution I get the following error:

Failed to create component
  'MainControl'.  The error message
  follows:
  'System.IO.DirectoryNotFoundException:
  Could not find a part of the path
  'C:\Program Files\Microsoft\Visual
  Studio
  9.0\Common\IDE\GIS\Data\Default...

This seems to indicate that it is looking for the \GIS\Data\Default directory in the Visual Studio program path but I have used Application.StartupPath to define this location throughout the control.
This error only occurs when attempting to embed the control in a form outside of the controls solution.  The solution I have created to develop this control has two projects (one for the control and one for a test form to do the debuging)
Can anyone provide me with some guidance on this?
Answer: This will happen when your control executes code while it is being used in the designer.  It does, stuff like the constructor, Load event, Paint event, etcetera will run when you drop the control on a form in Visual Studio.
You need to use the DesignMode property to prevent this code from running, and crashing, when the current working directory is wrong.  It will be wrong in the designer, the working directory is Visual Studio's, not the app's in which it will eventually be used.  Or use absolute paths, not relative paths.
If that doesn't help, how to debug design time problems is explained here.
Comment: Thanks Hans that did the trick.  It's kinda funny, I've been developing in VB.NET for about three years now and this is the first time I have come across this issue.  Anyway, your solution was the right one.


What regression model to use for a binary predictor and continuous outcome

Question: I have a binary variable, $X=\{0,1\}$ and I want to use this variable to predict a continuous outcome variable $y$
What regression model ought I use to estimate the predictive ability of $X$ of $y$?
I know that switching them the other way around, would allow me to use a logistic regression model but that doesn't seem applicable in this scenario.
What statistic would I use to assess the significance of this relationship?
How can I do this in R?
Comment: One could look at this as two completely separate questions.  (1) When $X=0$, how would you predict $y$? (2) When $X=1$, how would you predict $y$?  If you have a dataset of $(X,y)$ pairs, these two questions deal with disjoint subsets of the dataset--in effect, two different datasets. In each dataset $X$ does not vary.  Thus each is the same question and that common question boils down to "I have a set of $y$ values. How do I predict them?"  That is a standard, simple *univariate* problem--and it has many more solutions than those offered by regression models.
Comment: Just to clarify, you're looking to predict a function from (0,1) to, say, R (the reals). In other words, 0 maps to a, and 1 to b (where a and be are from the reals)?
Answer: No problem, you can try plain vanilla OLS.
A toy example in R:
<code>> set.seed(1235321)
> x <- c(rep(1,50), rep(0,50))
> epsilon <- rnorm(100)
> y <- 1 + 3 * x + epsilon
> coef(lm(y ~ x))
(Intercept)           x
   1.069068    2.987035
</code>
Of course, you'll get poor results if your "error" contains relevant omitted variables. E.g.:
<code>> z <- runif(100, 2, 6)
> y <- 1 + 0.5 * x + 3 * z + epsilon  # y depends on x _and_ z
> coef(lm(y ~ x))                     # you omit z
(Intercept)           x
  12.317986    1.201527
</code>
This should be your main concern.
Comment: Excellent analysis.  I would simply add that this assumes the distribution for the random variable is bimodal about two different means and the same variance about each.  Suppose not only the mean value, but also the variance (or the shape of the distribution) changed based on x.  Then I think you would have to model both populations separately as whuber suggests above, and the impact of x may not be measured with a single number.


Combine Multiple Content Types and View

Question: I have need to create a page with following information.
Personal Information,
Address and
Contract Information.
One Personal Information will have multiple address and multiple Contract information. I am thinking of creating three content types. The personal information page will have add address and add contract buttons which will popup the respective content type. When the address or contract popup is closed then control is passed to the Personal Information page, here I should be able to view the contact and address information just added in tabular format. I thought it may be a view.
My question is, Is it possible to achieve this kind of work in Drupal 7? If yes how can I do it. It will be nice to have some information so that I can look into the right direction. Some example sites would be help full.
Thanks
Answer: Instead of creating new content types. You can create fields and use FieldCollection module to group as many field as you like.
and show (Display) it using FieldCollection Views module.
Find demo here,
FieldCollection Demo
FieldCollection Views  Demo
Comment: Thanks for the information. I am looking at the demo and will try. If I have some additional problems then I will just put it here
Comment: I just view the presentation. My basic requirement is like this. I have the content type Personal Information. This page should also have a view of the Location content type as show in the demo in the same place where I enter the personal information content, not while viewing personal information.

Combine Multiple Content Types and View


showing an integral diverges

Question: I am working on the following problem:

Edit: So after thinking a little bit more about the problem, here is my (hopefully correct) solution. If there is an error, I would appreciate if someone could point it out.
Suppose that $\int_a^b f(x)g(x) \,dx $ exists. From the boundedness of $f$, we have $\rho\int_a^b g(x) \,dx \leq \int_a^bf(x)g(x)\,dx $.
By Cauchy's Criterion, $\exists r \in (a,b)$ such that $x_1,x_2 \in (r,b) \implies |\int_{x_1}^{x_2} f(x)g(x) \,dx| < \epsilon$.
Now assume $g > 0$ (otherwise consider $-g$). Then $ \rho M \leq\rho\int_{x_1}^{x_2} g(x) \,dx \leq\int_{x_1}^{x_2} f(x)g(x) \,dx =|\int_{x_1}^{x_2} f(x)g(x) \,dx|   < \epsilon$
Or more simply, $\rho M \leq \int_{x_1}^{x_2} f(x)g(x) \,dx < \epsilon$. However epsilon is arbitrary, $\implies$ $\rho M \leq 0$, a contradiction. Thus $\int_a^b f(x)g(x) \,dx$ diverges.
Comment: Note that the inclusion of border points in integration boundaries is optional, i.e.
$$\int_{[a,b]} = \int_{(a,b)}$$
Comment: I have made an attempt at a solution, any feedback would be appreciated.
Comment: @Glorfindel: Maybe go a little easy on the editing. In the past couple of hours, you've bumped almost three dozen years-old questions to the top of the queue. There's already so much current traffic on Math.SE that it's best to limit the influx of old stuff. (See, for instance, [this recent meta post](https://math.meta.stackexchange.com/q/29414/409) in the wake of rampant re-tagging of sangaku questions.)
Comment: @Blue heh, thanks for the warning. It's an automated script; I kept an eye on the front page but didn't notice any relevant activity there. Somehow the caching is off, I guess.
Comment: It's good that the process is automated; fixing all those image links by hand would be tedious. :)  Even so, there are over a dozen of your recent edits on the Top Questions/Interesting queue; your eye may not be noticing them, but mine certainly is. :) I see in your Revisions list that another couple-dozen edits were made 12 hours ago. Before then, maybe a dozen or so, then I got bored of counting. You might want to tweak your script to max-out at, say, five edits at a time.
Answer: Using the definition of an integral will also work here. Note that you can choose an infinite sequence of pairs $(a_1,b_1),(a_2,b_2) \ldots$ such that $a < a_1 < b_1 < a_2 < b_2 \ldots$ and all pairs are less than $b$, such that $|\int_{a_j}^{b_j} g(x) dx| \geq M$.  Then in the limit as $j \to \infty$, you will eventually have $|\int_{a_j}^{b_j} f(x)g(x) dx| > M \rho / 2$ since $f$ is continuous. Since $M \rho / 2$ is a fixed constant, this is enough to show the integral diverges.

showing an integral diverges


ASP Core Azure Active Directory - Get First and Last Name

Question: I created an Azure Active Directory Application and applied the code from the following tutorial to enable login: https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/
After login the following returns my email adress:
Console.WriteLine(User.Identity.Name)

How would i retreive the First and Last Name of this user?
Comment: OpenId scope returns first name and last name claims in token. Should be able to extract from claims principal after authN
Comment: Have you tried using Graph API?
Answer: Found it:
var fn = User.FindFirst(ClaimTypes.GivenName).Value;
var ln = User.FindFirst(ClaimTypes.Surname).Value;
System.Console.WriteLine("me :" + fn + " " + ln );

Answer: I use this, this gets you the first and last name together -
var name = claims.FirstOrDefault(c => c.Type == "name")?.Value;


If S is a set of reals such that between any two distinct elements of the set there is another element of the set, is S dense?

Question: Let S be a set of reals
such that
between any two distinct elements of the set
there is another element of the set.
Is S dense between its min amd max?
I outlined a proof that
this is true if
there is a real number $0 < r \le 1/2$ such that between any two distinct elements of the set a and b there is a third element c such that
$r \le |(c-a)/(b-a)| \le 1-r$
in my answer to this question:
How to prove that every real number is the limit of a convergent sequence of rational numbers?
The proof essentially involves repeated bisection, with the condition involving r ensuring that this converges.
Without the condition involving $r$
(or some condition like it),
this might be false.
I envision starting with the set
${0} \cup \{\frac1{n}| n \in \mathbb{N^+}\}$
and iterating it $\aleph_0$ times,
with the clumping at the left
being more pronounced
at each iteration.
I don't know if this is possible,
or if the set is dense.
Comment: Instead of min and max, you certainly mean inf and sup
Answer: No.  $(0,1) \cup (2,3)$ is a counterexample.  With the condition on $r$ it is true.  Given any $r$ in your range you can find $a$ just below $1$ and $b$ just above $2$ so that your condition on $r$ cannot be satisfied with this set.
Comment: Nice counterexample. I was looking for a set of individual points not intervals.
Comment: You can replace the intervals with dense sets as long as you don't have both endpoints of the empty interval.  For example you could just have the rationals in each interval and add in $1$ or $2$ but not both.  I think this is the structure of all the dense subsets of the reals-sets which are locally dense with gaps in between, but am not sure.


How to create a Hyper-V VM with Powershell DSC and module xHyper-V?

Question: I've been trying to create a VM on my Hyper-V 2016 host from my Windows 10 workstation using module xHyper-V with not a lot of joy.
My Hyper-V host is called Lithium and my DSC Script is below.
Configuration EndToEndXHyperV_RunningVM
{
    param
    (
        [string[]]$NodeName = 'lithium',

        [Parameter(Mandatory)]
        [string]$VMName,

        [Parameter(Mandatory)]
        [string]$StartupMemory,

        [Parameter(Mandatory)]
        [string]$MinimumMemory,

        [Parameter(Mandatory)]
        [string]$MaximumMemory,

        [Parameter(Mandatory)]
        [String]$SwitchName,

        [Parameter(Mandatory)]
        [Uint32]$ProcessorCount,

        [ValidateSet('Off','Paused','Running')]
        [String]$State = 'Off',

        [Switch]$WaitForIP
    )

    Import-DscResource –ModuleName 'PSDesiredStateConfiguration'
    Import-DscResource -module xHyper-V

    Node $NodeName
    {
        $NewSystemVHDPath = "\\lithium\VHDs-SSD\$($VMName)-System.vhdx"

        # Copy VHD File - hard coded to Windows 2016 Core Eval for now
        File SystemDisk {
            SourcePath = "\\lithium\Templates\Windows 2016 Core Template\System.vhdx"
            DestinationPath = $NewSystemVHDPath
            Type = "File"
            Ensure = "Present"
        }

        # create the generation 2 testVM out of the vhd.
        xVMHyperV NewVM
        {
            Ensure          = 'Present'
            Name            = $VMName
            VhdPath         = $NewSystemVHDPath
            SwitchName      = $SwitchName
            State           = $State
            Path            = $Path
            Generation      = 2
            StartupMemory   = $StartupMemory
            MinimumMemory   = $MinimumMemory
            MaximumMemory   = $MaximumMemory
            ProcessorCount  = $ProcessorCount
            RestartIfNeeded = $true
            WaitForIP       = $WaitForIP
            DependsOn       = "[File]SystemDisk"
        }
    }
}

I have granted the Machine account access to the shares and the file copy works fine, but I get an error adding the virtual hard disk. Any ideas?
PS C:\Repos\Infrastructure\DSC> Start-DscConfiguration -Path .\EndToEndXHyperV_RunningVM -Wait -Verbose -Force
VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namesp
aceName' = root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: An LCM method call arrived from computer COWSLIP with user sid S-1-5-21-1075642099-280362434-2919291742-1105.
VERBOSE: [LITHIUM]: LCM:  [ Start  Set      ]
VERBOSE: [LITHIUM]: LCM:  [ Start  Resource ]  [[File]SystemDisk]
VERBOSE: [LITHIUM]: LCM:  [ Start  Test     ]  [[File]SystemDisk]
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] The system cannot find the file specified.
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] The related file/directory is: \\lithium\VHDs-SSD\test-System.vhdx.
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] Building file list from cache.
VERBOSE: [LITHIUM]: LCM:  [ End    Test     ]  [[File]SystemDisk]  in 0.0510 seconds.
VERBOSE: [LITHIUM]: LCM:  [ Start  Set      ]  [[File]SystemDisk]
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] The system cannot find the file specified.
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] The related file/directory is: \\lithium\VHDs-SSD\test-System.vhdx.
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] Building file list from cache.
VERBOSE: [LITHIUM]:                            [[File]SystemDisk] Copying file \\lithium\Templates\Windows 2016 Core Template\System.vhdx to \\lithium\VHDs-SSD\test-Sy
stem.vhdx.
VERBOSE: [LITHIUM]: LCM:  [ End    Set      ]  [[File]SystemDisk]  in 17.2540 seconds.
VERBOSE: [LITHIUM]: LCM:  [ End    Resource ]  [[File]SystemDisk]
VERBOSE: [LITHIUM]: LCM:  [ Start  Resource ]  [[xVMHyperV]NewVM]
VERBOSE: [LITHIUM]: LCM:  [ Start  Test     ]  [[xVMHyperV]NewVM]
VERBOSE: [LITHIUM]: LCM:  [ End    Test     ]  [[xVMHyperV]NewVM]  in 1.0200 seconds.
VERBOSE: [LITHIUM]: LCM:  [ Start  Set      ]  [[xVMHyperV]NewVM]
VERBOSE: [LITHIUM]:                            [[xVMHyperV]NewVM] Checking if VM 'test' exists ...
VERBOSE: [LITHIUM]:                            [[xVMHyperV]NewVM] VM 'test' does not exist.
VERBOSE: [LITHIUM]:                            [[xVMHyperV]NewVM] Creating VM 'test' ...
Failed to add device 'Virtual Hard Disk'.
The Machine Account 'DUCK\LITHIUM$' or the user initiating the VM management operation or both do not have the required access to the file share
'\\lithium\VHDs-SSD\test-System.vhdx'.  Please ensure that the computer machine account and the user initiating the VM management operation have full access to the
file share as well as the file system folder backing the file share.  Error: 'General access denied error'
'test' failed to add device 'Virtual Hard Disk'. (Virtual machine ID 4DE01C38-E027-4366-B56A-85B527BB34CB)
'test': The Machine Account 'DUCK\LITHIUM$' or the user initiating the VM management operation or both do not have the required access to the file share
'\\lithium\VHDs-SSD\test-System.vhdx'.  Please ensure that the computer machine account and the user initiating the VM management operation have full access to the
file share as well as the file system folder backing the file share.  Error: 'General access denied error' (0x80070005). (Virtual machine ID
4DE01C38-E027-4366-B56A-85B527BB34CB)
    + CategoryInfo          : PermissionDenied: (:) [], CimException
    + FullyQualifiedErrorId : AccessDenied,Microsoft.HyperV.PowerShell.Commands.NewVM
    + PSComputerName        : lithium

Answer: The issue was I was using a file share to reference the VHD, when I should have used a local path. So the set-up for the drives is now:
    $NewSystemVHDPath = "E:\VHDs\$($VMName)-System.vhdx"

    # Copy VHD File - hard coded to Windows 2016 Core Eval for now
    File SystemDisk {
        SourcePath = "D:\Templates\Windows 2016 Core Template\System.vhdx"
        DestinationPath = $NewSystemVHDPath
        Type = "File"
        Ensure = "Present"
    }

Works fine.


Rank of a matrix products

Question: I'm struggling with the following demonstration:
Given A,B matrix in $R^{nxn}$. If Rank(A) = n-1 then rank(AB) $\geqslant$ rank(B) - 1
I've tried using induction but I'm not sure where should I do it, if with the Matix size or with the rank of B.
Thanks!
Answer: In this case induction is not advised.
Consider instead the composition of maps, i.e first you have
$$B:\mathbb{R}^n\rightarrow B(\mathbb{R}^n) \subset \mathbb{R}^n$$
and then
$$A:B(\mathbb{R}^n)\rightarrow AB(\mathbb{R}^n)\subset \mathbb{R}^n.$$
What is important here, is to notice that we restrict the domain of $A$ to $B\mathbb{R}^n$, whose dimension is by definition equal to the rank of $B$, and to the codomain to nothing but $AB(\mathbb{R}^n)$ whose dimension is equal to the rank of $AB$.
Now apply the dimension formula to the second map, and use the fact that the kernel of a linear map restricted to a smaller domain is most definitely contained in the kernel of the map on the bigger domain, hence the dimension of the first must be less or equal than the dimension of the latter. In symbols:
$$f:V\rightarrow W \text{ and } U\subset V \Rightarrow \ker(f|_U)\leq\ker(f)$$
In you case
$$\ker(A|_{B(\mathbb{R}^n)})\leq\ker(A)=1.$$
From this you should be able to conclude quite easily

Rank of a matrix products


dangerouslySetInnerHTML stretches / expands / grows the page display

Question: In my NextJs app, I am accessing CosmicJs, a headless CMS with content to display on my page.
I have 3 columns on the page, with the content from the CMS displayed in the 2nd column.
What is happening is the 2nd column is expanding shrinking the width of the 1st and 3rd coluns.
How can I prevent this from happening and prevent the expansion of the 2nd column?
I have tried flex-grow-0, grow-o on the div and parent attributes but nothing works.
Here is the code:

Thanks is advance for your assistance.
Answer: ok, I finally fiured out the issue.
I recently upgraded to NextJS 13 and doing so, the tailwind.config.js was not updated to include the /app directory.  Tailwind continued to use my custom settings and colors, but the default tailwind colors and spacing were not recognized.   I had 3 grid cols defined on my page with the blog content going in the middle column and was never able to adjust the grid column width.
I updated the tailwind.config.js to include the new /app directory, then things worked fine.
  content: ['./pages/**/*.{js,ts,jsx,tsx}',
  './components/**/*.{js,ts,jsx,tsx}',
  './app/**/*.{js,ts,jsx,tsx}',
  ],


Problema em chamada de action via JavaScript

Question: Estou criando um submit form através do meu javascript e enviando um objeto para ser consumido pela minha Action na Controller.
Já tentei de varias formas e mesmo assim não acontece da forma como esperado.
nesse código abaixo esta retornando erro 400.
JS
var valor = {"IdContato":0,"IdUsuario":0,"Nome":descricao,"Telefone":"","Email":"","Status":"","Corretor":"","Captador":"","Pessoa":"","IdPessoa":"","TipoContato":"","IdTipoContato":"","Genero":"","IdGenero":""};
var url = "/Contato/Inicio/";

post(url, valor);

function post(path, params, method = "POST") {
      const form = document.createElement('form');
      form.method = method;
      form.action = path;
      form.style = "style: none";
      for (const key in params) {
         if (params.hasOwnProperty(key)) {
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = params[key];

            form.appendChild(hiddenField);
         }
      }
      document.body.appendChild(form);
      form.submit();
   }

Minha Controller
[HttpPost("Contato/Inicio")]
      public async Task<IActionResult> Index(ContatoFilterDto filter)
      {
         await carregaDropDowns();
         var usuarioLogado = GetUsuarioLogado();
         filter.IdUsuario = usuarioLogado.Id;
         var result = await _contatoApplication.GetByFilter(filter);
         ViewBag.Contatos = result;
         return View();
      }

A intenção deses código é após a execução da controller, chamar a view de contatos com os dados filtrados.
Mas como mencionei, ao chamar o código acima, o browser indica erro 400, como se a pagina não existe.
Esse aqui é meu html. se trata de um navBar com um Select onde de acordo com a chave ele envia para uma pagina de pesquisa.
O que eu fiz no javascript, foi transformar o valor do input do select em um form e enviar via post pelo submit.
HMTL
@using Newtonsoft.Json;

@{

    var title = ViewData["Title"];
    UsuarioViewModel user = JsonConvert.DeserializeObject<UsuarioViewModel>(User.Claims.FirstOrDefault(c => c.Type == "Usuario").Value);
    var userId = user != null ? user.Id : 0;
    var webAppUrl = ViewBag.WebAppUrl;
    string imagemPerfil = user != null && user?.PossuiImagemPerfil == true ? $"{webAppUrl}/{user.CaminhoImagemPerfil}" : $"{webAppUrl}/images/profile-picture.jpg";
}

                @*<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Ref. Imóvel</button>

Contatos

Nome

E-mail

Telefone

CPF/CNPJ

Imóvel

Titulo do Imóvel

Código do Imóvel

Proprietário

Leads

Nome

E-mail

Telefone

Código do Imóvel

*@
               <select class="form-select btn btn-outline-secondary dropdown-toggle" id="slctBuscar" style="text-align:left"  aria-label="Default select example">
                  <optgroup label="Contatos">
                     <option value="1">Nome</option>
                     <option value="2">E-mail</option>
                     <option value="3">Telefone</option>
                     <option value="4">CPF/CNP</option>
                  </optgroup>
                  <optgroup label="Imóvel">
                     <option value="5">Titulo do Imóvel</option>
                     <option value="6">Código do Imóvel</option>
                     <option value="7">Proprietário</option>
                  </optgroup>
                  <optgroup label="Leads">
                     <option value="8">Nome</option>
                     <option value="9">E-mail</option>
                     <option value="10">Telefone</option>
                     <option value="11">Código do Imóvel</option>
                  </optgroup>
               </select>
                <input type="text" class="form-control" id="inputBuscar" aria-label="Pesquisa Ref. Imóvel">
                <button class="btn btn-outline-primary" type="button" id="btnBuscar">Pesquisar</button>

                  Cliente

                  Imóvel

                  Agenda

                  Atendimento

           <button type="button" id="btnContract" onclick="firstname.lastname@example.com("Edit", "Usuario", new { id = @userId })'+'#assinaturas'" class="btn btn-success">

                 Contratar
           </button>

            <button type="button" class="btn btn-outline-primary">

                Ver Site
            </button>

        @*

                15

                15 Notifications

                     4 new messages
                    3 mins

                     8 friend requests
                    12 hours

                     3 new reports
                    2 days

                See All Notifications

*@

                    Configurações

                    Sair

Classe ContatoFilterDto
using ProCorretor.Domain.Enumerators;
using System.Collections.Generic;

namespace ProCorretor.Domain.DTOs.Filters
{
    public class ContatoFilterDto
    {
        public int? IdContato { get; set; }
        public int? IdUsuario { get; set; }
        public string Nome { get; set; }
        public string Telefone { get; set; }
        public string Email { get; set; }
        public int Status { get; set; }
        public string Corretor { get; set; }
        public string Captador { get; set; }
        public int Pessoa { get; set; }
        public Pessoa IdPessoa { get; set; }
        public int TipoContato { get; set; }
        public TipoContato IdTipoContato { get; set; }
        public int Genero { get; set; }
        public Genero IdGenero { get; set; }

    }
}

Comment: 400 é *bad request* o que é direrente de um 404, *"como se a pagina não exitisse"* como você mencionou. O 400 pode acontecer por a requisição foi mal feita e não pode ser recebida nesse caso na action. Possíveis razões: - verbot errado (espera POST recebeu um GET), o objeto não é o esperado (esperar um Date e veio um int, etc), *header* inválido, etc. Isso era pra contextualizar, agora pra saber melhor falta ai no seu código o html por exemplo (está fazendo posto via form, falta a tag form), falta a definição da classe `ContatoFilterDto`, pra ver se faz match com o json
Comment: Pra um melhor debug sugiro ir na ferramente de debug do brower (F12) e ver lá na aba de rede (network) o que foi enviado e qual o erro, lá deve mostrar o problema, que pode ser a url, o tipo de chamada e também o objeto que foi enviado. Adicione esses dados na pergunta para te ajudarmos melhor :)
Comment: Efetuei a edição com o HMTL e a Classe.
Answer: Aparentemente o que está acontecendo é que no teu endpoint, você espera receber um objeto com as propriedades IdContato, IdUsuario, Nome, etc...
Mas o que você está enviando do front são somente essas propriedades "soltas".
Você teria a principio, duas soluções:

Mandar um objeto para o endpoint, por exemplo:

valor = {
    "objeto":{
        "IdContato":0,
        "IdUsuario":0,
        "Nome":"descricao",
        "Telefone":"",
        "Email":"",
        "Status":"",
        "Corretor":"",
        "Captador":"",
        "Pessoa":"",
        "IdPessoa":"",
        "TipoContato":"",
        "IdTipoContato":"",
        "Genero":"",
        "IdGenero":""
    }
};

Poderia também, adaptar teu endpoint, para receber esses dados
separados:

[HttpPost("Contato/Inicio")]
public async Task<IActionResult> Index(int idContato, int idUsuario, string nome, etc....)
{
    var filter  = new ContatoFilterDto()
    {
        IdUsuario = idUsuario,
        Nome = nome
        ....
    };

    await carregaDropDowns();
    var usuarioLogado = GetUsuarioLogado();
    filter.IdContato = usuarioLogado.Id;
    var result = await _contatoApplication.GetByFilter(filter);
    ViewBag.Contatos = result;
    return View();
}

Essa segunda solução ficaria melhor usando AutoMapper por exemplo, eu particularmente acho mais correto a primeira abordagem.
Answer: Consegui resolver o problema mencionado.
O que acontece é que mesmo enviando do Metodo "POST", ele enviava para o GET.
Alterei o endpoint para GET e a rotina executou corretamente, o próprio framework se encarrega de transformar o objeto Json em uma classe, basta enviar a propriedades iguais.
Encontrei em uma documentação que a chamada que eu estava executando, não aceita POST, por isso do problema.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


View item list ranking

Question: I have a view with a list of nodes of a certain type sorted by a custom field.
Is there any way to put a ranking number on the output of a view?
Thanks!
Answer: I Assume you just want a row counter (1, 2, 3…). Just add the field "Global: View result counter".
Answer: If I understand well your question, in Format of your View settings, select HTML list. and in the settings of this HTML list select Ordered list
Comment: This option could be useful, but since I'm using pagination, the counter is resets with every update. Your solution is good but @uwe999's is better. +1 for you! Thanks!

View item list ranking


Add theme_hook_suggestions only for nodes in content

Question: I am developing a blog with different categories (taxonomy terms) and I wanted to have custom node templates for the nodes displayed on the blog page and category pages. Because my blog page has a view, I am able to use this template for nodes on that view: node--view--blog.tpl.php. But there is no template I can use for the nodes loaded in www.example.com/category/cat_name (alias for www.example.com/taxonomy/term/3).
I tried suggesting a node template in template_preprocess_node() like this:
if(arg(0) == 'taxonomy') {
  array_push($vars['theme_hook_suggestions'], 'node__view__blog');
}

The problem with this is that now all the nodes inside that page are rendered with that template, including the ones in my sidebar.
Is there a way to filter inside template_preprocess_node the only ones that are part of the "main content" of the page?
Answer: I would recommend you override the default term page with a view, and then theme it like you are doing for your other view.
All you have to do is create a view with that same path (taxonomy/term/%) and it will override the default page.
There is even a view already configured for this purpose, you just have to enable it.
On the views listing admin page it is called "Taxonomy term". Just enable and configure this view and then you can override it's themeing.
Answer: The preprocess/process function invoked for the node.tpl.php file don't get any information about which region contains the node going to be rendered in the page. If that information is not given from a CSS class present in $variables['classes_array'], the preprocess/process functions don't have any way to get that information.
What you can do is doing as suggested by @rooby, or suggest a template file to use instead of page.tpl.php. See also the information give in hook_page_alter() about how a page rendering array is structured.


problemas com bootstrap grid

Question: estou usando o jsfiddle para aprender bootstrap, porém estou com problemas ao fazer o conteúdo aparecer na mesma linha. o meu conteúdo no jsffidle está aparecendo em duas linhas (queria uma linha e 2 colunas)

teste

teste

meu jdfiddle:
http://jsfiddle.net/hurv9jjr/
Answer: O problema é que você especificou apenas classes para dispositivos médios (>992px)  na suas divs com o  col-md-6. Ou seja, o grid do bootstrap só esta sendo ativado pra resoluções acima de 992px e a janela de preview do JSFiddle é inferior à este tamanho.
Para que seja mostrado da forma correta basta acrescentar as classes que especificam o grid pra resoluções menores:

teste

teste

Recomendo que dê uma pincelada no funcionamento do grid do boostrap. Boa sorte.

problemas com bootstrap grid


Showing a toolbar in pushed view controller in tab bar controller

Question: I have a navigation controller in a tab bar controller.  When I push a new view controller I want to show the toolbar.  I'm doing that like this from the pushed view controller.
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setToolbarHidden:NO animated:NO];
}

This works but the toolbar slides up from it's normal position where the tab bar is to go above it.  I want it to appear without this "slide up" animation above the tab bar.  Is that possible?
Here is my setup.  The "slide up" animation occurs when pushing from view controller 1 to view controller 2.  I only want the toolbar to appear in view controller 2.
[Tab Bar Controller]
  - [Navigation Controller]
     - [View Controller 1] -> Push -> [View Controller 2]

Comment: Can post enough code to reproduce the issue?
Comment: http://stackoverflow.com/a/23269013/384309 this is a working answer
Answer: Put your navigation controller embedded inside in your tab bar controller instead of the other way around.
So the tab bar will have the Nav bar as one of its view controllers
Comment: That's what I have now.  I added more info.
Answer: Make sure that in the storyboard all the view controllers have the "hide bottom bar" property unchecked
Answer: Have you tried destinationVC.hidesBottomBarWhenPushed = YES;?
Apple docs
Comment: Thanks for your response.  That does work to remove the animation but I want both the tab bar and toolbar visible.
Answer: Move [self.navigationController setToolbarHidden:NO animated:NO]; from viewWillAppearto viewDidloadthat should work.


Collections Counter not summing total values

Question: I'm trying to use the collections.counter method to count the number of values for each key. So as I'm iterating through my db I want it to keep a count of the number of times a value is found. Instead it just prints a value each time it occurs in the DB. This is my code for the function I use:
def clusters(tweetLocation):
    cityCount=None
    cities = {"London":[51.50722, -0.12750], "New York":[-74.006605 ,40.714623]}
    for k,v in cities.items():
        if distance.distance(v, tweetLocation).miles < 50:
            cityCount=k
        else:
            pass
    return cityCount

The code for the script:
city_counter=[]
while cursor.alive:#cursor reads all relevant values from the DB
    try:
        doc = cursor.next()
        if not doc['coordinates']:
            placeName = doc['place']['full_name']
            loc = g.geocode(placeName)
            time.sleep(0.15)
            city_counter=Counter([clusters([loc])])
        else:
            places = doc['coordinates']['coordinates']
            city_counter=Counter([clusters([places])])
    except (ValueError, geocoders.google.GQueryError):
        pass
    except StopIteration:
        break
print city_counter

So rather that returning something like:
Counter({New York: 25, London: 15})

I get:
Counter({None: 1})
Counter({None: 1})
Counter({New York: 1})
Counter({None: 1})
......

I've never used the collections.counter before, but I thought it would return a sum of the values.
Thanks
Answer: When you call Counter() you create a counter object. To add to it, use its update() method. It looks like you probably want to create a Counter object stored in city_counter, and then in your loop call city_counter.update([clusters([loc])])
See the documentation for more information
Comment: Thanks....for suggesting the update() method. I'll take a further look at the documentation  to.
Answer: The problem is you're creating a new Counter each time, so you're getting a new one returned each time.  You have three options here:
Get all the values at once, then create Counter
Basically, this would involve you getting the entire list of cities at once and then shoving it through a Counter.
cities = []
while cursor.alive:
    try:
       cities.append(cursor.next())
    except StopIteration:
       break
print collections.Counter(cities.keys())

Update Counter with each new doc
For this, all you have to do is make sure that you have a Counter created first, and then use the update method.
city_counter = collections.Counter()
while cursor.alive:
     city_counter.update([clusters[places]])
     # etc.

Use a defaultdict
For your situation, this might be the best option.
city_counter = collections.defaultdict(int)
while cursor.alive:
    city_counter[clusters[places]] += 1
    # etc.

Comment: You're right I'm creating new instances of a counter each time. I've been able to use the update() method. Thanks for your answer.


Problema ao persistir: "Cannot add or update a child row: a foreign key constraint fails..."

Question: Tabelas
Contato
CREATE TABLE IF NOT EXISTS `sgct-database1`.`contato` (
  `contato_id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `telefone` CHAR(10) NOT NULL,
  `celular` CHAR(11) NULL,
  PRIMARY KEY (`contato_id`))
ENGINE = InnoDB
AUTO_INCREMENT = 1

Endereço
CREATE TABLE IF NOT EXISTS `sgct-database1`.`endereco` (
  `endereco_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `endereco` VARCHAR(120) NOT NULL,
  `numero` CHAR(8) NOT NULL,
  `complemento` VARCHAR(40) NULL,
  `cep` CHAR(8) NULL,
  `bairro` VARCHAR(120) NULL,
  `cidade` VARCHAR(40) NOT NULL,
  `estado` VARCHAR(40) NOT NULL,
  PRIMARY KEY (`endereco_id`))
ENGINE = InnoDB
AUTO_INCREMENT = 1

Técnico
CREATE TABLE IF NOT EXISTS `sgct-database1`.`tecnico` (
  `tecnico_id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `nome` VARCHAR(128) NOT NULL,
  `login` VARCHAR(16) NOT NULL,
  `senha` VARCHAR(16) NOT NULL,
  `rg` CHAR(9) NOT NULL,
  `cpf` CHAR(11) NOT NULL,
  `observacoes` VARCHAR(300) NULL,
  `status` CHAR(12) NOT NULL,
  `contato_id` SMALLINT UNSIGNED NOT NULL,
  `endereco_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`tecnico_id`),
  UNIQUE INDEX `login_UNIQUE` (`login` ASC),
  INDEX `fk_tecnico_contato1_idx` (`contato_id` ASC),
  INDEX `fk_tecnico_endereco1_idx` (`endereco_id` ASC),
  CONSTRAINT `fk_tecnico_contato`
    FOREIGN KEY (`contato_id`)
    REFERENCES `sgct-database1`.`contato` (`contato_id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_tecnico_endereco`
    FOREIGN KEY (`endereco_id`)
    REFERENCES `sgct-database1`.`endereco` (`endereco_id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 1

Entidades
@Entity
public class Contato implements Serializable {

    private static final long serialVersionUID = -5117050430686257801L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "contato_id")
    private Short codigo;

    private String telefone;
    private String celular;

    public Contato() {
    }

    //gets e sets
    //hashcode() e equals()
}

Endereço
@Entity
public class Endereco implements Serializable {

    private static final long serialVersionUID = 5071505092437076722L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "endereco_id")
    private Long codigo;

    private String endereco;
    private Short numero;
    private String complemento;
    private String cep;
    private String bairro;
    private String cidade;
    private String estado;

    public Endereco() {
    }

    //gets e sets
    //hashcode() e equals()
}

Técnico
@Entity
public class Tecnico implements Serializable {

    private static final long serialVersionUID = 1832056502374198975L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "tecnico_id")
    private Short codigo;

    private String nome;

    @Column(unique = true)
    private String login;

    private String senha;
    private String rg;
    private String cpf;
    private String observacoes;

    @ElementCollection(targetClass = String.class)
    @JoinTable(name = "tecnico_permissao", uniqueConstraints = { @UniqueConstraint(columnNames = {
            "tecnico", "permissao" }) }, joinColumns = @JoinColumn(name = "tecnico"))
    @Column(name = "permissao", length = 50)
    private Set<String> permissao;

    @Enumerated(value = EnumType.STRING)
    private Status status;

    @OneToOne/*(cascade = CascadeType.ALL) - Não está funcionando */
    @JoinColumn(name = "contato_id")
    private Contato contato;

    @OneToOne/*(cascade = CascadeType.ALL) - Não está funcionando */
    @JoinColumn(name = "endereco_id")
    private Endereco endereco;

    public Tecnico() {
        permissao = new HashSet<String>();
    }

    //gets e sets
    //hashcode() e equals()
}

Impl DAO's
HibernateContatoDAO
public class HibernateContatoDAO implements ContatoDAO {

    private Session session;

    public HibernateContatoDAO(Session pSession) {
        this.session = pSession;
    }

    @Override
    public void salvar(Contato pContato) {
        this.session.save(pContato);
    }

    @Override
    public void atualizar(Contato pContato) {
        this.session.update(pContato);
    }

    @Override
    public void excluir(Contato pContato) {
        this.session.delete(pContato);
    }

    @Override
    public Contato carregar(Short pCodigo) {
        return (Contato) this.session.get(Contato.class, pCodigo);
    }

    @Override
    public List<Contato> listar() {
        return this.session.createCriteria(Tecnico.class).list();
    }

}

HibernateEnderecoDAO
public class HibernateEnderecoDAO implements EnderecoDAO {

    private Session session;

    public HibernateEnderecoDAO(Session pSession) {
        this.session = pSession;
    }

    @Override
    public void salvar(Endereco pEndereco) {
        this.session.save(pEndereco);
    }

    @Override
    public void atualizar(Endereco pEndereco) {
        this.session.update(pEndereco);
    }

    @Override
    public void excluir(Endereco pEndereco) {
        this.session.delete(pEndereco);
    }

    @Override
    public Endereco carregar(Short pCodigo) {
        return (Endereco) this.session.get(Endereco.class, pCodigo);
    }

    @Override
    public List<Endereco> listar() {
        return this.session.createCriteria(Endereco.class).list();
    }

}

HibernateTecnicoDAO
public class HibernateTecnicoDAO implements TecnicoDAO {

    private Session session;

    public HibernateTecnicoDAO(Session session) {
        this.session = session;
    }

    @Override
    public void salvar(Tecnico pTecnico) {
        this.session.save(pTecnico);
    }

    @Override
    public void atualizar(Tecnico pTecnico) {
        if (pTecnico.getPermissao() == null
                || pTecnico.getPermissao().size() == 0) {
            Tecnico tecnicoPermissao = this.carregar(pTecnico.getCodigo());
            pTecnico.setPermissao(tecnicoPermissao.getPermissao());
            this.session.evict(tecnicoPermissao);
        }

        this.session.update(pTecnico);
    }

    @Override
    public void excluir(Tecnico pTecnico) {
        this.session.delete(pTecnico);
    }

    @Override
    public Tecnico carregar(Short pCodigo) {
        return (Tecnico) this.session.get(Tecnico.class, pCodigo);
    }

    @Override
    public Tecnico carregarPorLogin(String pLogin) {
        String hql = "select t from Tecnico t where t.login = :login";
        Query consulta = this.session.createQuery(hql);
        consulta.setString("login", pLogin);
        return (Tecnico) consulta.uniqueResult();
    }

    @Override
    public Tecnico carregarPorRg(String pRg) {
        String hql = "select t from Tecnico t where t.rg = :rg";
        Query consulta = this.session.createQuery(hql);
        consulta.setString("rg", pRg);
        return (Tecnico) consulta.uniqueResult();
    }

    @Override
    public List<Tecnico> listar() {
        return this.session.createCriteria(Tecnico.class).list();
    }
}

Classe de Teste
HibernateTecnicoDAOTest
public class HibernateTecnicoDAOTest {

    private TecnicoDAO tecnicoDAO;
    private ContatoDAO contatoDAO;
    private EnderecoDAO enderecoDAO;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {

    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {

    }

    @Before
    public void setUp() throws Exception {
        tecnicoDAO = DAOFactory.criarTecnicoDAO();
        enderecoDAO = DAOFactory.criarEnderecoDAO();
        contatoDAO = DAOFactory.criarContatoDAO();

        HibernateUtil.getSessionFactory().getCurrentSession()
                .beginTransaction();
    }

    @After
    public void tearDown() throws Exception {
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction()
                .commit();
        HibernateUtil.getSessionFactory().getCurrentSession().close();
    }

    @Test
    public void testSalvarSucesso() {
        Tecnico tecnico = new Tecnico();
        Endereco endereco = new Endereco();
        Contato contato = new Contato();

        tecnico.setNome("Galisteu da Silva");
        tecnico.setCpf("12345678901");
        tecnico.setRg("112223334");
        tecnico.setLogin("galisteu");
        tecnico.setSenha("123");
        tecnico.setStatus(Status.DISPONIVEL);

        contato.setTelefone("11112222");
        contato.setCelular("981112222");

        endereco.setCidade("São Paulo");
        endereco.setEstado("São Paulo");
        endereco.setCep("12233444");
        endereco.setEndereco("Rua Maria Souza");
        endereco.setNumero((short) 123);

        tecnico.setEndereco(endereco);
        tecnico.setContato(contato);

        enderecoDAO.salvar(endereco);
        contatoDAO.salvar(contato);

        System.out.println("ID_CON: " + contato.getCodigo());
        System.out.println("ID_END: " + endereco.getCodigo());

        tecnicoDAO.salvar(tecnico);
    }
}

Exception
Hibernate: insert into Endereco (bairro, cep, cidade, complemento, endereco, estado, numero) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into Contato (celular, telefone) values (?, ?)
ID_CON1
ID_END1
Hibernate: insert into Tecnico (contato_id, cpf, endereco_id, login, nome, observacoes, rg, senha, status) values (?, ?, ?, ?, ?, ?, ?, ?, ?)
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
    at com.sun.proxy.$Proxy15.save(Unknown Source)
    at org.sgct.model.HibernateTecnicoDAO.salvar(HibernateTecnicoDAO.java:25)
    at org.sgct.model.HibernateTecnicoDAO.main(HibernateTecnicoDAO.java:110)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`sgct-database1`.`tecnico`, CONSTRAINT `fk_tecnico_contato` FOREIGN KEY (`contato_id`) REFERENCES `sgct-database1`.`contato` (`contato_id`) ON DELETE CASCADE ON UPDATE NO ACTION)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
    at com.mysql.jdbc.Util.getInstance(Util.java:383)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1049)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2840)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
    at com.zaxxer.hikari.proxy.PreparedStatementJavassistProxy.executeUpdate(PreparedStatementJavassistProxy.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 29 more

Configuração
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQL5InnoDBDialect
        </property>
        <property name="hibernate.show_sql">
            true
        </property>
        <property name="hibernate.connection.provider_class">
            com.zaxxer.hikari.hibernate.HikariConnectionProvider
        </property>
        <property name="hibernate.current_session_context_class">
            thread
        </property>
        <property name="hibernate.hbm2ddl.auto">
            update
        </property>

        <property name="hibernate.hikari.dataSourceClassName">
            com.mysql.jdbc.jdbc2.optional.MysqlDataSource
        </property>
        <property name="hibernate.hikari.dataSource.url">
            jdbc:mysql://localhost:3306/sgct-database1?createDatabaseIfNotExist=true
        </property>
        <property name="hibernate.hikari.dataSource.user">
            root
        </property>
        <property name="hibernate.hikari.dataSource.password">
            adm123
        </property>
        <property name="hibernate.hikari.maximumPoolSize">
            10
        </property>
        <property name="hibernate.hikari.idleTimeout">
            30000
        </property>

        <mapping class="org.sgct.model.Tecnico" />
        <mapping class="org.sgct.model.Contato" />
        <mapping class="org.sgct.model.Endereco" />

    </session-factory>

</hibernate-configuration>

Perguntas

Estou tendo problemas ao persistir um objeto Tecnico, pois toda a vez que eu tento persisti-lo, é lançado a exception descrita anteriormente, mas, resumindo, a causa poderia ser esta:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (sgct-database1.tecnico, CONSTRAINT fk_tecnico_contato FOREIGN KEY (contato_id) REFERENCES sgct-database1.contato (contato_id) ON DELETE CASCADE ON UPDATE NO ACTION).

As instâncias de Contato e Endereco persistem normalmente.
O atributo cascade de anotações como @OneToOne podem assumir diversos valores, mas no meu caso quando eu atribuo CascadeType.PERSIST ao atributo cascade, simplemente não funciona. Uso JPA nas entidades e Hibernate nas DAO's.

Há alguma coisa que deixei de fazer ou isso é problema do Hibernate mal configurado?
Comment: O erro do constraint, pelo que imagino é que sua tabela Tecnico tenta usar um foreign key que é chave primaria na tabela Contato, entretanto o valor que você indica não existe. Já chegou a verificar isso?
Comment: Já chequei sim, tanto que coloquei um `sysout` na classe de teste para ver mesmo se o hibernate após persistir recuperou as chaves geradas pelo banco de dados para ser usada na instância Tecnico. Uma coisa, quando se executa o `save()` do hibernate ele executa o `flush()` internamente? E usando o `CascadeType.PERSIST` ocorre o mesmo erro.
Answer: Eu resolvi o problema analisando o código das tabelas após sua criação, e descobri que em uma das tabelas era criado uma primary key SMALLINT(5) e em outra tabela referenciada era criada uma SMALLINT(6). Assim, alterando a tabela com o primary key SMALLINT(6) para SMALLINT(5) voltou a funcionar normalmente.
Uma coisa que aprendi para evitar problemas é definir diretamente o tamanho da coluna para evitar problemas futuros como este.


Cassandra Failed to create a selector. Multithreading multiple concurrent cassandra connections

Question: I am running an ExecutorService of more than 50 threads concurrently. Each thread is opening a connection to Cassandra and performing inserts using springframework.data.cassandra. The problem is when I open more than 50 connections at a time, I get the following error.
Caused by: org.jboss.netty.channel.ChannelException: Failed to create a selector.
    at org.jboss.netty.channel.socket.nio.AbstractNioSelector.openSelector(AbstractNioSelector.java:343)
    at org.jboss.netty.channel.socket.nio.AbstractNioSelector.<init>(AbstractNioSelector.java:100)
    at org.jboss.netty.channel.socket.nio.AbstractNioWorker.<init>(AbstractNioWorker.java:52)
    at org.jboss.netty.channel.socket.nio.NioWorker.<init>(NioWorker.java:45)
    at org.jboss.netty.channel.socket.nio.NioWorkerPool.createWorker(NioWorkerPool.java:45)
    at org.jboss.netty.channel.socket.nio.NioWorkerPool.createWorker(NioWorkerPool.java:28)
    at org.jboss.netty.channel.socket.nio.AbstractNioWorkerPool.newWorker(AbstractNioWorkerPool.java:143)
    at org.jboss.netty.channel.socket.nio.AbstractNioWorkerPool.init(AbstractNioWorkerPool.java:81)
    at org.jboss.netty.channel.socket.nio.NioWorkerPool.<init>(NioWorkerPool.java:39)
    at org.jboss.netty.channel.socket.nio.NioWorkerPool.<init>(NioWorkerPool.java:33)
    at org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory.<init>(NioClientSocketChannelFactory.java:151)
    at org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory.<init>(NioClientSocketChannelFactory.java:116)
    at com.datastax.driver.core.Connection$Factory.<init>(Connection.java:532)
    at com.datastax.driver.core.Cluster$Manager.<init>(Cluster.java:1201)
    at com.datastax.driver.core.Cluster$Manager.<init>(Cluster.java:1144)
    at com.datastax.driver.core.Cluster.<init>(Cluster.java:121)
    at com.datastax.driver.core.Cluster.<init>(Cluster.java:108)
    at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:177)
    at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1109)

If I open exactly 50 threads (or less), it works fine. Is there a way to configure this so I can allow more? In my cassandra.yaml file, rpc_max_threads according to the comments by default "The default is unlimited"
Comment: It says by default that number is 128
Answer: My guess is you are overwhelming your OS by creating too many connections.  You should only create 1 Cluster instance per Cassandra cluster.   Clusters create Sessions, which manage their own connection pools.  Both Cluster and Session are thread safe, so you can share them between threads.
Four simple rules for coding with the driver distills these concepts well:

When writing code that uses the driver, there are four simple rules that you should follow that will also make your code efficient:

Use one cluster instance per (physical) cluster (per application lifetime)
Use at most one session instance per keyspace, or use a single Session and explicitly specify the keyspace in your queries
...

A Cluster instance allows to configure different important aspects of the way connections and queries will be handled. At this level you can configure everything from contact points (address of the nodes to be contacted initially before the driver performs node discovery), the request routing policy, retry and reconnection policies, and so forth. Generally such settings are set once at the application level.
While the session instance is centered around query execution, the Session it also manages the per-node connection pools. The session instance is a long-lived object, and it should not be used in a request-response, short-lived fashion. The code should share the same cluster and session instances across your application.


(VERI-1322) prefix of assignment pattern must be a data type

Question: Here is a snippet from my code;
always_ff @(posedge clk) begin : output_assigment // left side should only be "_q"
    if(reset_n == 1'b0 || clear == 1'b1) out_signal_q <= {8'{!(REPORT_POL)}};

But i see this error:   (VERI-1322) prefix of assignment pattern must be a data type
How can this be corrected for the assignment "out_signal_q <= {8'{!(REPORT_POL)}}"
Can you please help ?
end
Answer: It always helps to show declarations of all signals involved in the expression. I have to assume that REPORT_POL is a single bit and you want it replicated 8 times to assigned to out_signal_q. In that case you want to remove the ' and just write
out_signal_q <= {8{!REPORT_POL}};


Customising Start Menu programs using GPO

Question: Theres so much junk in the "All Programs" section of Windows these days. I'm trying to customise it so that it just shows a restricted list of relevant apps to the users. I'm using Server 2003 and Win 7 clients. I'm managed to remove everything using
User Configuration / Policies / Administrative Templates / Start Menu and Taskbar / Remove All Programs List from the start menu

I've then tried to add the shortcust back in using:
Preferences / Windows Settings / Shortcuts / Shortcut (Path: %StartMenuDir%\Application.ink)

However this hasn't worked and the start menu is blank, whats the best way to go about customising the programs in the start menu?
Comment: When you say "junk" is that just your opinion or do you have a mandate to "clean up" the start menu.
Comment: Thats mostly my opinion. Stuff like "Windows Live Mail" and "Windows Live Messenger" doesn't need to be there for our purposes.
Answer: http://gps.cloudapp.net/ is a live saver sometimes when looking for GPO options.
I used the following search term "start  menu\programs"
I think a combination of these might help you out:
Remove common program groups from Start Menu
Remove Default Programs link from the Start menu.
Remove Documents icon from Start Menu
Remove Downloads link from Start Menu
Remove Drag-and-drop context menus on the Start Menu
Remove Favorites menu from Start Menu


What does crypto/cipher-XORKeyStream do to the src []byte?

Question: I'm doing AES encryption using Go, I found that the source bytes changed after encryption. Seems that XORKeyStream function does the change if cap(source) > len(source), what it exactly does to the src []byte?
go version go1.12.5 darwin/amd64
func main() {
    byte1 := []byte("123abc")
    fmt.Println("content1:", byte1, "len1:", len(byte1), "cap1:", cap(byte1)) // content1: [49 50 51 97 98 99] len1: 6 cap1: 6
    buf := bytes.NewBuffer([]byte("123abc"))
    byte2, _ := ioutil.ReadAll(buf)
    fmt.Println("content2:", byte2, "len2:", len(byte2), "cap2:", cap(byte2)) // content2: [49 50 51 97 98 99] len2: 6 cap2: 1536

    _, _, _, err := crypt.AESEnc(byte1)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("content1:", byte1, "len1:", len(byte1), "cap1:", cap(byte1)) // content1: [49 50 51 97 98 99] len1: 6 cap1: 6
    _, _, _, err = crypt.AESEnc(byte2)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("content2:", byte2, "len2:", len(byte2), "cap2:", cap(byte2)) // content2: [132 200 7 200 195 8] len2: 6 cap2: 1536
}

func AESEnc(data []byte) ([]byte, []byte, string, error) {
    key := make([]byte, 16)
    iv := make([]byte, 16)
    _, err := io.ReadFull(rand.Reader, key)
    if err != nil {
        return nil, nil, "", err
    }
    _, err = io.ReadFull(rand.Reader, iv)
    if err != nil {
        return nil, nil, "", err
    }
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, nil, "", err
    }
    pdata := pckspadding(data, block.BlockSize())
    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(pdata, pdata)
    return key, iv, base64.StdEncoding.EncodeToString(pdata), nil
}

func pckspadding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

byte2 changes after encryption, what happened?
Answer: I'm not familiar a crypto/cypher-XORKeyStream but I can tell you what XOR does to bits if that is helpfull.  I have some Electronic experience and here is the truth table to an XOR gate:

Inputs X and Y represent two bits. The output Z is the result of XOR-ing X and Y.
In English you would say to yourself "Inputs, either one or the other but not both" results in an output of "True".
Don't know how much help this will be or how to apply it to more than two input bits with a crypto/cypher-XORKeyStream.
But here would be an example:
X = 00110001010
Y = 11111111111
Z = 11001110101

Good Luck!
Answer: It XORs each byte in the provided slice with a byte in the cipher's key stream, or as the documentation puts it:
    // XORKeyStream XORs each byte in the given slice with a byte from the
    // cipher's key stream. Dst and src must overlap entirely or not at all.
    //
    // If len(dst) < len(src), XORKeyStream should panic. It is acceptable
    // to pass a dst bigger than src, and in that case, XORKeyStream will
    // only update dst[:len(src)] and will not touch the rest of dst.
    //
    // Multiple calls to XORKeyStream behave as if the concatenation of
    // the src buffers was passed in a single run. That is, Stream
    // maintains state and does not reset at each XORKeyStream call.
    XORKeyStream(dst, src []byte)

This means it mutates dst, which is why you're observing a different input buffer after encryption is performed.


Are circle of fifths progressions generally practical for modes?

Question: Earlier today I was working on mode utilizations, and as I was making a circle of fifths, here's what I got:

C Ionian mode: C - F - Bdim - Em - Am - Dm - G - C (I - IV - viio - iii - vi - ii - V - I)
D Dorian mode: Dm - G - C - F - Bdim - Em - Am - Dm (i - IV - VII - III - vio - ii - v - i)
E Phrygian mode: Em - Am - Dm - G - C - F - F7(b5) - Em (i - iv - vii - III - VI - II - Fr. 6/i - i)
F Lydian mode: F - Bdim - Em - Am - Dm - G - C - F (I - ivo - vii - iii - vi - II - V - I)
G Mixolydian mode: G - C - F - Bdim - Em - Am - Dm - G (I - IV - VII - iiio - vi - ii - v - I)
A Aeolian mode: Am - Dm - G - C - F - Bdim - Em - Am (i - iv - VII - III - VI - iio - v - i)
B Locrian mode: Bm(no5) - Em - Am - Dm - G - C - C7(no5) - Bm(no5) (i(no5) - iv - vii - iii - VI - II - It. 6/i - i(no5))
C Ionian mode: C - F - Bdim - Em - Am - Dm - G - C (I - IV - viio - iii - vi - ii - V - I)

Like this:

However, I think I have heard that circle of fifths progressions are basically tonal and not modal.  Are they practical for modes or not?
Comment: Write the list in a circle, and you'll see that each list starts on a different part of that circle. All you've done is repeat the pattern (with a couple of spurious chords). C Ionian has the same stuff as D Dorian, E Phrygian, F Lydian, etc.
Comment: E Phrygian with F7b5. And a dom 7 chord isn't the same as a Fr/ItGer6th. And Locrian doesn't work too well in this (or many other) situation.
Comment: What do you mean by practical? Are you doing composition, or analysis of existing music?
Comment: What makes a sequence of chords practical? Do you like the way it sounds? If you do, what could be more practical?
Comment: In historical use such progressions would have had more chromatic alteration (for example, a raised leading tone on the penultimate chord whenever it has a minor third, for example in the Dorian).  These chromatic alterations were a big part of what led to the development of tonal music.  I suspect that illustrating that is one of the points of doing an exercise like this.
Comment: @Tim - What do you mean by "spurious chords"?
Comment: @Tim - Tim, I used the French tritone sub chord in order to get the ^2 in the bass to give the Phrygian character without using a chord multiple times.  It subs for 5 in a 1-4-7-3-6-2-5-1 progression.
Answer: I would say that a circle of fifths progression in modal music is just as practical, or impractical, as in tonal music.  The effect of motion is similar, and runs the same risk of getting boring if carried too far.


Can't open connection to remote database

Question: I have php script running on XAMPP on my local PC and I want to access some databse other than one on my localhost. Even if I call script with my own IP address I can't connect to the database.
PHP script looks like:
<?php

$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$database = $_GET['database'];

$con = mysql_connect($host,$username,$pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("performance_schema", $con);
$zavrsni = "zavrsni";

$result = mysql_query("SELECT `OBJECT_NAME`,`COUNT_INSERT`,`AVG_TIMER_INSERT`,`COUNT_UPDATE`,`AVG_TIMER_UPDATE`,`COUNT_DELETE`,`AVG_TIMER_DELETE` FROM `table_io_waits_summary_by_table` where `OBJECT_SCHEMA` =\"".$database."\"");

while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}

print(json_encode($output));

mysql_close($con);

?>

I call this script as:
http://zavrsni.noip.me/dohvat.php?username=root&pass=ficko1&database=zavrsni&host=zavrsni.noip.me

And then I get error:
Warning: mysql_connect(): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in C:\xampp\htdocs\dohvat.php on line 8
Could not connect: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

I know that this is not the most secure way of connecting the database, but I'm new to PHP so don't judge the terrible code.
Comment: Everything is in error message
Comment: Your hostname may be wrong
Comment: sorry, but I don't unserstand what to do, that's why I asked question here
Comment: Try to connect from the mysql command line interface. What error message do you get?
Comment: hostname is the right one because it's the same as one I have my apache server on
Comment: @AlexMonthy this is what i get while connecting via cmd: ERROR 2003 (HY000): Can't connect to MySQL server on 'zavrsni.noip.me' (10060)
Comment: there is no open mysql port on your ip http://pastebin.com/kfkJPWBY make sure Mysql in ON, port is open to world (check firewall), and remote access is granted. As @Kasyx said, everything is in error message...
Comment: From your PHP script, try to connect to host 127.0.0.1 - does that work? So that the URL would read "...&host=127.0.0.1"
Comment: @AlexMonthy yeah it works if I try to connect via host=localhost or host=127.0.0.1
Answer: Your database is not open for connections from outside.
Log in to the server on which the database resides, log in to your database as root and then enter:
USE zavrsni;
GRANT ALL PRIVILEGES ON * to root@% identified by 'ficko1';

or better
GRANT SELECT ON * to root@% identified by 'ficko1';

Please note that it global grants are highly unsure. Learn how to use the privilege system and later grant only those privileges which are actually needed.
If this still does not work, your mysql server is not permitting connections from outside. Have a look at http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html


Have Apache send a response defined in the configuration file

Question: I would like my Apache VirtualHost to respond with the same content, no matter the URL requested. I know it is possible with an additional file containing the static response (https://askubuntu.com/a/485017/600828).
However, my response content is very short and simple, and I would like to know if it is possible to include it in the Apache site config file directly (so that I have only one file to deploy & maintain instead of 2).
Comment: nginx can do this very easily with [`return`](https://nginx.org/r/return), i.e.: `return 200 "Hi there";` but I can't find anything relevant for Apache.
Comment: Indeed @MichaelHampton. The reason I want to do it with Apache is that I am using Apache as a reverse proxy to multiple apps, so if I use anything else it would be behind Apache anyway.
Answer: You can define the text for 404 and other error conditions in the main Apache httpd.conf with the ErrorDocument directive https://httpd.apache.org/docs/2.4/custom-error.html
When your documentRoot is empty and you don't permit directory listings requests for your bare domain should trigger an 403 error and all other URLs will trigger a 404 so with the following (ugly) solution you get what you want
<VirtualHost *:80>
   ServerName www.example.com
   DocumentRoot /path/to/empty/dir
   ErrorDocument 404 "some text"
   ErrorDocument 403 "some text"
   .,.
 </VirtualHost >

Please note that your some text needs to be long enough to prevent certain browsers from displaying their own friendly error messages
Comment: Thank you for your suggestion. It is an interesting workaround, but I'd rather have a success code returned... Upvoted anyway.


Qual é a vantagem do ponto e vírgula em linguagens de programação?

Question: Sei que em linguagens de programação como Java e C#, o ponto e vírgula indica o fim da instrução, como no exemplo abaixo, em C#:
<code>System.Console.WriteLine("Hello, World!");
</code>
Porém, ainda sim existem linguagens em que o ponto e vírgula não é necessário (e nem possível), como no caso do Visual Basic, F#, Go, entre muitas outras.

Qual é a vantagem de se indicar o fim das instruções?
No caso do C#/VB, indicar o fim da instrução faz do C# mais performático
que o VB.NET na compilação?
Comment: Relacionado [**Semicolon (;) no ECMAScript 6 não é mais necessário?**](https://pt.stackoverflow.com/a/174178/3635) ?
Answer: Não muda na performance, isso é apenas sintático, sequer é semântico.
A primeira vantagem óbvia é que permite que instruções (statements) possam ser escritas em mais de uma linha, o que pode organizar melhor e deixar o código mais legível em algumas situações. Essa é uma forma de dar um ponto final na "frase". Ao mesmo tempo permite mais de um statement na mesma linha.
Algumas linguagens preferiram estabelecer que só poderia ter uma linha e o indicador de nova linha marca o final da "frase".
Claro que é possível ter outras soluções para essa necessidade, como indicar um marcador específico quando precisar continuar em outra linha.
Outra vantagem menos óbvia é a redundância. Por incrível que pareça redundância em código pode torná-lo mais confiável que está expressando a ideia certa e evita cometer erros por algum descuido. Além disso o compilador pode identificar erros mais facilmente e talvez dar uma mensagem mais próxima do que precisa para corrigir. É possível dar boas mensagens sem ter um terminador de instrução, mas complica bastante o compilador.
O mesmo ocorre com o humano que vai ler. Ter algo visual que mostre que a instrução encerrou ajuda os olhos dar um "parse" no texto.
E não podemos deixar de considerar a vantagem de que linguagens populares usam há muito tempo, e ter algo que as pessoas já estão acostumadas ajudam a aceitação de novas linguagens.
Escrever compiladores para linguagens sem terminação explícita do statement é mais difícil, então é uma vantagem para o outro lado, o dos escritores de compiladores :)
Mas eu acho mais limpo sem ele. Acho que polui e geram erros sem necessidade em muitos casos porque a pessoa esqueceu de colocar o terminador. Ser mais limpo não quer dizer que é melhor, mas é indiscutível que menos informação é algo mais limpo. Claro que limpeza demais pode trazer outros problemas. Quando a limpeza tira a proteção pode ser ruim.
Mas se a linguagem foi criada para usá-lo, deve usar, mesmo que seja opcional. Estou falando do JavaScript que as pessoas agora "resolveram" que não precisam mais do ponto e vírgula.
Há brigas religiosas por causa deste e outros tópicos de sintaxe de linguagens de programação.
Coloquei no GitHub para referência futura.
Comment: "Há brigas religiosas por causa deste e outros tópicos de sintaxe de linguagens de programação" Infelizmente é verdade.Tem gente que prefere linguagens sem terminação (explícita) de linha e brigam por besteira. Pessoalmente tenho programado nos últimos 30 anos de basic num Z80 até C# passando por Java, Delphi, VB6, Borland C, Javascript com um pouco de PHP, Haskell... eu pessoalmente acho linguagens com "final de linha" tem uma sintaxe mais organizada e limpa.
Comment: @jean nosso *background*  é incrivelmente semelhante. Faltou Clipper para você :P Eu aproveitei e editei para discordar um pouco de você, sem tirar a sua razão :P
Comment: Blz, adoro debater sem dogmatismos. Eu acho que (com;) fica mais limpo no sentido de falta de dubiedade. Sim brinquei um pouco com assembly, clipper, cobol, a lista é grande =). Agora temos strings com @ no C#t e pra mim era a única coisa que faltava =D
Comment: Em ADVPL (Totvs) indica uma continuação de linha ...
Comment: @Motta Na verdade desde o Clipper. Não lembro se o dBase aceitava, acho que não. È o que eu falei no 4o. parágrafo de forma genérica.
Comment: Só quis dar um pitaco aí vc está alterando um advpl e uma function plsql ao mesmo tempo o ; vira um inimigo ...  :)


When can we use the z-score? (Since it's impossible to know the population SD)

Question: Sometimes I see papers that report the z-score. I am confused because the z-score requires us to know the population standard deviation, which is impossible. What are some reasons people still report the z-score?? Can you give an example please? (The only thing I can think of is when the sample size is large enough so the t-distribution converges to a normal distribution. Also, if the sample is large enough, the sample SD will approximately converge to the population SD. However, even in that situation, shouldn't the researcher report the t-score just to be more sure and conservative?)
Thank you!
Comment: If the purpose is *descriptive,* everything is fine, because the relevant standard deviation is the empirical SD of your data.
Answer: Remember that the T-statistic also requires your data to be normal, which is usually not true either. We end up using Z scores in large samples because of the central limit theorem, one version of which tells us that for arbitrary random variables $ \{X_i\}_{i=1}^n $ with finite variance and the same unknown distribution $F$, the test statistic becomes normally distributed i.e. $$ \sqrt{n}(\bar{X}_n - \mu_0)/s \stackrel{d}{\to} \mathcal{N}(0,1).$$ By abusing asymptotics, we basically end up using critical values like 1.96 (which is a z-critical value at the 5% level!) to reject the null that $\mathbb{E}[X] = \mu_0 $.
Answer: When comparing proportions, one way to compute a p-value and confidence interval is to compute a z-ratio also called a z-score. T ratios aren't used.
When comparing means, you are right, I think. The t ratio should be used.
Don't confuse the z-score with "z-factor", which is used when evaluating high-throughput screening of drugs, and has an entirely different meaning than the z-score.


How can I make a center-aligned text's with to be just the text's width?

Question: Wondering how I can make centered text's width the width of the text?
Highlighted in red, it shows that the width is 100%.
http://jsfiddle.net/kenhimself/ktkdypyo/
CSS:
h1 {
    text-align: center;
    font-size: 5vh;
    line-height: 1;
    white-space: nowrap;
    background:red;
    color:white;
}

Thanks in advance!
Answer: Change your HTML structure like below and apply style for h2 as well.

text is centered

but the width is 100%.

How can I make it so that the width

is only the widht of the text?

CSS
h1 {
font-size: 5vh;
line-height: 1;
white-space: nowrap;
background:red;
color:white;
display:inline-block;
}

DEMO
Comment: Brilliant — Thank you. I have marked your answer as the correct one :)
Comment: Actually — one more question. How can I make it so that when I hover over any of those texts, it fades out and gets replaced by a different text?
Comment: If you want to replace text then you need to use jquey/javascript
Comment: well, I'm looking for a css only trick, but I modified this: any ideas? http://jsfiddle.net/kenhimself/ktkdypyo/5/  isn't a way to use functions like ~, +, >, etc?
Comment: that'll be a great start for me— thank you :) however, when noticed that when I scale down the window, the text responds to the height of the window, but the line-height increases for some reason. any idea as to how to solve this?
Answer: http://jsfiddle.net/ktkdypyo/2/ you can add span inside h1 tag and then just give red color to span
html, body {
    width:100%;
    height:100%;
    font-size:100%;
    font-family:helvetica;
    font-weight:normal;
    font-style:normal;
}
h1 {
    text-align: center;

}
span{
  font-size: 5vh;
    line-height: 1;
    white-space: nowrap;
    background:red;
    color:white;
}

text is centered

but the width is 100%.

How can I make it so that the width

is only the widht of the text?

And your another question in the comments How can I make it so that when I hover over any of those texts, it fades out and gets replaced by a different text?
here is a working fiddle: http://jsfiddle.net/u7tYE/5060/
Comment: thanks for the solution, but when i scale down the window, the line-height increases. how can I fix that?
Comment: give the font-size in pixels  `font-size: 20px;`
Comment: but text needs to be responsive to the height. is there any way to solve this?
Comment: mediaquery.. if thats really very much required.. you can set different font-sizes for different heights.
Comment: thats a really awesome solution, but the line-height is still changing :/
Comment: no.. where is line height changing.. I dont see that in this fiddle
Comment: take a look: http://jsfiddle.net/kenhimself/u7tYE/5061/
you need to make sure you scale down the window of the code's result, not the browser window
Comment: define the font-size in `px`. then the line height wont change.. if you want line height not changing too much but still want font-size to be changing- try setting mediaquery for changing font.. things will work
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/68466/discussion-between-kenhimself-and-naeem-shaikh).
Answer: You need to wrap your text in a span and apply the background-color in span instead of h1. You can't use the same element because they are block-level element. You will need to put an inline-block element in a block-element to get the result you want.
For example

this is the entered text

CSS
span {
    background: red;
}

Comment: You're missing the point of the red background — when you highlight the text, regardless the red background is applied to span or h1, it still registers the width being 100%. aligning the text means it needs to have a left and right border — in this case, the border is the body & html.
Comment: Sorry, didn't read the question well. I thought it was about text highlight. Anyway, the explanation about block-level and inline-block element is still valid.
Comment: Please don't apologize! Many thanks for the feedback anyway :)
Answer: Question is already answered but adding
margin: 0 auto;
display: table;

to the css gets the job done without changing the markup. I've tested it on ie, chrome, mozilla and opera, seems okay on all.
Comment: I heard using tables is a bad idea these days and has been recommended to me numerous of times that it should be avoided. do you know why?
Comment: but you're not using table here. you're having h1 behave like a `table` element. in your markup it's still ``. using  element for layout is not a good idea as explained here: [link](http://phrogz.net/css/WhyTablesAreBadForLayout.html)
Comment: oh I see, thank you for the suggestion. however, when I scale down the window, the text responds to the height but the line-height increases.. any idea how to fix it? http://jsfiddle.net/kenhimself/ktkdypyo/7/


Print all li's children's text without getting sub children's for each li

Question: Hi I am trying to print all li's elements text without getting their sub children's text but I am not able to get proper result:
My HTML:
<!doctype html>

  <meta charset="utf-8">
  <title>child demo</title>

Item 1

Item 2

Nested item 1

Nested item 2

Nested item 3

Item 3

After the script is run I am getting weird things in arr:
The output comes like:
0:"Item 1"
1:"Item 2↵    ↵  "
2:"Item 3"

Can anybody explain me meaning of these arrows and how can I just only get the text of all li's.
I want my array to be:
0:"Item 1"
1:"Item 2"
2:"Item 3"

Where I am getting wrong?
Answer: The text covers the whole node, and it probably is reading the line-breaks in the child li also.
You could just use trim() to remove that like
var li = $("#abc > li");
 var arr = [];
 for(var i=0;i<li.length;i++){
   arr.push($(li[i]).clone().children().remove().end().text().trim());
 }
 console.log(arr);

Comment: Thank you. It's right I am just curious as this method takes lot of time. Is there a fast and a more efficient solution to do this?
Comment: I have also found one more solution: $( "ul.topnav > li" ).each(function( index ) {
  arr.push( $( this ).html().split("\n")[0]);
}); Is this one fast or the real one?
Comment: You haven't used `$(this)` ? I just noticed that right now!
Comment: The one you put just assumes that the line break will always be in the end ;)
trim will remove it from both sides.
Comment: That is okay but is there any more fast way to do this?
Comment: Don't think so, at least I am not aware of any, you could use vanillaJS method for textNodes but I am not sure it will make a huge difference.
Answer: I do not know if this is faster but is certainly more cleaner
var arr = [];
$('.topnav > li').filter(function() {
    var temp = $(this)[0].firstChild.data;
    arr.push(temp);
});

Comment: yes this is more cleaner but I just want to add in the solution here also while giving the data it gives you the nodes. So the correct will be arr.push(temp.trim()).


Picking interaction effects for PB design and Hamada-Wu analysis

Question: I am trying to use Plackett-Burman design to construct a design matrix for $OA(12, 2^{11})$. However, my experiment has only $6$ main effect factors. Similar to the well-known Cast Fatigue experiment, this means I would need to add 5 columns that correspond to the 5 unknown two-level interaction factors such that each of those 5 columns are orthogonal to any other column in the design matrix.
Question: do we have a particular way to pick which of the two-level interaction factors (there are $6C2 = 15$ of those factors) for these $5$ columns? Also, if we are only interested in finding out the significant main effects, would it be valid to pick the first 6 columns of the design matrix $OA(12, 2^{11})$, even though the dimension of $OA(12, 2^{11})$ is $12\times 11$?
On a related topic to PB design: does anyone happen to know of a concrete example that uses Hamada and Wu's analysis for PB design that you can share with me, particularly if such example has the accompanying code? I would love to see an example that uses R to conduct this analysis, as the theoretical description of their strategy is still abstract to me.
Comment: The interactions will be uniquely determined by the main effect levels, so you don't choose them separately from your choice of columns for main effects. Are you wanting to choose 6 of the 11 columns from the PB-12 run design?  Also, what does $\mathrm{OA}(12,2^11)$ mean?
Comment: Is it just a typo of $\mathrm{OA}(12, 2^{11})$?
Comment: @neverKnowsBest Thank you very much for your help. How do we know which interactions would be chosen by the main effect levels for column $7 - 11$ though? And yes, it was a typo. I fixed it.
Comment: There might still be some typos ...
Answer: You don't want to pick interactions first because you can choose AB, AC, and BC columns that are impossible (no A, B, and C columns can produce them so you can't run that experiment in the real world).  Also, if you have 6 main effects than there are 6 choose 2 (so 15) two-factor interactions.
The canonical approach is to pick the columns for the main effects first and then determine the properties of your estimators (including the estimators for interaction).  But even here we have a problem, since the full model with two-factor interactions has 22 terms but you're only collecting data from 12 distinct points, and thus no orthogonal design can exist.  But we can choose the least bad design in some sense. Let's continue.
Plackett-Burman designs are nongeometric designs that have partially aliased terms.  See section of 8.6.3 of Design and Analysis of Experiments, 9ed (2019) by Montgomery for discussion.  Also section 8.4 of Experiments: Planning, Analysis and Optimization, 2ed (2009) by Wu and Hamada is also a good resource. I'm sure Box, Hunter, and Hunter is also a good resource but it's stuck in my garage right now.
For concreteness I'll use some R code to show the design and the resulting properties of the 2 factor interaction estimates.  Plackett-Burman designs can be generated with the FrF2 package.  As in the comment I'll choose the last 6 columns for my main effects.  The design matrix below gives the conditions for each of the 12 runs.
> library(FrF2)
> design <- pb(12)[,6:11]
> print(design)
     F  G  H  J  K  L
 1   1 -1  1  1 -1  1
 2  -1 -1 -1 -1 -1 -1
 3  -1 -1  1 -1  1  1
 4  -1 -1 -1  1 -1  1
 5   1  1 -1 -1 -1  1
 6   1 -1 -1 -1  1 -1
 7  -1  1  1  1 -1 -1
 8   1  1  1 -1 -1 -1
 9   1 -1  1  1  1 -1
 10 -1  1  1 -1  1  1
 11  1  1 -1  1  1  1
 12 -1  1 -1  1  1 -1

We can build the model matrix as follows
X <- model.matrix(
    ~ .:.,            # This tells R to look at all main effects and 2 factor interactions
    data=design
)

There are 462 possible choices of 6 columns from the 11 columns in the PB design.
There are many ways to look at these designs in order to pick one. Let's look at "$D$-optimality" which seeks to minimize the determinant of the covariance matrix for the parameter estimates of the given design.
The determinant of the covariance matrix has the property that:
$$
\left|\left(\mathbf{X}^\mathrm{T} \mathbf{X}\right)^{-1}\right|
=
\frac{1}{
\left|\mathbf{X}^\mathrm{T} \mathbf{X}\right|
}
$$
so a reasonable choice of columns are those that maximize $\left|\mathbf{X}^\mathrm{T} \mathbf{X}\right|$ and hence minimize the determinant of the covariance matrix.
In R I can simply enumerate these and choose the best ones.
 design <- pb(12)
 columns <- combn(1:11, 6)
 d.criteria <- apply(
    columns,            # Look at all 462 combinations of 6 columns
    2,
    function(ix){
        X <- model.matrix(
            ~ .:.,
            data=design[,ix]
        )
        return(det(t(X) %*% X))
    }
 )

and then select the best (there are 12 of them)
> ix <- which(d.criteria == max(d.criteria))
> good.columns <- columns[,ix]
> print(good.columns)
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]    1    1    1    1    1    1    1    2    2     2     2     3
 [2,]    2    2    2    3    3    4    5    3    4     4     5     5
 [3,]    3    4    4    4    5    5    7    5    5     6     6     6
 [4,]    5    5    8    6    7    6    8    6    7     8     7     8
 [5,]    6    7   10    8    8    7    9    8    9     9     8    10
 [6,]   11   10   11    9   10   10   11   11   10    11    11    11

One such good design is to choose columns 1, 2, 3, 5, 6, and 11.  This design is about 21% more efficient than just choosing the last 6 columns (in terms of $D$-criterion).
In the above cited books I'd suggest reading about aliasing and the Alias matrix so you can see how the design will affect the expected value of your estimators. My advice is to read at least one of the above sources and play around - hopefully the R code can help with that.