RAID configuration of a Sun Blade X6270 M2 Server Module

Question: One Sun Blade X6270 M2 server module has four 146GB disks, but the running RHEL5-x64 O.S. finds only a 146GB disk. I guess two from the four disks are a RAID 1 volume -- the one found by O.S; and the two remaining disks are unused.
I need a tool to (at least) display the current RAID configuration and configure the other two disks to create a new RAID volumen and make it available to the O.S.
Do you know any tool to achieve this?
I tried to use the ILOM-CMM but I find no disk drive information.
Thanx in advance
Answer: sas2ircu is an Avago Technology tool to get that information. No instalation is required -- the tool is a single binary (click here to browse its download page).
<code># ./sas2ircu
LSI Corporation SAS2 IR Configuration Utility.
Version 11.00.00.03 (2011.10.14) Copyright (c) 2009-2011
LSI Corporation. All rights reserved.

SAS2IRCU: No command specified.
  sas2ircu <controller #> <command> <parameters> ...
    where <controller #> is:
      Number between 0 and 255
    where <command> is:
      DISPLAY    - display controller, volume and physical device info
      LIST       - Lists all available LSI adapters (does not need ctlr #>
      CREATE     - create an IR volume
      DELETE     - Delete entire RAID configuration on the selected controller
      DELETEVOLUME  - Delete a specific RAID Volume on the selected controller
      HOTSPARE   - make drive a hot spare
      STATUS     - display current volume status info
      CONSTCHK   - Start Consistency Check operation on the specified IR Volume
      ACTIVATE   - Activate an Inactive IR volume
      LOCATE     - Locate a disk drive on an enclosure
      LOGIR      - Upload or Clear IR Log data
      BOOTIR     - Select an IR Boot Volume as primary boot device
      BOOTENCL   - Select an Enclosure/Bay as primary boot device
      HELP       - Display help information
    where <parameters> are:
      Command specific values; enter "sas2ircu <controller #> <command>"
      to get command specific help
</code>
sas2ircu commands need a controller number (or index). That controller number is given by the list command:
<code># ./sas2ircu list
LSI Corporation SAS2 IR Configuration Utility.
Version 11.00.00.03 (2011.10.14)
Copyright (c) 2009-2011 LSI Corporation. All rights reserved.

         Adapter      Vendor  Device                       SubSys  SubSys
 Index    Type          ID      ID    Pci Address          Ven ID  Dev ID
 -----  ------------  ------  ------  -----------------    ------  ------
   0       SAS2008     1000h    72h   00h:01h:00h:00h      1000h   3180h
</code>
One you know the controller ID, you can use the status command to get information about the RAID volume:
<code># ./sas2ircu 0 status
LSI Corporation SAS2 IR Configuration Utility.
Version 11.00.00.03 (2011.10.14)
Copyright (c) 2009-2011 LSI Corporation. All rights reserved.

Background command progress status for controller 0...
IR Volume 1
  Volume ID                               : 902
  Current operation                       : None
  Volume status                           : Enabled
  Volume state                            : Optimal
  Volume wwid                             : 0c73f86fdc7305cf
  Physical disk I/Os                      : Not quiesced
SAS2IRCU: Command STATUS Completed Successfully.
SAS2IRCU: Utility Completed Successfully.
</code>
Or use the display command to get all details:
<code># ./sas2ircu 0 display
LSI Corporation SAS2 IR Configuration Utility.
Version 11.00.00.03 (2011.10.14)
Copyright (c) 2009-2011 LSI Corporation. All rights reserved.

Read configuration has been initiated for controller 0
------------------------------------------------------------------------
Controller information
------------------------------------------------------------------------
  Controller type                         : SAS2008
  BIOS version                            : 7.03.04.00
  Firmware version                        : 4.05.52.00
  Channel description                     : 1 Serial Attached SCSI
  Initiator ID                            : 0
  Maximum physical devices                : 831
  Concurrent commands supported           : 1775
  Slot                                    : 0
  Segment                                 : 0
  Bus                                     : 1
  Device                                  : 0
  Function                                : 0
  RAID Support                            : Yes
------------------------------------------------------------------------
IR Volume information
------------------------------------------------------------------------
IR volume 1
  Volume ID                               : 902
  Status of volume                        : Okay (OKY)
  Volume wwid                             : 0c73f86fdc7305cf
  RAID level                              : RAID1
  Size (in MB)                            : 139236
  Physical hard disks                     :
  PHY[0] Enclosure#/Slot#                 : 1:0
  PHY[1] Enclosure#/Slot#                 : 1:1
------------------------------------------------------------------------
Physical device information
------------------------------------------------------------------------
Initiator at ID #0

Device is a Hard disk
  Enclosure #                             : 1
  Slot #                                  : 0
  SAS Address                             : 5000cca-0-0ad9-9d21
  State                                   : Optimal (OPT)
  Size (in MB)/(in sectors)               : 140009/286739328
  Manufacturer                            : HITACHI
  Model Number                            : H103014SCSUN146G
  Firmware Revision                       : A2A8
  Serial No                               : 001039FVP2DE
  GUID                                    : 5000cca00ad99d20
  Protocol                                : SAS
  Drive Type                              : SAS_HDD

Device is a Hard disk
  Enclosure #                             : 1
  Slot #                                  : 1
  SAS Address                             : 5000cca-0-0ad9-6fd5
  State                                   : Optimal (OPT)
  Size (in MB)/(in sectors)               : 140009/286739328
  Manufacturer                            : HITACHI
  Model Number                            : H103014SCSUN146G
  Firmware Revision                       : A2A8
  Serial No                               : 001039FVL1WE
  GUID                                    : 5000cca00ad96fd4
  Protocol                                : SAS
  Drive Type                              : SAS_HDD

Device is a Hard disk
  Enclosure #                             : 1
  Slot #                                  : 2
  SAS Address                             : 5000cca-0-0ad7-ed1d
  State                                   : Hot Spare (HSP)
  Size (in MB)/(in sectors)               : 140009/286739328
  Manufacturer                            : HITACHI
  Model Number                            : H103014SCSUN146G
  Firmware Revision                       : A2A8
  Serial No                               : 001039FUS9HE
  GUID                                    : 5000cca00ad7ed1c
  Protocol                                : SAS
  Drive Type                              : SAS_HDD

Device is a Hard disk
  Enclosure #                             : 1
  Slot #                                  : 3
  SAS Address                             : 5000cca-0-0ad8-59d9
  State                                   : Hot Spare (HSP)
  Size (in MB)/(in sectors)               : 140009/286739328
  Manufacturer                            : HITACHI
  Model Number                            : H103014SCSUN146G
  Firmware Revision                       : A2A8
  Serial No                               : 001039FUZJZE
  GUID                                    : 5000cca00ad859d8
  Protocol                                : SAS
  Drive Type                              : SAS_HDD
------------------------------------------------------------------------
Enclosure information
------------------------------------------------------------------------
  Enclosure#                              : 1
  Logical ID                              : 500605b0:028cd7c0
  Numslots                                : 8
  StartSlot                               : 0
------------------------------------------------------------------------
SAS2IRCU: Command DISPLAY Completed Successfully.
SAS2IRCU: Utility Completed Successfully.
</code>
Here you can see the RAID configuration of the internal SAS disks: 2 disks for the RAID-1 volume and the 2 hot spare disks.

Thanks to Pascal Kreyer answer for his help.
Comment: And for complete access, look for a copy of `lsiutil` - but if you go that route, be careful. `lsiutil` can brick your hardware.
Comment: @Andrew, unlike **`sas2ircu`**, **`lsiutil`** does not provide information about the RAID configuration -- it merely displays the RAID disks. Thanks for your help, anyway :)
Comment: *`lsiutil` does not provide information about the RAID configuration -- it merely displays the RAID disks. Thanks for your help, anyway* Per the user guide: [Option 21 RAID Actions, suboption 1 Show Volumes](https://www.thomas-krenn.com/de/wikiDE/images/4/44/Lsi_userguide_2006_20130528.pdf)  Here's an [example](http://www.unixarena.com/2015/05/how-to-rebuild-hardware-raid-from-os-level.html).  Do you have anything else to add?
Comment: @Andrew, just apologies and a request -- you appear to master the **``lsiutil``** tool. Why does you not add an answer in order to be properly rewarded?
Comment: I have no problem to admit my first comment was a mistake and I would want your help to be recognized as useful as Pascal Kreyer's is. I think your contribution is worthy to appear like an answer, not just like a simple comment.


JS export excel file - File corrupted

Question: I'm having trouble exporting an excel file that's being generated in my NETCORE 3.1 server.
I have to do a POST request to it.
Here is the code
JS:
function exportRelatorio(tabela) {

var data = JSON.stringify(tabela);

$.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: "/Relatorios/ExportRelatorio/",
    data: JSON.stringify(data),
    success: function (result) {
        var blob = new Blob(
            [result],
            { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," }
        );

        // Programatically create a link and click it:
        var a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = "circuitos.xlsx";
        a.click();

    },
});

}
Server Code:
[HttpPost]
        public IActionResult ExportRelatorio([FromBody] string data)
        {
            var relatorios = JsonConvert.DeserializeObject<List<Relatorio>>(data);
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            string fileName = "GestãoCircuitos-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx";
            try
            {
                using (var workbook = new XLWorkbook())
                {
                    IXLWorksheet worksheet = workbook.Worksheets.Add("Relatórios");
                    worksheet.Cell(1, 1).Value = "Data";
                    worksheet.Cell(1, 2).Value = "Matricula";
                    worksheet.Cell(1, 3).Value = "Condutor";
                    worksheet.Cell(1, 4).Value = "Rota";
                    worksheet.Cell(1, 5).Value = "Distância Ideal";
                    worksheet.Cell(1, 6).Value = "Kms";
                    worksheet.Cell(1, 7).Value = "Diferencial";
                    worksheet.Cell(1, 8).Value = "Desvio (%)";
                    worksheet.Cell(1, 9).Value = "Tempo de Condução";
                    for (int index = 1; index <= relatorios.Count; index++)
                    {
                        worksheet.Cell(index + 1, 1).Value = relatorios[index - 1].Data;
                        worksheet.Cell(index + 1, 2).Value = relatorios[index - 1].Viatura;
                        worksheet.Cell(index + 1, 3).Value = relatorios[index - 1].Condutor;
                        worksheet.Cell(index + 1, 4).Value = relatorios[index - 1].Rota;
                        worksheet.Cell(index + 1, 5).Value = relatorios[index - 1].DistanciaIdeal;
                        worksheet.Cell(index + 1, 6).Value = relatorios[index - 1].Kms;
                        worksheet.Cell(index + 1, 7).Value = relatorios[index - 1].Dif;
                        worksheet.Cell(index + 1, 8).Value = relatorios[index - 1].Desvio;
                        worksheet.Cell(index + 1, 9).Value = relatorios[index - 1].TempoConducao;
                    }
                    using (var stream = new MemoryStream())
                    {
                        workbook.SaveAs(stream);
                        var content = stream.ToArray();
                        return File(content, contentType, fileName);
                    }
                }

            }
            catch (Exception ex)
            {
                return View();
            }
    }

It gives me a file corrupted message when I open the downloaded file.
The excel error message says excel cannot open the file because the format or extension are not valid.
What am I doing wrong?
Answer: $.ajax doesn't seem to be able to deal with binary data.
You might want to try the fetch() API with native blob support instead.
Also, I added some cleanup here.
async function exportRelatorio(tabela) {
    const resp = await fetch("/Relatorios/ExportRelatorio/", {
        body: JSON.stringify(tabela),
        credentials: 'same-origin',
        method: 'POST',
        headers: {
            "Content-Type": 'application/json; charset=utf-8',
        },
    });
    if(!resp.ok) throw new Error("Not OK");
    const blob = await resp.blob();
    // Programatically create a link and click it:
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "circuitos.xlsx";
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {  // Clean up
        URL.revokeObjectURL(a.href);
        a.parentNode.removeChild(a);
    }, 1000);
}

Comment: Oops, I forgot `method: 'POST'`.
Comment: it gives me this Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
    at exportRelatorio (site.js?v=5xX4gJKPY3gfDGyOLiFigwQFjBCzZVADmZpcWj30iSQ:59)
    at HTMLButtonElement.onclick (Relatorios:1)
Comment: Almost there, now my argument in the server side, data, comes null ..
Comment: can you help,please?
Comment: Can you see your browser still posting the data in your browser's inspector?

JS export excel file - File corrupted


How to include task links in twig node template

Question: I have created a custom twig node template. It displays the content in the manner that I want but it is not displaying the task buttons. How do I include the display of the task buttons if the user who is viewing the page has the permission to see them?
I have tried Googling for a solution, but haven't found anything. I figure this should be pretty straight forward to do (at least I would hope it is).
Thanks.
Answer: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links
The manual says:
Contextual links are stored in title_suffix. This variable needs to be printed in the html.twig file, such as in this example from block.links.contextual.yml.
<code><div{{ attributes }}>
  {{ title_suffix }}
  ...
</div>
</code>


Htaccess HTTPS redirection

Question: I'm trying to get my .htaccess file to redirect only certain pages/folders to https and if its not the pages that need to be encrypted then it should shoot the user the the http page. Also I would like to be able to list certain folders that can either be HTTP or HTTPS
Here is what I tried using writing up myself. But seemed to not work all correctly.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

RewriteCond %{SERVER_PORT} 80
RewriteCond $1 ^(myaccount|payment\.html)
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

RewriteCond %{SERVER_PORT} 443
RewriteCond $1 !^(myaccount|payment\.html)
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
</IfModule>

Answer: You're checking a literal $1 in your RewriteCond patterns. It should be:
RewriteCond %{REQUEST_URI} ...stuff to match against here...

Answer: This should do what you want.
RewriteCond %{SERVER_PORT} 443 [NC]
RewriteCond %{REQUEST_URI} !^/(myaccount|payment)\.html [NC]
RewriteRule . http://www.domain.com/%{REQUEST_URI}/ [R=301,L]

Htaccess HTTPS redirection


Prove $\sqrt{x-1} + \sqrt{y-1} \le xy, x \ge 1, y \ge 1$

Question: Let $x$ and $y$ be real numbers, such that $x \ge 1$ and $y \ge 1$.
Prove that this inequality is true: $\sqrt{x-1} + \sqrt{y-1} \le xy$
Can someone show me steps to solve it.
PS:I need to give steps on how to solve it.
Comment: "logic"???.............
Comment: @MauroALLEGRANZA => yes, I have to solve it while showing the steps logically not just here is the solution.
Comment: A mathematical logic course is a incredibly different beast, to explain Mauro's comment
Comment: @FShrike yes we study a subject in it and we get some simple logic problems like here is this propositions show that they are true or false ...
and prove that
but one of those questions was this above
which I have to show that I understand {conjunction and disjunction} by proving that the inequality above is true for all x >=1 and y>=1...

PS: my english is bad so I can't explain here a lot in english I just try
Comment: One way to show it is with calculus. This is probably a bit overkill, but do you know about differentiation and the identification of turning points / increasing properties?
Answer: Both sides are positive. So it is an equivalent inequality to the one you get from squaring both sides.
Then do some algebra to isolate a square root again. It should look like:
$$2\sqrt{(x-1)(y-1)} ≤ x^2y^2 - x - y + 2$$
But since $x\geq1$, then $x^2\geq x$ and similar for $y$. So it suffices to show
$$2\sqrt{(x-1)(y-1)} ≤ xy - x - y + 2=(x-1)(y-1)+1$$
Now you have a situation where $c$ is some positive number and you need to show that $2\sqrt{c}\leq c+1$. Can you do this last step?
Comment: @hikarujakafura When I see an equation or inequality with two radicals like this one, I consider arranging things so the two radicals are alone on one side, and then squaring will reduce to only having one radical. Repeat that and you can have no radicals. You have squared twice so the terms may be messy now. But sometimes it helps clear some things up. This is what first occurred to me to look into.
Comment: isn't in the first inequality you wrote, there should be 2$\sqrt((x-1)(y-1))$ I think you forgot the 2 there, but I understand the idea of what you did if you can explain what to do with that 2
Comment: @hikarujakafura Thanks, good eye for detail. Keeping track of that $2$ doesn't chage things, it turns out.
Comment: @ 2'59'2  okk thank you for this solution, I want to ask you something I see a lot of people use (Am gm, ...) these techniques to solve inequalities , did you use any of those techniques here or how did you come to think of the solution , because sometimes I take days with one problem I can't solve it until someone gives me the solution
Comment: ok thank you so much
Answer: Using Cauchy Schwarz and AM-GM
$$\sqrt{x-1}+\sqrt{y-1} \le \sqrt{2(x+y-2)} \le \frac{2(x+y-2)+1}{2} \le x+y-1 $$
Now it suffices to prove that
$$x+y-1 \le xy$$
Wich is equivalent to $$(x-1)(y-1) \ge 0$$
So we are done.
Comment: thank you so much this really some good information I'm getting on this website I really appreciate it
Answer: you can use schwartz inequality directly
we know ;$a_1 b_1+a_2b_2 \leq \sqrt{a_{1}^2+a_{2}^2} \sqrt{b_{1}^2+b_{2}^2}$
just put $a_1 =\sqrt{x-1}$
$a_2 =1$
$b_1 =1$
and
$b_2 =\sqrt{y-1}$
so you will get ;$\sqrt{x-1} .1+1.\sqrt{y-1} \leq \sqrt{x-1+1}\sqrt{y-1+1}=\sqrt{xy}$


puppet 2.6.4 .deb package

Question: Is there any 3rd party repositories that keeps up to date puppet client versions? I am looking for a puppet 2.6.4 .deb package?
Comment: for which distro/release?
Answer: If by "third party" you mean "not the puppet developers", Launchpad has one for Natty Narwhal; the "Published versions" sections has links for e.g. puppet 2.6.4-2ubuntu1 in i386, puppet 2.6.4-2ubuntu1 in amd64.
Answer: Official up to date version can be found from Debian Wheezy (testing) repository at http://packages.debian.org/wheezy/puppet.
You don't mention the distribution you use, but here's instructions for Debian Squeeze.
How to use up to date version of Puppet in Debian Squeeze (stable)?
Create a file /etc/apt/apt.conf.d/20release with content:
APT::Default-Release "stable";

Create a file /etc/apt/preferences.d/20puppet with content:
Package: *
Pin: release a=testing
Pin-Priority: 1

Package: puppet
Pin: release a=testing
Pin-Priority: 1001

Package: puppet-common
Pin: release a=testing
Pin-Priority: 1001

Package: puppetmaster
Pin: release a=testing
Pin-Priority: 1001

Package: puppetmaster-common
Pin: release a=testing
Pin-Priority: 1001

Create a file /etc/apt/sources.list.d/20testing.list with content:
deb http://ftp.debian.org/debian/ testing main

Run:
apt-get update
apt-get dist-upgrade

Comment: mixing packages from testing into a stable release is a bad idea.  especially is security is a concern
Answer: Debian backports has puppet 2.6.4 in their repository now.
http://packages.debian.org/lenny-backports/puppet

puppet 2.6.4 .deb package


Atualizando dados de gráficos já instanciados

Question: Estou utilizando o Google Charts e estou precisando atualizar um mapa que ja está instanciado como um mapa valido, na verdade quero quando clicar no botão atualizar os dados de dentro de um mapa.
Hoje estou fazendo da seguinte maneira:
var dataGraf = google.visualization.arrayToDataTable(parsVal);
var chart = document.getElementById('curve_chart');
chart.draw(dataGraf);

Porém nada acontece. Para eu instanciar meu mapa utilizei os seguintes comandos:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable(parsVal);
  var options = {
    title: 'Membros x Visitantes',
    curveType: 'function',
    legend: { position: 'bottom' }
  };
 var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
 chart.draw(data, options);
}

Como posso fazer para atualizar, justamente quando clico no botão. Lembrando que meu dataGraf tem meu array com os novos valores.
Fiz um JsFiddle para exemplificar meu problema.
Answer: Quando clicar no botão você redesenha o gráfico inteiro.
$("#botaoAtualizar").click(function(){
    redrawChart();
});

Usa a função que você já fez passando os novos dados.
function drawChart() {

  var dataGraf = google.visualization.arrayToDataTable(parsVal);

  var options = {
    title: 'Membros x Visitantes',
    curveType: 'function',
    legend: { position: 'bottom' }
  };

 var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
 chart.draw(dataGraf, options);

}


Ícone fica pequeno na notificação

Question: Estou com uma notificação simples,porém o ícone não preenche toda a parte. Gerei ele através do Android Asset e coloquei cada resolução em sua respectiva pasta no mipmap.
Notificação Android 4.1

Notificação Android 5.0

Notification noti = new Notification.Builder(MainActivity.this).
                setTicker("BPF Denúncia")
                .setContentTitle("BPF Denúncia")
                .setContentText("Há Uma Nova Denúncia Contra Você!")
                .setSmallIcon(R.mipmap.notification)
                .setContentIntent(pIntent).getNotification();

Como resolver para que preencha todo o espaço da Notificação ?
Comment: Pode mostrar um exemplo de como gostaria que fosse?
Comment: Queria que ele preenchesse toda a parte.Se eu tenho um ícone retangular,em vez de ele por o ícone dentro de outro,o icone em si preenchesse tudo,sem ficar borda nenhuma.,aqui um exemplo usando o mesmo ícone:https://s31.postimg.org/n07w0y6l7/image.png
Comment: Outro Exemplo,agora ele está fazendo isso:
https://s31.postimg.org/57goqfu0n/atual.png

o certo,seria isto:
https://s31.postimg.org/psvgicblj/novo.png
Answer: Você precisa definir qual é o ícone grande da sua notificação com setLargeIcon. Se você não definir, o pequeno é usado no lugar e não cresce sozinho.
Comment: Obrigado,fiz isto e funcionou !

Ícone fica pequeno na notificação


Spivak, Ch. 15, Trigonometric Functions", Proof of $\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha \sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$.

Question: The following problem is from Chapter 15 "Trigonometric Functions" from Spivak's Calculus

Prove that

$$\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha
 \sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$$
indicating any restrictions on $\alpha$ and $\beta$.

My question is about the restrictions on $\alpha$ and $\beta$. I will show the solution from the solution manual first, and then specify my question.
Here is the solution manual solution

From the addition formula for $\sin$ we obtain, for $|\alpha|\leq 1$
and $|\beta|\leq 1$,
$$\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\sin{(\arcsin{\alpha})\cos{(\arcsin{\beta})}}+\cos{(\arcsin{\alpha})\sin{(\arcsin{\beta})}}$$
$$=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}$$

Note that though it is not mentioned a significant step is taken in showing that
$$\cos{(\arcsin{x})}=\sqrt{1-x^2}$$
This is done by computing the derivative of $\sin(x)$ as the reciprocal of the derivative of $\arcsin$ at $\sin{x}$.

Consequently
$$\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}\tag{1}$$
provided that $-\pi/2\leq\arcsin{\alpha}+\arcsin{\beta}\leq\pi/2$. [If
$\pi/2<\arcsin{\alpha}+\arcsin{\beta}\leq \pi$, the right side must be
replaced with
$\pi-\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$, and if
$-\pi\leq \arcsin{\alpha}+\arcsin{\beta}\leq -\pi/2$, replaced with
$-\pi-\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$.]

My question is about the last paragraph.
Let's start at the point where we have
$$\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}$$
and we want to take the $\arcsin$ of each side to obtain $(1)$.
Now, $\arcsin{\alpha}$ and $\arcsin{\beta}$ are each in $(-\pi/2, \pi/2)$. Their sum is in $(-\pi, \pi)$, and the whole left expression is thus in $[-1,1]$.
$\pm 1$ occur when $\arcsin{\alpha}+\arcsin{\beta}=\pm \frac{\pi}{2}$.
If one of these two cases occurs, then $\arcsin$ isn't defined for $\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\pm 1$.
EDIT: the sentence above is is incorrect. I confused $\arcsin$ with its derivative $\arcsin'$.
So my first question is about the following snippet of the solution manual solution

provided that $-\pi/2\leq\arcsin{\alpha}+\arcsin{\beta}\leq\pi/2$

where the values $\pi/2$ and $-\pi/2$ are included in the possibilities. Are these values really allowed?
EDIT: given the first edit above, yes, these values are allowed.
My second question is about the discussion when $\pi/2<\arcsin{\alpha}+\arcsin{\beta}\leq \pi$ or $-\pi\leq \arcsin{\alpha}+\arcsin{\beta}\leq -\pi/2$. What is happening in these cases, I don't know what Spivak's solution manual did there.
Comment: "If one of these two cases occurs, then arcsin isn't defined for sin(arcsinα+arcsinβ)=±1." I am not getting how you commented this.
Comment: You know what, I think I have been staring at these functions for too long today, and I have confused the derivative of $\arcsin$ with $\arcsin$ itself.
Comment: This silly mistake solves the first question, but the second question remains.
Comment: For the second question, while taking arcsin on both sides of $\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}$,we have to make cases as  $\sin${($\arcsin${$\alpha$}=$\alpha$ only when  $\pi/2 \leq$ $\alpha$ $\leq\ \pi/2$.
Answer: I'd start from the conditions first.
When it exists, the right-hand side is an angle in the interval $[-\pi/2,\pi/2]$, so the left-hand side must as well.
The existence condition is (with $a=\alpha,b=\beta$ for ease of typing)
$$
\textstyle \lvert\, a\sqrt{1-b^2}+b\sqrt{1-a^2}\,\rvert\le 1\tag{*}
$$
In particular, $|a|\le1$ and $|b|\le1$, but this was already known from examining the left-hand side.
Condition (*) is satisfied for $|a|\le 1$ and $|b|\le 1$ by using Cauchy-Schwarz with the vectors
$$
\textstyle v=(a,\sqrt{1-a^2}\,)\qquad w=(\sqrt{1-b^2},b)
$$
and the standard CS inequality $|v\cdot w|\le\|v\|\,\|w\|$ becomes
$$
\textstyle \lvert\, a\sqrt{1-b^2}+b\sqrt{1-a^2}\,\rvert\le\sqrt{a^2+1-a^2}\sqrt{1-b^2+b^2}=1
$$
OK, this leaves only the condition that
$$
-\frac{\pi}{2}\le \arcsin a+\arcsin b\le\frac{\pi}{2} \tag{**}
$$
Under this condition, we can take the sine of both sides. From the left-hand side we get
$$
\textstyle
\sin(\arcsin a)\cos(\arcsin b)+\cos(\arcsin a)\sin(\arcsin b)
=a\sqrt{1-b^2}+b\sqrt{1-a^2}
$$
because, for $|x|\le 1$, we have
$$
\textstyle\cos(\arcsin x)=\sqrt{1-\sin^2(\arcsin x)}=\sqrt{1-x^2}
$$
because $-\pi/2\le\arcsin x\le\pi/2$ and so $\cos\arcsin x\ge0$.
Thus we conclude that, for $|a|\le1$ and $|b|\le 1$,

$\arcsin a+\arcsin b=\arcsin\bigl(a\sqrt{1-b^2}+b\sqrt{1-a^2}\,\bigr)$ if and only if $\lvert\arcsin a+\arcsin b\rvert\le \pi/2$
Answer: Let's start at the point where we have
$$\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}\tag{1}$$
and we want to take the $\arcsin$ of each side to obtain $(1)$.
First, let's just note that $\alpha$ and $\beta$ are each in $[-1,1]$, and thus $\arcsin{\alpha}$ and $\arcsin{\beta}$ are each in $[-\pi/2,\pi/2]$. The sum $(\arcsin{\alpha}+\arcsin{\beta})$ is thus in $[-\pi,\pi]$.
We need to consider what happens for all such possible values of $(\arcsin{\alpha}+\arcsin{\beta})$.
Case 1: $-\pi/2\leq \arcsin{\alpha}+\arcsin{\beta}\leq\pi/2 $
The equation
$$\arcsin{(\sin{(\arcsin{\alpha}+\arcsin{\beta})})}=\arcsin{\alpha}+\arcsin{\beta}\tag{2}$$
is true.
We can thus take the $\arcsin$ of both sides of $(1)$ and end up with
$$\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$$
Case 2: $\pi/2\leq \arcsin{\alpha}+\arcsin{\beta}\leq\pi $
Equation $(2)$ is no longer true (indeed, it doesn't even make sense because of the domain of $\arcsin$).
However, it is true that $\sin{x}=\sin{\pi-x}$. Thus,
$$(\pi-\arcsin{\alpha}-\arcsin{\beta}) \in (-\pi/2,0]$$
and
$$\sin{(\pi-\arcsin{\alpha}-\arcsin{\beta})}=\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}\tag{3}$$
Now it is true that
$$\arcsin{(\sin{(\pi-\arcsin{\alpha}-\arcsin{\beta})})}=\pi-\arcsin{\alpha}-\arcsin{\beta}$$
So we can take the $\arcsin$ of the first and last expressions in $(3)$ to obtain
$$\pi-\arcsin{\alpha}-\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$$
and the desired
$$\arcsin{\alpha}+\arcsin{\beta}=\pi-\arcsin{(\alpha\sqrt{1-\beta^2}-\beta\sqrt{1-\alpha^2})}$$
Case 3: $-\pi\leq \arcsin{\alpha}+\arcsin{\beta}<-\pi/2$
This case is similar to case 2. Since
$$\sin{(-\pi-x)}=\sin{x}$$
we have that
$$(-\pi-\arcsin{\alpha}-\arcsin{\beta}) \in (-\pi/2,0]$$
$$\sin{(-\pi-\arcsin{\alpha}-\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}\tag{3}$$
and taking the $\arcsin$ of each side we obtain
$$-\pi-\arcsin{\alpha}-\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}-\beta\sqrt{1-\alpha^2})}$$
$$\arcsin{\alpha}+\arcsin{\beta}=-\pi-\arcsin{(\alpha\sqrt{1-\beta^2}-\beta\sqrt{1-\alpha^2})}$$
$\blacksquare$
Spivak's solution manual sure does skip a lotta steps.
Answer: HINT

$\arcsin(\sin\alpha)=\alpha$ only when $\alpha\in[-\frac\pi2,\frac\pi2]$

$\arcsin(\sin\alpha)=\pi-\alpha$ when $\alpha\in[\frac\pi2,\pi]$

$\arcsin(\sin\alpha)=-\pi-\alpha$ when $\alpha\in[-\pi,-\frac\pi2]$


Are duplicate http header names supported in .net 4?

Question: I noticed when consuming my simple resource (listed below) that i am able to get the Accept header by referencing "WebOperationContext.Current.IncomingRequest.Accept" although to conform to a specification I need to iterate over all the provided Accept headers names, although it appears WCF only returns the first one it finds.
 [WebGet(UriTemplate = "system", ResponseFormat = WebMessageFormat.Json)]

If i put all of the header name values into one string and separate by commas, it works. But that's not the issue I'm talking about here.
I would say that it is what it is, although http://www.faqs.org/rfcs/rfc2616.html section 4.2 indicates that multiple header names are permitted as long as their values can be joined by a comma and still be proper syntax (which it can be).
So it's funny to me that this would not be supported. Am I missing something?
Answer: I haven't tested this at all, but have you tried WebOperationContext.Current.IncomingRequest.Headers["Accept"]?
I know that if you call WebHeaderCollection.Add multiple times for the same header it will concatenate them with commas where appropriate. But in theory it could be that the IncomingWebRequestContext stores the first Accept header separately, since it is just a convenience property and may only work with the common case of only one Accept header.
Comment: Thanks for your reply Gerald. I have iterated through the WebOperationContext.Current.IncomingRequest.Headers when I was positive there were duplicate Accept names coming through and there was only one Accept in the collection. But to your question I have yet to explicitly check the ["Accept"].
Comment: Thanks again, it seems that 'WebOperationContext.Current.IncomingRequest.Headers.GetValues("Accept");' works fine.


ADI and CoV - Move thresholds based on dataset?

Question: I am currently working on demand forecasting. During my research online I came to know about methods used to classify demand which helps us to focus on series which have better forecasting ability etc. So, the classification of demand happens mainly based on Coefficient of Variation (CoV), Average Demand Interval (ADI). This leads us to analysis like ABC XYZ segmentation and demand classification like - Intermittent, Lumpy, erratic, Smooth etc.
does all the above approaches work makes sense only when they have fixed thresholds like I often see in online are fixed and they all use the same threshold cut-off (at least based on my exposure of articles online). You can refer here and here
1.Smooth demand (ADI < 1.32 and CV² < 0.49)
2.Intermittent demand (ADI >= 1.32 and CV² < 0.49)
3.Erratic demand (ADI < 1.32 and CV² >= 0.49)
4.Lumpy demand (ADI >= 1.32 and CV² >= 0.49)
So, my question,
a) should these thresholds be alerted to reflect our dataset? For ex: Can I run a 1D-Kmeans clustering on CV and identify the natural breaks in my data to come up with XYZ segmentation or demand classification ADI or CV**2? For ex - I get 0.95, 2.6 and 3.31 as CoV value limit for X, Y and Z. Average CoV is 1.67. Is this right thing to do or should I just stick to fixed limits given online?
b) Should we compute average sales only by considering the active period (non-zero sales time periods) or full time period (using time periods when customer was inactive)
Comment: Sorry it took me a while to get to this...
Comment: I am grateful for your help and for sharing knowledge with the community
Comment: @StephanKolassa - I have read some of your academic articles/books online, is it possible that you can help me with academic related question - https://academia.stackexchange.com/questions/206070/semiconductor-industry-specific-journals-for-applied-data-science-low-to-med-i
Answer: These limits are absolutely not cast in stone. They go back to work by Aris Syntetos and John Boylan about 15 years ago on classifying demand as intermittent, lumpy or continuous, and rely essentially on one or very few datasets. There is no particular reason why these specific limits should work well for new datasets - and what "working well" means is already something one can argue about. You do find time series that are classified as "intermittent" based on these limits, but that anyone eyeballing them would classify as "lumpy".
So by all means, go ahead and choose other thresholds. Clustering is one way. Another one is to just play around with possible limits until you get a "good" result. Keep in mind that this classification is just a means to an end, so be mindful of what a "good" result is.
Average sales, in this classification, are calculated across all time periods. (Cutting off spurious zeros at the beginning when the product is not available, of course.) If you remove zeros, then you can't very well classify the series as intermittent or lumpy any more.
And that already leads us to a shortcoming of this simple classification: it will happily classify a series as intermittent or lumpy that absolutely isn't, because there are patterns to zeros, patterns which this method does not even look at. Here is an example of "intermittent" data (because it has "many zeros"), which is actually seasonal, not intermittent: Explain the croston method of R
So don't over-rely on this classification, but keep other possible features like seasonality in mind. For instance, Talagala et al. (2022) and literature cited therein give a nice intro into the entire stream of leveraging time series features.


Modify CSS class "two" if class "one" is not shown on screen

Question: I use Php to set the CSS class of element "one" to display : none under certain conditions.
Is there a way, using CSS only, to change the color of class "two" if class "one" is not shown on screen (display : none is active, set by Php)?
I know how to do this using php, javascript, etc, I am just wondering if there is a CSS-only alternative...
Thank you!
Comment: Basically, if your presentation involves an 'if,' your presentation layer will require JavaScript or a server-side script to deal with it. CSS has no capacity for conditionals (currently).
Answer:
to change the color of class "two" if class "one" is not shown on screen

That's not possible using CSS only. CSS got no conditions, just styling.


How can I calculate the angle of an ellipse given it's matrix representation?

Question: I have the following two matrices which represent two ellipses with different angles of rotation:
$$\begin{pmatrix} 0.137956 & 0.00275827 \\ 0.00275827 & 0.0406408\end{pmatrix}$$
$$\begin{pmatrix}0.0698865 & 0.0545128 \\ 0.0545128 & 0.0698865\end{pmatrix}$$
From the matrices, how can I calculate the angle of rotation of each ellipse ?
Thanks,
Andrew
Comment: What have you attempted thus far?
Comment: I have looked through many of the relevant posts before posting my question. My math level is maybe not sufficient for extracting a practical solution for me from these posts.
Answer: If you know how to compute eigenvectors of a matrix, then you can find the rotation angle by computing them for this matrix because the eigenvectors of the matrix of a conic point in the directions of its principal axes.
Alternatively, you can solve for it directly. When an ellipse is axis-aligned, its equation doesn't have any $xy$ terms. This corresponds to the off-diagonal entries of the matrices being zero. So, you need to find the rotation angle that will make these entries vanish. Rotating an ellipse through an angle $-\theta$ is accomplished with the following matrix multiplication: $$\begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix} \begin{bmatrix}a&b\\b&c\end{bmatrix} \begin{bmatrix}\cos\theta&\sin\theta\\-\sin\theta&\cos\theta\end{bmatrix}.\tag{*}$$ Expanding the off-diagonal elements results in the equation $$b\cos2\theta+\frac12(a-c)\sin2\theta = 0$$ from which $$\tan2\theta = {2b\over c-a}.$$ If you're coding this, I suggest using the two-parameter version of the arctangent function since the denominator could be zero. Note, too, that there's more than one possible rotation angle, all 90° apart, so you'll have to decide which of these you mean by the rotation angle. For instance, if you want the angle to the major axis, you'll need to add the constraint that the upper-left element in the result of the product (*) is less than the lower-right one. In terms of eigenvectors, you want the eigenvector that corresponds to the smaller eigenvalue in absolute value.
Comment: Thanks for describing these two approaches so clearly and the word of caution about the arctangent function. I will try both. Much appreciated !


Life after linear algebra and multivariate calculus

Question: I have been following Strang's Linear Algebra course, and found it quite challenging. My goal, however, is to learn application of linear algebra and calculus in applied statistics (regression, linear mixed models, structural equation modeling, et cetera). I want to understand the math behind these techniques. Some people suggest learning abstract algebra after linear algebra. However, after trying one to two lectures by Benedict Gross (on youtube), I find that it is totally not for me - I was lost very soon about what he talked about. In addition, I am unsure if abstract algebra is very useful to applied statistics. Therefore, I am unsure what I should learn after linear algebra and calculus, and I preferably want to learn something with online videos (as self-learning stats can be quite difficult).
Comment: So... what's your question?
Comment: You don't need abstract algebra to do statistics and regression.  My favorite intro to Prob/Stats at your level is Larson - you can get a used copy here: https://smile.amazon.com/Introduction-Probability-Theory-Statistical-Inference/dp/0471059099/ref=sr_1_1?ie=UTF8&qid=1470573201&sr=8-1&keywords=larson+probability
Comment: One should certainly NOT have to learn abstract algebra in order to understand justifications of statements in linear algebra! (I don't mean that as any disparagement of abstract algebra.) $\qquad$
Comment: If strang's book is confusing you, attempting to learn abstract algebra will largely be a waste of time.  I would start by reading a couple books on statistics.  But perhaps you are looking for non-statistics books to read?  Then you want an introductory book on mathematical analysis.  This will help you gain the skills you need to be able to read more advanced material, and it'll help your mathematical maturity level as some say.  Sources exist online, on youtube, wherever... just google it.
Comment: @Gregory Grant Thanks! I will take a look.
Comment: Suggest you contact someone in your local university statistics department, and ask her what to do.
Answer: One place in statistics where abstract algebra (specically finite fields)  is used is  in the construction of mutually orthogonal latin squares which are used in Design of (statistical) Experiments.  Knowing  linear algebra, matrix, eigenvalues, positive definiteness, generalized inverses is the most important thing. You can safely skip abstract algebra and focus on applications of matrices.  One small book that does this well  is  by Bapat (Linear Algebra and Linear Models?) published by Hindustan Book Agency, New Delhi.
Comment: Thanks! It looks helpful! Other important books/resources on catching up with the stats behind statistical techniques quick? I am familiar with how to actually use these stats without understanding the math behind them.


Centos 5.9 glibc > 2.10

Question: so I have a little problem. I have a piece of software that requires glibc (libstdc++.i686 is that needs glibc) (32 bit version) that is >= 2.10.90-7. The problem is, CentOS 5.9 only has glibc 2.5 or something like that... I have tried installing everything from RPM's etc, I just keep getting a BUNCH of dependencies errors...
Comment: If it is on the EPEL repo, use EPEL; if it isn't, compile it into RPMs from source using [fpm](https://github.com/jordansissel/fpm). Don't pick random RPMs from nowhere.
Comment: Use CentOS 6, then.
Answer: The GLibC in EL should not be updated outside of what the distribution creator provides as it could cause issues with existing software; that software is not runnable on CentOS 5 without recompilation.

Centos 5.9 glibc > 2.10


How can I get all the href links from a single page when web scraping using Python and Selenium?

Question: I am working on my first programming project.
I am currently using an XPATH method to obtain the links from a webpage, however, when the program runs it returns "[None]". Not sure why this is happening and how to solve this problem.
The href links are implemented in the html code like this:

                Title≠≠

This is the code I've tried so far:
        chrome_path = '/Users/name/Downloads/chromedriver'
        driver = webdriver.Chrome(executable_path=chrome_path)
        driver.get('https://www.website.com/')

        driver.implicitly_wait(10)

        # scrape for links on the page

        elems = driver.find_elements_by_xpath("//h3[@class='fixed-recipe-card__h3']")

        #store them in a list
        links = []

        for elem in elems:
        #fetch and store the links
           links.append(elem.get_attribute('href'))

        #remove the duplicates in list links []
        res = [i for n, i in enumerate(links) if i not in links[:n]]
        print (str(res))

Answer: elems = driver.find_elements_by_xpath("//h3[@class="fixed-receipe-card__h3"]/a')

You're trying to get the href attribute for an h3 tag instead of the a tag.
Comment: It worked. I should've looked closer at what I was doing. Thank you SO MUCH.
Comment: No prob! Could you click the tick at the side to accept the answer. Thanks!
Answer: You can use css selector also:
elems = driver.find_elements_by_css_selector(".fixed-recipe-card__h3 [href]")
links = [elem.get_attribute('href') for elem in elems]


Can I rename a property that already exist and that has values in it?

Question: Is there a clause in Cypher that would allow me to rename property o.operating_system into o.os? I already have values assigned to a property.
Answer: In general, with Cypher/openCypher, you can do this by copying the old property and then removing it. As a concrete example, using the air-routes data set (tested using Amazon Neptune but it should work elsewhere). In this example we change the property called code to a new one named iata.
MATCH (a:airport {code: 'SFO'})
SET a.iata = a.code
REMOVE a.code
RETURN a

And we can see the update has worked...
{
  "results": [
    {
      "a": {
        "~id": "23",
        "~entityType": "node",
        "~labels": [
          "airport"
        ],
        "~properties": {
          "desc": "San Francisco International Airport",
          "lon": -122.375,
          "runways": 4,
          "type": "airport",
          "country": "US",
          "region": "US-CA",
          "lat": 37.6189994812012,
          "iata": "SFO",
          "elev": 13,
          "city": "San Francisco",
          "icao": "KSFO",
          "longest": 11870
        }
      }
    }
  ]
}

Comment: If I've had any relationships do I need to recreate them?
Comment: If you are just updating a node property, any relationships that node has should be unaffected.


How to get a loop query into one query in php

Question: I got something like this.
It's working, but have to do a mysql query like 40 times is not the best thing.
Can somebody help me get it in to one query?
$string_unique  = 'Unique string';

$number = count($something);

for ($i=0; $i < $number; $i++)
{

if(!empty($some_input)) {
    $string_one     = 'Something_one' . $i;
    $string_two     = 'Something_two' . $i;

    mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());
} else {
    $string_one     = '';
    $string_two     = '';

    mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());

}

Answer: You can generate a single query in that loop and then execute it only once:
$query = 'INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES ';
$queryValues = array();

$string_unique  = 'Unique string';

$number = count($something);

for ($i=0; $i < $number; $i++)
{
    if(!empty($some_input)) {
        $string_one     = 'Something_one' . $i;
        $string_two     = 'Something_two' . $i;

        $queryValues[] = sprintf('("%s", "%s", "%s")', $unique_string, $string_one, $string_two);
    } else {
        // I can't understand what are you using this part for... Anyway.
        $queryValues[] = sprintf('("%s", "", "")', $unique_string);
    }
}

$query .= implode(', ', $queryValues);

// And here is the unique key updating.
// I don't know whole the structure, so I just guess you have the PRIMARY `id` row
// What you did in your ON DUPLICATE KEY was unnecessary.
$query .= ' ON DUPLICATE KEY UPDATE `id`=`id`';

// Don't use mysql_* functions in new code.
// See: http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php
mysql_query($query);

Answer: You're a allowed to add multiple rows of data in an insert statement in MySQL. That way, you can build one big insert statement in the loop, and execute it in one go after the loop. That is way faster and much more efficient.
Answer: You can insert multi row with sql,
here an example
insert into table1 (First,Last) values ("Fred","Smith"),
  ("John","Smith"),
  ("Michael","Smith"),
  ("Robert","Smith");
Comment: yeah. i did it like that. but couldn't get it to work with the duplicate key. :\


Import data from another table and mapping in xml file

Question: I am creating c#.net windows form application with sql server. I have to import data into one table from another table but the mapping between two tables are in xml configuration file and it is dynamic it may be changed by user in future. There are more then 100 fields in each table so how to import data with dynamic mapping.
Actually my xml is like
<Mapper MapID="3" Name="thridMappingDoc" SrcDB="OPTICS_SQL" gtDB="TargetSAMPLE">
    <Source>
        <OPTICS_SQL.OrderHDR Spk="" Sfk="" SfkRelation="" />
    </Source>
    <Target>
        <TargetSAMPLE.Sales WhereClause="">
            <TargetSAMPLE.Sales.SaleID Src="OPTICS_SQL.OrderHDR.OrderID" Tpk="Tfk="" TfkRelation="" ConstantValue="" Formula="" AlternateValue="" />
            <TargetSAMPLE.Sales.SaleDate Src="OPTICS_SQL.OrderHDR.OrderDate" Tpk="" Tfk="" TfkRelation="" ConstantValue="" Formula="" AlternateValue="" />
        </TargetSAMPLE.Sales>
    </Target>
</Mapper>

second xml file
Suppose we have two xml file,one have define source connection string,target connection string and other one xml having define mapping between srcdb and trgt db.
1-  I have to read source connection and target connection. make a connection based on consetting xml file.
Note:- you can also define your connection string in Consetting xml file
2- I have to read second mapper xml file,according to source connection and target connection find first what tables are attached in both src db and targetdb  . ex.- OrderHDR table column OrderId - 101,102,103  please insert first manually in sql.
3- Check this condition which is given in second mapper xml file

Note:  This means OrderHDR table feild OrderID assign to targetdb "TargetSample", table name "Sales" ,column name "SalesID"
Note: Here OPTICS_SQL is source connection string name
4- Insert OrderID all value which you read from src db to targetdb sales table column salesId.
 Please find attachment below. and first see these xml file,i have also attached
sql script.
Comment: An example of what you're working with would be helpful.
Comment: And what is your question?
Comment: I have described question properly..Please help for the same.
Answer: You may simply create the insert statement dinamically whith column names and values parsed from xmlfile:
XmlDocument doc = new XmlDocument();
doc.Load("xmlfile1.xml");

string databasename = doc.DocumentElement.Name;

foreach (XmlNode node in doc.SelectNodes("/" + databasename + "/*[starts-with(name(), 'SourceTableName')]"))
{
    string tablename = node.Attributes["targetTable"].Value;
    string Columns = "";
    string Values = "";

    foreach (XmlNode field in node.SelectNodes("Field"))
    {
        Columns += (!string.IsNullOrEmpty(Columns) ? ", " : "") + field.Attributes["targetField"].Value;
        Values += (!string.IsNullOrEmpty(Values) ? ", " : "") + "'" + field.InnerText + "'";
    }

    //Generate insert statement
    string statement = string.Format("Insert Into {0}.{1} ({2}) Values ({3})",
                                    databasename,
                                    tablename,
                                    Columns,
                                    Values);

    Console.WriteLine(statement);
}


How do I set a date range variable dynamically and redraw a Google chart?

Question: I am using PHP to set a date range for creating a Google Line Chart.  For each date in the range a variable is set ($running_balance) to create the points on the line chart using data in a database.  I would like to be able to set the variable $end, which essentially determines the date range, dynamically, but I am not sure how to do this so that the chart would be redrawn according to this new range.  I am aware that I could create a new function that includes drawChart(); to redraw the chart, and I would be using three buttons to either set the date range to 1 year, 3 months, or 1 month, but I am not sure how to put all this together.  Here is the code that I currently have:
$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime('+365 days')));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt ) {

$date_display = $dt->format("D j M");

.....  code to generate $running_balance .....

$temp = array();

    $temp[] = array('v' => (string) $date_display);
    $temp[] = array('v' => (string) $running_balance);
    $temp[] = array('v' => (string) $running_balance);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

Comment: You should make (at least) two separate functions. Function #1 will retrieve data. Function #2 will call the data-retrieving function and draw the chart. When you click a button/change a dropdown, it should call a handler function that will get the appropriate data and send it to the chart drawing function. Basically, take the first half of your code (before `drawChart()`) and turn it in to a function that accepts the $end parameter. Have you tried something like that already?
Answer: OK, if I'm understanding you correctly, you're having trouble conceiving and designing what parts of these actions are server-side (PHP) and what parts are client side (Javascript) and then the client-server communication strategy.  This is a common speedbump.  There's several ways to deal with it.
First (and less preferred) you could create a form and reload the whole page with the new date range:
// we're looking for '+1 year', '+3 months' or '+1 month'. if someone really
// wants to send another value here, it's not likely to be a security risk
// but know your own application and note that you might want to validate
$range = isset($_GET['range'])&&$_GET['range']?$_GET['range']:'+1 year';

$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime($range)));
// ... the rest of your code to build the chart.
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="get">
    <select name="range" size="1">
        <option value="+1 year">1 year</option>
        <option value="+3 months">3 months</option>
        <option value="+1 month">1 month</option>
    </select>
    <input type="submit" name="action" value="Redraw Chart">
</form>

... the reason that's the less preferred is because it causes a whole refresh of the page.
If you want to avoid a whole page refresh, you're doing pretty much the same thing, but do it with ajax.  The setup is almost identical, just a couple minor changes:
// between building the data table and the javascript to build the chart...
$jsonTable = json_encode($table);
if (isset($_GET['ajax']) && $_GET['ajax']) {
    echo json_encode(array('table' => $table));
    exit;
}
// remainder of your code, then our new form from above
?>
<form id="redraw_chart_form" action="<?= $_SERVER['PHP_SELF']; ?>" data-ajaxaction="forecast.php" method="get">
    <? foreach ($_GET as $key => $val) { ?>
    <input type="hidden" name="<?= $key; ?>" value="<?= $val; ?>">
    <? } ?>
    <input type="hidden" name="ajax" id="redraw_chart_form_ajax" value="0">
    <select name="range" size="1">
        <option value="+1 year">1 year</option>
        <option value="+3 months">3 months</option>
        <option value="+1 month">1 month</option>
    </select>
    <input type="submit" name="action" value="Redraw Chart">
</form>

Edit for clarity:

Don't forget to use the following block of code from the first (page refresh) example, otherwise you're not using the form at all:
$range = isset($_GET['range'])&&$_GET['range']?$_GET['range']:'+1 year';
$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime($range)));
Ajax will only work if the only data you're sending back is the json encoded block, which means your chart building data needs to be at the top of the script before any HTML output is started, including your page template.  If you can't put the chart building code at the top of the script, then you'll have to add it to a whole separate script that all it does is calculate the data for the chart, and then you can have it return the ajax data without all of the other HTML on the page.  If you can't do either of those things, you'll just have to turn off the Ajax bit and do a whole page refresh.

Edit 2: I added the data-ajaxaction attribute to the <form> element, this is a user defined attribute that I made up to provide a different action just for ajax.  I also changed the $.ajax() call to use this attribute rather than the action attribute.
Comment: Thanks. Yes, you understand me correctly, and yes I prefer the  AJAX method.  I have jQuery installed.  I have included your code on the page, but when clicking on the 'Redraw Chart' button, I'm redirected to the url `http://www.finance.nickputman.com/?ajax=0⦥=%2B1+year&action=Redraw+Chart` which shows me my home page, rather than the current page which has the following url: `http://www.finance.nickputman.com/?page_id=174`.  Any ideas why this is happening?
Comment: OK, first things first, in the form tag change `action=""` to `action="?"`.  This will keep you on `page_id=174`, and fixing that *should* get the form to work, just with a page refresh.  Secondly, it looks like it's not executing any of the jQuery onsubmit event.  Look for errors in the javascript console that would keep the javascript from executing (if you're using Chrome, hit f12 and hit the "console" tab).  Before `preventDefault()`, put `alert('debug');`, see if it runs.
Comment: Thanks.  The jQuery error is `'Semantic Issue - Expected token ')'` on this line: `url: $(this).attr('action'),`.  There is still an issue with the URL string for the form action.  With your suggested modification I am still redirected to the home page.  If I leave out `` and `?` from the URL, then the URL is correct apart from the inclusion of the question mark, i.e. `http://www.finance.nickputman.com/page_id=174?ajax=0⦥=%2B3+months&action=Redraw+Chart`.
Comment: There were missing curly braces around the ajax parameters.  Also, instead of adding the query string to the form "action", I added a block to create hidden inputs for them to pass through.  Updated code in the edited answer.  Your URL without PHP_SELF is not going to work unless you've got some strange mod_rewrite rules going on, because you need the `?` before `page_id=174`.  That's what the new hidden input block is for.
Comment: Thanks, the jQuery conflict has gone now on page load, but now when I click the redraw chart button, nothing happens - i.e. the URL doesn't update.  Instead, after a few seconds I get the following error in the console: `format+en,default,core chart.l.js - Other Issue - Error: Table has no columns.` There appears then to be an issue relating to the way your script is communicating with the Google API.
Comment: Your script.  I'm just helping out.  I can only test so much without actual access to your page, and I didn't load it all up to check for typos and the like.  Odds are it's just a simple error like that which I can't see without running the page.  It's correct that it doesn't update the URL, that's how ajax works.
Comment: OK, thanks. Because the page loads/works fine, and even works fine with another form & script that I am using to redraw the graph (adding starting balances to first value in the chart), and because the error only appears when clicking on the button in your form, I presumed that the issue was related to your script, rather than the existing script.  I appreciate your help, but now I'm not sure what to do. I could give you access to the page and the full script as it currently stands if you like.
Comment: I'm happy to look at your page if you give me access.  I don't mean to suggest that the problem exists outside of the code in my answer and I don't mind trying to make sure it's 100% correct.  But without full access to your codebase I'm unlikely to be more than 99% successful, ultimately it's up to you to recognize where my limited access to information means you need to tweak my answer to fit your script.
Comment: OK, thanks Jason.  Is there an email where I could send you a login for my site, or a way of sending you a PM via Stack Overflow?
Comment: OK, thanks. Hopefully you have now received an email from me.
Comment: I've updated my answer with some clarifications based on your page.
Comment: Thanks for the clarification, which was helpful.  I now have the form working with the page refresh method.  I am still a little unclear about the ajax method, which is the one I am aiming for.  I think my preferred method, of those suggested would be to have a separate script.  But I'm not sure what code to put into this script and how to refer to it in the code/script running on the 'forecast' page.  Any further pointers would be welcome. Thanks again.
Comment: What you need to put in the separate script is everything from line 94 (`$rows = array();`) to line 323 (the end of the `echo json_encode(array('table' => $table));` block).  You *also* need to include anything at the beginning of the script that provides resources that you'll need to use (such as the initialization of `$wpdb`).
Comment: @Jason your answer is missing a couple things. drawchart() is missing both arguments in your answer. You'll need to build an options object and use drawchart(table, options)
Comment: @Rawrgulmuffins take a closer look. `drawChart()` is a custom function that doesn't take any arguments, just uses global data.  Namely, `table`, which I populate right before calling `drawChart()`.
Comment: @Jason Ahh, you're saying call the draw chart which is in his question but replace data with table?
Comment: I'm saying that in his original question, drawChart() is defined thus: `function drawChart() { var data = new google.visualization.DataTable(table);`... the very first thing it does is build `data` from the global `table` variable.
Comment: @Jason Thanks. I now have the code you referred to in a separate script (forecast.php).  I'm sorry for being slow on this one, but I'm now not sure how to use the forecast.php file.  Do I remove all the code that I am putting in forecast.php from the original page and then just use `include("forecast.php");` on the original page?
Comment: I didn't make that very clear.  forecast.php becomes the target URL for your ajax request.  If that doesn't make sense, I'll update my answer in a bit to include your new file
Comment: @Jason Thanks. I have updated the code, and included the correct path to forecast.php, but for some reason the page is still refreshing. (I have also awarded the bounty as I wanted to make sure I did so in time).
Comment: @Jason Sorry, I should have checked that. It's the error I was getting before: `Error: Table has no columns.` and line 60 of the script **format+en,default,core chart.l.js** is highlighted.
Comment: What browser are you using? Chrome has the easiest debugging tools, when I give instructions on where to look, that's the only place they'll work. After your page has loaded, hit f12, and go to the "Network" tab. Hit "Redraw Chart". You'll see the ajax communication popup on the screen. Click it, then click the "Preview" tab. You'll see the error generated in your forecast.php script there. `Fatal error: Call to a member function get_results() on a non-object in forecast.php on line 21`. I know just enough about Wordpress to know that you've not started your DB connection appropriately.
Comment: @Jason Thanks. As the script was running outside of a Wordpress page I needed to include **wp-blog-header.php**.  When I did this I got an error because the array 'dates' wasn't included in forecast.php.  So I included all of the code above line line 94 in the forecast.php as well.  Then I got no errors, and the 'Preview' tab in Chrome is reporting that the correct data is returned, i.e. 91 rows for three months and 30 rows for 1 month, but the chart isn't redrawn on the page.
Comment: It looks like your data is being sent back appropriately, which is good. For whatever reason, it's not appropriately accessing the table data to populate on the successful return.  So, try this: change `echo json_encode(array('table' => $table));` to `echo json_encode($table);` and change `table = data.table;` to `table = data;`.  I've confirmed that `data` looks to hold the right data, but with the extra `data.table` dereference it's breaking, and troubleshooting is troublesome on my end.
Comment: @Jason Thanks. I've made those changes, with the same result.  The data is being sent back OK, but the chart isn't redrawn. I am seeing 'Uncaught error: Table has no columns' in the Console - it appears around the same time that the data is returned -i.e. it doesn't appear on page load.
Comment: This is now substantially a separate issue from the one you started with, and may benefit from fresh eyes by asking a new question.  For some reason, your page isn't accessing the information in the way I expect it to work.  It may be a simple error on in the ajax code, but I've got a blind spot for it.
Comment: @Jason. OK. I'll ask another question about it on SO and will report back. Thanks for sticking with me on this one! Nick


Site to Site VPN devices behind ISP modem

Question: site to site vpn setup when behind isp wifi router image

I've read through many site to site vpn posts on this site but I still haven't found a solution to my issue. Here is the situation. I was asked to connect two sites together so the remote site B's users can print to printers and access the file shares at site A.  Both sites are using comcast business modems, and have been for quite some time so turning the ISP modems to bridge mode is an absolute last resort option.
I'm not entirely clear on how to go about setting up the vpn router to allow traffic from the xfinity business modems to see each other over the site to site vpn connection. Both sites connect, but I can't ping either one.
Here's what I've done so far:
1. at both the remote site and the main site I've gone in to the isp cable modem and changed the local ip ranges so they are different, site A local up range is 10.1.10.X and site b is range is 10.20.30.X

I've gone in to the tp-link interfaces and setup WAN 1 to a static IP on the local subnet for each site. Tp link at site A wan1 is set to 10.1.10.215 and site b is 10.20.30.233
On both comcast modems I've setup port fowarding for the respective static ips of the tp-link devices so that ports 4500 and 500 UDP are open
I've gone in the admin panel of the tplink r600vpn routers and setup the site to site ipsec and connected both sites together.  Both sites have static internet/public ip addresses which are placed in to the proper fields. I'm using WAN1 as the adapter in the settings.

This is where things fall apart for me. I can see that the vpn connection is working from the control panel on the tp-link routers, but I cannot ping the local IP addresses on either site from computers connected to the cable modems. Pings to 10.1.10.X network from site B time out, and vice versa.
I've read about static routing, but I don't understand if I need to set this up on just the tp-link routers, or if I need to set this up on the comcast modem router or both.  I tried messing with this already but it didn't work either.  I tried making the static routing destination for the tp-link at site b as 10.1.10.0 with hop 1 at 10.20.30.1 on WAN1 as the interface but that didn't work. Is there a firewall rule I need to look for that might prevent this from working?
I'm also having a hard time understanding which physical network ports need to be connected. Right now I have the tp-r600vpn routers connected via the WAN1 port only. Do I need to instead have this device connected on one of the 4 lan ports instead?
I'll keep googling for answers, but I've yet to find one that explains this type of setup and figured I would ask.
Comment: If the tunnels are up and you can't "ping", then you don't have routes. You either need to configure static routes or configure a route propagation protocol such as BGP on the routers for them to do it automatically.
Answer: The issue is that data is not flowing from the clients to the TPLink routers.
A more conventional would (depending on your ISP and requirements) be to ditch the ISP router aand replace it with the TPLink router, or - as you say - convert the ISP router into a bridge.   Another (less then ideal, but sometimes most practical) option would be to use "double NAT", ie connect the Internet to the ISP router, and a LAN port of the ISP router to the WAN port of the TPLink router on both sides.  You would need to disable WIFI on the ISP router and enable it on the TPLink (or get an AP).  You would want to change the ISP router LAN to be in the 19.168.X range in each case.
An alternative which may work - depending on your particular routers, would be to add routes from the ISP router to the TP-Link router.  This is not ideal because you are going to induce asymetric routing and some firewalls and other stuff can break - ie packets going out will go from PC -> ISP router -> TP-Link Router -> VPN while packets returning will go VPN - TPLink router -> PC (not seen as going through the ISP router because the traffic, because the VPN abstracts the VPN hop)
Comment: So in the double nat option you're describing, this sounds like what I have setup already, but I have the tp-link plugged in from the WAN1 port to the switch, but you're saying instead I'd plug it directly in to one of the 4 free lan ports on the back of the comcast router. The wifi issue wouldn't be a problem at the remote site since they're using wifi aps already, but could I instead change the Tp-link router to be in the 10.20.30.x range instead of the isp modem to 192.168?
Comment: also If I do switch the tp-link to the 10.20.30.x range would I need to divide the open ports in to separate ranges?  Like on the tp-link router it would only be dhcp on 10.20.30.200-254 and on the isp modem have it dhcp as 10.20.30.2-199?
Comment: If your picture is correct, I don't see where double nat is coming from (switches do not do nat).  I'm saying the ONLY thing you should plug into your ISP router is the internet connection on the WAN site and the Wan side of the TPLink router to the LAN side of the ISP router.  Everything else currently in the ISP router needs to be moved to the LAN of the TPLink router or switch.  (on both sides)
Comment: On the ISP modem you would not be running 10.20.30 at all. You really need someone to help you to understand network fundamentals - you really need to learn about subnets, DHCP etc, and this is not the appropriate place to have that discussion (and its been discussed to death on superuser.com)


Interpretation of relationship between residuals and predicted values in a mixed model

Question: I'm using a linear mixed effects model (varying slope + intercept, with glmer from "lme4") to look at the association of the interaction between two categorical predictors (time + X1 - where X1 is a grouping variable) with a continuous outcome (Y1, has both positive and negative values)
The model looks like this:
<code>glmer(Y1~ Time*X1+ (1 + Time+ X1 | Subject))
</code>
[Subject is to account for random intercepts in the individual subjects)
The problem is, my residuals vs predictors plot looks like this:

The way I interpret (based on this) this is that there's little heteroscedasticity here, but the model is biased. (in the sense that there's a relationship between the residuals + predictors).
This source tells me I might be missing a predictor, but I can't think of any that I'm missing.
So my questions are:

How big of a problem is this in terms of interpreting the model output?
Could it have something to do with the glm family that I'm using ("Gaussian")? Is this appropriate for such a continuous outcome variable?
What should/can I do to improve the model?

Thanks for the tip, Florian. This is what the plot looks like when I use "re.form = NULL" in predict():

Looks exactly the same. Any ideas why?
Answer: Per default, fitted() uses the full model predictions, including the REs. Plotting residuals against these conditional predictions often creates spurious patterns that have nothing to do with a model misspecification, see a bit more detail here https://github.com/florianhartig/DHARMa/issues/43.
Solution is to plot residuals against the fixed effects predictions only, adding re.form = NULL to the predict function - I would only worry if you still have a pattern.
Additionally, you should check REs against predictors though.
Comment: OK, then I don't know ... I would guess that there is something going on with the random effects, because the pattern looks very regular / directed, which is in my experience more likely to be caused by REs than by misspecified fixed effects. Maybe try to fit at standard LM and see if the pattern remains. Btw., for fitting an LMM, you should prefer lmer.
Comment: Thanks! I just did that and the plot looks exactly the same (see above).


An argument regarding showing two closed subspaces are equal in a Banach space

Question:
Let $X$ be a Banach space and suppose $V$ and $W$ are two subspaces of $X$ such that $V\subset W$. Also, both $V$ and $W$ are closed subspaces of $X$.[Edited according to @G.Sassatelli's answer] To prove $V=W$, it suffices to show that any continuous linear functional on $W$ which vanishes on $V$ is identically equal to $0$.

This is an argument made in a proof in Temam's Navier Stokes Equations(page 13). Would anybody explain the "it suffices to show" part?
Answer: If $V$ is not closed, it's not true: namely, pick $W=\overline V$.
If $V$ is closed and $x\in W\setminus V$, Hahn-Banach guarantees the existence of a continuous functional $\phi\in W'$ and $\alpha\in\Bbb R$ such that $\phi(x)>\alpha$ and $\phi(y)<\alpha$ for all $y\in V$. Now, let's prove that, actually, $V\subseteq \ker \phi$. Suppose $\phi(y)\ne0$ for some $y\in V$, then $$\phi\left(\frac{\lvert \alpha\rvert+1}{\phi(y)}y\right)=\lvert \alpha\rvert+1>\alpha\\ \frac{\lvert \alpha\rvert+1}{\phi(y)}y\in V$$
Which contradicts the constructive hypothesis of $\phi$. So, $\phi$ is a continuous functional on $W$ which is $0$ on $V$ but not on the whole $W$.
Comment: Thank you for your answer. Are you saying that one should assume that $V$ is closed instead of $W$?
Comment: I edited the question accordingly.
Comment: @jack Yes, you certainly need $V$ closed. Closedness of $W$ is unnecessary, since Hahn-Banach strictly separates points (or compact convex susbets) from closed convex subsets regardless of the ambient space being a Banach space. See "Important consequences" and "Hahn-Banach separation theorem" on [wikipedia](https://en.wikipedia.org/wiki/Hahn%E2%80%93Banach_theorem).
Comment: I'm not sure if I fully understand you argument. Suppose that "any continuous linear functional on $W$ which vanishes on $V$ is identically equal to $0$." So the goal is to show $W=V$. For the sake of argument, you assumed that $W\setminus V$ is not empty, which gives the existence of an $x$. Then the Hahn-Banach Theorem gives a $\phi\in W'$ such that $V\subset\text{ker}\phi$. By our assumption, $\phi$ must be identically $0$. But $\phi$ cannot be so. Is that correct?
Comment: If $W\supsetneq V$, there exists a continuous functional $0\ne\phi\in W'$ such that $\left.\phi\right\rvert_V=0$. The contrapositive of this lemma, provided $W\supseteq V$, is that if there doesn't exist a continuous functional $\phi\in W'$ such that $\phi\ne 0$ and $\left.\phi\right\rvert_V=0$, then $W=V$. Or, that if the only continuous functional $\phi\in W'$ such that $\phi\rvert_V=0$ is $0$, then $W=V$. In this sense, "*it suffices to show*" what the text says.
Comment: Thanks for your elaboration. If one does have $V$ and $W$ both being closed, can one avoid using Hahn-Banach here? Can (*) imply $V$ is dense in $W$?
Comment: If you pick $w\notin V$ and specialise the result to $W=V\oplus\langle w\rangle$ (which is closed when $V$ is closed), you obtain the fact that a point and a closed vector subspace can be strictly separated by a continuous functional. Which is one of the classic consequences of Hahn-Banach. So, I guess you kinda need it for the general result.


Add Additional Logic To Node Save/Submit Process

Question: Where can I hook into drupal to modify the value of a specific field just before it is inserted into the database?
For example, lets say I wanted to trigger an email or run an arbitrary piece of code just before the node is inserted into the database?
I've been looking at hook_node_presave and it looks like it will do what I want, but I need it to only apply to one content type.
Answer: You can probably use either hook_entity_presave(), hook_node_presave() hook_field_attach_presave(). These hooks are all pretty similar right now. Actually not sure why there are 3 of them :)
Simply add a check for the content type and/or the existense of the field you want to alter.
Comment: Thank you, that was exactly what I was looking for.

For searchers:
`function hook_node_presave($node) {
    if ($node->type == 'node_machine_name' && $node->is_new === TRUE) {
        //Logic Here
    }
}`
Comment: Looks good, feel free to edit that directly into my answser (yeah, you can do that, someone with more points just needs to approve it afterwards). That's much more readable than in a comment.


Docker and VirtualBox on Fedora 27

Question: I installed virtualbox 5.2 from their website. And I ran this command..
docker-machine create -d virtualbox dev

then I got this..
Running pre-create checks...
Error with pre-create check: "We support Virtualbox starting with version 5. Your VirtualBox install is
"WARNING: The vboxdrv kernel module is not loaded. Either there is no module
available for the current kernel (4.14.3-300.fc27.x86_64) or it failed to
load. Please recompile the kernel module and install it by
sudo /sbin/vboxconfig
You will not be able to start VMs until this problem is fixed.\\n5.2.2r119230\".
Please upgrade at https://www.virtualbox.org"

I did as it suggested..
sudo /sbin/vboxconfig

then..
vboxdrv.sh: Stopping VirtualBox services.
vboxdrv.sh: Building VirtualBox kernel modules.
This system is currently not set up to build kernel modules.
Please install the Linux kernel "header" files matching the current kernel
for adding new hardware support to the system.
The distribution packages containing the headers are probably:
kernel-devel kernel-devel-4.14.3-300.fc27.x86_64
This system is currently not set up to build kernel modules.
Please install the Linux kernel "header" files matching the current kernel
for adding new hardware support to the system.
The distribution packages containing the headers are probably:
kernel-devel kernel-devel-4.14.3-300.fc27.x86_64

..and I don't understand anymore. Please help.
Comment: Did u try `sudo apt-get install virtualbox`?
Comment: Nope. I did not.
Answer: Install the kernel-devel package and it will continue.  Btw, this is not a programming question, there are better forums for such questions...
Comment: Jeez.. this is why I came here last. I did, sir. I did. I did ask on #fedora, ask.fedora and r/fedora. But I haven't got answer from those yet. Thanks anyway.

Docker and VirtualBox on Fedora 27


DDD restringe escrita de código baseado no idioma do cliente?

Question: Meu pouco conhecimento sobre DDD foi intimado e gostaria de saber mais sobre.
O DDD restringe a escrita de código baseado no idioma do cliente por conta da linguagem ubíqua?
Comment: Que restrição está falando? Está dizendo que só pode fazer assim?
Comment: Fortemente relacionada/duplicata: https://pt.stackoverflow.com/q/139272/357
Comment: Bem... Isso vai do contexto e do cliente. Mas, o cliente sendo brasileiro, eu tenho que colocar meus códigos em português. Eu me sinto mais confortavel em inglês...
Por exemplo... Imagine o seguinte contexto:
RelatorioFactory... é feio português com inglês... ClienteController ... Isso quebra um pouco as boas práticas...
Answer: Primeiro, tenho que dizer que acho uma bobagem muitas das regras que o pessoal cria. Especialmente em DDD tem um monte que por si só acho bobas, não que tudo seja ruim nele.
DDD diz que a linguagem (e aqui não importa se é uma língua, é para usar as mesmas palavras para evitar ambiguidade de entendimento) usada no código deve ser a que o cliente usa. Seu cliente usa tudo em inglês? Se não usa, então tem que ser em português, segundo a regra. Tem que ser algo que o consumidor do sistema entenda.
Inclusive se o cliente não usa inglês você acha que vai dar os nomes certos? Pode ocorrer, mas eu sempre vi aberrações de tradução, nem o cliente, nem ninguém usava aqueles termos, apenas o programador que criou o código. Ele se julgava fluente em inglês mas fazia traduções literais, e nem usava DDD.
Já parou pra pensar que alguns termos são intraduzíveis? Mesmo. Um exemplo é ICMS.
Essa regra faz sentido? Na teoria sim, na prática ocorre essas coisas que você demonstrou no comentário. Mas o problema não é misturar, o problema é que essa tão falada linguagem ubíqua não costuma ocorrer de fato. O cliente não entende o que você faz, isso sempre foi uma falácia. Se até programadores não entendem bem o que estão fazendo imagina quem é leigo. Essa regra é um idealismo. E não vi evidências que comprovem que ela sequer é útil de verdade mesmo que ela seja feita perfeitamente. O que mais vejo é as pessoas que usam DDD reclamando que não deu certo ou que não viram vantagem, e vejo consultores em DDD dizendo que eles não souberam fazer, mesmo que tenha sido eles que treinaram a equipe pra fazer o DDD.
Uma das críticas que faço ao DDD, especialmente a tal linguagem ubíqua é que só funciona bem quando não há interligação do domínio com o mecanismo, o que na prática é o oposto do que ocorre. Talvez tenha uma regra que diz que esses casos não precisam seguir a mesma coisa, mas não sei, não sou especialista.
Pra mim, bom senso e trabalho duro sempre superou qualquer metodologia, até porque nenhuma metodologia toma decisões por você e são elas que contam pro resultado final. Mas se for seguir essa regra específica tem que entender a motivação dela, é a linguagem ubíqua foi criada para comunicar melhor com o cliente, então isso ocorrerá no seu caso se fizer em português ou inglês? Se não é para comunicar melhor com o cliente, aí o problema é pior porque nem sabe porque está usando DDD, só o faz por estar na moda. Pense nisso.
Coloquei no GitHub para referência futura.


Changing variable in c++

Question: I started learning C++ and I made a simple thing like printing variables etc, but I wanted to make a new value on a variable like in Python:
test = "hello world"
print(test)
test = 5
print(test + 6)

So I had this:
string test = "hello world";
cout << test << "\n";

And now I wanted to assign a number to test, so I used int test = 5;, but I got an error:

redefinition of 'test' with a different type

Is it possible to assign a new type to a variable somehow?
Comment: not with in a specific scope- you could surround the definition in curly braces
Comment: Why not just make a new variable?
Comment: https://en.cppreference.com/w/cpp/language/definition
Answer:
is it possible to assign a new type to a variable somehow?

A new type, no.  C++ is a statically typed language.  Variable types are specified at compile-time and cannot change at runtime.
For what you are asking, the closest thing available is std::variant in C++17 and later, which is a fixed class type that can hold different kinds of values at runtime, eg:
#include <iostream>
#include <string>
#include <variant>

using myVariant = std::variant<int, std::string>;

void print(const myVariant &v)
{
    std::visit([](const auto &x) { std::cout << x; }, v);
    std::cout << "\n";
}

int main()
{
    myVariant test;
    test = "hello world";
    print(test);
    test = 5;
    print(test);
    return 0;
}

Online Demo
Comment: 15 seconds. Beat me by 15 seconds. Well done :P
Comment: Actually, both of you may be misleading him. What he meant was not `std::variant` since it only considers what data type inside this `<>`. In Python, unlike `c++`, an object or function can have more than one definition.
Comment: @OrkhanAliyev • `std::any`?
Comment: @OrkhanAliyev a variable in Python would be more like `std::any` in C++. But that type really should not be used in most cases, in part because it has no concept of what it is actually holding, and doesn't make it easy for the user to get data out of it unless they know exactly what was stored in it to begin with. And as such, `std::any` can't (easily) be printed. Plus, most people don't need that flexibility, they only work with a few types at a time, and `std::variant` is better suited for that purpose, with better type safety and functionality.
Comment: To a new learner, offering _variant_ is like offering them a shotgun to shoot their own foot off. OP, I encourage you to use specific variable for specific things of known types. Don't go mixing random stuff in the same variable.
Comment: @Jeffrey "*... is like offering them a shotgun to shoot their own foot off*" - C++ is good at that.  There are a lot of ways it lets people shoot themselves.  It doesn't hold their hands. "*I encourage you to use specific variable for specific things of known types. Don't go mixing random stuff in the same variable*" - and while that is good advice in general, there are valid use cases for using `variant`, otherwise the C++ committee wouldn't have added it to the standard library.
Comment: @Jeffrey, actually `std::variant` is not that hard. The way he explained is quite enough as surface.
Answer: In C++17 and newer, std::variant is a type that can be used to store multiple different types of data. Though you'll have to do a bit of finagling with visitors to get the polymorphic print you know from Python.
#include <variant>
#include <string>
#include <iostream>

struct PrintVisitor {
  template <typename T>
  void operator()(const T& arg) {
    std::cout << arg << std::endl;
  }
};

int main() {
  std::variant<std::string, int> test = "hello world";
  std::visit(PrintVisitor(), test);
  test = 5;
  std::visit(PrintVisitor(), test);
}

Changing variable in c++


How to change page.html.twig depending on the content type I am viewing in Drupal 8?

Question: I was wondering how I would change page.html.twig depending on the content type of the node I am viewing?
For example I would like the title to be shown on pages with the article content type but be hidden on the site page content type.
Answer: Page title is available as a block, and you can control the visibility from there.
However, to answer your question, here's how to provide different template suggestions based on content type:
function YOUR_THEME_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
  // Try to get the node, so we can check if we're on the node page.
  $node = Drupal::request()->attributes->get('node');
  if ($node && $node->getType() == 'YOUR_CONTENT_TYPE') {
    $suggestions[] = 'page__NAME_OF_YOUR_TEMPLATE';
  }
}

This will allow you to use page--NAME-OF-YOUR-TEMPLATE.html.twig template in your theme only for specific content types.
You can read more about hook_theme_suggestions_HOOK_alter() here.


SAS: Starting Problem

Question: Here's the error I receive when trying to start my SAS server.

Windows could not start the SAS
  [EMTM-Lev1] Analytics Platform Server
  service on Local Computer.
Error 1068: The dependency service or
  group failed to start.

The same goes to the other 3 services which SAS requires them to start to run.
Answer: I confirmed that it has expired since December 30th. But the weird thing was it worked last week. Maybe it was the grace period.
Answer: Right-click the service, look at its properties, and look at the dependencies. What are they? Are they started?
What's changed since it 'used to work'?
Comment: Hi an update here, I have uninstalled and trying to install again now. It used to work for months even until I fully developed an App in my server using port 80. A few days later it stopped starting.
Answer: Can you start the services manually or do they exit with an error?
In the past we had problems with the metadata server taking too long to start. That resulted in an error for that service. Depended services were not able to start.
Otherwise you'll have to look at the different log files from the SAS services failing to start

SAS: Starting Problem


Rotation of conics sections using linear algebra

Question: When given an equation of the form $$Ax^2+Bxy+Cy^2 + Dx + Ey + F$$ where $B \not= 0$ and it is not a degenerate conic, then you can use $\Delta = B^2 -4AC $ to see what type of conic it is, and then (after a lengthy process) you are able to find an equation with $B = 0$, where your $x$ and $y$ are parameterized into $x'$and $y'$, where $x',y'$ are a set axis with each one being either perpendicular to your axis of symmetry of parallel to it.
While I know how to do this process by way of lengthy algebraic manipulation, I was wondering if there was a way to do this with linear algebra? I know that we can express the standard form equation as $$x^{\top}Ax + B^{\top}x + F$$ where $x = \left[ \begin{array}{c} x \\y\end{array}\right]$, $A = \left[ \begin{array}{cc} A & B/2\\ B/2 & C\end{array}\right]$, and $B = \left[ \begin{array}{c} D \\E\end{array}\right]$. I don't really know where to go from there, though.
Comment: See this [pdf](http://mathsforall.co.uk/userfiles/Section%207g(1).pdf).
Comment: @JuanSebastianLozanoMuñoz: Or this [pdf](http://www.numbertheory.org/book/cha7.pdf).
Comment: $x^{\top}Ax$ is a quadratic form that can be reduced to a canonical form (a sum of squares) by changing a basis.
Comment: @user35603 How would I find my new basis vectors?
Answer: The matrix $A$ is symmetric, and assuming the coefficients $a,b,\ldots,f$ are real or complex, $A$ is then orthogonally (unitarily) similar to a real diagonal matrix (I will just assume we're working with real numbers from here on). So you have $A=P^TDP$. Now let $X=PX'$ where $X'=(x',y')^T$ is your new coordinate system. So then we have \begin{equation} X^TAX=(PX')^TA(PX')=X'^T(P^TAP)X'=X'^TDX'=\lambda_1x'^2+\lambda_2y'^2, \end{equation} which is what we want. So if we then take $B^TPX'=(d',e')(x',y')^T=d'x'+e'y'$the full equation then becomes: \begin{equation}X'^TDX'+B^TPX'+f=\lambda_1x'^2+\lambda_2y'^2+d'x'+e'y'+f.\end{equation}
So, in a nutshell, you just have to do orthogonal diagonalization on $A$, and then do the substitution as above and multiply out. The matrix $P$ is then a rotation transformation matrix (if det$(P)=-1$ then you can just interchange the columns of $P$ and $D$ so that the new matrix $P'$ then has determinant 1, ensuring it is a rotation and not a reflection about a line through the origin)
(The source for most of this: Linear Algebra (4th ed) by Friedberg et al, p.388-392)


How to display values from table, modify them , save them again

Question: I am trying to display values from table and want to modify the values on form submit.

here is my code:

<?php
$sql = mysql_query("SELECT * FROM TABLENAME");

//Get and store values into new variable

while ($row = mysql_fetch_array($sql)) {
    $name[]   = $row['name'];
    $status[] = $row['status'];

}

//run for loop to identify values
for ($i = 0; $i < count($name); $i++) {
        echo "
 ";
        echo "" . $name[$i] . "	";
        echo "<input  name='offer_new_name' size='5' type='text' value='$status[$i]' />	";

}
echo '<form action="" method="post">';
echo '<input type="submit" value="Save New Values" name="save_new">';
echo "</form>";

if (isset($_REQUEST['save_new'])) {
    for ($i = 0; $i < count($name); $i++) {
        echo "name:$name[$i]
";
        echo "status:$status[$i]";
    }
}

When I click Save New Values , it displays the old values ,, taken from db.
Please guide me how to save
echo "<input  name='new_status' size='5' type='text' value='$status[$i]' />	";

into new variable for each name and save them into the same table again.
Please guide me if my approach is wrong towards this requirement.

Update1:

table structure:
id       name:               status:
auto     name1                  0
auto     name2                  1
auto     name3                  0

Where this runs,
 while ($row = mysql_fetch_array($sql)) {
        $name[]   = $row['name'];
        $status[] = $row['status'];

    }

values are stored like this
 $name[0]
  $status[0]
  $name[1]
  $status[1]
  $name[2]
  $status[2]

I can run update query like this
UPDATE TABLE set status=$status[0] where name= $name[0]

Comment: where is your `update` query ?
Comment: i will handle update query ,, first i want to echo , values,, once new values are taken update can be run
Comment: you want to view the new `submitted` result ? not the db updated results, right ?
Comment: firstly , i want to view the results from db,, then once modified ,, i want to view the modified results
Comment: then you have to provide your update query example !
Comment: format will be like this : --------
$sql=mysql_query("UPDATE TABLENAME set  status=$status[$i]  WHERE name=$name[$i]  ");
Comment: @sadiarehman look at my answer, I think this will help you
Comment: @LucaJung , replied to your answer
Answer: First, the following line should be in the <form></form>
echo "<input  name='new_status' size='5' type='text' value='$status[$i]' />	";

Second, this code block should be on top of your script:
if(isset($_REQUEST['save_new'])){
  //Your update query
}

In this code block you need an update query, which updates your database e.g
UPDATE TABLENAME SET a = new_value WHERE b = c;

This is the variable you can access the entered value;
$_POST['new_status'];

Lastly I can strongly recommend to use prepared statements. Otherwise your code will be open for SQL-Injections.
Pseudo code:
<?php
//if the submit button is pressed, update the Database
if (isset($_REQUEST['save_new'])) {
    //Update your Database
}

//get the new values from Database
$sql = mysql_query("SELECT * FROM TABLENAME");

//store values into new variable
$name = array();
$status = array();
$id = array();
while ($row = mysql_fetch_array($sql)) {
    $name[]   = $row['name'];
    $status[] = $row['status'];
    $id[] = $row['id'];
}

//create HTML-From
echo '<form action="" method="post">';
for ($i = 0; $i < count($name); $i++) {
    echo "
 ";
    echo "" . $name[$i] . "	";
    echo "<input  name='new_status' size='5' type='text' value='$status[$i]' />	";
}
echo '<input type="submit" value="Save New Values" name="save_new">';
echo "</form>";
?>

This 'new id' can be saved as a hidden input in your script:
$indecipherable_id = (int)$id * 7258289382234; //Only a example --> use a more complex algorithm!

Before your update query you can decrypt the id and select the row.
Comment: What do you mean with new values? The value you entered in the form?
Comment: once i get the values from db ,, i will modify them , how to get modified (inputted ) values ??
Comment: Ok the values, you get from db are stored in $name and $status
Comment: if i update multiple values , how does the query will know about this ..
 $sql=mysql_query("UPDATE TABLENAME set status=$status WHERE name=$name");
Comment: No, the new value from input is $_POST['offer_new_name']. If you want to update your db then you have to use this variable. and form multiple values you can use set a=b, c=d, e=f WHERE ...
Comment: But in order to update it you have to keep the old value. This can be down e.g by a session value.
Comment: not yet .. could not find a way  oon how to write update query. as i am not sure where the values are being stored and how to match status with name
. $sql=mysql_query("UPDATE TABLENAME set status=$status WHERE name=$name");
Comment: @sadiarehman Where the value is stored in your db or in the php script? Can you give some more informations, then I may help you
Comment: this is where i get the values
while ($row = mysql_fetch_array($sql)) {
    $name[]   = $row['name'];
    $status[] = $row['status'];

}
$name[0] and $status[0] . like that..
Comment: Ok and which value would you change in database? And in which way do you identify the row to update?
Comment: @sadiarehman Ok you would only change the status, not the name?
Comment: yes, name will not be changed i need only status to be changed w.r.t name
Comment: @sadiarehman Then you need to save the name somewhere. It is very unsafe to save it as a hidden input. You need a algorithm that makes it indecipherable. e.g you fetch the ID of them and multiply it with several numbers. look my example
Comment: Updated my answer, hope that gives you food for thought. It's not a final solution, you have to adjust it.