text:
Q: How can i create and display a self designed window on current webpage instead of popup? I want to create and display a self designed window on current webpage instead of popup as you can see on this page
Open the link and click first "Demo" button on that page.
and the same type window appeared when I tried to put a link on this question on stackoverflow which accepted my link.
for example facebook also uses this type of window to display tagged images.
please help me.

A: If you're using ASP.NET, that functionality is available in the Ajax Control Toolkit.
It's also possible to do it using straight up HTML and JavaScript.
You simply create a div with the content that you want in the pop-up, and set its "Display" property to "none".
Upon user interaction (mouse click, button click, etc) use JavaScript to set the Display to "block".  (There is a bit more to it, but that's the gist of it.)
Of course, you can just get the component that does it from the page you linked to as well.

For another way to do it, and a fuller explanation, there's a full example with source code here:  http://www.c-sharpcorner.com/uploadfile/rahul4_saxena/modal-popup-window-in-Asp-Net/

A: If you are looking for the exact code to popup a div box then here it is. Displaying the div box in the centre of the browser is harder, and will involve some more javascript to work out the centre.
Note the 'return false;' in the OnClientClick event of the button. This stops the button performing a postback and reloading the entire page.

        <form id="form1" runat="server">

            <asp:Button ID="btnPopUp" OnClientClick="togglePopUp('popUpDiv'); return false;"
                 text="Pop Up a div boxt" runat="server" />

             My popup box

        </form>


text:
Q: "dpkg: error: requested operation requires superuser privilege". Cannot remove all configuration info from removed packages, sudo doesn't work I want to run this command (see section 4 from here https://help.ubuntu.com/community/AptGet/Howto#Removal_commands):
dpkg -l | grep '^rc' | awk '{print $2}' | xargs dpkg --purge

I use sudo at the beginning but anyway I get an error:
user@user-desktop:~$ sudo dpkg -l | grep '^rc' | awk '{print $2}' | xargs dpkg --purge
[sudo] password for user:
dpkg: error: requested operation requires superuser privilege

Why sudo doesn't work? What else should I type?

A: try to login as root, to gain the super-power, you can do this by typing:
sudo -i

then write (copy/paste :: Ctrl + C / Ctrl + Shift + V <-- paste in terminal) your command in terminal, and it should work

A: sudo only applies to a single command, not the whole pipeline. In your case, the command ran as superuser was dpkg -l – which is not necessary.
On the contrary, the command really requiring the superuser access in your pipeline is dpkg --purge, so prepend sudo directly to it.
dpkg -l | grep '^rc' | awk '{print $2}' | xargs sudo dpkg --purge

By the way, awk can filter rows using regular expressions just like grep does, so you can save one command:
dpkg -l | awk '/^rc/{print $2}' | xargs sudo dpkg --purge

A: sudo -i dpkg -l | grep '^rc' | awk '{print $2}' | xargs dpkg --purge

This may run your command with ROOT priviliges.
Sudo and root is different. Reference

redpajama_set_name: RedPajamaStackExchange


text:
Q: cannot access json github api response correctly I am trying to access a JSON response data from the github job posting API. Here is the JSON response structure:
 [
    {"id":"1", "title":"gameon"},
    {"id":"2", "title":"hardlife"},
    {"id":"3", "title":"lotsofbugs"}
 ]

I have been crazy finding solutions accessing id and title. I tried several ways like (assuming the response is stored in a JS variable named jsonResponse) this:

jsonResponse[0][1]["title"]

and even something like

jsonResponse[1]["title"]

but everything seems to not work at all. I want to access each id and title for every part of the response but I cannot find a way. I use to alert everything while testing it if I could access it. Everything it says is undefined whenever I try to access the JSON response data. Can someone please help me?

A: If you want to access each in turn you can use the forEach function.
var response =  [
     {"id":"1", "title":"gameon"},
     {"id":"2", "title":"hardlife"},
     {"id":"3", "title":"lotsofbugs"}
];

response.forEach(function(obj) {
   var id = obj.id;
   var title = obj.title;
   // Do things with the data here
});

A: You are dealing with a javascript object if you are dealing with json data.   You really should just use $.parseJSON() if you can, but if not, you should be able to access the object by using myObj.id and myObj.title.   OR possibly myObj[0].id , myObj[0].title etc...  (if you need more in depth, try the javascript object reference)
Just got some updated code and a JSFIDDLE for you...   this is some code that kind of tests and demos the stringify and parseJSON functions so you can play around with it.  As you can see it's getting the correct data and alerting it. :)
(function($){
    $(function(){  //document.ready

    var myResponseData = [
        {"id":"1", "title":"gameon"},
        {"id":"2", "title":"hardlife"},
        {"id":"3", "title":"lotsofbugs"}
     ];
        myResponseData = JSON.stringify(myResponseData);
        console.dir(myResponseData);
        var myObj = $.parseJSON(myResponseData);
        console.dir(myObj);
        alert(myObj[0].title);
    });
})(jQuery);

Also as the other answer suggests, you can use a for each loop to iterate over the contents.   I would def console.dir() the response and make sure you are getting the data back correctly before ripping your hair out.  :)   Using chrome dev tools you can view the contents of the response by putting this line in your code...
console.dir(myResponseData);

You can also view the data going back and forth by clicking on "Network" in chrome dev tools, then clicking on the filename of your ajax script.   It should default to 'Response' but if not, click on that.

Please let me know if you have any questions.


text:
Q: Expected waiting time - simplified I need some assistance with a calculation I'm trying to do.
I have access to surgery waiting times data (date arrived, date completed) and I want to figure out the expected waiting time for a new patient - this should take into account the number of patients already waiting and those who have completed (I think).
I've tried looking at the average time to wait for the past three hours but this doesn't seem the right way to do it (too simple I think).
I've also thought about perhaps looking at the average wait time for the same day of the week for a previous week...would that be sensible?
There are so many variables to consider but I need something relatively simple...


text:
Q: Is the union of two circles in $R^{2}$ a locally Euclidean space? Let $S$ be the topological space defined by the union of the two circles in $R^{2}$ with radius 1 and centers $(-1,0)$ and $(1,0)$, and the topology induced by the usual one of $R^{2}$.
Is $S$ a locally Euclidean Space?
I have got some ideas to prove that it is not a locally Euclidean Space, but I am stuck in the last steps.
My proof is:
Let $V\subset S$ be a neighborhood of $(0,0)$, and inside the unit open ball centered at the origin. If $S$ is locally Euclidean, then $V$ is homeomorphic to $R$, then $V$-{$(0,0)$} is homeomorphic to $R$-{$0$}.
Then, I tried to find a contradiction. I got some ideas from online sources which claim that the homeomorphism between $V$-{$(0,0)$} is homeomorphic to $R$-{$0$} will not happen since $V$-{$(0,0)$} has at least four connected components but $R$-{$0$} has only two.
I am really confused about the claim, and I checked the definition of connected component, but I still don't understand. How to prove that $V$-{$(0,0)$} has at least four connected components but $R$-{$0$} has only two? and how do you get the idea of the number of connected components?
Thank you so much!

A: The idea, while not being enough to comprise a proof, is very simple : on paper, removing the point $0$ from $\mathbb R$ gives two parts which seem "connected" : one on either end of zero. $V \setminus \{(0,0)\}$ has four parts : to convince yourself, draw a small circle around the point $(0,0)$ and see that the removal of that point results in four different sections. Anyway, this was said in the comments as well, but for the completeness of the answer, it must be said.
Here is a nice trick to show that $\mathbb R \setminus \{0\}$ has exactly two connected components, while $V \setminus \{(0,0)\}$ has four connected components.
First, the rather not so interesting statement:

If two spaces are homeomorphic, there is a bijection between their connected components. In particular, if the number of connected components of $X$ is finite, the the number of connected components of $Y$ is equal, and therefore also finite.

Of course, since if $X$ and $Y$ are homeomorphic, then since $f$ and $f^{-1}$ are both continuous, they both map connected components to connected components, so from here you should be able to figure out the bijection.
Second :

A subset of $\mathbb R$ is connected if and only if it is an interval.

This is a fairly standard proof, I request you to look it up . It does not use the next result, but rather uses the g.l.b property, which characterizes the real line.
Third, the following amazing statement :

Let $X$ be a set. Let $Y_n = \{1,2,\ldots,n\}$ with the discrete topology i.e. every subset is open. Then, $X$ has atleast $n$ connected components if and only if there is a continuous surjective function from $X$ to $Y_n$.

In one direction, let $X$ have $m$ connected components and let $n \leq m$. Number all the connected components from $1$ to $n$ so that all numbers from $1$ to $n$ are covered, which can be done as $n \leq m$. Then, for $x \in X$, send $x$ to the number of the component which $x$ belongs to. This is surjective since every number is the image of some connected component. On the other hand it is continuous, since the inverse image of any subset of $Y$ is just a union of connected components, which is open. So we are done.
In the other direction, suppose that $X$ has less than $n$ connected components. Then, let $f$ be a continuous surjection from $X$ to $Y_n$. It is clear that  $f$ takes connected sets to connected sets, so each connected component of $X$ must go to the same number, but then $X$ has less than $n$ connected components, so some number in $Y$ must miss out, which can't happen : $f$ is surjective.

Using the three above facts, now you have a rigorous treatment in front of you:

*

*Map $S= \mathbb R \setminus \{0\}$ to $\{1,2\}$ via $f(x) = 1$ if $x < 0$ and $2$ otherwise. This is continuous, and surjective, so $S$ has at least two connected components. But the two parts are intervals so they are already connected, so $S$ has exactly two connected components.

*Find the following description of $T = V \setminus \{(0,0)\}$ : without loss of generality we can assume that $V$ was actually a ball around the origin, of radius $r < 1$, so then $T$ has a nice description . You can find a constant $c$ depending on $r$ so that : $$T = \{(x_1,x_2) : |(x_1,x_2) - (1,0)| = 1 , -c < x_2 < 0\} \\ \quad \cup \{(x_1,x_2) : |(x_1,x_2) - (1,0)| = 1 , c > x_2 > 0\}  \\\quad  \cup \{(x_1,x_2) : |(x_1,x_2) - (-1,0)| = 1 , -c < x_2 < 0\} \\\quad \cup \{(x_1,x_2) : |(x_1,x_2) - (-1,0)| = 1 , c > x_2 > 0\}$$

*Drawing a diagram will convince you of the relationship between $c$ and $r$, but I intend not to derive it. The key point : the above sets are disjoint by triangle inequality, and furthermore, each one of them is homeomorphic to an interval, since we can parametrize the circle of radius one via the angle it makes with the $x$-axis or something like that, and then map each point in the set to the parameter it corresponds to.

*Finally, conclude that $V$ is homeomorphic to four disjoint intervals in $\mathbb R$. We can do what we did earlier : find a map to $\{1,2,3,4\}$ which is continuous and surjective, and note that there are four intervals to find that $T$ has four connected components.
So, there's a lot that goes on behind the scenes. I hope to have uncovered some of the magic lying behind these uncolourful statements.


text:
Q: WIX - How to use RemoveFiles We have multiple configuration files. Based on the environment selected, right file gets copied and the rest of the files should get deleted.
I am using RemoveFile but that doesn't delete anything or may be I am not using it right. Can someone give an example to delete *.config from [INSTALLDIR] during the install, after all files have been copied.

A: In the example below RemoveFile is used to delete all icons (.lnk extension) on uninstallation, also the parent folder will be removed by using RemoveFolder
<DirectoryRef Id="DirName">
  <Component Id="cmpName" Guid="{429BC364-BE5F-4EC8-9AB9-8A522F8EC089}">
    <RemoveFile Id="removeDesktopShortcuts" On ="uninstall" Name="*.lnk"/>
    <RemoveFolder Id="RemoveFolder1" On="uninstall"/>
  </Component>
</DirectoryRef>

A: Why don't you go with option of custom action. Create a method in C# or other and then call it after 'InstallFinalize'.
Example :
[CustomAction]
public static ActionResult RemoveConfigs(Session session)
{
    string configfiles = "\"" + session["INSTALLDIR"].ToString() + "*.config\"" ;
    System.Diagnostics.Process.Start("cmd.exe", "/C del " + configfiles);

    return ActionResult.Success;
}

In CustomAction.wxs add
<Custom Action="ZA_RemoveConfigs" After="InstallFinalize">NOT INSTALLED AND NOT REMOVE</Custom>


text:
Q: Getting physical device sensor output with Qt I'm Trying to develop a program with Qt Creator 5.1.1 for android that can get output of three sensors (QAccelerometer,Qtilt,Qmagnetometer) of physical device (HTC One x)
Everything is ok , but there is an issue that when i want to show the output in the textlabel , the output disappear very quickly and it is turning to zero.
Here is My MainWindow.cpp :
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QTimer *timer;
    timer = new QTimer();
    connect(timer,SIGNAL(timeout()),this,SLOT(update()));
    timer->start(10);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::update(){

//----------------------TiltSensor--------------///////
    QSensor sensor("QTiltSensor");
    sensor.start();
    QSensorReading *reading = sensor.reading();
    qreal xrotation = reading->property("xRotation").value<qreal>();
    qreal yrotation = reading->property("yRotation").value<qreal>();

//---------------QMagnetometer-------------------/////////

    QSensor sensor2("QMagnetometer");
    sensor2.start();
    QSensorReading *reading2 = sensor2.reading();
    qreal xmagnet = reading2->property("x").value<qreal>();
    qreal ymagnet = reading2->property("y").value<qreal>();
    qreal zmagnet = reading2->property("z").value<qreal>();

//----------------------QAccelerometer--------------------------/////

    QSensor sensor3("QAccelerometer");
    sensor3.start();
    QSensorReading *reading3 = sensor3.reading();
    qreal xAccel = reading3->property("x").value<qreal>();
    qreal yAccel = reading3->property("y").value<qreal>();
    qreal zAccel = reading3->property("z").value<qreal>();
//-----------------------------------------------------------------///

    {
    ui->label->setText(QString::number(xrotation));
    ui->label_2->setText(QString::number(yrotation));

    }

    {
            ui->label_10->setText(QString::number(xmagnet));
            ui->label_8->setText(QString::number(ymagnet));
            ui->label_11->setText(QString::number(zmagnet));
    }

    {
            ui->label_17->setText(QString::number(xAccel));
            ui->label_16->setText(QString::number(yAccel));
            ui->label_15->setText(QString::number(zAccel));
    }
    }

i googled a lot and reading every document in Qt-Help but got nothing , i even try to use readychange() signal but it doesn't seem to be useful.

A: After you run sensor start you need to wait. You should probably start the sensor in you constructor and connect the signal readingChanged to your slot. Hope this helps

A: Old post but maybe people still have the same issue.
change the name of your function from update() to updateVals() for example.
update() is reserved and it will give you issues without warning you about it.


text:
Q: Off-screen navigation - right and left - css only I'm trying to create a right and left off-screen navigation drawer with only css and I'm having problems getting each side to work properly.
I'm using checkboxes as my buttons like this:
<input type="checkbox" id="toggle-right">
<input type="checkbox" id="toggle-left">

If I have the toggle-right place on top then the right drawer opens, but not the left.
If I reverse the order like this:
<input type="checkbox" id="toggle-left">
<input type="checkbox" id="toggle-right">

Toggle left will work, but not toggle right.
I made a JSFiddle to show you what I mean.
If someone has time to take a look and help me figure this out I would appreciate it.
While reviewing the JSFiddle, reverse the order of the checkbox toggles to see what I'm talking about.

A: The problem lies with the usage of + - adjacent sibling selector. As it works only for next element to your checkbox, it will only works for one of them. The solution is to use ~ - general sibling selector.

header {
  width: 100%;
  height: 90px;
  background-color:#f1f1f1;}

.menu-toggle {
  text-decoration: none;
  text-align: center;
  width: 44px;
  height: 44px;
  font-size: 30px;
  color: rgba(0, 0, 0, 0.5);
  -webkit-transition: all 0.15s ease-out 0s;
  -moz-transition: all 0.15s ease-out 0s;
  transition: all 0.15s ease-out 0s;
  position: absolute;
  top: 0px;
  right: auto;
  bottom: 0;
  left: 20px;
  z-index: 2; }

.menu-toggle:hover {
  color: #000000; }

#toggle-left {
  display: none; }
#toggle-left:checked ~ .page-wrap nav.menu {
  left: 0px; }
#toggle-left:checked ~ .page-wrap .menu-toggle {
  left: 220px; }

.profile-toggle {
  text-decoration: none;
  text-align: center;
  width: 44px;
  height: 44px;
  font-size: 30px;
  color: rgba(0, 0, 0, 0.5);
  -webkit-transition: all 0.15s ease-out 0s;
  -moz-transition: all 0.15s ease-out 0s;
  transition: all 0.15s ease-out 0s;
  position: absolute;
  top: 0px;
  right: 40px;
  bottom: 0;
  left: auto;
  z-index: 2; }

.profile-toggle:hover {
  color: #000000; }

#toggle-right {
  display: none; }
#toggle-right:checked + .page-wrap nav.profile {
  right: 0px; }
#toggle-right:checked + .page-wrap .profile-toggle {
  right: 220px; }

nav.menu {
  position: fixed;
  top: 0px;
  right: auto;
  bottom: 0px;
  left: -270px;
  -webkit-transition: all 0.15s ease-out 0s;
  -moz-transition: all 0.15s ease-out 0s;
  transition: all 0.15s ease-out 0s;
  height: auto;
  width: 200px;
  background: #111111;
  z-index: 2000; }

nav.profile {
  position: fixed;
  top: 0px;
  right: -270px;
  bottom: 0px;
  left: auto;
  -webkit-transition: all 0.15s ease-out 0s;
  -moz-transition: all 0.15s ease-out 0s;
  transition: all 0.15s ease-out 0s;
  height: auto;
  width: 200px;
  background: #990000;
  z-index: 2000; }
<input type="checkbox" id="toggle-left">
<input type="checkbox" id="toggle-right">

      ☰
      +


text:
Q: How to remove the .Trash-1000 folder from a Samba network volume This is a follow up on the question Prevent Nautilus / Nemo from creating .Trash-1000 folder in mounted devices. In essence, the creation of this folder is hard-coded in these programmes and can not be switched off. The wisest thing to do is not use these programmes to access network volumes.
Now I would like to delete the .Trash-1000 folder Nemo created on a network volume (Samba). It is taking up unnecessary space and confusing other users. However, this what I get when I try to do so:
$ rm -rf .Trash-1000/
rm: cannot remove '.Trash-1000/files/n00e005_dem.tif': Device or resource busy
rm: cannot remove '.Trash-1000/files/s50w080_dem.tif': Device or resource busy
rm: cannot remove '.Trash-1000/files/s45e145_dem.tif': Device or resource busy

Using sudo results in the same messages. How can I remove this folder from the volume?
P.S.: there is a previous question on how to delete this folder from a USB volume, but that is a different problem (and straightforward to solve).


text:
Q: Thread open forms in Delphi I want to create new instances of form(and show them) from a Thread. But it seems that it freeze my application and my thread(my thread becomes an non syncrhonization thread, and it freeze my aplication).
Like this(but it doesn't make what i am looking for)
procedure a.Execute;
var frForm:TForm;
    B:TCriticalSection;
begin
   b:=TCriticalSection.Create;
   while 1=1 do
   begin
     b.Enter;

        frForm:=TForm.Create(Application);
        frForm.Show;
     b.Leave;
     sleep(500); //this sleep with sleep my entire application and not only the thread.
      //sleep(1000);
   end;
end;

I don't want to use Classes.TThread.Synchronize method

A: TThread.Synchronize() is the simplest solution:
procedure a.Execute;
begin
  while not Terminated do
  begin
    Synchronize(CreateAndShowForm);
    Sleep(500);
  end;
end;

procedure a.CreateAndShowForm;
var
  frForm:TForm;
begin
  frForm:=TForm.Create(Application);
  frForm.Show;
end;

If you are using a modern version of Delphi and don't need to wait for the TForm creation to complete before letting the thread move on, you could use TThread.Queue() instead:
procedure a.Execute;
begin
  while not Terminated do
  begin
    Queue(CreateAndShowForm);
    Sleep(500);
  end;
end;

Update: If you want to use PostMessage(), the safest option is to post your messages to either the TApplication window or a dedicated window created via AllocateHWnd(), eg:
const
  WM_CREATE_SHOW_FORM = WM_USER + 1;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  Application.OnMessage := AppMessage;
end;

procedure TMainForm.AppMessage(var Msg: TMsg; var Handled: Boolean);
var
  frForm:TForm;
begin
  if Msg.message = WM_CREATE_SHOW_FORM then
  begin
    Handled := True;
    frForm := TForm.Create(Application);
    frForm.Show;
  end;
end;

procedure a.Execute;
begin
  while not Terminated do
  begin
    PostMessage(Application.Handle, WM_CREATE_SHOW_FORM, 0, 0);
    Sleep(500);
  end;
end;

.
const
  WM_CREATE_SHOW_FORM = WM_USER + 1;

var
  ThreadWnd: HWND = 0;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  ThreadWnd := AllocateHWnd(ThreadWndProc);
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
  DeallocateHwnd(ThreadWnd);
  ThreadWnd := 0;
end;

procedure TMainForm.ThreadWndProc(var Message: TMessage);
var
  frForm:TForm;
begin
  if Message.Msg = WM_CREATE_SHOW_FORM then
  begin
    frForm := TForm.Create(Application);
    frForm.Show;
  end else
    Message.Result := DefWindowProc(ThreadWnd, Message.Msg, Message.WParam, Message.LParam);
end;

procedure a.Execute;
begin
  while not Terminated do
  begin
    PostMessage(ThreadWnd, WM_CREATE_SHOW_FORM, 0, 0);
    Sleep(500);
  end;
end;

A: You cannot create a notoriously thread-unsafe VCL form in this way, (note - it's not just Delphi - all GUI development I have seen has this restriction).  Either use TThread.Synchronize to signal the main thread to create the form, or use some other signaling mechanism like the PostMessage() API.
Overall, it's best to try an keep GUI stuff out of secondary threads, as far as you can.  Secondary threads are better used for non-GUI I/O and/or CPU-intensive operations, (especially if they can be split up and be performed in parallel).
PostMessage example, (the form has just one speedbutton on it):
unit mainForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Buttons;

const
  CM_OBJECTRX=$8FF0;

type
  EmainThreadCommand=(EmcMakeBlueForm,EmcMakeGreenForm,EmcMakeRedForm);

  TformMakerThread = class(TThread)
  protected
    procedure execute; override;
  public
    constructor create;
  end;

  TForm1 = class(TForm)
    SpeedButton1: TSpeedButton;
    procedure SpeedButton1Click(Sender: TObject);
  private
    myThread:TformMakerThread;
  protected
    procedure CMOBJECTRX(var message:Tmessage); message CM_OBJECTRX;
  end;

var
  Form1: TForm1;
  ThreadPostWindow:Thandle;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.CMOBJECTRX(var message: Tmessage);
var thisCommand:EmainThreadCommand;

  procedure makeForm(formColor:integer);
  var newForm:TForm1;
  begin
    newForm:=TForm1.Create(self);
    newForm.Color:=formColor;
    newForm.Show;
  end;

begin
  thisCommand:=EmainThreadCommand(message.lparam);
  case thisCommand of
    EmcMakeBlueForm:makeForm(clBlue);
    EmcMakeGreenForm:makeForm(clGreen);
    EmcMakeRedForm:makeForm(clRed);
  end;
end;

function postThreadWndProc(Window: HWND; Mess, wParam, lParam: Longint): Longint; stdcall;
begin
  result:=0;
  if (Mess=CM_OBJECTRX) then
  begin
    try
      TControl(wparam).Perform(CM_OBJECTRX,0,lParam);
      result:=-1;
    except
      on e:exception do application.messageBox(PChar(e.message),PChar('PostToMainThread perform error'),MB_OK);
    end;
  end
    else
      Result := DefWindowProc(Window, Mess, wParam, lParam);
end;

var
  ThreadPostWindowClass: TWndClass = (
    style: 0;
    lpfnWndProc: @postThreadWndProc;
    cbClsExtra: 0;
    cbWndExtra: 0;
    hInstance: 0;
    hIcon: 0;
    hCursor: 0;
    hbrBackground: 0;
    lpszMenuName: nil;
    lpszClassName: 'TpostThreadWindow');

procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  TformMakerThread.create;
end;

{ TformMakerThread }

constructor TformMakerThread.create;
begin
  inherited create(true);
  freeOnTerminate:=true;
  resume;
end;

procedure TformMakerThread.execute;
begin
  while(true) do
  begin
    postMessage(ThreadPostWindow,CM_OBJECTRX,integer(Form1),integer(EmcMakeBlueForm));
    sleep(1000);
    postMessage(ThreadPostWindow,CM_OBJECTRX,integer(Form1),integer(EmcMakeGreenForm));
    sleep(1000);
    postMessage(ThreadPostWindow,CM_OBJECTRX,integer(Form1),integer(EmcMakeRedForm));
    sleep(1000);
  end;
end;

initialization
  Windows.RegisterClass(ThreadPostWindowClass);
  ThreadPostWindow:=CreateWindow(ThreadPostWindowClass.lpszClassName, '', 0,
      0, 0, 0, 0, 0, 0, HInstance, nil);
finalization
  DestroyWindow(ThreadPostWindow);
end.

A: Just use the "TThread.Synchronize" static method, as it is static and public it can be used even outside the thread
TThread.Synchronize(MyThread, procedure begin Myform.Show(); end);

at least in this event, in the others if "MyForm.DoubleBuffered: = true;" you will have no sync problems, but anything can call the "Application.ProcessMessages ();" method in sync.


text:
Q: dbmail failing to send intermittently We have a SQL Agent job that runs daily that sends emais out to our drivers with their schedules for the next day.
For 85% of drivers, the emails are not getting out of the SQL server. The other 15% send without error.
I checked the logs and see this error:

The mail could not be sent to the recipients because of the mail
  server failure. (Sending Mail using Account 3 (2020-03-22T16:00:06).
  Exception Message: Cannot send mails to mail server. (Failure sending
  mail.).  )

Does anyone have any idea what's wrong, or how to get a more detailed error?
This problem started after we migrated the server to a new datacenter.
We are running SQL Server 2014 on a Windows Server 2008 R2 host.

A: Adding to the SQL Mail Fail to Send quoted in the comments by LowlyDBA
From this question:
Comprehensive troubleshooting of DatabaseMail
I would first of all see what is the outcome of the following query (as you already got dbmail up and running):
--==============================================================
-- I'm doing a TOP 100 on these next several queries as they tend
-- to contain a great deal of data.  Obviously if you need to get
-- more than 100 rows this can be changed.
-- Check the database mail event log.
-- Particularly for the event_type of "error".  These are where you
-- will find the actual sending error.
--==============================================================
SELECT TOP 100 *
FROM msdb.dbo.sysmail_event_log
ORDER BY last_mod_date DESC;

--==============================================================
-- Check the actual emails queued
-- Look at sent_status to see 'failed' or 'unsent' emails.
--==============================================================
SELECT TOP 100 *
FROM msdb.dbo.sysmail_allitems
ORDER BY last_mod_date DESC;

--==============================================================
-- Check the emails that actually got sent.
-- This is a view on sysmail_allitems WHERE sent_status = 'sent'
--==============================================================
SELECT TOP 100 *
FROM msdb.dbo.sysmail_sentitems
ORDER BY last_mod_date DESC;

--==============================================================
-- Check the emails that failed to be sent.
-- This is a view on sysmail_allitems WHERE sent_status = 'failed'
--==============================================================
SELECT TOP 100 *
FROM msdb.dbo.sysmail_faileditems
ORDER BY last_mod_date DESC

Depending on the outcome of these queries, there are a few ways to troubleshoot.
Maybe the problem is not within sql? for that I use powershell to send a few test emails see if everything is ok. (change the details in the script below)
$smtpServer = "200.1.1.223"
$smtpPort = 25
$emailFrom = "donotreply@xxxxx.co.uk"
$emailTo = "mmiorelli@xxxxx.co.uk"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Port = $smtpPort
$subject = "ccatsql"
$body = "test email from ccatsql "
$smtp.Send($emailFrom, $emailTo, $subject, $body)

check if the .Net framework 3.5 is installed - that can cause weird errors, even in sql server 2016, as quoted in
SQL Server 2016 - Database Mail doesn't work without .NET 3.5
and from my own experience, sometimes, no error will be written to any log whatsoever, if the .NET 3.5 or any underlying component is missing or corrupt.
To work around this issue (ONLY if this is the issue), you can implement any one of the following:

*

*Create the DatabaseMail.exe.config and drop it next to the DatabaseMail.exe under the Binn folder.

You can use notepad.exe or any other editor to edit it.
Just make sure you save it by using UTF-8 encoding (in notepad.exe, select Save As... and in the Encoding combo box, select UTF-8):

*Run a repair setup action of SQL Server 2016.

*Manually install .Net Framework 3.5 on the machine.
please see more information on this answer.


text:
Q: Running a python file to train GAN using reinforcement learning I'm reading the Deep Reinforcement Learning Hands-On book by Maxim Lapan but have trouble running code here. I get the following error when running this file. I'm new to ubuntu's command line and PyTorch but I'm familiar to Deep Learning. Please help me solve this problem. Thank you!
I tried to run this file using python 03_atari_gan.py
How do I pass 'mode' while running the program?
Thanks!

INFO: Making new env: Breakout-v0 INFO: Making new env: AirRaid-v0
  Traceback (most recent call last):   File "03_atari_gan.py", line 138,
  in
      envs = [InputWrapper(gym.make(name)) for name in ('Breakout-v0', 'AirRaid-v0', 'Pong-v0')]   File "03_atari_gan.py", line 138, in

      envs = [InputWrapper(gym.make(name)) for name in ('Breakout-v0', 'AirRaid-v0', 'Pong-v0')]   File
  "/home/sandesh/rl/lib/python3.6/site-packages/gym/envs/registration.py",
  line 156, in make
      return registry.make(id, kwargs)   File "/home/sandesh/rl/lib/python3.6/site-packages/gym/envs/registration.py",
  line 101, in make
      env = spec.make(**kwargs)   File "/home/sandesh/rl/lib/python3.6/site-packages/gym/envs/registration.py",
  line 73, in make
      env = cls(_kwargs)   File "/home/sandesh/rl/lib/python3.6/site-packages/gym/envs/atari/atari_env.py",
  line 69, in init
      self.seed()   File "/home/sandesh/rl/lib/python3.6/site-packages/gym/envs/atari/atari_env.py",
  line 98, in seed
      ).format(self.game_mode, self.game, modes) AssertionError: Invalid game mode "0" for game air_raid. Available modes are: [1 2 3 4 5 6 7
  8]


text:
Q: How can I treat the circle as a control after drawing it? - Moving and selecting shapes Actually, after clicking on each circle i want its color to be changed, for instance, i  want it to turn into red,Overall, i wanna treat it as control.
i know how to draw the circles that represent the nodes of the graph when i Double click on the picturebox. i'm using the following code:
        public Form1()
    {
        InitializeComponent();

        pictureBox1.Paint += new PaintEventHandler(pic_Paint);
    }

    public Point positionCursor { get; set; }
    private List<Point> points = new List<Point>();
    public int circleNumber { get; set; }

    private void pictureBox1_DoubleClick(object sender, EventArgs e)
    {
        positionCursor = this.PointToClient(new Point(Cursor.Position.X - 25, Cursor.Position.Y - 25));

        points.Add(positionCursor);
        Label lbl = new Label();
        lbl.BackColor = Color.Transparent;
        lbl.Font = new Font("Arial", 7);

        lbl.Size = new Size(20, 15);

        if (circleNumber >= 10)
        {
            lbl.Location = new Point(points[circleNumber].X + 3, points[circleNumber].Y + 6);
        }
        else
        {
            lbl.Location = new Point(points[circleNumber].X + 7, points[circleNumber].Y + 7);
        }
        lbl.Text = circleNumber.ToString();
        pictureBox1.Controls.Add(lbl);
        circleNumber++;
        pictureBox1.Invalidate();
    }

    private void pic_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.SmoothingMode = SmoothingMode.AntiAlias;

        using (var pen = new Pen(Color.DimGray, 2))
        {
            foreach (Point pt in points)
            {
                g.FillEllipse(Brushes.White, pt.X, pt.Y, 25, 25);
                g.DrawEllipse(pen, pt.X, pt.Y, 26, 26);
            }
        }
    }

A: You need to perform a hit-test to check if a point is in a circle. As an option you can add a circle to a GraphicsPath and the use IsVisible method of the path to check if the point is in circle.
For example having a ponit p as top-left location of a circle with diameter d, you can check if current clicked point is in the circle or con this way:
var result = false;
using (var path = new GraphicsPath())
{
    path.AddEllipse(p.X, p.Y, d, d);
    result = path.IsVisible(e.Location);
}

Sample Code
I see you have asked multiple questions in this topic. So here I share some code to help you to be in right direction.
define variables for fill color, selected fill color, circle size, border width and etc, to be able to change them simply if you need.
List<Rectangle> Shapes = new List<Rectangle>();
int selectedIndex = -1;
Size size = new Size(25, 25);
Color fillColor = Color.White;
Color selectedfillCOlor = Color.Red;
Color borderColor = Color.Gray;
int borderWidth = 2;

DoubleClick
Here add circles to the Shapes list. It's enough to add the bounding rectangle of a circle to the list.
private void pic_MouseDoubleClick(object sender, MouseEventArgs e)
{
    var p = e.Location;
    p.Offset(-size.Width / 2, -size.Height / 2);
    Shapes.Add(new Rectangle(p, size));
    pic.Invalidate();
}

Click
Here perform hit-test to check if the point is in one of circles.Check if the Ctrl key is down when click, to make selection, then set the found index as selectedIndex to use it when painting.
private void pic_MouseClick(object sender, MouseEventArgs e)
{
    if (ModifierKeys != Keys.Control)
        return;
    selectedIndex = -1;
    for (int i = 0; i < Shapes.Count; i++)
    {
        using (var path = new GraphicsPath())
        {
            path.AddEllipse(Shapes[i]);
            if (path.IsVisible(e.Location))
                selectedIndex = i;
        }
    }
    pic.Invalidate();
}

Paint
Set SmoothingMode of graphics object to AntiAlias to have a more smooth drawing. Then draw shapes in a for loop and pay attention to selectedIndex to use a different fill color for selected shape.
To draw the text, yo don't need to use a label and you can simply draw text using TextRenderer class.
private void pic_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    for (int i = 0; i < Shapes.Count; i++)
    {
        var selected = (selectedIndex == i);
        using (var brush = new SolidBrush(selected ? selectedfillCOlor : fillColor))
            e.Graphics.FillEllipse(brush, Shapes[i]);
        using (var pen = new Pen(borderColor, borderWidth))
            e.Graphics.DrawEllipse(pen, Shapes[i]);
        TextRenderer.DrawText(e.Graphics, (i + 1).ToString(),
                this.Font, Shapes[i], Color.Black,
                TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter);
    }
}

Some Notes

*

*It's better to encapsulate codes in a new control derived from PictureBox or derived Controland set DoubleBuffered to true.

*It's a good option to encapsulate Circle in a Circle class which performs hit testing and rendering of a circle. Specially if you want to move them later or perform some other interactions or let each circle has it's own properties like color ,etc.
Sample Circle Class
Here is a sample circle class which can be a good start point.
public class Circle
{
    private Color selectedFillColor = Color.Red;
    private Color normalFillColor = Color.Red;
    private Color borderColor = Color.Red;
    private int borderWidth = 2;
    public Point Location { get; set; }
    public int Diameter { get; set; }
    public Rectangle Bounds
    {
        get
        {
            return new Rectangle(Location, new Size(Diameter, Diameter));
        }
    }
    public bool HitTest(Point p)
    {
        var result = false;
        using (var path = new GraphicsPath())
        {
            path.AddEllipse(Bounds);
            result = path.IsVisible(p);
        }
        return result;
    }
    public bool Selected { get; set; }
    public void Draw(Graphics g)
    {
        using (var brush = new SolidBrush(
            Selected ? selectedFillColor : normalFillColor))
            g.FillEllipse(brush, Bounds);
        using (var pen = new Pen(borderColor, 2))
            g.DrawEllipse(pen, Bounds);
    }
}


text:
Q: Can you switch integrals if you don't care about the infinite part? So, schematically, suppose one is doing some real integral
$$\mathcal{I}=\int_a^\Lambda \int_b^cf(x,y)\,dx\,dy,$$
where $\Lambda$ is some cutoff that one would like to take to infinity and suppose the inner integral is finite and $\int_b^c|f(x,y)|\,dx<\infty$ for any $y$. Further suppose that the whole integral diverges as $\Lambda\to\infty$ (for example, the case I have in mind is $\mathcal{I}\sim \alpha\Lambda + \beta\log\Lambda+$ finite). Obviously, switching the order of integration is not okay. However, if I am interested only in the non-divergent part of the integral, is switching the order of integration allowed? Or are there conditions under which it is allowed if I only want the part that is finite as $\Lambda\to\infty$?

A: Without going too far afield, e.g., theorems of Tonelli and Fubini,  if $f$ is continuous on a bounded rectangle $[a,b]\times [c,d]$, then it must hold that
$$\int_a^b \int_c^d f(x,y) \, dy \, dx =\int_c^d \int_a^b f(x,y) \, dx \, dy $$
This can be proved easily using the uniform continuity of $f$ on the compact rectangle.
A counterexample when $f$ is not continuous is
$$ \int_0^1\int_0^1 \frac{x-y}{(x+y)^3} \, dx\, dy = -\frac{1}{2}, \quad   \int_0^1 \int_0^1 \frac{x-y}{(x+y)^3} \, dy\, dx = \frac{1}{2}$$
The integrals are evaluated easily by noticing that
$$\frac{x-y}{(x+y)^3} = -\frac{\partial}{\partial x} \left( \frac{x}{(x+y)^2} \right) =\frac{\partial}{\partial y} \left( \frac{x}{(x+y)^2} \right),$$
and, hence,
$$ \int_0^1\int_0^1 \frac{x-y}{(x+y)^3} \, dx\, dy =  -\int_0^1\int_0^1\frac{\partial}{\partial x} \left( \frac{x}{(x+y)^2} \right) \,dx\,dy \\ = -\int_0^1\frac{1}{(1+y)^2} \, dy = \left.\frac{1}{1+y} \right|_0^1 = - \frac{1}{2}$$


text:
Q: Please delete the "best-practies" tag As we all know, Jeff Atwood has banned the best-practices tag. I had untagged a question fairly recently with the "mistyped" tag "best-practies", and just now I saw several recently asked questions with the tag. Please, could someone delete the tag so that it isn't used again?

A: Agree: this meta typo tag (ugh) has been burninated.


text:
Q: Errors Linking ColladaDom I'm trying to build a tool that uses colladadom, but I'm getting linker errors. This is my makefile
CXXFLAGS = -Wall -fPIC -g -t
OBJECTS = mesher.o oar.o primitive.o assigner.o meshmerizer.o primmesher.o colladifier.o        main.o
LIBS = -I/opt/local/include -L/opt/local/lib -lboost_system -lboost_filesystem -    lcollada14dom

default:    all

all: $(OBJECTS)
$(CXX) $(CXXFLAGS) -o oarcoll $^ $(LIBS)

main.o : src/meshmerizer.h src/primmesher.h src/main.cpp
$(CXX) $(CXXFLAGS) -c $^

colladifier.o : src/colladifier.cpp
$(CXX) $(CXXFLAGS) -c $^

assigner.o : lib/assigner.cpp
$(CXX) $(CXXFLAGS) -c $^

primitive.o : lib/assigner.h src/utils.h src/prim_enum.h src/primitive.cpp
$(CXX) $(CXXFLAGS) -c $^

mesher.o : src/mesher.cpp
$(CXX) $(CXXFLAGS) -c $^

oar.o : src/oar.cpp
$(CXX) $(CXXFLAGS) -c $^

primmesher.o : src/primmesher.cpp
$(CXX) $(CXXFLAGS) -c $^

meshmerizer.o : src/meshmerizer.cpp src/primmesher.h
$(CXX) $(CXXFLAGS) -c $^

clean:
rm -f oarcoll main.o $(OBJECTS) *~

When I compile, I get this result:
Undefined symbols for architecture x86_64:
  "boost::system::generic_category()", referenced from:
  __static_initialization_and_destruction_0(int, int)in colladifier.o
  __static_initialization_and_destruction_0(int, int)in main.o
  "boost::system::system_category()", referenced from:
  __static_initialization_and_destruction_0(int, int)in colladifier.o
  __static_initialization_and_destruction_0(int, int)in main.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [all] Error 1

I can compile with no problem if I do it all in one line and do not make .o files and link them later. I.e. this:
g++ domTest.cc -I/opt/local/include -L/opt/local/lib -lboost_system -lcollada15dom -o domTest

works fine on the same machine.
I've run nm on libboost_system.dylib and the symbols that are undefined appear in the dump.
There are multiple other threads similar to this, I've seen them and tried the solutions, but it still does not work for me.
Any ideas?


text:
Q: Check if there are a looping reference in a variable? Is there a way to detect if a PHP array contains a self-reference? Example: the variable $GLOBALS has a self-reference. If I do a looping array with nested calls, PHP breaks. For instance:
function nested_call ($data) {
  foreach ($data as $value) {
    if (is_array($value)) {
      nested_call($value);
    }
  }
}

The above example will work with:
array(1,2,3,array(4,5,6,array(7,8,9)))

But will fail with $GLOBALS because it self-reference. Is there some way to check, before start nested_call again?


text:
Q: highcharter - categories on the y axis I am stumped! I am trying to do a simple scatter plot in highcharter with the categories on the y-axis and I can't figure it out.
Below is my code:
library(highcharter)

LoginTrackerAggHourly <- aggregate(LoginTracker$X1, by = list(LoginTracker$Time,LoginTracker$Username),FUN=sum)
colnames(LoginTrackerAggHourly)[which(names(LoginTrackerAggHourly) == "Group.1")] <- "Time"
colnames(LoginTrackerAggHourly)[which(names(LoginTrackerAggHourly) == "Group.2")] <- "Username"
colnames(LoginTrackerAggHourly)[which(names(LoginTrackerAggHourly) == "x")] <- "Aggregate"

hc <- highchart() %>%
  hc_chart(zoomType = "x") %>%
  hc_yAxis(type = "category", title = list(text = "Dashboard Visits", style = list(color = "#ffffff")), labels = list(style = list(color = "#ffffff"))) %>%
  hc_xAxis(title = list(text = "Hour of day", style = list(color = "#ffffff")), labels = list(style = list(color = "#ffffff"))) %>%
  hc_add_series(data = LoginTrackerAggHourly, hcaes(x = Time, y = 1, size = Aggregate, group = Username),
                type = "scatter",
                tooltip = list(headerFormat = "Site: {point.Username}
",
                               pointFormat = "Visits: {point.Aggregate} on Hour {point.Time}"))

hc

It's currently set up to have no categories, y = 1, but when I change y = Username in the hc_add_series it doesn't plot. I have type = "category" in the hc_yAxis. Not sure why it is not working!
Below is dput output:
dput(LoginTracker)
structure(list(X1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Username = c("Maastricht",
"Monroe", "Monroe", "Monroe", "Singapore", "Singapore", "Singapore",
"Singapore", "Singapore", "Singapore", "Maastricht", "Maastricht",
"Maastricht", "Maastricht", "Maastricht", "Monroe", "Maastricht",
"Maastricht", "Central", "Maastricht", "Maastricht", "Monroe",
"Central", "Central", "Monroe", "Monroe", "Central", "Phoenix",
"Maastricht", "Maastricht", "Maastricht", "Temp", "Monroe", "Monroe",
"Central", "Temp", "Central", "Singapore", "Singapore", "Singapore",
"Singapore", "Singapore", "Singapore", "Maastricht", "Maastricht",
"Maastricht", "Maastricht", "Maastricht", "Singapore", "Maastricht",
"Monroe", "Maastricht", "Maastricht", "Maastricht", "KammererJ"
), Date = structure(c(-712889, -712889, -712889, -712889, -712889,
-712888, -712888, -712888, -712888, -712888, -712888, -712888,
-712888, -712888, -712888, -712888, -712888, -712888, -712888,
-712888, -712888, -712888, -712888, -712888, -712888, -712888,
-712888, -712888, -712887, -712887, -712887, -712887, -712887,
-712887, -712887, -712887, -712887, -712887, -712887, -712887,
-712887, -712887, -712887, -712886, -712886, -712886, -712886,
-712886, -712886, -712886, -712886, -712886, -712886, -712886,
-712886), class = "Date"), Time = c("11", "14", "15", "15", "22",
"01", "01", "02", "02", "02", "02", "03", "03", "04", "07", "07",
"08", "09", "11", "11", "12", "14", "15", "15", "15", "15", "16",
"17", "03", "05", "05", "07", "07", "09", "13", "16", "16", "19",
"19", "19", "20", "20", "20", "02", "02", "02", "02", "02", "04",
"04", "09", "10", "11", "11", "12")), .Names = c("X1", "Username",
"Date", "Time"), row.names = c(3L, 5L, 10L, 11L, 13L, 14L, 15L,
16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 26L, 29L, 30L, 33L,
39L, 41L, 43L, 45L, 46L, 48L, 52L, 53L, 54L, 55L, 56L, 57L, 58L,
62L, 71L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L,
85L, 86L, 87L, 88L, 90L, 91L, 93L, 94L, 98L), class = "data.frame")

A: LoginTrackerAggHourly <- aggregate(LoginTracker$X1, by = list(LoginTracker$Time,LoginTracker$Username),FUN=sum)
colnames(LoginTrackerAggHourly)[which(names(LoginTrackerAggHourly) == "Group.1")] <- "Time"
colnames(LoginTrackerAggHourly)[which(names(LoginTrackerAggHourly) == "Group.2")] <- "Username"
colnames(LoginTrackerAggHourly)[which(names(LoginTrackerAggHourly) == "x")] <- "Aggregate"

LoginTrackerAggHourly$Username <- as.factor(LoginTrackerAggHourly$Username)
LoginTrackerAggHourly <- mutate(LoginTrackerAggHourly, typenum = as.numeric(LoginTrackerAggHourly$Username) -1)
lvls <- LoginTrackerAggHourly %>% pull(Username) %>% levels()

max <- length(lvls) - 1

hc <- highchart() %>%
  hc_chart(zoomType = "x") %>%
  hc_yAxis(categories = lvls, title = list(text = "Dashboard Visits", style = list(color = "#ffffff")), labels = list(style = list(color = "#ffffff")), min = 0, max = max) %>%
  hc_xAxis(title = list(text = "Hour of day", style = list(color = "#ffffff")), labels = list(style = list(color = "#ffffff")), step = 1) %>%
  hc_add_series(data = LoginTrackerAggHourly, hcaes(x = Time, y = typenum, size = Aggregate, group = Username),
                type = "scatter",
                tooltip = list(headerFormat = "Site: {point.Username}
",
                               pointFormat = "Visits: {point.Aggregate} on Hour {point.Time}"))


text:
Q: How to make a conditionally recursive function return (null) in ReactJS? I have a conditionally recursive function in ReactJS that I need to return (null) instead of <></> when no conditions are satisfied.
So I am quite new to ReactJS and I created this recursive function that loops over an array of arbitrary dimensions and creates these <ViewCard>'s as seen in the code below. It works fine, however when there is an empty array [], which must occur sometimes, the function returns <></>, and I need it to instead return (null) or equal to null. Can I do that somehow? Would also be nice to know how I should handle the key attribute for the created children to avoid warnings/error in console.
A suiteable solution would be if I could remove the <></> wrapper around the list.map() expression. To just return the conditional output. But as I understand that is impossible due to syntax?
function Split({ list, selectedfunc, key }) {

  return (
    <>
      {list.map((item) => {
        return (
          <>
            {isInt(item[0]) && (
              <ViewCard id={item[0]} color="red" selectedfunc={selectedfunc} />
            )}

            {Array.isArray(item[0]) && (
              <Split list={item} selectedfunc={selectedfunc} />
            )}
          </>
       );
      })}
    </>
  );
}

Also, if this recursive solution is bad practice, let me know!
Thanks in advance!

A: you could add an if clause
if (list.length === 0) {
   return null
}

// the rest of your large return

having said that, AFAIK there's no perceived difference for the user to return null or a Fragment, as none of them render anything to the DOM.
by the way, your Fragment should have a key, so better use
return (
    <>
      {list.map((item) => {
        return (
          <React.Fragment key={item.id}>
            {isInt(item[0]) && (
              <ViewCard key={<some-unique-id>} id={item[0]} color="red" selectedfunc={selectedfunc} />
            )}

            {Array.isArray(item[0]) && (
              <Split key={<some-unique-id>} list={item} selectedfunc={selectedfunc} />
            )}
          </React.Fragment>
       );
      })}
    </>
  );

replace <some-unique-id> with a unique identifier for each element. It does not have to be unique across the whole page, just unique across its siblings. Worst case scenario, you can rely on the index of the iteration (last resort). Further info


text:
Q: How to merge several arrays in a List using Linq? I have List<Product[]> and I need to join them into one Product[].

A: You can use SelectMany and then ToArray to do this.
var result = source.SelectMany(i => i).ToArray();

A: You can use .Concat() extension method as well, and then .ToArray():
x.Concat(y).Concat(z).ToArray();

A: For any more complex joins IEnumerable, GetEnumerator and yield are your friends and are super performant. Just for fun, here's some code showing extending Linq with your own custom methods does not have to be scary;
public static class MyLinqExtensions
{
    public static IEnumerable<int> RoundRobin(this IEnumerable<int> a, IEnumerable<int> b)
    {
        var ae = a.GetEnumerator();
        var be = b.GetEnumerator();

        bool aHasNumber = ae.MoveNext();
        bool bHasNumber = be.MoveNext();

        while (aHasNumber || bHasNumber)
        {
            if (aHasNumber)
            {
                yield return ae.Current;
                aHasNumber = ae.MoveNext();
            }

            if (bHasNumber)
            {
                yield return be.Current;
                bHasNumber = be.MoveNext();
            }
        }
    }
}

void Main()
{

    var arr1 = new[] { 1, 2, 3, 4 };
    var arr2 = new[] { 4, 5, 6 };
    var arr3 = new[] { 7, 8, 9};
    var arr4 = new int[] {  };

    // arrays the same size
    Assert.AreEqual(new[] { 4, 7, 5, 8, 6, 9 }, arr2.RoundRobin(arr3).ToArray());

    // array 1 bigger than array 2
    Assert.AreEqual(new[] { 1, 4, 2, 5, 3, 6, 4 }, arr1.RoundRobin(arr2).ToArray());

    // array 1 smaller than 2
    Assert.AreEqual(new[] { 4, 1, 5, 2, 6, 3, 4 }, arr2.RoundRobin(arr1).ToArray());

    // 2 empty, 1 not
    Assert.AreEqual(new[] { 4, 5, 6 }, arr2.RoundRobin(new int[] { }).ToArray());

    // 1 empty, 2 not
    Assert.AreEqual(new[] { 1, 2, 3, 4 }, arr1.RoundRobin(new int[] { }).ToArray());

    // both empty
    Assert.AreEqual(new int[] {  }, arr4.RoundRobin(arr4).ToArray());

    // prove it's Linq
    Assert.AreEqual(new[] { 1, 4, 2}, arr1.RoundRobin(arr2).Take(3).ToArray());

    Console.WriteLine("pass");
}


text:
Q: How to Take user input under Brackets? The program must take the user input in brackets, How to achieve it?
The Code:
#include <iostream>
using namespace std;
int main()
{
 cout << "Available options [-] [+] [*] [/]" << '\n';
 cout << "---------------------------------" << '\n';
 cout << " + " << '\n';
 cout << " - " << '\n';
 cout << " * " << '\n';
 cout << " / " << '\n';
 char cd_1;
 cout << "Choose One Option: [" << " " << "]";
 cin >> cd_1;
}

A: std::cout << "Choose One Option: [ ]\b\b";

The \bs will backspace 2 steps, placing the cursor between [ and ].

In the unlikely event that \b performs a destructive backspace on your target machine (which I don't think will ever happen), you have one more option:
std::cout << "                     ]\rChoose One Option: [";

Here the \r returns the cursor back to the beginning of the line (carriage return) and then the beginning of the line is printed, creating the same visual look as in the first version.


text:
Q: Another Easy jQuery Question I have the bellow code, I wish to create an IF statement so the loadScript function is only called for a specific HREF. But when I try and alert the value of the href it returns "Undefined"...
Many Thanks,
J
$(document).ready(function()
        {
            $('.jNav').click(function()
            {
                $('#sandbox').load($(this).attr('href'),function()
                {
                    alert("From here " + $(this).attr('href') + " to here.");
                    loadScript();
                });
                return false;
            });
        });

A: Your issue is just scoping.  In your load() callback, this refers to the element you're calling load() on, which happens to be $('#sandbox'), and thus: no href.  Usually what I do is something like this:
$('.jNav').click(function()
{
  var self = this;
  $('#sandbox').load($(this).attr('href'),function()
  {
    // Notice the use of self here, as we declared above
    alert("From here " + $(self).attr('href') + " to here.");
    loadScript();
  });
  return false;
});

Doing this ensures that you can still get to the thing that you clicked from inside the load() callback.

A: The problem is one of context: The call to $(this) in the alert refers to $('#sandbox') not $('.jNav'). Simply define a variable for you first reference.

A: When you are inside the callback for $('#sandbox').load, this refers to $('#sandbox'), and not to $('.jNav').  If you want to alert the href, save that (or a reference to this) in a variable.
$('.jNav').click(function(){
  var that = this;
  $('#sandbox').load($(this).attr('href'),function(){
    alert($(that).attr('href'));
    //...
  });
}

OR
$('.jNav').click(function(){
  var href = $(this).attr('href');
  $('#sandbox').load($(this).attr('href'),function(){
    alert(href);
    //...
  });
}

A: $(this) was the .jNav, but in your callback it's now the #sandbox. Pre-cache the variable at the point where it's presented to you, then use it wherever you like.
Improving slightly on Groovetrain's answer, I'd write:
$('.jNav').click(function(event) {
  var $self = $(this);
  var href  = $self.attr('href');

  $('#sandbox').load(href, function() {
    alert("From here " + href + " to here.");
    loadScript();
  });

  event.preventDefault(); // better than `return false`
});

A: Inside your innnermost function the context (this) is set to the #sandbox element. You'll want to get the href attribute from the .jNav element beforehand and store it in a variable.
Example code

A: Take care of what "this" is in what part of your function. In the innermost function, you are calling it from $('#sandbox'),which I suspect doesn't have a href attribute. the best solution would probably be to pass the value of the href into the function or store it in a variable.

A: $(document).ready(function()
        {
            $('.jNav').click(function()
            {
                $('#sandbox').load($(this).attr('href'),function()
                {
                    alert("From here " + $(this).parent().attr('href') + " to here.");
                    loadScript();
                });
                return false;
            });
        });


text:
Q: How to get a more dense representation from Counter? I have a dict of values, which I want to sum up.
I have used this code to achieve this
countTest = Counter(chain.from_iterable(e.items() for e in tickets))
result = [{'name': key, 'value': value} for key, value in countTest.items()]
print(json.dumps(result, sort_keys=True, indent=4))

This produces the following values, which is the values that I expect.
[
    {
        "name": [
            "ticket",
            "Class A"
        ],
        "value": 1
    },
    {
        "name": [
            "ticket",
            "Class B"
        ],
        "value": 2
    },
    {
        "name": [
            "ticket",
            "Class C"
        ],
        "value": 3
    }
]

However I would like a more dense representation of this, preferably like this
{
    "ticket": {
        "Class A": 1,
        "Class B": 2,
        "Class C": 3
    }
}

How can I achieve this?

A: Try something like this,
In [11]: lst = [{'name': ['ticket', 'Class A'], 'value': 1},
...:  {'name': ['ticket', 'Class B'], 'value': 2},
...:  {'name': ['ticket', 'Class C'], 'value': 3}]

In [12]: {'tickets':dict((i['name'][1],i['value']) for i in lst)}
Out[12]: {'tickets': {'Class A': 1, 'Class B': 2, 'Class C': 3}}

Where lst is the first result that you generated.

A: itertools harder.
>>> {name: {item['name'][1]: item['value'] for item in items} for name, items in itertools.groupby(result, lambda x: x['name'][0])}
{'ticket': {'Class A': 1, 'Class B': 2, 'Class C': 3}}

From there the JSON is easy.

A: Starting with your original result and assuming that "ticket" is the only attribute:
print(json.dumps({'ticket' : {x['name'][1] : x['value'] for x in result}},
                  sort_keys=True, indent=4))
#{
#    "ticket": {
#        "Class A": 1,
#        "Class B": 2,
#        "Class C": 3
#    }
#}


text:
Q: GUI calculate button coding error in java Okay, first of all the project I am working on has two packages, first is murach.business which contains invoiceCalculations.java Second is murach.forms which contain InvoiceForm.java(JFrame) and SwingValidator.java
I need to add an event handler for the actionPerformed event of the Calculate button. Add code to this event handler that gets the customer type and subtotal from the form, uses the calculateDiscountPct method in the InvoiceCalculations class to calculate the the discount percent based on those values, calculates the discount amount and total, and formats and displays the values on the form.
The form has 5 rows for instance first customer type, subtotal, discount percent, discount amount and total and below that is calculate and exit button.
Here is the stack trace:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "R"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Double.parseDouble(Double.java:510)
    at murach.forms.InvoiceForm.calculateButtonActionPerformed(InvoiceForm.java:183)
    at murach.forms.InvoiceForm.access$300(InvoiceForm.java:15)
    at murach.forms.InvoiceForm$4.actionPerformed(InvoiceForm.java:81)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6382)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
    at java.awt.Component.processEvent(Component.java:6147)
    at java.awt.Container.processEvent(Container.java:2083)
    at java.awt.Component.dispatchEventImpl(Component.java:4744)
    at java.awt.Container.dispatchEventImpl(Container.java:2141)
    at java.awt.Component.dispatchEvent(Component.java:4572)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
    at java.awt.Container.dispatchEventImpl(Container.java:2127)
    at java.awt.Window.dispatchEventImpl(Window.java:2489)
    at java.awt.Component.dispatchEvent(Component.java:4572)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:704)
    at java.awt.EventQueue.access$400(EventQueue.java:82)
    at java.awt.EventQueue$2.run(EventQueue.java:663)
    at java.awt.EventQueue$2.run(EventQueue.java:661)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:677)
    at java.awt.EventQueue$3.run(EventQueue.java:675)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:674)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 25 seconds)

So far I am getting error when i hit calculate button for my code. This is my current code, could you tell me what changes i need to make to code and why?
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
      // TODO add your handling code here:
   double c = Double.parseDouble(customertypeTextField.getText());
   double s = Double.parseDouble(subtotalTextField.getText());
   pct d = Percent.parsepct(discountpercentTextField.getText());
   double a = Double.parseDouble(discountamountTextField.getText());
   double total = InvoicCalculations.calculateTotal(c, s, d);
   NumberFormat currecny = NumberFormat.getCurrencyInstance();
   totalTextField.setText(currency.format(total));
}

A: One of the textfields contains a letter, causing Double.parseDouble to fail because it is not valid. From documentation:

Throws:
NullPointerException - if the string is null

NumberFormatException - if the string does not contain a parsable double.

To prevent this, you can:

*

*ensure that when you hit the calculate button, the fields only contain valid data.  You can do this by using an InputVerifier.

*or verify before parsing that the input is valid, and display a popup or an error message if it isn't.

Others have mentioned it, and it is important enough to be stressed here: do not use Double for representing money.


text:
Q: Order buttons that represent attached monitors by Windows Display order I have the below code to draw a button(s) onto a panel for each monitor that is currently connected to the PC.
var padding = 5;
var buttonSize = new Size(95, 75);
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
    var screen = Screen.AllScreens[i];
    Button monitor = new Button
    {
        Name = "Monitor" + screen,
        AutoSize = true,
        Size = buttonSize,
        Location = new Point(12 + i * (buttonSize.Width + padding), 14),
        BackgroundImageLayout = ImageLayout.Stretch,
        BackgroundImage = Properties.Resources.display_enabled,
        TextAlign = ContentAlignment.MiddleCenter,
        Font = new Font("Segoe UI", 10, FontStyle.Bold),
        ForeColor = Color.White,
        BackColor = Color.Transparent,
        Text = screen.Bounds.Width + "x" + screen.Bounds.Height
    };

    monitorPanel.Controls.Add(monitor);
}

For devices with one or more monitors attached, the code works just fine and this is the end result:

However, while it works, I'd like to (if possible) order them as they appear in the Windows display view:

In the first screenshot, they are ordered as 2 | 3 | 1 instead of 3 | 2 | 1.
Is what I'm after possible?

A: Multiple screens in Windows are handled as one, big, "glued" working area. Based on that, order of screens in configuration is according to their position in the new working area. Assuming that all of your screens are in one line, you can just use
screen.Bounds.X
as ordering property. If the screens are layed out in multiple rows, then ordering will also have to consider Y component.
EDIT:
You could just use Linq for sorting, specifically OrderBy().
Example usage for case when screens are in one row and collection will be iterated once.
Change
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
   var screen = Screen.AllScreens[i];

to
foreach(var screen in Screen.AllScreens.OrderBy(i => i.Bounds.X))
{


text:
Q: How to concat the column name in the Range method of vba? startColumn=startRange.Column
endColumn  =endRange.Column
Range(startColumn & "5" : endColumn & "5")

I want to concatenate both column Name name and row number in  vba *

A: The .Column property returns the number of the first column in the first area in the specified range, therefor returning a numeric value. So a better practice would be:
Range(Cells(5,startColumn),Cells(5,endColumn ))

Now to improve your code a little bit it's wise to use explicit sheet references.
Dim rng as range
With Sheet1 'Change according to your sheet's CodeName
    Set rng = .Range(.Cells(5,startColumn),.Cells(5,endColumn))
End with


text:
Q: Can i run a magento2 store that sells goods to US and EU customers from a server that is in Germany(EU)? I have a magento2 store that is running on a dedicated server that is located in Germany(EU). I started selling in EU so at that time it made sense to host it there.
Question is: if I want to start selling to US customers will it have a huge impact on performance? Should I expect a very slow loading time for US customers? Or should it be ok?
P.S I've done a few tests with two cloud servers with dedicated resources one from US/NY and one from EU/GE/Berlin, both of them running a basic apache installation. The loading time for the basic apache2 welcome page was US ~100ms and EU ~200ms (Both tests done on a pc in US/TX). Will this translate into a much longer loading time for my magento2 store?

A: If you already have a single dedicated server in Germany, the store can still operate in other countries.
A CDN such as CloudFront or Fastly can reduce the loading time / latency of static resources and media. This is a fairly affordable way to achieve what you want, without too much extra effort. This makes a big difference in my experience. I personally use CloudFront, but the first time setup was somewhat complicated.
Magento Cloud uses Fastly as their default CDN. There is a free Magento 2 module that connects the CDN as well. I've never used Fastly, but I've heard good things about it.


text:
Q: How to make a ViewModel in knockout.js bind to an anonymous collection returned from a WebAPI? below code works for me

    Newly Added Customer  :

    Newly Added Product   :

    Newly Added Company   :

    Total No of Customers :

    Total No of Products  :

    Total No of Companies :

But I wanted to make a ViewModel such that , it could directly bind with the JSON object when calling AJAX Request. Instead of each time assiging each observable the value , can the ViewModel be optimized as a collection?

A: Have you looked at the knockout mapping plugin?
You use it like this:
var viewModel = ko.mapping.fromJSON(data);

inside your getJSON success function.


text:
Q: Reemplazar todas los caracteres en python tengo esto, opcionRandom es una palabra y quisiera reemplazar todos los caracteres por * sin embargo solo reemplaza algunos caracteres y no todos, que podria hacer?
for letra in opcionRandom:
    palabraReemplazada = opcionRandom.replace(letra, '*')

print(palabraReemplazada)


text:
Q: Publish ClickOnce using the Internet I've seen this asked a couple times but there's either no answer at all, or the answer uses VS 2012 or earlier when this was allowed. It seems Microsoft removed this feature in VS 2013.
Is there any way to publish a ClickOnce application as a web page?
Edit: Here's the feedback report for the removal of the feature:
https://connect.microsoft.com/VisualStudio/feedback/details/1013145/vs-2013-4-rc-publish-xbap-via-http

A: It looks like the feature is still there.
This guide explains how to specify a web page How to: Specify a Publish Page for a ClickOnce Application

A: XBAPs were removed, but you can still publish to an HTTP/HTTPS hosted endpoint.  All XBAPs gave you were browser-hosted apps, but the deployment mechanism can still apply for a desktop experience with ClickOnce.
For example, I use Azure Blob Storage to host the published files, using the publish.htm as the front-end to send users.  Each time I publish, I have to push the files to the blob store, but it's very easily automated.  User's are directed to go to: http://your-blob-store-url/publish.htm
The approach I use is based on this article: How to host a ClickOnce deployment in Azure Blob Storage


text:
Q: Converting Knowledge base to prolog New Task:
I have a set of objects aka fruits in my bag:
apple(b).
orange(c).
pear(d).
carrot(e).
onion(f).
pepper(g).

And these are the rules:

*

*∀x, Fruit(x) V Vegetable(x) [everything is a fruit or vegetable]

*∀x, Apple(x) -> Red(x) V Green(x) [Apples are red or green]

*∀x, Apple(x) V Orange(x) V Pear(x)) -> Fruit(x) [apples, oranges and pears are fruits]

*∀x, Carrot(x) V Pepper(x) -> Vegetable(x) [carrots and peppers are veges]

*∀x, fruit(x) -> tasty(x)   [all fruit are tasty]

*∀x, Carrot(x) -> tasty(x)   [all carrot are tasty]

*∀x, Onion(x) -> ¬tasty(x) [onion are not tasty]

Old Task completed:

*

*∀x, Dogs(x) V Cats(x) [everything is a dog or a cat]

*∀x, GShephard(x) -> Black(x) V White(x) [germanshephard are black or white]

*∀x, GShephard(x) V Canine(x) V Rottweiler(x)) -> Dog(x) [germanshephard, canine and rottweiler are dog]

*∀x, lion(x) -> hairy(x) [all lion are hairy]

*∀x, fish(x) -> ¬hairy(x) [fish are not hairy]

Based on what Daniel helped me learn and what I've tried on my own this is the code i've come up with:
% the Facts

apple(a).
apple(b).
orange(c).
pear(d).
carrot(e).
onion(f).
pepper(g)

I want to be able to ask these questions to my knowledge base:

*

*What fruits are red?

*Is some onion tasty?

*What things are coloured?

*Is there a tasty vegetable?

So far, only 2 and 3 works when I use the queries: 2 tasty(f) returns false which i think is correct and for 3 I use coloured(X) and it returns the apples. Any idea how to get ask queries to get answers for 1 and 4?

A: Let's start with the first one:
dog_or_cat(X) :- dog(X) ; cat(X).

This could also be represented with multiple clauses:
dog_or_cat(X) :- dog(X).
dog_or_cat(X) :- cat(X).

Rule #2 will be similar.
Rule #3. It's common for a statement like this to appear "backwards" in Prolog. This is because Prolog is really attempting to prove something, and to do that it has to fulfill the body of the clause. So let's look at it:
dog(X) :- gshephard(X) ; canine(X) ; rottweiler(X).

What Prolog will do when it sees dog(X) is attempt to find a solution to gshephard(X). If that fails, it will try canine(X) etc. That this happens in a certain order is both necessary for computation and a major difference between actual logic and Prolog, but anyway, that's usually how implication gets handled in Prolog.
Rules 4 and 5 are similar to 3, except you need to know that negation in Prolog is furnished by the \+ operator.
Edit: In response to your new questions:
red_fruit(X) :- fruit(X), red(X).  % question 1
tasty_veg(X) :- vegetable(X), tasty(X). % question 4

It looks like you're having trouble with how to say "and" in Prolog. It's just ",", meaning, satisfy this and then that. red_fruit(X) is read as "to prove X is a red fruit, first prove X is a fruit, then prove X is red."


text:
Q: Open an overlay while nextpage is loading Trying to open an overlay (with JqueryTools) with loading message before the page changes, can't find how to use the href attribute of my trigger (i'm using a class .btn_menu for multiple button)
HTML

JS
$(function() {

    var triggers = $(".btn_menu a").overlay({
    expose: {
        color: '#000',
        loadSpeed: 200,
        opacity: 0.9
    },

    closeOnClick: false,
    onBeforeLoad: function(){ //right ?
    window.location = //need to get href attribute of clicked trigger

    }

    });

    var buttons = $("#loading button").click(function(e) {
    var yes = buttons.index(this) === 0;
    });

});

A: I haven't use jQuery tools much, but you could structure it a little differently to cache each .
$(function(){
  $('.btn_menu a').each(function(){
    var url=this.href;
    $(this).overlay({
      //other options
      onBeforeLoad: function(){
        //do something with url
      }
    });
  });
});


text:
Q: Schedule the shell script in different servers using same DAG file I am completely new to Apache Airflow. I have a situation. The code I have used is
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
from airflow.contrib.operators.ssh_operator import SSHOperator
from airflow.contrib.hooks.ssh_hook import SSHHook

default_args = {
                 'owner': 'john',
                 'depends_on_past': False,
                 'email': [''],
                 'email_on_failure': False,
                 'email_on_retry': False,
                 'retries': 0,
                 'retry_delay': timedelta(minutes=5)
               }

 dag = DAG(
            'tutorial',
            default_args = default_args,
            description='A simple tutorial DAG',
            schedule_interval=None)

bash_tutorial = """
  echo "Execute shell file: /A/B/server/tutorial.ksh"
  echo "{{macros.ds_format(ds, "%Y-%m-%d", "%m-%d-%Y"}}"
  source /home/johnbs/.profile
  /A/B/server/tutorial.ksh
 """

t1 = SSHOperator(
                ssh_conn_id='dev'
                task_id='tutorial.ksh'
                command=bash_tutorial,
                dag=dag
        )

Using airflow, I want to trigger a ksh script in different servers like dev and test servers i.e.
tutorial.ksh is present in dev server(conn_id is 'dev') of the path (/A/B/C/tutorial.ksh) and in test server(conn_id is 'test') of the path (/A/B/D/tutorial.ksh)...Here you can see C folder from dev and D folder from test...Which area should I update the code?

A: Each instance of SSHOperator execute a command on a single server.
You will need to define each connection separately as explained in the docs and then you can do:
server_connection_ids = ['dev', 'test']
start_op = DummyOperator(task_id="start_task", dag=dag)
for conn in server_connection_ids:
    bash_tutorial = f"""
      echo "Execute shell file: /A/B/server/tutorial.ksh"
      echo "{{macros.ds_format(ds, "%Y-%m-%d", "%m-%d-%Y"}}"
      source /home/johnbs/.profile
      /A/B/{conn}/tutorial.ksh
     """
    ssh_op = SSHOperator(
        ssh_conn_id=f'{conn}',
        task_id=f'ssh_{conn}_task',
        command=bash_tutorial,
        dag=dag
    )

This will create a task per server.


text:
Q: tomcat deploy only manager on startup i have a little strange problem.
The security department in my company wants every tomcat to respect the following configuration parameters:
autoDeploy="false"
deployOnStartup="false"

When i configure the above parameters no web app (including the manager-app) will be deployed on startup and i can't deploy apps through the manager-app...
Can i define the deployment of the manager-app in server.xml or something like this? I want only to deploy the manager-app on startup.
Edit:
Here is my ${CATALINA_HOME}/conf/server.xml
...
<Service name="Catalina">
...

<Engine name="Catalina" defaultHost="localhost">
...
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="false"
            deployOnStartup="false"
            xmlValidation="false" xmlNamespaceAware="false"
            deployXml="false">
...

and this is my ${CATALINA_HOME}/webapps/manager/META-INF/context.xml
<Context path="/manager"
        docBase="/usr/share/tomcat6/webapps/manager"
        debug="0"
        privileged="true"
        autoDeploy="true"
        deployOnStartup="true">

    <ResourceLink name="users"
                global="UserDatabase"
                type="org.apache.catalina.UserDatabase"/>

    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
                allow="127.0.0.1"/>

</Context>

greets
Goetz

A: From the Apache 6 documentation:
https://tomcat.apache.org/tomcat-6.0-doc/config/context.html
in the Attributes section of Context, the documentation for the path attribute specifies:

This attribute must only be used when statically defining a Context in server.xml. In all other circumstances, the path will be inferred from the filenames used for either the .xml context file or the docBase.
Even when statically defining a Context in server.xml, this attribute must not be set unless either the docBase is not located under the Host's appBase or both deployOnStartup and autoDeploy are false. If this rule is not followed, double deployment is likely to result.

The same documentation exists in Tomcat 7, so I tried the following on Tomcat 7 and I managed to deploy only the manager application.
<Host appBase="webapps"  autoDeploy="false"  deployOnStartup="false" name="localhost" unpackWARs="true">
        <Context docBase="manager"
               path="/manager"
               antiResourceLocking="false" privileged="true"
               />
</Host>

Basically, what I did was to copy the contents of the webapps/manager/META-INF/context.xml and paste them inside the <Host> element of server.xml, ensuring of course that the path and docBase attributes were also present, as the documentation specifies. In your case I believe it would be:
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="false"
            deployOnStartup="false"
            xmlValidation="false" xmlNamespaceAware="false"
            deployXml="false">

<Context path="/manager"
        docBase="/usr/share/tomcat6/webapps/manager"
        debug="0"
        privileged="true">

    <ResourceLink name="users"
                global="UserDatabase"
                type="org.apache.catalina.UserDatabase"/>

    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
                allow="127.0.0.1"/>

</Context>

</Host>

A: You can get help from this  link , I think it's the solution you are looking for.


text:
Q: How does one switch OS users in a ruby script? I have a ruby script always initiated by the root user. The script has a certain function called fou(). This function needs to be executed as the user 'otherguy' rather than 'root'. How do i switch users mid ruby script, execute the function and then switch back to root?
NEEDS TO BE ONE PROCESS
NO CHILD PROCESSES
OS specific code is welcome as long as it will work for all/most UNIX systems.
EDIT: I'd really prefer a solution without the use of external gems, only what's built into Ruby2.0.0

A: With Process::Sys.seteuid(integer) and Process::Sys.setegid you can change the effective user id and group id. Don't confound it with Process::Sys.setuid(integer) and Process::Sys.setgid(integer). I think
Process::Sys.seteuid(12345)
Process::Sys.setegid(54321)
fou()
Process::Sys.seteuid(0)
Process::Sys.setegid(0)

is what you are looking for (with Linux).


text:
Q: How to mock the dtabase in J2EE for junit without spring boot I am working on a legacy project which is build on purely Java/J2EE servlets. No spring and other frameworks. It is built on ant.
Now I want to integrate junit with my project, I am able to integrate but I want to mock the DB and run the test cases in the mocked DB connection.
I think in spring boot we can easily do that with H2 database. But only challenge I am facing is we are not using spring boot.
I am able to mock the functions and run the test cases but what I need is to mock the full database and run the test classes on my mocked database.
Any leads how I can achieve this or it is feasible or not?

A: You can run h2 database in pure java since it is written in it. See H2 Documentation.

Start h2 database server in pure java and run sql script

*

*To start a tcp-server you can use a Server tool:
Server server = Server.createTcpServer();
server.start();

To to start also a web-server (with h2-console) you can add:
Server server = Server.createWebServer();
server.start();

*To open JdbcConnection and RunScript you can write something like this:
private void createTables(String url, String username,
                          String password, File script)
        throws SQLException, IOException {

    Properties info = new Properties();
    info.put("user", username);
    info.put("password", password);

    JdbcConnection connection = new JdbcConnection(url, info);
    InputStreamReader reader =
            new InputStreamReader(new FileInputStream(script));

    RunScript.execute(connection, reader);

    reader.close();
    connection.close();
}

See also:

*

*How to enable h2-console in spring-webmvc without spring-boot?

*Setting up in-memory H2 database without Spring Boot

*Executing script file in h2 database


text:
Q: UITableview - Can't Reload data I'm noob in Obj-c programming. I'm making an iPad application composed of a ViewController that shows me 2 text boxes , a button in the upper side , just to make a sum.
In the same Viewcontroller, i have a TableView and a Button. This Tableview initially shows me an element, but i'd want to refresh this list just clicking the button.
The function linked at the button to refresh the list ( touch down event ) is called " listaPDF " .
Viewcontroller.h
#import <UIKit/UIKit.h>

@interface VPViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    IBOutlet UITextField *txtPrimoAddendo ;
    IBOutlet UITextField *txtSecondoAddendo ;
    IBOutlet UILabel *lblTotale ;
    IBOutlet UITableView *tabella;
    NSMutableArray *lista;
   }

@property (nonatomic, retain) IBOutlet UITextField *txtPrimoAddendo;
@property (nonatomic, retain) IBOutlet UITextField *txtSecondoAddendo;
@property (nonatomic, retain) IBOutlet UILabel *lblTotale;
@property (nonatomic, retain) IBOutlet UITableView *tabella;
@property (nonatomic, retain) NSMutableArray *lista;

-(IBAction)somma ;
-(IBAction)listaPDF;

@end

Viewcontroller.m
    #import "VPViewController.h"

    @interface VPViewController ()

    @end

    @implementation VPViewController

    -(void)somma {

    int x = [[txtPrimoAddendo text] intValue];
    int y = [[txtSecondoAddendo text] intValue];
    int somma = x + y ;

    NSString *totale = [NSString stringWithFormat:@"La somma fa : %d", somma];

    [lblTotale setText:totale];
    [lblTotale setHidden:FALSE];

    }
    - (void)listaPDF {

    int contatore = 1;

    NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] resourcePath] error: nil];
    for (int i = 0; i < dirFiles.count ; i++) {

        NSString *files = dirFiles[i];
        int indice = files.length - 4 ;
        NSString *extension = [files substringFromIndex:indice];

        if([extension  isEqual: @".pdf"]) {

            NSLog(@"********* File PDF : %@", files);
            [lista insertObject:files atIndex:contatore];
            contatore++;
        }
    }
    [tabella reloadData];

    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [lista count];
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *simpleTableIdentifier = @"CellID";

    UITableViewCell *cell = [tabella dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    cell.imageView.image = [UIImage imageNamed:@"pdf.png"];
    cell.textLabel.text = [lista objectAtIndex:indexPath.row];
    return cell;
    }

    - (void)viewDidLoad
    {
        tabella.delegate = self;
        tabella.dataSource = self;

        tabella = [[ UITableView alloc] init];
        lista = [[NSMutableArray alloc] init];

        [lista insertObject:@"FIRST ELEMENT" atIndex:0];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    }

    - (void)didReceiveMemoryWarning
    {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

@synthesize lblTotale;
@synthesize txtPrimoAddendo;
@synthesize txtSecondoAddendo;
@synthesize tabella;
@synthesize lista;

@end

Thanks

A: I have tried your code as it is.
Why you initializing UITableView object in viewDidLoad. It doesn't need to be allocated if you are adding on Xib file. If you creating UITableView Programmatically then its required. Just comment/remove that initializing line and tableView's delegate methods will be called.
And In 'ListaPDF' function no items is being added to array 'lista', that's why no new entry was visible in UITableView.

A: NSMutableArray indices begin at 0 - not 1
int contatore = 1;

...
[lista insertObject:files atIndex:contatore];
contatore++;

Use addObject to add an object to a NSMutableArray
[lista addObject:files];

Remove all of your instance variables, because this:
 @property (nonatomic, retain) NSMutableArray *lista;

creates an instance variable called _lista - not lista
You have quite a bit of code backwards:
tabella.delegate = self;
tabella.dataSource = self;

tabella = [[ UITableView alloc] init];
lista = [[NSMutableArray alloc] init];

You're trying to set the delegate and datasource before the table is allocated.
It should be:
tabella = [[ UITableView alloc] init];
lista = [[NSMutableArray alloc] init];

tabella.delegate = self;
tabella.dataSource = self;

However the UITableView has been added inside Interface Builder, right?
That means it's already being created for you and you shouldn't be allocating the table here.
Also: inside Interface Builder you can rightclick+drag (or ctrl+leftclick+drag) to connect your UITableView to yourUIViewController as its delegate and datasource


text:
Q: Flutter block scroll of PageView inside another PageView I have the following Widget which displays vertically a list of pictures of some recipes, and when swipe to the right page of each of these recipes, it goes to its description page. The problem here is that when I go to DescriptionScreen, I can scroll down and go to other recipies' RecipeScreen. I want to block that, to allow vertical scroll only when user is on RecipeScreen, else if he is on DescriptionScreen, to be able just to swipe to left and continue scrolling. How it would be possible to achieve that?
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      extendBodyBehindAppBar: true,
      body: Column(
        children: [
          Expanded(
            child: PageView.builder(
              controller: verticalPageController,
              scrollDirection: Axis.vertical,
              itemCount: recipes.length,
              allowImplicitScrolling: true,
              itemBuilder: (BuildContext context, int index) {
                return PageView(
                  controller: pageControllers[index],
                  children: [
                    RecipeScreen(
                      recipe: recipes[index],
                      onRecipeDelete: onRecipeDelete,
                      ),
                    ),
                    DescriptionScreen(
                      recipeId: recipes[index].id,
                      onRecipeSave: onRecipeSave,
                    ),
                  ],
                );
              },
            ),
          ),
          SafeArea(
            top: false,
            child: Container(height: 0),
          ),
        ],
      ),
      bottomNavigationBar: BottomBar(
        page: currentPage,
      ),
    );
  }

A: I would add a onPageChanged to your horizontal PageViews and when the user goes to the DescriptionScreen, you set the physics of your vertical PageView to NeverScrollableScrollPhysics.
High level code:
class MyStatefulWidgetState extends State<MyStatefulWidget> {
  ScrollPhysics physics;

  void setScrollPhysics(ScrollPhysics physics) {
    setState(() {
      this.physics = physics
    });
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: //...
        PageView.builder(
          controller: verticalPageController,
          // ...
          physics: physics, // this line will enable / disable scroll
          itemBuilder: (ctx, index) {
            return PageView(
              controller: pageControllers[index],
              onPageChanged: (page) {
                // enable / disable vertical scrolling depending on page
                setScrollPhysics(page == 1 ? NeverScrollableScrollPhysics() : null);
              }
            )
          }
        )
    );
  }
}


text:
Q: Custom name server removes the ability of visiting websites with 'dev' in the url I am a web developer and in my younger years I tried setting up a custom name server on my mac without really knowing what I was doing. I wanted to be able to visit my own website on adreses like 'sam.dev'.
I know that I succeeded at some point and threw the program, that helped me set it up, from my macbook because it was just a trial version.
Now, a couple of years later I notice that I cannot go to any website that has .dev or dev. in the url.
This means I cannot visit websites like nodejs.dev or web.dev
I have tried resetting my DNS but I can't get it to work again.
How would I go about resetting this and what did I do wrong?
more info:
scutil --dns significant return values:

resolver #8
  domain   : test
  nameserver[0] : 127.0.0.1
  port     : 20560
  flags    : Request A records, Request AAAA records
  reach    : 0x00030002 (Reachable,Local Address,Directly Reachable Address)

resolver #9
  domain   : dev
  nameserver[0] : 127.0.0.1
  port     : 20560
  flags    : Request A records, Request AAAA records
  reach    : 0x00030002 (Reachable,Local Address,Directly Reachable Address)

contents of etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost
# BEGIN section for OpenVPN Client SSL sites
127.94.0.1  client.openvpn.net
# END section for OpenVPN Client SSL sites

I fixed my problem for .dev domains like web.dev but I still have the problem for sites like dev.to

A: I have been passively looking for this for over a year now.
thanks to @nohillside I found that the .dev redirect were resolvers and looked into my /etc/ and found a folder called resolver.
(get to /etc/resolver/ on mac using CMD-SHIFT-G in finder)
This folder contained the file named dev with the contents:
# Lovingly generated by Pow
nameserver 127.0.0.1
port 20560

from the pow website:

And Pow eliminates the need to edit /etc/hosts.

I am now wondering if I used some other application that used Pow internally and didn't clean up after itself.


text:
Q: How can an array of a data type with the size [1] suddenly be bigger than the datatype itself in Java today I have been experimenting with memory in java. Specifically, I was deserializing objects into binary data and reserializing them. Something caught my eye and that is that for example an array of bytes with the size 1 takes up less binary data than defining a byte. Here's what I mean:
I defined a single byte in java and printed out the binary data of the byte:
byte size: 75bytes
101011001110110100000000000001010111001101110010000000000000111001101010011000010111011001100001001011100110110001100001011011100110011100101110010000100111100101110100011001011001110001001110011000001000010011101110010100001111010100011100000000100000000000000001010000100000000000000101011101100110000101101100011101010110010101111000011100100000000000010000011010100110000101110110011000010010111001101100011000010110111001100111001011100100111001110101011011010110001001100101011100101000011010101100100101010001110100001011100101001110000010001011000000100000000000000000011110000111000000000001

and here's a byte[1] array
byte[] size: 28bytes
10101100111011010000000000000101011101010111001000000000000000100101101101000010101011001111001100010111111110000000011000001000010101001110000000000010000000000000000001111000011100000000000000000000000000000000000100000001

But if I print out the size of byte[0] (byte at location 0 in the array) it suddenly grows back to 75bytes:
size of byte[0] in byte array:
101011001110110100000000000001010111001101110010000000000000111001101010011000010111011001100001001011100110110001100001011011100110011100101110010000100111100101110100011001011001110001001110011000001000010011101110010100001111010100011100000000100000000000000001010000100000000000000101011101100110000101101100011101010110010101111000011100100000000000010000011010100110000101110110011000010010111001101100011000010110111001100111001011100100111001110101011011010110001001100101011100101000011010101100100101010001110100001011100101001110000010001011000000100000000000000000011110000111000000000001

And yes, it's the full object and not metadata or something because using this binary i can reconstruct the object to it's original state so the values are stored inside the binary data. Here's the code I used to find out the size of the data:
public class MemoryFunctions {
    static int sizeOf(Object input) {
        int size = 0;
        ByteArrayOutputStream checker = new ByteArrayOutputStream();

        try {
            ObjectOutputStream byteArray = new ObjectOutputStream(checker);
            byteArray.writeObject(input);
            byteArray.flush();
            byte sizeDetector[]  = checker.toByteArray();
            size = sizeDetector.length;
            int amountOfBytes = 0;
            for (byte b:
                 sizeDetector) {
                System.out.print(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'));
                amountOfBytes +=1;
            }
            System.out.println("real size in byte " + amountOfBytes);
            System.out.println();
        } catch (Exception e) {
            System.err.println(e);
        }
        return size;
    }
}

Is there any reason, that a byte array takes up less space than the byte itself? I need to heavily optimize a program. Using this information, would it be a better idea to have the values of a class that I want to deserialize into binary data in array form or are there any benefits of using "the full value"? Also, I am kind of confused with this information because as far as I know, byte and byte[] are primitive datatypes so they don't get called by reference but are stored as binary in memory "as is". What I also found out that getting the size of value 0 in the smaller array suddenly generates me a new int because it's size is again 75 bytes. Does this mean that values are generated another time when you call an index of an array?
It'd be nice if any of you had more information about this topic and could answer my questions.

A: In Java byte is a primitive type passed by-value, but all arrays are effectively objects and by-reference, including byte[].
If you pass a byte[1] to your sizeOf it passes the array, because all object types are subclasses of and compatible with the parameter Object input, and sizeOf serializes the array.
If you try to pass a primitive byte it doesn't work, because no primitive type is a reference type so it cannot be compatible with java.lang.Object or any other object type. Instead the byte is 'boxed' to an an object of the language-defined class java.lang.Byte (note different spelling) -- and sizeOf serializes that object. This is often called auto-boxing (and auto-unboxing for the reverse) because the compiler does these conversions without you writing them in the source code. The boxed object is actually about the same size in memory as the array (and both are significantly larger than the primitive), but as commented by https://stackoverflow.com/users/869736/louis-wasserman the serialization of the java.lang.Byte object is more complicated and longer than the serialization of the byte[1] array.