问:
Capture stored proc's print messages from C# SSIS Script task (2016) when completed successfully
I am trying to output the print messages from a stored proc that is being execute from SSIS script task.  Here is what I have so far:

```<code>public event SqlInfoMessageEventHandler InfoMessage;
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
    string LogFile = "\\fld6filer\\BrsSystems\\Workitems\\TF19816\test_" + datetime + ".log";
        /*Dts.Variables[""].Value.ToString() + "\\" + Dts.Variables[""].Value.ToString() + "_" + datetime + ".log";*/
    using (StreamWriter writer = new StreamWriter(LogFile))
    {
        writer.Write(e.Message);
    }
}

public void Main()
{
    string par1 = "26";
    string par2 = "202111";
    string par3 = "09";
    string par4 = "tblISF09202111";
    string par5 = "tblSUFGenericPseudo202111";
    string par6 = "tblSUFGenericPseudo202111";
    string par7 = "tblSUFGenericPseudo202111";
    string par8 = "tblSUFGenericPseudo202111";
    string par9 = "tblSUFGenericFF202111";
    string par10 = "1";

    try
    {
        //USE ADO.NET Connection from SSIS Package to get data from table
        SqlConnection MyConnection = new SqlConnection();
        MyConnection = (SqlConnection)Dts.Connections["ADODB"].AcquireConnection(null);

        //MyConnection.Open();

        SqlCommand Storproc = new SqlCommand();
        Storproc.Connection = MyConnection;
        Storproc.CommandTimeout = 7200;
        Storproc.CommandType = CommandType.StoredProcedure;
        Storproc.CommandText = "[SurveyInterface].[uspCEProcessingMainScriptAllProcesses]";
        SqlParameter Parameter1 = new SqlParameter("@InputSurveyGroupCodeId", par1);
        SqlParameter Parameter2 = new SqlParameter("@InputReferencePeriod", par2);
        SqlParameter Parameter3 = new SqlParameter("@InputSurveyCodeId", par3);
        SqlParameter Parameter4 = new SqlParameter("@InputISFTable", par4);
        SqlParameter Parameter5 = new SqlParameter("@InputSUFFrameTable", par5);
        SqlParameter Parameter6 = new SqlParameter("@InputExtraVarSUFTable", par6);
        SqlParameter Parameter7 = new SqlParameter("@InputPreviousPseudoFrameTableName", par7);
        SqlParameter Parameter8 = new SqlParameter("@InputPreviousPseudoFrameTableExtra", par8);
        SqlParameter Parameter9 = new SqlParameter("@InputFFTable", par9);
        SqlParameter Parameter10 = new SqlParameter("@DEBUG_MODE", par10);
        Storproc.Parameters.Add(Parameter1);
        Storproc.Parameters.Add(Parameter2);
        Storproc.Parameters.Add(Parameter3);
        Storproc.Parameters.Add(Parameter4);
        Storproc.Parameters.Add(Parameter5);
        Storproc.Parameters.Add(Parameter6);
        Storproc.Parameters.Add(Parameter7);
        Storproc.Parameters.Add(Parameter8);
        Storproc.Parameters.Add(Parameter9);
        Storproc.Parameters.Add(Parameter10);

        Storproc.ExecuteNonQuery();

        MyConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);

        MyConnection.Close();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
    catch (Exception ex)
    {
        Dts.Events.FireError(0, "ERROR", ex.Message, null, 0);
        Dts.TaskResult = (int)ScriptResults.Failure;
    }
}
</code>```

I don't know why, but when the execution fails, I get all I want in the execution results tab (From Visual Studio), but I don't get anything in my output file.  The file is not even being created.

答:
Why not simply moving the write log code into the Catch block. myConnection_InfoMessage is meaningless in your case:

public void WriteToLog(string message)
{
    string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
    string LogFile = "\\fld6filer\\BrsSystems\\Workitems\\TF19816\test_" + datetime + ".log";

    using (StreamWriter writer = new StreamWriter(LogFile))
    {
        writer.Write(message);
    }
}

public void Main()
{
    string par1 = "26";
    string par2 = "202111";
    string par3 = "09";
    string par4 = "tblISF09202111";
    string par5 = "tblSUFGenericPseudo202111";
    string par6 = "tblSUFGenericPseudo202111";
    string par7 = "tblSUFGenericPseudo202111";
    string par8 = "tblSUFGenericPseudo202111";
    string par9 = "tblSUFGenericFF202111";
    string par10 = "1";

    try
    {
        //USE ADO.NET Connection from SSIS Package to get data from table
        SqlConnection MyConnection = new SqlConnection();
        MyConnection = (SqlConnection)Dts.Connections["ADODB"].AcquireConnection(null);

        //MyConnection.Open();

        SqlCommand Storproc = new SqlCommand();
        Storproc.Connection = MyConnection;
        Storproc.CommandTimeout = 7200;
        Storproc.CommandType = CommandType.StoredProcedure;
        Storproc.CommandText = "[SurveyInterface].[uspCEProcessingMainScriptAllProcesses]";
        SqlParameter Parameter1 = new SqlParameter("@InputSurveyGroupCodeId", par1);
        SqlParameter Parameter2 = new SqlParameter("@InputReferencePeriod", par2);
        SqlParameter Parameter3 = new SqlParameter("@InputSurveyCodeId", par3);
        SqlParameter Parameter4 = new SqlParameter("@InputISFTable", par4);
        SqlParameter Parameter5 = new SqlParameter("@InputSUFFrameTable", par5);
        SqlParameter Parameter6 = new SqlParameter("@InputExtraVarSUFTable", par6);
        SqlParameter Parameter7 = new SqlParameter("@InputPreviousPseudoFrameTableName", par7);
        SqlParameter Parameter8 = new SqlParameter("@InputPreviousPseudoFrameTableExtra", par8);
        SqlParameter Parameter9 = new SqlParameter("@InputFFTable", par9);
        SqlParameter Parameter10 = new SqlParameter("@DEBUG_MODE", par10);
        Storproc.Parameters.Add(Parameter1);
        Storproc.Parameters.Add(Parameter2);
        Storproc.Parameters.Add(Parameter3);
        Storproc.Parameters.Add(Parameter4);
        Storproc.Parameters.Add(Parameter5);
        Storproc.Parameters.Add(Parameter6);
        Storproc.Parameters.Add(Parameter7);
        Storproc.Parameters.Add(Parameter8);
        Storproc.Parameters.Add(Parameter9);
        Storproc.Parameters.Add(Parameter10);

        Storproc.ExecuteNonQuery();

        WriteToLog("Stored procedure executed successfully");

        MyConnection.Close();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
    catch (Exception ex)
    {
        WriteToLog(ex.Message);
        Dts.Events.FireError(0, "ERROR", ex.Message, null, 0);
        Dts.TaskResult = (int)ScriptResults.Failure;
    }
}
```

Update 1

If you are looking to read output messages from the stored procedure, you can alter the stored procedure and add an output parameter to send the message to the C# script:

Return a message from a stored procedure to C# app

If this is not allowed, try using the SqlConnection.InfoMessage properly:

Accessing InfoMessages for SQL Server queries in C#

Body:
I am trying to output the print messages from a stored proc that is being execute from SSIS script task.  Here is what I have so far:

public event SqlInfoMessageEventHandler InfoMessage;
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
    string LogFile = "\\fld6filer\\BrsSystems\\Workitems\\TF19816\test_" + datetime + ".log";
        /*Dts.Variables[""].Value.ToString() + "\\" + Dts.Variables[""].Value.ToString() + "_" + datetime + ".log";*/
    using (StreamWriter writer = new StreamWriter(LogFile))
    {
        writer.Write(e.Message);
    }
}

public void Main()
{
    string par1 = "26";
    string par2 = "202111";
    string par3 = "09";
    string par4 = "tblISF09202111";
    string par5 = "tblSUFGenericPseudo202111";
    string par6 = "tblSUFGenericPseudo202111";
    string par7 = "tblSUFGenericPseudo202111";
    string par8 = "tblSUFGenericPseudo202111";
    string par9 = "tblSUFGenericFF202111";
    string par10 = "1";

    try
    {
        //USE ADO.NET Connection from SSIS Package to get data from table
        SqlConnection MyConnection = new SqlConnection();
        MyConnection = (SqlConnection)Dts.Connections["ADODB"].AcquireConnection(null);

        //MyConnection.Open();

        SqlCommand Storproc = new SqlCommand();
        Storproc.Connection = MyConnection;
        Storproc.CommandTimeout = 7200;
        Storproc.CommandType = CommandType.StoredProcedure;
        Storproc.CommandText = "[SurveyInterface].[uspCEProcessingMainScriptAllProcesses]";
        SqlParameter Parameter1 = new SqlParameter("@InputSurveyGroupCodeId", par1);
        SqlParameter Parameter2 = new SqlParameter("@InputReferencePeriod", par2);
        SqlParameter Parameter3 = new SqlParameter("@InputSurveyCodeId", par3);
        SqlParameter Parameter4 = new SqlParameter("@InputISFTable", par4);
        SqlParameter Parameter5 = new SqlParameter("@InputSUFFrameTable", par5);
        SqlParameter Parameter6 = new SqlParameter("@InputExtraVarSUFTable", par6);
        SqlParameter Parameter7 = new SqlParameter("@InputPreviousPseudoFrameTableName", par7);
        SqlParameter Parameter8 = new SqlParameter("@InputPreviousPseudoFrameTableExtra", par8);
        SqlParameter Parameter9 = new SqlParameter("@InputFFTable", par9);
        SqlParameter Parameter10 = new SqlParameter("@DEBUG_MODE", par10);
        Storproc.Parameters.Add(Parameter1);
        Storproc.Parameters.Add(Parameter2);
        Storproc.Parameters.Add(Parameter3);
        Storproc.Parameters.Add(Parameter4);
        Storproc.Parameters.Add(Parameter5);
        Storproc.Parameters.Add(Parameter6);
        Storproc.Parameters.Add(Parameter7);
        Storproc.Parameters.Add(Parameter8);
        Storproc.Parameters.Add(Parameter9);
        Storproc.Parameters.Add(Parameter10);

        Storproc.ExecuteNonQuery();

        MyConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);

        MyConnection.Close();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
    catch (Exception ex)
    {
        Dts.Events.FireError(0, "ERROR", ex.Message, null, 0);
        Dts.TaskResult = (int)ScriptResults.Failure;
    }
}

I don't know why, but when the execution fails, I get all I want in the execution results tab (From Visual Studio), but I don't get anything in my output file.  The file is not even being created.

Body:
Why not simply moving the write log code into the Catch block. myConnection_InfoMessage is meaningless in your case:

public void WriteToLog(string message)
{
    string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
    string LogFile = "\\fld6filer\\BrsSystems\\Workitems\\TF19816\test_" + datetime + ".log";

    using (StreamWriter writer = new StreamWriter(LogFile))
    {
        writer.Write(message);
    }
}

public void Main()
{
    string par1 = "26";
    string par2 = "202111";
    string par3 = "09";
    string par4 = "tblISF09202111";
    string par5 = "tblSUFGenericPseudo202111";
    string par6 = "tblSUFGenericPseudo202111";
    string par7 = "tblSUFGenericPseudo202111";
    string par8 = "tblSUFGenericPseudo202111";
    string par9 = "tblSUFGenericFF202111";
    string par10 = "1";

    try
    {
        //USE ADO.NET Connection from SSIS Package to get data from table
        SqlConnection MyConnection = new SqlConnection();
        MyConnection = (SqlConnection)Dts.Connections["ADODB"].AcquireConnection(null);

        //MyConnection.Open();

        SqlCommand Storproc = new SqlCommand();
        Storproc.Connection = MyConnection;
        Storproc.CommandTimeout = 7200;
        Storproc.CommandType = CommandType.StoredProcedure;
        Storproc.CommandText = "[SurveyInterface].[uspCEProcessingMainScriptAllProcesses]";
        SqlParameter Parameter1 = new SqlParameter("@InputSurveyGroupCodeId", par1);
        SqlParameter Parameter2 = new SqlParameter("@InputReferencePeriod", par2);
        SqlParameter Parameter3 = new SqlParameter("@InputSurveyCodeId", par3);
        SqlParameter Parameter4 = new SqlParameter("@InputISFTable", par4);
        SqlParameter Parameter5 = new SqlParameter("@InputSUFFrameTable", par5);
        SqlParameter Parameter6 = new SqlParameter("@InputExtraVarSUFTable", par6);
        SqlParameter Parameter7 = new SqlParameter("@InputPreviousPseudoFrameTableName", par7);
        SqlParameter Parameter8 = new SqlParameter("@InputPreviousPseudoFrameTableExtra", par8);
        SqlParameter Parameter9 = new SqlParameter("@InputFFTable", par9);
        SqlParameter Parameter10 = new SqlParameter("@DEBUG_MODE", par10);
        Storproc.Parameters.Add(Parameter1);
        Storproc.Parameters.Add(Parameter2);
        Storproc.Parameters.Add(Parameter3);
        Storproc.Parameters.Add(Parameter4);
        Storproc.Parameters.Add(Parameter5);
        Storproc.Parameters.Add(Parameter6);
        Storproc.Parameters.Add(Parameter7);
        Storproc.Parameters.Add(Parameter8);
        Storproc.Parameters.Add(Parameter9);
        Storproc.Parameters.Add(Parameter10);

        Storproc.ExecuteNonQuery();

        WriteToLog("Stored procedure executed successfully");

        MyConnection.Close();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
    catch (Exception ex)
    {
        WriteToLog(ex.Message);
        Dts.Events.FireError(0, "ERROR", ex.Message, null, 0);
        Dts.TaskResult = (int)ScriptResults.Failure;
    }
}

Update 1

If you are looking to read output messages from the stored procedure, you can alter the stored procedure and add an output parameter to send the message to the C# script:

Return a message from a stored procedure to C# app

If this is not allowed, try using the SqlConnection.InfoMessage properly:

Accessing InfoMessages for SQL Server queries in C#


来源: stackexchange

问:
Java: sleep() method is stopping my whole code
I'm doing a blackjack game using android studio and I encountered a problem when running the sleep method.
I want that when the player hit the stand button it will do 2 tasks:

flip the dealer card and diplay the dealer hand points

keep dealing cards to the dealer until he has 17. and having a dealy between every card creation and diplaying the new value of points every card creation.
and I want to have a delay between the 2 tasks.
but when I use the sleep method it stops for the duration and then it is displaying the 2 tasks instantly.

code:

```<code>stand.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
          //task 1
                ImageView iv;                                         // declaritaion
                int i = 0;

                iv = new ImageView(MainActivity.this);                // make the imageview for the card i want to flip

                iv.setTranslationX(400);                              // set all attributes
                iv.setTranslationY(1000);
                iv.setLayoutParams(layoutParams);

                String s = r.getdHand().getQ().get(0).getImg();       // get the image name of the card I want to flip (I already have the card stored in dealer hand)
                int imagekey = getResources().getIdentifier(s, "drawable", getPackageName());
                iv.setImageResource(imagekey);
                dealerPoints.setText(Integer.toString(r.getdHand().sum)); // change the text view that displays the dealer points

                main.addView(iv);                                        // add card
                                // here i want a delay of 1 second
                 // task 2
                while (r.getdHand().sum < 17) {
                    ImageView add;                                                       // declariation
                    int index = 2;

                    cards c = r.d.dealNextCard();                                        // add card to dealer hand
                    r.getdHand().add(c);

                    add = new ImageView(MainActivity.this);                         // make a new image view
                    add.setTranslationX(400 + 190 * index);
                    add.setTranslationY(1000);
                    add.setLayoutParams(layoutParams);

                    s = r.getdHand().getQ().get(index).getImg();                   // get the image name
                    imagekey = getResources().getIdentifier(s, "drawable", getPackageName());
                    add.setImageResource(imagekey);
                    main.addView(add);
                    dealerPoints.setText(Integer.toString(r.getdHand().sum));      // change the dealer points in the text view as before

                    index++;
                              // here i want another delay between every card creation
                }
            }
        });
</code>```

答:
You can use this to sleep for a certain period of time

```<code>TimeUnit.SECONDS.sleep(1)
</code>```

Put it where you want the delay

ContentLicense: CC BY-SA 4.0

Body:
I'm doing a blackjack game using android studio and I encountered a problem when running the sleep method.
I want that when the player hit the stand button it will do 2 tasks:

flip the dealer card and diplay the dealer hand points

keep dealing cards to the dealer until he has 17. and having a dealy between every card creation and diplaying the new value of points every card creation.
and I want to have a delay between the 2 tasks.
but when I use the sleep method it stops for the duration and then it is displaying the 2 tasks instantly.

code:

stand.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
          //task 1
                ImageView iv;                                         // declaritaion
                int i = 0;

                iv = new ImageView(MainActivity.this);                // make the imageview for the card i want to flip

                iv.setTranslationX(400);                              // set all attributes
                iv.setTranslationY(1000);
                iv.setLayoutParams(layoutParams);

                String s = r.getdHand().getQ().get(0).getImg();       // get the image name of the card I want to flip (I already have the card stored in dealer hand)
                int imagekey = getResources().getIdentifier(s, "drawable", getPackageName());
                iv.setImageResource(imagekey);
                dealerPoints.setText(Integer.toString(r.getdHand().sum)); // change the text view that displays the dealer points

                main.addView(iv);                                        // add card
                                // here i want a delay of 1 second
                 // task 2
                while (r.getdHand().sum < 17) {
                    ImageView add;                                                       // declariation
                    int index = 2;

                    cards c = r.d.dealNextCard();                                        // add card to dealer hand
                    r.getdHand().add(c);

                    add = new ImageView(MainActivity.this);                         // make a new image view
                    add.setTranslationX(400 + 190 * index);
                    add.setTranslationY(1000);
                    add.setLayoutParams(layoutParams);

                    s = r.getdHand().getQ().get(index).getImg();                   // get the image name
                    imagekey = getResources().getIdentifier(s, "drawable", getPackageName());
                    add.setImageResource(imagekey);
                    main.addView(add);
                    dealerPoints.setText(Integer.toString(r.getdHand().sum));      // change the dealer points in the text view as before

                    index++;
                              // here i want another delay between every card creation
                }
            }
        });

Body:
You can use this to sleep for a certain period of time

TimeUnit.SECONDS.sleep(1)

Put it where you want the delay


问:
Using OSGi to implement auto-update
What I'd like to do is create a "launcher" framework for my code that, given a URL and a predefined versioning scheme:
1) go check if an update exists
2) download the updates
3) "install" the update
4) "re-run" the application

I want to a) do all of this inside of the existing JVM and b) be platform independent.  Tall order right?  Based on my (limited) knowledge of OSGi and Apache Felix I'm pretty sure this is possible, but I'm really getting lost in the details.

Checking for an update and downloading it is trivial. Causing the "old" bundle to unload and the "new" bundle to load is where I'm getting stuck.  I've done OSGi work in the past but it was a lot less dynamic than this.  A good starting place or a hard shove in the right direction would be most appreciated.

If I'm seriously over-baking something that's already been solved with a free library then tell me this too, but I haven't found anything so far. :-)

答:
you can check well-known provisioning solutions that can do all your steps instead of you (check for a new version, download, install/update, restart etc.)

For Equinox framework: p2 http://www.eclipse.org/equinox/p2/

For any OSGi R4 framework: Apache ACE http://incubator.apache.org/ace/a-brief-introduction.html

best regards,
Dmytro

ContentLicense: CC BY-SA 3.0

Title: Using OSGi to implement auto-update


问:
Easy way to add multiple existing .csproj to a Visual Studio Solution?
I've checked out a branch of C# code from source control. It contains maybe 50 projects in various folders. There's no existing .sln file to be found.

I intended to create a blank solution to add existing solutions. The UI only lets me do this one project at a time.

Is there something I'm missing? I'd like to specify a list of *.csproj files and somehow come up with a .sln file that contains all the projects.

答:
Plenty of answers here already, but none quite as clear as this powershell oneliner</p>
```<code>Get-ChildItem -Recurse -Include *.csproj | ForEach-Object { dotnet sln add $_ }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Plenty of answers here already, but none quite as clear as this powershell oneliner

Get-ChildItem -Recurse -Include *.csproj | ForEach-Object { dotnet sln add $_ }


问:
Make a loop wait for 2 seconds after fetching every 5 pages
I want the script call to wait for 2 seconds after every 5 pages.

My requirements are that the for loop should wait for 2 seconds when pageData.Number reaches page 5. So basically, the loop should wait for 2 seconds after every 5 pages.

Not sure how to check if the page reaches page 5 and wait for 2 seconds.

for (var i = 1; i <= pageData.Number; i++) {
  var pageRequest = $.getJSON(URL, function (data) {
    if (i % 5 == 0) {
      sleep(5000);
    }
    /* .... */
  }).fail(function () {
    errorPage.push(i);
  });
}

// from https://www.sitepoint.com/delay-sleep-pause-wait/
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
```

答:
I think you need something like this. It uses javascript remainder operator and a custom sleep function.

for (var i = 1; i <= pageData.Number; i++) {
  //setTimeout(func, 2000);
  var pageURL = Url + "?startDate=" + moment(startDate).format(dateFormat) + "&endDate=" + moment(endDate).add(1, 'day').format(dateFormat) + "&pageNumber=" + i;
  var pageRequest = $.getJSON(URL, function (data) {
  if (i % 5 == 0) {
    sleep(2000);
  }
}

// from https://www.sitepoint.com/delay-sleep-pause-wait/
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}```


问:
Is there a Python DICOM Modality Worklist setup library?
I've been down a couple of rabbit holes trying to find suitable ways of creating a DICOM modality worklist (or .wl worklist files rather).

What I have setup so far:

I have an Orthanc DICOM server running in a local docker container.

I can create DICOM text dump files with a small Python program. See the example of how this looks below.

I can convert the above-mentioned text dump files to .wl worklist files by using the dump2dcm command.

I can move the created .wl files to a folder that is shared with the docker.

Orthanc can "see" these files and serve them correctly to medical machines on the local network.

I have the coffee machine on a timer. This allows for a consistent caffeine fix.

My problem is with the creation of the DICOM text dump files.
I'm currently using Python's String.format() function to format a template string. This then substitutes certain placeholders in my template string with actual patient data. Although not elegant, it works. But it's a very static solution and may not be very robust.

Is there a Python library that can be used to generate such text dump files? or even beter, the .wl files? I am willing to trade 3 magic beans, and our family recipe for potato salad, for such a library. (The secret ingredient is not paprika)

For completeness, here is how the template dicom worklist string looks:

```<code>dicom_wl_template_string = """
    # Dicom-File-Format
    # Dicom-Meta-Information-Header
    # Used TransferSyntax: Unknown Transfer Syntax

    # Dicom-Data-Set
    # Used TransferSyntax: Little Endian Implicit
    (0002,0000) UL [123]
    (0002,0002) UI [1.2.111.222222.5.1.4.1.1.104.1]
    (0002,0003) UI [1.2.3.4.5.6.132437.17.4.10123450.312346792082.12349.1]
    (0002,0010) UI [1.2.840.10008.1.2.1]
    (0002,0012) UI [1.2.276.0.7230010.3.0.3.6.6]
    (0002,0013) SH [OFFIS_DCMTK_366]

    (0008,0005) CS [{SpecificCharacterSet}]                     #  10, 1 SpecificCharacterSet e.g ISO_IR 100
    (0008,0012) DA [{InstanceCreationDate}]                     #   8, 1 InstanceCreationDate e.g 20220101
    (0008,0050) SH [{AccessionNumber}]                          #   8, 1 AccessionNumber e.g 1234
    (0010,0010) PN [{PatientName}]                              #  14, 1 PatientName e.g SURNAME^ABC
    (0010,0020) LO [{PatientID}]                                #  14, 1 PatientID e.g 7001011234080
    (0010,0030) DA [{PatientBirthDate}]                         #   8, 1 PatientBirthDate e.g. 19700101
    (0010,0040) CS [{PatientSex}]                               #   2, 1 PatientSex e.g. M
    (0020,000d) UI [{StudyInstanceUID}]                         #  54, 1 StudyInstanceUID e.g 1.2.3.4.5.6.132437.17.4.10123450.312346792082.12349.1
    (0032,1060) LO [{RequestedProcedureDescription}]            #  16, 1 RequestedProcedureDescription
        (0040,0100) SQ (Sequence with explicit length #=1)          #  90, 1 ScheduledProcedureStepSequence
            (fffe,e000) na (Item with ??explicit length #=5??)          #  82, 1 Item
                (0008,0060) CS [{Modality}]                                 #   4, 1 Modality e.g. CT, MR, CR, NM, PT, US, XA
                (0040,0001) AE [{ScheduledStationAETitle}]                  #   4, 1 ScheduledStationAETitle e.g Foo
                (0040,0002) DA [{ScheduledProcedureStepStartDate}]          #   8, 1 ScheduledProcedureStepStartDate e.g. 20220101
                (0040,0003) TM [{ScheduledProcedureStepStartTime}]          #   8, 1 ScheduledProcedureStepStartTime e.g. 080000
                (0040,0006) PN [{ScheduledPhysicianName}]                   #   8, 1 Scheduled Performing Physicians Name e.g. EMMETBROWN
                (0040,0007) LO [{ScheduledProcedureStepDescription}]        #  22, 1 ScheduledProcedureStepDescription e.g SOMETHING
                (0040,0009) SH [{ScheduledProcedureStepID}]                 #   4, 1 ScheduledProcedureStepID e.g 0001
            (fffe,e00d) na (ItemDelimitationItem for re-encoding)       #   0, 0 ItemDelimitationItem
        (fffe,e0dd) na (SequenceDelimitationItem for re-encod.)     #   0, 0 SequenceDelimitationItem
    (0040,1001) SH [unknown]                                    #   8, 1 RequestedProcedureID
    """
</code>```

答:
pydicom should be able to do this and probably allow you to skip the text dump step (disclaimer - I'm a contributor to pydicom):

from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.uid import ExplicitVRLittleEndian

ds = Dataset()

# Add file meta information elements
ds.file_meta = FileMetaDataset()
ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian

# Fill out the worklist query elements
ds.SpecificCharacterSet = "ISO_IR 6"
ds.ScheduledProcedureStepSequence = [Dataset()]
ds.ScheduledProcedureStepSequence[0].Modality = "CT"
# etc...

ds.save_as("query.wl", write_like_original=False)
```

If you decide to go this way, the dataset introduction tutorial is a good place to start.

Body:
I've been down a couple of rabbit holes trying to find suitable ways of creating a DICOM modality worklist (or .wl worklist files rather).

What I have setup so far:

I have an Orthanc DICOM server running in a local docker container.

I can create DICOM text dump files with a small Python program. See the example of how this looks below.

I can convert the above-mentioned text dump files to .wl worklist files by using the dump2dcm command.

I can move the created .wl files to a folder that is shared with the docker.

Orthanc can "see" these files and serve them correctly to medical machines on the local network.

I have the coffee machine on a timer. This allows for a consistent caffeine fix.

My problem is with the creation of the DICOM text dump files.
I'm currently using Python's String.format() function to format a template string. This then substitutes certain placeholders in my template string with actual patient data. Although not elegant, it works. But it's a very static solution and may not be very robust.

Is there a Python library that can be used to generate such text dump files? or even beter, the .wl files? I am willing to trade 3 magic beans, and our family recipe for potato salad, for such a library. (The secret ingredient is not paprika)

For completeness, here is how the template dicom worklist string looks:

dicom_wl_template_string = """
    # Dicom-File-Format
    # Dicom-Meta-Information-Header
    # Used TransferSyntax: Unknown Transfer Syntax

    # Dicom-Data-Set
    # Used TransferSyntax: Little Endian Implicit
    (0002,0000) UL [123]
    (0002,0002) UI [1.2.111.222222.5.1.4.1.1.104.1]
    (0002,0003) UI [1.2.3.4.5.6.132437.17.4.10123450.312346792082.12349.1]
    (0002,0010) UI [1.2.840.10008.1.2.1]
    (0002,0012) UI [1.2.276.0.7230010.3.0.3.6.6]
    (0002,0013) SH [OFFIS_DCMTK_366]

    (0008,0005) CS [{SpecificCharacterSet}]                     #  10, 1 SpecificCharacterSet e.g ISO_IR 100
    (0008,0012) DA [{InstanceCreationDate}]                     #   8, 1 InstanceCreationDate e.g 20220101
    (0008,0050) SH [{AccessionNumber}]                          #   8, 1 AccessionNumber e.g 1234
    (0010,0010) PN [{PatientName}]                              #  14, 1 PatientName e.g SURNAME^ABC
    (0010,0020) LO [{PatientID}]                                #  14, 1 PatientID e.g 7001011234080
    (0010,0030) DA [{PatientBirthDate}]                         #   8, 1 PatientBirthDate e.g. 19700101
    (0010,0040) CS [{PatientSex}]                               #   2, 1 PatientSex e.g. M
    (0020,000d) UI [{StudyInstanceUID}]                         #  54, 1 StudyInstanceUID e.g 1.2.3.4.5.6.132437.17.4.10123450.312346792082.12349.1
    (0032,1060) LO [{RequestedProcedureDescription}]            #  16, 1 RequestedProcedureDescription
        (0040,0100) SQ (Sequence with explicit length #=1)          #  90, 1 ScheduledProcedureStepSequence
            (fffe,e000) na (Item with ??explicit length #=5??)          #  82, 1 Item
                (0008,0060) CS [{Modality}]                                 #   4, 1 Modality e.g. CT, MR, CR, NM, PT, US, XA
                (0040,0001) AE [{ScheduledStationAETitle}]                  #   4, 1 ScheduledStationAETitle e.g Foo
                (0040,0002) DA [{ScheduledProcedureStepStartDate}]          #   8, 1 ScheduledProcedureStepStartDate e.g. 20220101
                (0040,0003) TM [{ScheduledProcedureStepStartTime}]          #   8, 1 ScheduledProcedureStepStartTime e.g. 080000
                (0040,0006) PN [{ScheduledPhysicianName}]                   #   8, 1 Scheduled Performing Physicians Name e.g. EMMETBROWN
                (0040,0007) LO [{ScheduledProcedureStepDescription}]        #  22, 1 ScheduledProcedureStepDescription e.g SOMETHING
                (0040,0009) SH [{ScheduledProcedureStepID}]                 #   4, 1 ScheduledProcedureStepID e.g 0001
            (fffe,e00d) na (ItemDelimitationItem for re-encoding)       #   0, 0 ItemDelimitationItem
        (fffe,e0dd) na (SequenceDelimitationItem for re-encod.)     #   0, 0 SequenceDelimitationItem
    (0040,1001) SH [unknown]                                    #   8, 1 RequestedProcedureID
    """

Body:
pydicom should be able to do this and probably allow you to skip the text dump step (disclaimer - I'm a contributor to pydicom):

from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.uid import ExplicitVRLittleEndian

ds = Dataset()

# Add file meta information elements
ds.file_meta = FileMetaDataset()
ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian

# Fill out the worklist query elements
ds.SpecificCharacterSet = "ISO_IR 6"
ds.ScheduledProcedureStepSequence = [Dataset()]
ds.ScheduledProcedureStepSequence[0].Modality = "CT"
# etc...

ds.save_as("query.wl", write_like_original=False)

If you decide to go this way, the dataset introduction tutorial is a good place to start.


问:
How to add custom pylint warning?
I want to add a warning message to my pylint for all print statements reminding myself I have them in case I print sensitive information. Is this possible? I can only find answers about disabling pylint errors, not enabling new ones.</p>

答: I suggest writing a custom checker. I've never done this before myself, but the documentation for how to do it is here: https://pylint.pycqa.org/en/latest/how_tos/custom_checkers.html</p>

Title: How to add custom pylint warning?


问:
Invalid identifier when binding variables in snowflake
I have created a stored procedure which gets certain values from a table and uses those values into another sql query
I successfully got the values I needed however
I keep getting invalid identifier for the values I pass through binding
Below is a snippet of my code

```<code>    var v_role       = sqlRS1.getColumnValue(1);
    var v_database   = sqlRS1.getColumnValue(2);
    var v_schema     = sqlRS1.getColumnValue(3);
    var v_table      = sqlRS1.getColumnValue(4);
    var v_column     = sqlRS1.getColumnValue(5);

    var v_tableColumn = v_table + `_` + v_column;

    var v_sqlCode5 = `SELECT *
                      FROM  db.sch.tbl
                      WHERE DATABASE_NAME = identifier(?)
                      AND   SCHEMA_NAME   = identifier(?)
                      AND   POLICY_NAME IN (identifier(?))`;

    var sqlStmt2 = snowflake.createStatement({sqlText:v_sqlCode5,binds:[v_database,v_schema,v_tableColumn]});
    var sqlRS2   = sqlStmt2.execute();

</code>```

the error will say that there is invalid identifier for the value passed in DATABASE_NAME
I checked the query history and I see that the value passed is correct
So I am unsure of how to solve this, any help would be greatly appreciated

答:
Identifiers are using to replace table names (which can been seen in this example). Where what you have seems like it should be normal equality join:

Another way of saying this is your generated SQL:

```<code>SELECT * FROM DB.SCH.TBL
WHERE DATABASE_NAME = identifier('AD')
    AND SCHEMA_NAME = identifier('DB')
    AND POLICY_NAME IN (identifier('M_E'));
</code>```

does this run with no errors for you in the UI?

I suspect you need to change it to:

```<code>SELECT * FROM DB.SCH.TBL
WHERE DATABASE_NAME = 'AD'
    AND SCHEMA_NAME = 'DB'
    AND POLICY_NAME IN ('M_E');
</code>```

to get it to work.

What you are wanting is to make sure the passed in values are fully quoted. so things don't escape, which was my understand of what passing them as bound variables does.

which implies you source should be:

```<code>    var v_sqlCode5 = `SELECT *
                      FROM  db.sch.tbl
                      WHERE DATABASE_NAME = ?
                      AND   SCHEMA_NAME   = ?
                      AND   POLICY_NAME IN (?)`;
</code>```

Body:
I have created a stored procedure which gets certain values from a table and uses those values into another sql query
I successfully got the values I needed however
I keep getting invalid identifier for the values I pass through binding
Below is a snippet of my code

    var v_role       = sqlRS1.getColumnValue(1);
    var v_database   = sqlRS1.getColumnValue(2);
    var v_schema     = sqlRS1.getColumnValue(3);
    var v_table      = sqlRS1.getColumnValue(4);
    var v_column     = sqlRS1.getColumnValue(5);

    var v_tableColumn = v_table + `_` + v_column;

    var v_sqlCode5 = `SELECT *
                      FROM  db.sch.tbl
                      WHERE DATABASE_NAME = identifier(?)
                      AND   SCHEMA_NAME   = identifier(?)
                      AND   POLICY_NAME IN (identifier(?))`;

    var sqlStmt2 = snowflake.createStatement({sqlText:v_sqlCode5,binds:[v_database,v_schema,v_tableColumn]});
    var sqlRS2   = sqlStmt2.execute();

the error will say that there is invalid identifier for the value passed in DATABASE_NAME
I checked the query history and I see that the value passed is correct
So I am unsure of how to solve this, any help would be greatly appreciated

Body:
Identifiers are using to replace table names (which can been seen in this example). Where what you have seems like it should be normal equality join:

Another way of saying this is your generated SQL:

SELECT * FROM DB.SCH.TBL
WHERE DATABASE_NAME = identifier('AD')
    AND SCHEMA_NAME = identifier('DB')
    AND POLICY_NAME IN (identifier('M_E'));

does this run with no errors for you in the UI?

I suspect you need to change it to:

SELECT * FROM DB.SCH.TBL
WHERE DATABASE_NAME = 'AD'
    AND SCHEMA_NAME = 'DB'
    AND POLICY_NAME IN ('M_E');

to get it to work.

What you are wanting is to make sure the passed in values are fully quoted. so things don't escape, which was my understand of what passing them as bound variables does.

which implies you source should be:

    var v_sqlCode5 = `SELECT *
                      FROM  db.sch.tbl
                      WHERE DATABASE_NAME = ?
                      AND   SCHEMA_NAME   = ?
                      AND   POLICY_NAME IN (?)`;


问:
React native maps issue in iOS app (undefined symbols for architecture x86_64)
I am very new to react native. While trying to install react native maps (M1 mackbook pro), I am getting the below error (on iOS):
React native version: 0.67 RC 6

Please help me to solve it:

https://rentry.co/n2ixn

This is my POD file:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'dollseCab' do

  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => true
  )

  rn_maps_path = '../node_modules/react-native-maps'
  pod 'react-native-google-maps', :path => rn_maps_path

  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'

  target 'dollseCabTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  #use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end```
</div>
</div>
</p>
<p>and this is AppDelegate.m</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>#import "AppDelegate.h"
#import <Firebase.h>
#import <GoogleMaps/GoogleMaps.h>
#if RCT_DEV
#import <React/RCTDevLoadingView.h>
#endif
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

[GMSServices provideAPIKey:@"APzaSyAOgaVvtCIIkuLcuLJ1thYma3CrpOiq7mI"];

[FIRApp configure];
#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
#if RCT_DEV
  [bridge moduleForClass:[RCTDevLoadingView class]];
#endif
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"dollseCab"
                                            initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end</code>```

everything worked fine until I installed google maps

答:
Same here unfortunately. I found it is connected to this Some tips to working with react-native 0.64 on an Apple M1 Silicon chip.

This should help with other packages, but for me I could not get it to run with the google package.

Body:
I am very new to react native. While trying to install react native maps (M1 mackbook pro), I am getting the below error (on iOS):
React native version: 0.67 RC 6

Please help me to solve it:

https://rentry.co/n2ixn

This is my POD file:

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'dollseCab' do

  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => true
  )

  rn_maps_path = '../node_modules/react-native-maps'
  pod 'react-native-google-maps', :path => rn_maps_path

  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'

  target 'dollseCabTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  #use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

and this is AppDelegate.m

#import "AppDelegate.h"
#import <Firebase.h>
#import <GoogleMaps/GoogleMaps.h>
#if RCT_DEV
#import <React/RCTDevLoadingView.h>
#endif
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

[GMSServices provideAPIKey:@"APzaSyAOgaVvtCIIkuLcuLJ1thYma3CrpOiq7mI"];

[FIRApp configure];
#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
#if RCT_DEV
  [bridge moduleForClass:[RCTDevLoadingView class]];
#endif
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"dollseCab"
                                            initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

everything worked fine until I installed google maps


问:
Display pretty print of JSON in Vue.js
I wonder how do people display pretty print of JSON in Vue.js

```<code><v-expansion-panels>
  <v-expansion-panel v-for="(entrie, i) in objects.log.entries" :key="i">
    <v-expansion-panel-header class="text-left">

      {{ entrie.request.postData.text }}
    </v-expansion-panel-header>
    <v-expansion-panel-content class="green--text">

      {{ entrie.response.content.text }}

    </v-expansion-panel-content>
  </v-expansion-panel>
</v-expansion-panels>
</code>```

Fiddle

Just to make my point clear, I'm hoping to see something like this :

答:
You can add a filter to stringify the data in a nicer format.

filters: {
  pretty: (val, indent = 2) => {
    if (typeof val !== "object") {
      try {
        val = JSON.parse(val)
      } catch (err) {
        console.warn("value is not JSON")
        return val
      }

      return JSON.stringify(val, null, indent)
    }
  }
}
```
<p>Use CSS <code>white-space</code> or simply use a <code>``` tag to keep formatting in your template

```{{ entrie.response.content.text | pretty(4) }}```
```

Demo ~ https://jsfiddle.net/ktz49q1h/

Note that filters are not supported in Vue3. See the migration strategy for solutions.

Title: Display pretty print of JSON in Vue.js

Body:
I wonder how do people display pretty print of JSON in Vue.js

<v-expansion-panels>
  <v-expansion-panel v-for="(entrie, i) in objects.log.entries" :key="i">
    <v-expansion-panel-header class="text-left">

      {{ entrie.request.postData.text }}
    </v-expansion-panel-header>
    <v-expansion-panel-content class="green--text">

      {{ entrie.response.content.text }}

    </v-expansion-panel-content>
  </v-expansion-panel>
</v-expansion-panels>

Fiddle

Just to make my point clear, I'm hoping to see something like this :

Body:
You can add a filter to stringify the data in a nicer format.

filters: {
  pretty: (val, indent = 2) => {
    if (typeof val !== "object") {
      try {
        val = JSON.parse(val)
      } catch (err) {
        console.warn("value is not JSON")
        return val
      }

      return JSON.stringify(val, null, indent)
    }
  }
}

Use CSS white-space or simply use a <pre> tag to keep formatting in your template

<pre>{{ entrie.response.content.text | pretty(4) }}</pre>

Demo ~ https://jsfiddle.net/ktz49q1h/

Note that filters are not supported in Vue3. See the migration strategy for solutions.


问:
How to delete a file from a jar which is part of another jar
I need to remove JMSAppender class from log4j-1.2.17.jar. This jar is wrapped in my executable jar named xyz.jar. What is the most effective and easy way to delete JMSAppender class and make the jar as it is again?

File directory looks like this:

xyz.jar

|- BOOT-INF/lib/log4j-1.2.17.jar

|- META-INF

|- org

log4j-1.2.17.jar

|- org

|---apache

|-----log4j

|-------net

|---------JMSAppender.class

|- META-INF

答:
A jar file is nothing different than a zip archive renamed to '.jar'.
Therefore any solution to remove or change something in a zip file is applicable, such as

https://superuser.com/questions/600385/remove-single-file-from-zip-archive-on-linux

How do I delete or replace a file in a zip archive?

There may be problems however if that jar carries a signature. In that case any recipient would be able to verify that the signature is broken which means the file was tampered with. To learn about signed jars, read

https://docs.oracle.com/en/java/javase/14/docs/specs/man/jarsigner.html


问:
Prometheus cannot scrape from spring-boot application over HTTPS
I'm deploying a spring-boot application and prometheus container through docker, and have exposed the spring-boot /actuator/prometheus endpoint successfully. However, when I enable prometheus debug logs, I can see it fails to scrape the metrics:

```<code>ts=2022-02-02T03:54:46.210Z
caller=scrape.go:1292
level=debug
component="scrape manager"
scrape_pool=spring-actuator
target=https://127.0.0.1:8443/actuator/prometheus/
msg="Scrape failed"
err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"
</code>```

I'm thinking it's something to do with how I've set up my spring-boot HTTPS. I am generating a self-signed certificate during the building of my spring-boot application, using the command:

```<code>keytool
  -genkey
  -alias <alias>
  -dname <dname>
  -keyalg RSA
  -keysize 4096
  -storetype PKCS12
  -keystore <path_to_keystore>
  -validity 3650
  -storepass <keystore_pass>
</code>```

I then export the cert to a .pem file, and extract the .crt and .key:

```<code>openssl pkcs12 -in cert.p12 -out cert.pem -nodes -passin pass:<pass>
</code>```

This is mounted through a shared volume to my prometheus container, which has a --web.config.file containing:

```<code>tls_server_config:
  cert_file: /path/to/cert.crt
  key_file: /path/to/cert.key
</code>```

And for good measure I added insecure_skip_verify: true to the prometheus.yml config:

```<code>- job_name: 'spring-actuator'
metrics_path: '/actuator/prometheus/'
scrape_interval: 60s
scheme: https
static_configs:
  - targets: [ '127.0.0.1:8443' ]
tls_config:
  insecure_skip_verify: true
</code>```

答:
Ok, I think I found my problem. I made two changes:

First, I moved the contents of the web.config.file into the prometheus.yml file under the 'spring-actuator'.
Then I changed the target to use the hostname for my backend container, rather than 127.0.0.1.

The end result was a single prometheus.yml file:

```<code>- job_name: 'spring-actuator'
metrics_path: '/actuator/prometheus/'
scrape_interval: 60s
scheme: https
static_configs:
  - targets: [ 'backend:8443' ]
tls_config:
  cert_file: /path/to/cert.crt
  key_file: /path/to/cert.key
  insecure_skip_verify: true
</code>```

So just some silly mistakes, not caused by the certs from what I can see. :)

Body:
I'm deploying a spring-boot application and prometheus container through docker, and have exposed the spring-boot /actuator/prometheus endpoint successfully. However, when I enable prometheus debug logs, I can see it fails to scrape the metrics:

ts=2022-02-02T03:54:46.210Z
caller=scrape.go:1292
level=debug
component="scrape manager"
scrape_pool=spring-actuator
target=https://127.0.0.1:8443/actuator/prometheus/
msg="Scrape failed"
err="Get \"https://127.0.0.1:8443/actuator/prometheus/\": dial tcp 127.0.0.1:8443: connect: connection refused"

I'm thinking it's something to do with how I've set up my spring-boot HTTPS. I am generating a self-signed certificate during the building of my spring-boot application, using the command:

keytool
  -genkey
  -alias <alias>
  -dname <dname>
  -keyalg RSA
  -keysize 4096
  -storetype PKCS12
  -keystore <path_to_keystore>
  -validity 3650
  -storepass <keystore_pass>

I then export the cert to a .pem file, and extract the .crt and .key:

openssl pkcs12 -in cert.p12 -out cert.pem -nodes -passin pass:<pass>

This is mounted through a shared volume to my prometheus container, which has a --web.config.file containing:

tls_server_config:
  cert_file: /path/to/cert.crt
  key_file: /path/to/cert.key

And for good measure I added insecure_skip_verify: true to the prometheus.yml config:

- job_name: 'spring-actuator'
metrics_path: '/actuator/prometheus/'
scrape_interval: 60s
scheme: https
static_configs:
  - targets: [ '127.0.0.1:8443' ]
tls_config:
  insecure_skip_verify: true

Body:
Ok, I think I found my problem. I made two changes:

First, I moved the contents of the web.config.file into the prometheus.yml file under the 'spring-actuator'.
Then I changed the target to use the hostname for my backend container, rather than 127.0.0.1.

The end result was a single prometheus.yml file:

- job_name: 'spring-actuator'
metrics_path: '/actuator/prometheus/'
scrape_interval: 60s
scheme: https
static_configs:
  - targets: [ 'backend:8443' ]
tls_config:
  cert_file: /path/to/cert.crt
  key_file: /path/to/cert.key
  insecure_skip_verify: true

So just some silly mistakes, not caused by the certs from what I can see. :)


问:
Why does my kill .sh script sometimes not kill the intended processes?
I have a .sh script that calls a number of other .sh scripts and tee's them into log files, and runs them in the background:

startMyProg.sh:

```<code>#!/bin/bash

./MyProg1.sh | tee /path/to/log/prog1_`date +\%Y\%m\%d_\%H\%M\%S`.log &
./MyProg2.sh | tee /path/to/log/prog2_`date +\%Y\%m\%d_\%H\%M\%S`.log &
./MyProgN.sh | tee /path/to/log/progN_`date +\%Y\%m\%d_\%H\%M\%S`.log &
</code>```

I also have a simple helper script that will kill all the processes with MyProg in the name:

killMyProgs.sh:

```<code>#!/bin/bash
kill $(ps aux | grep MyProg | awk '{print $2}')
</code>```

This system generally works, but occasionally the killMyProg.sh script doesn't kill the processes that it finds using the ps|grep|awk pattern.  The part that really throws me for a loop is, when I face an instance where the .sh script doesn't kill the processes, I can call kill $(ps aux | grep MyProg | awk '{print $2}') directly from the command line and it will do what I expect it to! Is there something that I'm missing in my approach? Are there any useful debugging techniques that can help me figure out why my .sh script doesn't kill the processes but calling the exact command from the command line does?

A couple of details that may be relevant:
the "./MyProgN" scripts are calls to to start the same MyProg.jar file with different inputs.  So the ps|grep of "MyProg" shows both the .sh scripts AND the java applications that they started and kills all of them.

Using RHEL7

答:
Test few time to run:

```<code> ps aux | grep MyProg | awk '{print $2}'
</code>```

You will notice that sometimes the grep command comes before MyProg

And sometimes grep command comes after MyProg (depnding on the pid).

Because grep command is listed as well in ps aux.

Therefore sometimes your script is killing the first grep command instead of your command.

The easiest solution is to use pkill command.

```<code>  pkill -9 -f MyProg
</code>```

Body:
I have a .sh script that calls a number of other .sh scripts and tee's them into log files, and runs them in the background:

startMyProg.sh:

#!/bin/bash

./MyProg1.sh | tee /path/to/log/prog1_`date +\%Y\%m\%d_\%H\%M\%S`.log &
./MyProg2.sh | tee /path/to/log/prog2_`date +\%Y\%m\%d_\%H\%M\%S`.log &
./MyProgN.sh | tee /path/to/log/progN_`date +\%Y\%m\%d_\%H\%M\%S`.log &

I also have a simple helper script that will kill all the processes with MyProg in the name:

killMyProgs.sh:

#!/bin/bash
kill $(ps aux | grep MyProg | awk '{print $2}')

This system generally works, but occasionally the killMyProg.sh script doesn't kill the processes that it finds using the ps|grep|awk pattern.  The part that really throws me for a loop is, when I face an instance where the .sh script doesn't kill the processes, I can call kill $(ps aux | grep MyProg | awk '{print $2}') directly from the command line and it will do what I expect it to! Is there something that I'm missing in my approach? Are there any useful debugging techniques that can help me figure out why my .sh script doesn't kill the processes but calling the exact command from the command line does?

A couple of details that may be relevant:
the "./MyProgN" scripts are calls to to start the same MyProg.jar file with different inputs.  So the ps|grep of "MyProg" shows both the .sh scripts AND the java applications that they started and kills all of them.

Using RHEL7

Body:
Test few time to run:

 ps aux | grep MyProg | awk '{print $2}'

You will notice that sometimes the grep command comes before MyProg

And sometimes grep command comes after MyProg (depnding on the pid).

Because grep command is listed as well in ps aux.

Therefore sometimes your script is killing the first grep command instead of your command.

The easiest solution is to use pkill command.

  pkill -9 -f MyProg


问:
Why can't my .NET 6 Minimal API deserialize POST body?
I've build a very simple, vanilla minimal API with .NET 6. All I'm trying to do for now is prove that I can receive HTTP POST requests and log them. Hopefully if I can get this working I'll start doing something more interesting, but even this vanilla out of the box functionality isn't working.

Some things I've tried:

Changing my logMessage to a record

Adding a default constructor to the logMessage

My full code is posted below, can anyone see what is wrong with this? Or how to fix it?

My minimal API:

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// NOTE: tried the below but it made no difference. Commented back out.
// builder.Services.Configure<JsonOptions>(options =>
// {
//     options.SerializerOptions.IncludeFields = true;
// });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.MapPost("/", (logMessage message) =>
{
    Console.WriteLine($"[{DateTime.Now.ToShortDateString()}] Received message:");
    Console.WriteLine(message.LogMessage);
    return Results.Accepted;
});

app.Run("http://localhost:5025");

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

public class logMessage
{
    public string? LogMessage {get;set;}
}
```
<p>My post message (testing from Postman, but also tried sending from various other places):</p>
<pre class="lang-json prettyprint-override"><code>{
    "LogMessage":"test"
}
</code>```

The result:

```<code>System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported. Path: $.Method.ReturnParameter.Member.DeclaringType.
 ---> System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported.
   at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.HttpResponseJsonExtensions.WriteAsJsonAsyncSlow[TValue](Stream body, TValue value, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<<HandleRequestBodyAndCompileRequestDelegate>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

Same result if I try from the Swagger page.

答:
This is how I changed your code and now it works

```<code>app.MapPost("/", (logMessage message) =>
 {
   Console.WriteLine($"[{DateTime.Now.ToShortDateString()}] Received
   message:");
   Console.WriteLine(message.LogMessage);
   return logMessage.GetResult();
});
</code>```

And then

```<code> public class logMessage
  {
    public static IResult GetResult()
    {
      return Results.Accepted("");
    }
    public string? LogMessage { get; set; }
  }

</code>```

Body:
I've build a very simple, vanilla minimal API with .NET 6. All I'm trying to do for now is prove that I can receive HTTP POST requests and log them. Hopefully if I can get this working I'll start doing something more interesting, but even this vanilla out of the box functionality isn't working.

Some things I've tried:

Changing my logMessage to a record

Adding a default constructor to the logMessage

My full code is posted below, can anyone see what is wrong with this? Or how to fix it?

My minimal API:

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// NOTE: tried the below but it made no difference. Commented back out.
// builder.Services.Configure<JsonOptions>(options =>
// {
//     options.SerializerOptions.IncludeFields = true;
// });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.MapPost("/", (logMessage message) =>
{
    Console.WriteLine($"[{DateTime.Now.ToShortDateString()}] Received message:");
    Console.WriteLine(message.LogMessage);
    return Results.Accepted;
});

app.Run("http://localhost:5025");

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

public class logMessage
{
    public string? LogMessage {get;set;}
}

My post message (testing from Postman, but also tried sending from various other places):

{
    "LogMessage":"test"
}

The result:

System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported. Path: $.Method.ReturnParameter.Member.DeclaringType.
 ---> System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported.
   at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack& state, NotSupportedException ex)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.HttpResponseJsonExtensions.WriteAsJsonAsyncSlow[TValue](Stream body, TValue value, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<<HandleRequestBodyAndCompileRequestDelegate>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Same result if I try from the Swagger page.

Body:
This is how I changed your code and now it works

app.MapPost("/", (logMessage message) =>
 {
   Console.WriteLine($"[{DateTime.Now.ToShortDateString()}] Received
   message:");
   Console.WriteLine(message.LogMessage);
   return logMessage.GetResult();
});

And then

 public class logMessage
  {
    public static IResult GetResult()
    {
      return Results.Accepted("");
    }
    public string? LogMessage { get; set; }
  }


问:
How to convert a space delimited file to a csv in Python?
My only use the first column of an csv.
For example, Col 1, row 1 has:

```<code>import pandas as pd
url = 'C:/Users/~filename.csv'
data = pd.read_csv(url, sep= " ", header = None)
data.head()
</code>```

答:
Since your column headers have space inside their name, you can't use sep=" " or sep=\s+. They will give the wrong split.

Instead, modify your split pattern to sep=\s{2,}:

df = pd.read_csv(url, sep='\s{2,}', engine='python')
```

Body:
My only use the first column of an csv.
For example, Col 1, row 1 has:

import pandas as pd
url = 'C:/Users/~filename.csv'
data = pd.read_csv(url, sep= " ", header = None)
data.head()


问:
Keep track of connected sockets with socket.io
How do I keep track of all the connected clients in socket.io?

I have tried this on the server:

```<code>let numSockets = 0;

io.on('connection', (socket) => {
  io.sockets.emit('numSockets', ++numSockets);

  socket.on('disconnect', () => {
    io.sockets.emit('numSockets', --numSockets);
  });
});
</code>```

and this on the client:

```<code>const socket = io();

socket.on('numSockets', function (numSockets) {
  console.log(numSockets);
});
</code>```

It does print a number, but the number, however, if I open 2 windows, it shows 4 connected sockets.

Is this the correct way to do it?

What I want to achieve is to print a list of the connected sockets' ids in a sidebar on my website, and let the user set a username (instead of the automatically generated id) if they want to.

But before moving on to this, I will make sure I can keep track of the sockets in a correct way.

答:
```<code>const count = io.engine.clientsCount;
</code>```

This seems like a more inclusive approach and may be the same count of Socket instances in the main namespace as below. But depending on namespaces and usage they could be different.

```<code>const count2 = io.of("/").sockets.size;
</code>```

https://socket.io/docs/v4/server-api/#engineclientscount

Body:
How do I keep track of all the connected clients in socket.io?

I have tried this on the server:

let numSockets = 0;

io.on('connection', (socket) => {
  io.sockets.emit('numSockets', ++numSockets);

  socket.on('disconnect', () => {
    io.sockets.emit('numSockets', --numSockets);
  });
});

and this on the client:

const socket = io();

socket.on('numSockets', function (numSockets) {
  console.log(numSockets);
});

It does print a number, but the number, however, if I open 2 windows, it shows 4 connected sockets.

Is this the correct way to do it?

What I want to achieve is to print a list of the connected sockets' ids in a sidebar on my website, and let the user set a username (instead of the automatically generated id) if they want to.

But before moving on to this, I will make sure I can keep track of the sockets in a correct way.

Body:
const count = io.engine.clientsCount;

This seems like a more inclusive approach and may be the same count of Socket instances in the main namespace as below. But depending on namespaces and usage they could be different.

const count2 = io.of("/").sockets.size;

https://socket.io/docs/v4/server-api/#engineclientscount


问:
An error with a three dimensional field (of vectors) in rcpp armadillo
I am trying to create a field in rcpp arma due to more than three iterations, but got an error. As an example, see the following simple code:

```<code>//[[Rcpp::export]]
field<vec> testgg(int k, int h, int g){
  field<vec> res(k, h, g);
  return(res);
}
</code>```

I do nothing in this code, so this code should give me something. However, I got an error when I do this function like this.

```<code>> testgg(3,4,5)
Error in testgg(3, 4, 5) :
  dims [product 12] do not match the length of object [60]
> testgg(3,4,1)
     [,1]      [,2]      [,3]      [,4]
[1,] numeric,0 numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0 numeric,0
[3,] numeric,0 numeric,0 numeric,0 numeric,0
</code>```

My guess is that the rcpp does not get this three dimensional field, but can get the field up to 2 dimensions. Why does this happen and how can I get a three dimensional field?

答:
Please see the open issue #263 and maybe also other ones.  There was a bug, there is a fix, but you currently need to set a #define to enable the fix (as we need to sort out if this has side-effects on other packages assuming the current behaviour).

So in short do for example

```<code>> Sys.setenv(PKG_CPPFLAGS="-DRCPP_ARMADILLO_FIX_Field")  ## sets #define RCPP_ARMADILLO_FIX_Field
> Rcpp::cppFunction("arma::field<arma::vec> testgg(int k, int h, int g) { arma::field<arma::vec> res(k, h, g); return(res);}", depends="RcppArmadillo")
> testgg(2,3,4)
, , 1

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

, , 2

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

, , 3

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

, , 4

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

>
</code>```

So if you compile with the correct flag, the field dimension is not reduced down.

Edit And maybe you wanted cube instead of field ?

```<code>> Rcpp::cppFunction("arma::cube testhh(int k, int h, int g) { arma::cube res(k, h, g); return(res);}", depends="RcppArmadillo")
> testhh(4,3,2)
, , 1

     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    0    0    0

, , 2

     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    0    0    0

>
</code>```

Body:
I am trying to create a field in rcpp arma due to more than three iterations, but got an error. As an example, see the following simple code:

//[[Rcpp::export]]
field<vec> testgg(int k, int h, int g){
  field<vec> res(k, h, g);
  return(res);
}

I do nothing in this code, so this code should give me something. However, I got an error when I do this function like this.

> testgg(3,4,5)
Error in testgg(3, 4, 5) :
  dims [product 12] do not match the length of object [60]
> testgg(3,4,1)
     [,1]      [,2]      [,3]      [,4]
[1,] numeric,0 numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0 numeric,0
[3,] numeric,0 numeric,0 numeric,0 numeric,0

My guess is that the rcpp does not get this three dimensional field, but can get the field up to 2 dimensions. Why does this happen and how can I get a three dimensional field?

Body:
Please see the open issue #263 and maybe also other ones.  There was a bug, there is a fix, but you currently need to set a #define to enable the fix (as we need to sort out if this has side-effects on other packages assuming the current behaviour).

So in short do for example

> Sys.setenv(PKG_CPPFLAGS="-DRCPP_ARMADILLO_FIX_Field")  ## sets #define RCPP_ARMADILLO_FIX_Field
> Rcpp::cppFunction("arma::field<arma::vec> testgg(int k, int h, int g) { arma::field<arma::vec> res(k, h, g); return(res);}", depends="RcppArmadillo")
> testgg(2,3,4)
, , 1

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

, , 2

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

, , 3

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

, , 4

     [,1]      [,2]      [,3]
[1,] numeric,0 numeric,0 numeric,0
[2,] numeric,0 numeric,0 numeric,0

>

So if you compile with the correct flag, the field dimension is not reduced down.

Edit And maybe you wanted cube instead of field ?

> Rcpp::cppFunction("arma::cube testhh(int k, int h, int g) { arma::cube res(k, h, g); return(res);}", depends="RcppArmadillo")
> testhh(4,3,2)
, , 1

     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    0    0    0

, , 2

     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    0    0    0

>


问:
How to add TFS bindings to a Visual Studio 2010 project?
There's a question already discussing how to add project/solution bindings to TFS, however it seems to only apply to Visual Studio 2008 (I am unable to find the "Change Source Control" dialog in VS2010).

I have a solution and source code on my local machine already in TFS, however it does not have TFS bindings (the thing that produces the padlock icon in the Visual Studio Solution Explorer and allows automatic checkout).

How can I add bindings to an existing TFS project using Visual Studio 2010?

答: I ran into this problem and, for me, the issue was that my solution was offline with respect to TFS.  Upon trying to change source control, I received a message stating that it is already associated with source control but is offline.  I placed the solution on-line, per my recollection, using the File->Source Control->Go Online menu option and this seemed to fix the problem.</p>


问:
How to suppress the Redirect URI that appears in the user consent journey screen
How to suppress the Redirect URI that appears in the user consent journey screen

User consent journey with Redirect URI

答:
This doesn't look to possible. The OAuth authorization page layout is fixed and unless there's an option in the developer portal that allows you to change the way the redirect URL is displayed, there's nothing you can do about it.

Displaying the redirect URL on the OAuth authorization page is pretty standard and the most you could hope for is to be able to specify a label to be shown instead of the raw URL.


问:
Centering a table header
I'm having issues centering a single table header.
Below is the tablea snapshot of the table Im trying to center Its header.
A snapshot of the HTML code for the table </p>

答:
lots of ways to do this.  I would use flex.  as you can see where id='zero' the solution by カメロン does NOT work

#one{
   text-align:center;
   width:100%;
}

#two{
   margin:0 auto;
}

#three{
   display:flex;
   justify-content:center;
}

#zero th{
width:100%;
text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<table id='zero'>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<table id='one'>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<table id='two'>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<div id='three'>
<table>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>
</div></code>```

Title: Centering a table header

Body:
lots of ways to do this.  I would use flex.  as you can see where id='zero' the solution by カメロン does NOT work

#one{
   text-align:center;
   width:100%;
}

#two{
   margin:0 auto;
}

#three{
   display:flex;
   justify-content:center;
}

#zero th{
width:100%;
text-align:center;
}

<table>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<table id='zero'>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<table id='one'>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<table id='two'>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>

<div id='three'>
<table>
  <tr>
    <th> one</th>
    <th>two</th>
  </tr>
  <tr>
    <td>cat</td>
    <td>dog</td>
  </tr>
</table>
</div>


问:
TimeoutException - Selenium - Python
I would appreciate some help: it finds an element with this XPATH:

driver.find_element(By.XPATH, "//*[contains(text(), '100')]")

However, when clicking I get the ElementNotInteractableException. Then, I try to solve it like this:

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), '100')]")))
element.click()
</code>```

Then, I get TimeoutException that I cannot solve. Thank you very much in advance.

This is the DOM where it is inserted:

```<code><div class="mat-menu-content ng-tns-c83-207">
 <div _ngcontent-xpe-c205="" class="option info-f12-w400-space-gray600 cursor-pointer ng-tns-c83-207">
   <div _ngcontent-xpe-c205="" class="value selected ng-star-inserted"> 25 </div>
   <div _ngcontent-xpe-c205="" class="value ng-star-inserted">50</div>
   <div _ngcontent-xpe-c205="" class="value ng-star-inserted"> 100 </div>
</div>
</div>

</code>```

答:
you can use this function it will give you the element if it ready else you will get None</p>
```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
def find_element_by_xpath(self, xpath, delay=5):
    delay = delay  # seconds
    xpath_referrers = xpath
    try:
        my_elem = WebDriverWait(self.browser, delay).until(
            EC.presence_of_element_located((By.XPATH, xpath_referrers)))
        return my_elem
    except TimeoutException:
        print(f"cant find elem at {delay} delay times ")
        return None

</code>```

Title: TimeoutException - Selenium - Python

Body:
I would appreciate some help: it finds an element with this XPATH:

driver.find_element(By.XPATH, "//*[contains(text(), '100')]")

However, when clicking I get the ElementNotInteractableException. Then, I try to solve it like this:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), '100')]")))
element.click()

Then, I get TimeoutException that I cannot solve. Thank you very much in advance.

This is the DOM where it is inserted:

 25

50

 100

Body:
you can use this function it will give you the element if it ready else you will get None

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
def find_element_by_xpath(self, xpath, delay=5):
    delay = delay  # seconds
    xpath_referrers = xpath
    try:
        my_elem = WebDriverWait(self.browser, delay).until(
            EC.presence_of_element_located((By.XPATH, xpath_referrers)))
        return my_elem
    except TimeoutException:
        print(f"cant find elem at {delay} delay times ")
        return None


问:
Find duplicated elements with dplyr
I tried using the code presented here to find ALL duplicated elements with dplyr like this:

```<code>library(dplyr)

mtcars %>%
mutate(cyl.dup = cyl[duplicated(cyl) | duplicated(cyl, from.last = TRUE)])
</code>```

How can I convert code presented here to find ALL duplicated elements with dplyr? My code above just throws an error? Or even better, is there another function that will achieve this more succinctly than the convoluted x[duplicated(x) | duplicated(x, from.last = TRUE)]) approach?

答:
You can create a Boolean mask with duplicated():

```<code>iris %>% duplicated()
  [1] FALSE FALSE FALSE .... TRUE FALSE
[145] FALSE FALSE FALSE FALSE FALSE FALSE
</code>```

And pass through square brackets indexing:

```<code>iris[iris %>% duplicated(),]
    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
143          5.8         2.7          5.1         1.9 virginica
</code>```

Note: This approach is the closest thing to Pandas
that could be done with R and dplyr:

```<code>iris[iris %>% duplicated(), c("Petal.Length","Petal.Width","Species")]
    Petal.Length Petal.Width   Species
143          5.1         1.9 virginica
</code>```

Title: Find duplicated elements with dplyr

Body:
I tried using the code presented here to find ALL duplicated elements with dplyr like this:

library(dplyr)

mtcars %>%
mutate(cyl.dup = cyl[duplicated(cyl) | duplicated(cyl, from.last = TRUE)])

How can I convert code presented here to find ALL duplicated elements with dplyr? My code above just throws an error? Or even better, is there another function that will achieve this more succinctly than the convoluted x[duplicated(x) | duplicated(x, from.last = TRUE)]) approach?

Body:
You can create a Boolean mask with duplicated():

iris %>% duplicated()
  [1] FALSE FALSE FALSE .... TRUE FALSE
[145] FALSE FALSE FALSE FALSE FALSE FALSE

And pass through square brackets indexing:

iris[iris %>% duplicated(),]
    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
143          5.8         2.7          5.1         1.9 virginica

Note: This approach is the closest thing to Pandas
that could be done with R and dplyr:

iris[iris %>% duplicated(), c("Petal.Length","Petal.Width","Species")]
    Petal.Length Petal.Width   Species
143          5.1         1.9 virginica


问:
Cron Task which displays something (task launched but nothing happens)
I well used the command "crontab -e" and added this task :

```<code>* * * * * * bash /home/user1/launcher.sh
</code>```

The content of launcher.sh is :

```<code>#!/bin/bash

PATH=/home/user1/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

/usr/bin/gedit
</code>```

Permissions of launcher.sh are 777.

I was expecting to see gedit launched every minute....but nothing happens. Why ?

I think crontab well launch "launcher.sh", as i can see in syslog :

```<code>Feb  7 22:58:01 librempc CRON[5922]: (user1) CMD (bash /home/user1/launcher.sh)
Feb  7 22:58:01 librempc CRON[5921]: (CRON) info (No MTA installed, discarding output)
</code>```

答:
By default, Cron executes tasks with very few environnement variables.

It was well explained there :
cron & the environment variables

For the environment variable "PATH", it's possible to define it in the bash script of the task itself :

```<code>PATH=/home/user1/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
</code>```

But for the environment variable "DISPLAY" (which is mandatory if the task you launch display something), it must be precised in cron file directly.

```<code>* * * * * * DISPLAY=:0 bash /home/user1/launcher.sh
</code>```

Body:
I well used the command "crontab -e" and added this task :

* * * * * * bash /home/user1/launcher.sh

The content of launcher.sh is :

#!/bin/bash

PATH=/home/user1/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

/usr/bin/gedit

Permissions of launcher.sh are 777.

I was expecting to see gedit launched every minute....but nothing happens. Why ?

I think crontab well launch "launcher.sh", as i can see in syslog :

Feb  7 22:58:01 librempc CRON[5922]: (user1) CMD (bash /home/user1/launcher.sh)
Feb  7 22:58:01 librempc CRON[5921]: (CRON) info (No MTA installed, discarding output)

Body:
By default, Cron executes tasks with very few environnement variables.

It was well explained there :
cron & the environment variables

For the environment variable "PATH", it's possible to define it in the bash script of the task itself :

PATH=/home/user1/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

But for the environment variable "DISPLAY" (which is mandatory if the task you launch display something), it must be precised in cron file directly.

* * * * * * DISPLAY=:0 bash /home/user1/launcher.sh


问:
Prevent button from being focused by arrow key click
How can I prevent that if the user presses one of the arrow keys, a button on the form is focused?

 I am programming a small game, so this would prevent the user from being able to move. Sorry for the vague explanation.

EDIT:

The player is a PictureBox with a graphic in it that is moved by:

```<code>private async void Form1_KeyDown(object sender, KeyEventArgs e)
</code>```

答:
What works for me is to set the button property "TabStop" to false and you can also play with the TabIndex property of the controls on the form to technically set what will be focused when the form loads.

TabStop - sets if pressing TAB can set/give focus to the control and when pressing the TAB key it will increment through the controls on the form according to the -
TabIndex - which dictates which control will get focus next.

So if Button A has tabIndex 1 and Button B has tabIndex 2 and button C has tabIndex 3, but Button B has tabStop = false, then pressing TAB will go from button A to Button C, it will skip Button B.

-Keep in mind that not all controls seem to have a "TabStop" property, I have noticed that textbox, button and datagridview does have the property, but stuff like labels and groupbox and picturebox does not have TabStop, only TabIndex.

Body:
How can I prevent that if the user presses one of the arrow keys, a button on the form is focused?

 I am programming a small game, so this would prevent the user from being able to move. Sorry for the vague explanation.

EDIT:

The player is a PictureBox with a graphic in it that is moved by:

private async void Form1_KeyDown(object sender, KeyEventArgs e)


问:
How to secure socket.io using Nodejs and Flutter
I developed app using Nodejs and Flutter with socket.io client. I want to secure the Socket.io during the communication between two users. Any guide or suggestion pls? Thanks.</p>

答:
On Flutter, you can an extra header to your option headers.
'extraHeaders': {HttpHeaders.authorizationHeader: '$accessToken'}

```<code>import 'package:socket_io_client/socket_io_client.dart' as IO;

IO.Socket createSocket(String accessToken) {
  final url = 'https://$yourDomainHere';
  return IO.io(url,
    <String, dynamic>{
      'transports': ['websocket'],
      'rejectUnauthorized': false,
      'autoConnect': false,
      'extraHeaders': {HttpHeaders.authorizationHeader: '$accessToken'}
    });
}
</code>```

Body:
On Flutter, you can an extra header to your option headers.
'extraHeaders': {HttpHeaders.authorizationHeader: '$accessToken'}

import 'package:socket_io_client/socket_io_client.dart' as IO;

IO.Socket createSocket(String accessToken) {
  final url = 'https://$yourDomainHere';
  return IO.io(url,
    <String, dynamic>{
      'transports': ['websocket'],
      'rejectUnauthorized': false,
      'autoConnect': false,
      'extraHeaders': {HttpHeaders.authorizationHeader: '$accessToken'}
    });
}