问:
Entity Framework Apply Migrations Programatically
I am trying to apply migrations through c# code using entity framework.
I want to drop certain tables(not all of them) and recreate programatically.
I have something like this:

```<code>try
{
    await dbContext.Database.ExecuteSqlRawAsync("drop table if exists results");
    await dbContext.GetInfrastructure().GetService<IMigrator().MigrateAsync("20230104163600_AfterSync");
}
catch (Exception e)
{
    throw;
}
</code>```

I try to run specific custom migration which contains only some of the entities of the DbContext.
Here's the migration:

```<code>[DbContext(typeof(TempDbContext))]
[Migration("20230104163600_AfterSync")]
public partial class AfterSync : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "results",
            columns: table => new
            {
                id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                groupId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
            },
            constraints: table =>
            {
                table.PrimaryKey("pK_results", x => x.id);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "results");
    }
}
</code>```

If I remove the line

```<code>await dbContext.Database.ExecuteSqlRawAsync("drop table if exists results");
</code>```

It says:

Microsoft.Data.SqlClient.SqlException: 'There is already an object named 'results' in the database.'

If I remove the override of Down method in the migration and leave the previous line, the application just crashes.

Can someone help how I can drop and recreate only certain tables not all of them withtout using the database.Migrate() method. Thanks

Body:
I am trying to apply migrations through c# code using entity framework.
I want to drop certain tables(not all of them) and recreate programatically.
I have something like this:

try
{
    await dbContext.Database.ExecuteSqlRawAsync("drop table if exists results");
    await dbContext.GetInfrastructure().GetService<IMigrator().MigrateAsync("20230104163600_AfterSync");
}
catch (Exception e)
{
    throw;
}

I try to run specific custom migration which contains only some of the entities of the DbContext.
Here's the migration:

[DbContext(typeof(TempDbContext))]
[Migration("20230104163600_AfterSync")]
public partial class AfterSync : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "results",
            columns: table => new
            {
                id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
                groupId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
            },
            constraints: table =>
            {
                table.PrimaryKey("pK_results", x => x.id);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "results");
    }
}

If I remove the line

await dbContext.Database.ExecuteSqlRawAsync("drop table if exists results");

It says:

Microsoft.Data.SqlClient.SqlException: 'There is already an object named 'results' in the database.'

If I remove the override of Down method in the migration and leave the previous line, the application just crashes.

Can someone help how I can drop and recreate only certain tables not all of them withtout using the database.Migrate() method. Thanks


来源: stackexchange

问:
Upgrading Entity Framework package with SqlLite integration tests throws SqlLiteException
In the process of upgrading our version of Entity Framework from 2.2.6 to 6.0.12 many of the integration tests have broken.  These use an in memory sqlite database.

The error revolves around migrations and a database function that was added in a migration.  This function is used to define a Computed Column in the dbContext OnModelCreating() method.  During unit test set up we run

```<code> _dbContext.Database.EnsureDeleted();
 _dbContext.Database.EnsureCreated();
</code>```

Calling EnsureCreated results in this exception being thrown:
Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'near "(": syntax error'.

Stack tracing this, it occurs OnModelCreating when we call.

```<code>modelBuilder.Entity<MyObject>()
            .Property(p => p.LinkId)
            .HasComputedColumnSql("Schema.fn_link_id([Id])");
</code>```

The syntax for this appears to be correct, so despite the exception error message, this seems to be occurring because the function does not exist as EnsureCreated() does not run a migration.

So my question is what is the best method to update an in memory sqlite database to include a database function that was added during a migration and fix this error?

Things I've attempted:

Replacing the call to .EnsureCreated() with a call to .Migrate().  This doesn't work because of the limitations of SqLite migrations, being unable to AlterColumns etc.  A work around exists where I could rewrite all of the existing migrations by hand to accommodate sqlite, but I'd like to avoid having to do this for 5+ years of migrations.

Use .Migrate() and also change the database provider to a local instance of SqlServer.  This resolves the issue and the unit tests pass locally.  However, this would result in additional overhead and considerations in our CICD pipeline which we'd like to avoid.

Create the function in the test itself to bypass a need for migrations - Results in the same unhelpful syntax error:

```<code>var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();

connection.CreateFunction("Schema.fn_link_id", (int Id) => Guid.NewGuid());

var options = new DbContextOptionsBuilder<MyDbContext>()
                .UseSqlite(connection)
                .Options;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the process of upgrading our version of Entity Framework from 2.2.6 to 6.0.12 many of the integration tests have broken.  These use an in memory sqlite database.

The error revolves around migrations and a database function that was added in a migration.  This function is used to define a Computed Column in the dbContext OnModelCreating() method.  During unit test set up we run

 _dbContext.Database.EnsureDeleted();
 _dbContext.Database.EnsureCreated();

Calling EnsureCreated results in this exception being thrown:
Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'near "(": syntax error'.

Stack tracing this, it occurs OnModelCreating when we call.

modelBuilder.Entity<MyObject>()
            .Property(p => p.LinkId)
            .HasComputedColumnSql("Schema.fn_link_id([Id])");

The syntax for this appears to be correct, so despite the exception error message, this seems to be occurring because the function does not exist as EnsureCreated() does not run a migration.

So my question is what is the best method to update an in memory sqlite database to include a database function that was added during a migration and fix this error?

Things I've attempted:

Replacing the call to .EnsureCreated() with a call to .Migrate().  This doesn't work because of the limitations of SqLite migrations, being unable to AlterColumns etc.  A work around exists where I could rewrite all of the existing migrations by hand to accommodate sqlite, but I'd like to avoid having to do this for 5+ years of migrations.

Use .Migrate() and also change the database provider to a local instance of SqlServer.  This resolves the issue and the unit tests pass locally.  However, this would result in additional overhead and considerations in our CICD pipeline which we'd like to avoid.

Create the function in the test itself to bypass a need for migrations - Results in the same unhelpful syntax error:

var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();

connection.CreateFunction("Schema.fn_link_id", (int Id) => Guid.NewGuid());

var options = new DbContextOptionsBuilder<MyDbContext>()
                .UseSqlite(connection)
                .Options;


问:
Android: an open-source app that contains a list of items in a vertical menu that could be moved up/down WITH INERTIA
In a list where the element could be moved up/down with inertia you just need to drag/push/kick an item at the right high speed to move it (at least approximately) to the top, or approximately to the desired position.

I'm looking for an exemple of code used by an open-source app (or directly a code). Do you know one?

I can't even find a gif showing this effect (which seems quite common).


问:
Can viper architecture be used on android with jetpack compose?
According to my research, viper architecture is mostly used on the iOS side, but is it used with jetpack compose on the android side? What's the difference with most common architecture mvvm in android ? If it is more advantageous than mvvm, what advantage does it have? because it doesn't seem like there are many users on the android side</p>


问:
how to set a variable in postgresql to optimize query?
I'm writing a query in postgresql and I've hardcoded the month value in multiple places in the code. E.g, if I'm running the query for December then I've used 12 everywhere in the calculations. But the issue is everytime I need to change the month I need to change the number 12 in all locations which is not a great way to code. How do I declare the month as 12 at the very top so I need to make only one change in my query at the top?

I tried using the following -

DECLARE month_number numeric := 50

but no luck.


问:
Image as a Button shows Non-clickable blank button; Tkinter Python
I have already done some small things with Tkinter for college assignments, but now i am writing this GUI interface for a desktop app as a final assignement. So i tried wrinting the code for it to go inbetween frames and not pop-up frames. And somehow the using an image as a button is not functioning and i have tried most of the things i know and even more.

Can somebody help me? Here's the code i have the far. As an example of the (un)working button we have one on the class PageOne:

import tkinter as tk
from tkinter import *
from tkinter.ttk import *
#Fontes Constantes

LARGE_FONT = ("Verdana", 12)

#Base line code that is necessary for adding pages
class FoodRecipes(tk.Tk): #inherit tk.Tk tk class within Tkinter
    def __init__(self,*args, **kwargs ): #init is really a method not a function - is going to initalize upon with the class (whenever the class is called)

        tk.Tk.__init__(self, *args, **kwargs) #initialize tkinter too
        tk.Tk.iconbitmap(self, default="assets\pngegg.ico")
        tk.Tk.wm_title(self, "Food Recipes")
        tk.Tk.wm_geometry(self, "1440x1024")

        container = tk.Frame(self) #frame is a part of tkinter, what you i'll think as a window
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1) #0 is min size; weight who gets priority

        self.frames = {}

        for F in (StartPage, PageOne, PageTwo):

            frame = F(container, self) #initial page

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew") #stretch everything to the sides of that window

        self.show_frame(StartPage) #pull/starts StartPage always first

    def show_frame(self, cont): #cont = controlller

        frame = self.frames[cont] #self.frames is all the frames - cont is the key, looking for the value of self.frames with this key. and whatever that is is being thrown in the frame and we're saying that .tkraise()
        frame.tkraise() #going to raise it to the front - raise one up to the front. there's no real order here, whatevers behind the frontpage is being hidden

class StartPage(tk.Frame): #any tkinter window

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent) #parent class - Food Recipes, that is our main class here
        label = tk.Label(self, text="Start Page", font=LARGE_FONT) #Label is the class and i created the object it is in
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Visit Page One",
                            command= lambda: controller.show_frame(PageOne)) #PageOne is a class
        button1.pack()

        button2 = tk.Button(self, text="Visit Page Two",
                            command= lambda: controller.show_frame(PageTwo)) #PageOne is a class
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page One", font=LARGE_FONT) #Label is the class and i created the object it is in
        label.pack(pady=10,padx=10)

        # Creating a photoimage object to use image
        photo = PhotoImage(file = r"assets/frame0/button_allrecipes.png")

        # here, image option is used to
        # set image on button
        button_photo = Button(self, text = 'Click Me !', image = photo).pack(side = TOP)

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page Two", font=LARGE_FONT) #Label is the class and i created the object it is in
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home",
                            command= lambda: controller.show_frame(StartPage)) #PageOne is a class
        button1.pack()

        button2 = tk.Button(self, text="Back to Page One",
                            command= lambda: controller.show_frame(PageOne)) #PageOne is a class
        button2.pack()

app = FoodRecipes()
app.resizable(False, False)
app.mainloop()```


问:
Why is there a red underline error under the showsnackbar?
void _showSnackBar(String text) {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text(text),
));
}

void _showSnackBar(String text) {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text(text),
));
}
//no red underline under showsnackbar


问:
In Juni5, how to run multiple test suites
I created multiple test suites for different categories (each category has its own test suite).
I want to create a super test suite that all the other test suites will be executed after the super test suite is executed (it contains a generic setup for the all test suites).

Example:

Test1 in the first test suite:

@ExtendWith(TestSuiteX.class)
public class Test1SuiteX {

    @Test
    public void Test1SuiteX() {
        System.out.println("Inside Test1Suite1");
    }
}
```
<p>Test2 in the second test suite:</p>
<pre class="lang-java prettyprint-override"><code>@ExtendWith(TestSuiteY.class)
public class Test2SuiteY {

    @Test
    public void Test2SuiteY() {
        System.out.println("Inside Test1Suite1");
    }
}
</code>```

TestSuiteX:

@Suite
@SelectPackages({"tests packages ..."})
public class TestSuiteX implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
        if (!started) {
            started = true;
            System.out.println("TestSuiteX setting up");
            context.getRoot().getStore(GLOBAL).put("any unique name", this);
        }
    }

    @Override
    public void close() {
        System.out.println("TestSuiteX tearing down");
    }

}
```
<p>TestSuiteY:</p>
<pre class="lang-java prettyprint-override"><code>@Suite
@SelectPackages({"tests packages ..."})
public class TestSuiteY implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
        if (!started) {
            started = true;
            System.out.println("TestSuiteY setting up");
            context.getRoot().getStore(GLOBAL).put("any unique name", this);
        }
    }

    @Override
    public void close() {
        System.out.println("TestSuiteY tearing down");
    }

}
</code>```

The above is working fine, I want to introduce a new test suite that make me able to run some code before executing the tests inside TestSuiteX and TestSuiteY (and any other existing test suites).

Example:

@Suite
@SelectPackages({"tests packages ..."})
public class MainSuite implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    Method1(): // WANT THIS TO RUN IN THE BEGINNING (before the beforeAll() methods in TestSuiteX and TestSuiteY)

    Method2(): // WANT THIS TO RUN IN THE END (after the close() methods in TestSuiteX and TestSuiteY)

}
```

Is that possible in JUni5?

Body:
I created multiple test suites for different categories (each category has its own test suite).
I want to create a super test suite that all the other test suites will be executed after the super test suite is executed (it contains a generic setup for the all test suites).

Example:

Test1 in the first test suite:

@ExtendWith(TestSuiteX.class)
public class Test1SuiteX {

    @Test
    public void Test1SuiteX() {
        System.out.println("Inside Test1Suite1");
    }
}

Test2 in the second test suite:

@ExtendWith(TestSuiteY.class)
public class Test2SuiteY {

    @Test
    public void Test2SuiteY() {
        System.out.println("Inside Test1Suite1");
    }
}

TestSuiteX:

@Suite
@SelectPackages({"tests packages ..."})
public class TestSuiteX implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
        if (!started) {
            started = true;
            System.out.println("TestSuiteX setting up");
            context.getRoot().getStore(GLOBAL).put("any unique name", this);
        }
    }

    @Override
    public void close() {
        System.out.println("TestSuiteX tearing down");
    }

}

TestSuiteY:

@Suite
@SelectPackages({"tests packages ..."})
public class TestSuiteY implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
        if (!started) {
            started = true;
            System.out.println("TestSuiteY setting up");
            context.getRoot().getStore(GLOBAL).put("any unique name", this);
        }
    }

    @Override
    public void close() {
        System.out.println("TestSuiteY tearing down");
    }

}

The above is working fine, I want to introduce a new test suite that make me able to run some code before executing the tests inside TestSuiteX and TestSuiteY (and any other existing test suites).

Example:

@Suite
@SelectPackages({"tests packages ..."})
public class MainSuite implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    Method1(): // WANT THIS TO RUN IN THE BEGINNING (before the beforeAll() methods in TestSuiteX and TestSuiteY)

    Method2(): // WANT THIS TO RUN IN THE END (after the close() methods in TestSuiteX and TestSuiteY)

}

Is that possible in JUni5?


问:
redux-saga-test-plan partial assertion on put not matching
I have a Redux saga I am trying to test with redux-saga-test-plan. The saga SomeActions.someAction calls ToastActions.showToast and I am trying to assert on that call. However, it is not matching the output correctly.

I don't really care about the payload being passed to showToast, I only care that a toast is being shown.

How do I assert on this?

Thank you!

The test:

test("...", () => {
  return expectSaga(knockSaga)
    .withState(...)
    .provide(...)
    .put.actionType(ToastActions.showToast)
    .dispatch(SomeActions.someAction(...))
    .run();
});
```
<p>The error:</p>
```SagaTestError:
put expectation unmet:

Expected
--------
{
  action: {
    type: [Function: actionCreator] {
      toString: [Function (anonymous)],
      type: 'toast/showToast',
      match: [Function (anonymous)]
    }
  }
}

Actual:
------
1. {
  '@@redux-saga/IO': true,
  combinator: false,
  type: 'PUT',
  payload: {
    channel: undefined,
    action: {
      type: 'toast/showToast',
      payload: {
        ...
      }
    }
  }
}
```

Body:
I have a Redux saga I am trying to test with redux-saga-test-plan. The saga SomeActions.someAction calls ToastActions.showToast and I am trying to assert on that call. However, it is not matching the output correctly.

I don't really care about the payload being passed to showToast, I only care that a toast is being shown.

How do I assert on this?

Thank you!

The test:

test("...", () => {
  return expectSaga(knockSaga)
    .withState(...)
    .provide(...)
    .put.actionType(ToastActions.showToast)
    .dispatch(SomeActions.someAction(...))
    .run();
});

The error:

SagaTestError:
put expectation unmet:

Expected
--------
{
  action: {
    type: [Function: actionCreator] {
      toString: [Function (anonymous)],
      type: 'toast/showToast',
      match: [Function (anonymous)]
    }
  }
}

Actual:
------
1. {
  '@@redux-saga/IO': true,
  combinator: false,
  type: 'PUT',
  payload: {
    channel: undefined,
    action: {
      type: 'toast/showToast',
      payload: {
        ...
      }
    }
  }
}


问:
How to execute code in isolated environment
I'm creating dynamic expression invocation and need to have security mechanism for code execution.
The parameter of context below is visible to the "world", so someone who can write some piece of a script.

Simple expression:

```<code>context => "a" + "b"
</code>```

Parsing:

```<code>Expression<Context, int> expression = Parse(@"context => \"a\" + \"b\"");
</code>```

Now, let's assume that context has some properties on which it can operate, so the expression could look like this and this is correct:

```<code>context => context.State.Value1 + "c";
</code>```

Here is the problem. Someone who writes the script can also do something like:

```<code>context => string.Join(", ", context.GetType().Assembly.GetTypes().Where(...)
</code>```

and access some core classes, invoke unauthorized logic etc.

Also it's worth to say that someone could do this:

```<code>context => Assembly.GetExecutingAssembly().GetTypes().Where(...)
</code>```

So the question is - how to prevent this and separate context of exeucution which should handle only neccessary data and should be executed in isolation from main/calling assembly.

I'm not sure if separate AppDomain will help.
Checking input against keywords, method access - I think it's not a solution, we cannot prevent all available unathorized method access. It can be done in too many ways.

Body:
I'm creating dynamic expression invocation and need to have security mechanism for code execution.
The parameter of context below is visible to the "world", so someone who can write some piece of a script.

Simple expression:

context => "a" + "b"

Parsing:

Expression<Context, int> expression = Parse(@"context => \"a\" + \"b\"");

Now, let's assume that context has some properties on which it can operate, so the expression could look like this and this is correct:

context => context.State.Value1 + "c";

Here is the problem. Someone who writes the script can also do something like:

context => string.Join(", ", context.GetType().Assembly.GetTypes().Where(...)

and access some core classes, invoke unauthorized logic etc.

Also it's worth to say that someone could do this:

context => Assembly.GetExecutingAssembly().GetTypes().Where(...)

So the question is - how to prevent this and separate context of exeucution which should handle only neccessary data and should be executed in isolation from main/calling assembly.

I'm not sure if separate AppDomain will help.
Checking input against keywords, method access - I think it's not a solution, we cannot prevent all available unathorized method access. It can be done in too many ways.


问:
OWL-S Ontology Protégé
how can I interpret this in the ontological graph in protégé:
1 - profile -- hasParameter(domain > range) -> Parameter
2 - serviceParameter -- sParameter (subClass all) -> owl:Thing

How can I describe this in my ontology?

Title: OWL-S Ontology Protégé


问:
git returns an error "does not appear to be a git repository" and "Could not read from remote repository"
Good afternoon.
I lifted git to an ubuntu server that is installed on a virtual machine. When sending a file to git, I get an error (attached screenshot). Although everything is set according to "https://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server " manual. Tell me how to fix it.error

When interacting with github, everything is ok.

I will immediately answer the question why do I need git on a virtual machine, I have a Synology NAS at work on which git is also installed and configured. But again, when I try to contact him, I got the same error.
Client git - Sourcetree

Everything is also configured on my computer.
my pc


问:
Setting app icon in xcconfig file not working
I am trying to set different app icon sets for different schemes in Xcode (for an app exclusively for iOS). I have an xcconfig file for dev, test, and prod. In my Development.xcconfig I have the following.

```<code>ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon-dev
</code>```

And correspondingly in the files for test and prod. In my assets folder I have the AppIcon-dev icon set etc. I have created build configuration for the different xcconfig files and have connected them to different schemes. But when I try building the project I get the follwing error.

```<code>error build: Command CompileAssetCatalog failed with a nonzero exit code
</code>```

If I change the icon set name back to just AppIcon, the error goes away and I can build the project. Even though I still have the ASSETCATALOG_COMPILER_APPICON_NAME variable set to AppIcon-dev in the xcconfig file (and I have activated the dev scheme).

Do I need to do anything else to get it to work with different icon sets? I know that I can set the icon set names for different build configuration under Build Settings > Primary App Icon Set Name, but then what is the point of having the xcconfig file if I need to define the icon set names in two different places?

To set up the xcconfig files, I followed this guide: https://pewpewthespells.com/blog/xcconfig_guide.html

Body:
I am trying to set different app icon sets for different schemes in Xcode (for an app exclusively for iOS). I have an xcconfig file for dev, test, and prod. In my Development.xcconfig I have the following.

ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon-dev

And correspondingly in the files for test and prod. In my assets folder I have the AppIcon-dev icon set etc. I have created build configuration for the different xcconfig files and have connected them to different schemes. But when I try building the project I get the follwing error.

error build: Command CompileAssetCatalog failed with a nonzero exit code

If I change the icon set name back to just AppIcon, the error goes away and I can build the project. Even though I still have the ASSETCATALOG_COMPILER_APPICON_NAME variable set to AppIcon-dev in the xcconfig file (and I have activated the dev scheme).

Do I need to do anything else to get it to work with different icon sets? I know that I can set the icon set names for different build configuration under Build Settings > Primary App Icon Set Name, but then what is the point of having the xcconfig file if I need to define the icon set names in two different places?

To set up the xcconfig files, I followed this guide: https://pewpewthespells.com/blog/xcconfig_guide.html


问:
Powershell script that takes output of one command and pastes it in another command
Internally we are trying to remove bitdefender from ~250 devices. We have got stuck as Windows still thinks bitdefender is installed. We created a script, but its coming back with an Invalid Parameter. Any help?

Our Script:

```<code>$bitdefender = Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct | Where-Object {$_.displayName -like "bitdefender"}
$instanceGuid = $bitdefender.instanceGuid
Remove-WmiObject -path \\localhost\ROOT\securitycenter2:AntivirusProduct.instanceGuid="$instanceGuid"
</code>```

The first command will show the antivius's that are installed, we want to remove BitDefender not Windows Defender, so when creating the script, I tried to copy the instanceGuid from just BitDefender. Internally we tested by manually copying the instanceGuid, and pasting in the remove command, which works flawlessly, but when trying to 'automate' it, we get the following error:

```<code>.Remove-WmiObject : Invalid parameter
\bitdefender_removal.ps1
PS C:\temp> At C:\temp\bitdefender_removal.ps1:3 char:1
+ Remove-WmiObject -path \\localhost\ROOT\securitycenter2:AntivirusProd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-WmiObject], ManagementException
    + FullyQualifiedErrorId : System.Management.ManagementException,Microsoft.PowerShell.Commands.RemoveWmiObject
</code>```

Any help would be greatly appreciated

I have tried to automate this, to no avail. We can always manually do this, but for 200+ devices, its kind of a ball ache

Body:
Internally we are trying to remove bitdefender from ~250 devices. We have got stuck as Windows still thinks bitdefender is installed. We created a script, but its coming back with an Invalid Parameter. Any help?

Our Script:

$bitdefender = Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct | Where-Object {$_.displayName -like "bitdefender"}
$instanceGuid = $bitdefender.instanceGuid
Remove-WmiObject -path \\localhost\ROOT\securitycenter2:AntivirusProduct.instanceGuid="$instanceGuid"

The first command will show the antivius's that are installed, we want to remove BitDefender not Windows Defender, so when creating the script, I tried to copy the instanceGuid from just BitDefender. Internally we tested by manually copying the instanceGuid, and pasting in the remove command, which works flawlessly, but when trying to 'automate' it, we get the following error:

.Remove-WmiObject : Invalid parameter
\bitdefender_removal.ps1
PS C:\temp> At C:\temp\bitdefender_removal.ps1:3 char:1
+ Remove-WmiObject -path \\localhost\ROOT\securitycenter2:AntivirusProd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-WmiObject], ManagementException
    + FullyQualifiedErrorId : System.Management.ManagementException,Microsoft.PowerShell.Commands.RemoveWmiObject

Any help would be greatly appreciated

I have tried to automate this, to no avail. We can always manually do this, but for 200+ devices, its kind of a ball ache


问:
React Native app that blocks certain numbers from calling
Is there a way to block certain numbers from calling using React Native? We want to implement something like TrueCaller, where the app ends the call automatically if the number is on a blocked list. Does anyone know if this is possible to build in React Native?</p>


问:
how to use battery query wmi, to get specific battery percent. ex: 24,562 %
this is my code, i using timer and button to trigger the event

```<code>using System.Management;
using System.Management.Instrumentation;
</code>```
```<code>namespace battery_efficiency_meter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Remaining_Timer_Tick(object sender, EventArgs e)
        {
           try
            {
              // Create a ManagementObjectSearcher object to run WMI queries
                 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Battery WHERE DeviceID = '1234****9Ice LakeLi-ion Battery'");

              // Looping each query result
                foreach (ManagementObject obj in searcher.Get())
                {
                     // Get the remaining and full battery capacity values in mAh
                     int remainingCapacity = (int)(uint)obj["RemainingCapacity"];
                     int fullChargeCapacity = (int)(uint)obj["FullChargeCapacity"];

                     // count battery
                     double batteryPercentage = (double)remainingCapacity / fullChargeCapacity * 100;

                     // show battery percent on string format
                     Percentage.Text = string.Format("{0:0.000}%", batteryPercentage);
                }
           }
           catch (ManagementException ex)
            {
                // Tampilkan pesan error jika terjadi exception
                MessageBox.Show("Error: " + ex.Message + "\n\n" + ex.StackTrace);
            }
</code>```
```<code>//button Start_But to trigger the event
int FN = 1;
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        private void Start_But_Click(object sender, EventArgs e)
        {
            if (FN == 1)
            {
                Stopwatch_Timer.Start();
                stopwatch.Start();
                PowerStatus ps = SystemInformation.PowerStatus;
                listBox2.Items.Add(FN++ + ".  " + lbl_Time.Text + " =  " + Percentage.Text);

                var batteryLifePercent = Convert.ToInt32(ps.BatteryLifePercent);
                chart1.Series["Battery"].Points.AddXY(FNChart, ps.BatteryLifePercent * 100);

            }
            else
            {
                Stopwatch_Timer.Start();
                stopwatch.Start();

            }
            Start_But.Enabled = false;
            Pause_But.Enabled = true;
            Reset_But.Enabled = true;
            Record_But.Enabled = true;
            write_data.Enabled = true;

        }
</code>```

i have done :

add using System.Management; as reference

add using System.Management.Instrumentation; as reference

run visual studio 2022 as administrator

add this <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges>  to app.config or web.config

add my battery id to my code

but when i enter my battery id, its always catch some error. which part should i add or fix?

Body:
this is my code, i using timer and button to trigger the event

using System.Management;
using System.Management.Instrumentation;

namespace battery_efficiency_meter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Remaining_Timer_Tick(object sender, EventArgs e)
        {
           try
            {
              // Create a ManagementObjectSearcher object to run WMI queries
                 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Battery WHERE DeviceID = '1234****9Ice LakeLi-ion Battery'");

              // Looping each query result
                foreach (ManagementObject obj in searcher.Get())
                {
                     // Get the remaining and full battery capacity values in mAh
                     int remainingCapacity = (int)(uint)obj["RemainingCapacity"];
                     int fullChargeCapacity = (int)(uint)obj["FullChargeCapacity"];

                     // count battery
                     double batteryPercentage = (double)remainingCapacity / fullChargeCapacity * 100;

                     // show battery percent on string format
                     Percentage.Text = string.Format("{0:0.000}%", batteryPercentage);
                }
           }
           catch (ManagementException ex)
            {
                // Tampilkan pesan error jika terjadi exception
                MessageBox.Show("Error: " + ex.Message + "\n\n" + ex.StackTrace);
            }

//button Start_But to trigger the event
int FN = 1;
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        private void Start_But_Click(object sender, EventArgs e)
        {
            if (FN == 1)
            {
                Stopwatch_Timer.Start();
                stopwatch.Start();
                PowerStatus ps = SystemInformation.PowerStatus;
                listBox2.Items.Add(FN++ + ".  " + lbl_Time.Text + " =  " + Percentage.Text);

                var batteryLifePercent = Convert.ToInt32(ps.BatteryLifePercent);
                chart1.Series["Battery"].Points.AddXY(FNChart, ps.BatteryLifePercent * 100);

            }
            else
            {
                Stopwatch_Timer.Start();
                stopwatch.Start();

            }
            Start_But.Enabled = false;
            Pause_But.Enabled = true;
            Reset_But.Enabled = true;
            Record_But.Enabled = true;
            write_data.Enabled = true;

        }

i have done :

add using System.Management; as reference

add using System.Management.Instrumentation; as reference

run visual studio 2022 as administrator

add this <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges>  to app.config or web.config

add my battery id to my code

but when i enter my battery id, its always catch some error. which part should i add or fix?


问:
Override default XML type in generated XSD schema for primitives
I have a class from which I generate an XSD schema. The class contains a string property which I need to serialize as a different type (not 'xs:string') into the XSD schema.

I've tried fiddling around with the XmlElementAttribute, setting Namespace and DataType properties, but this either throws an exception or doesn't serialize it correctly.

Here's an example of my class

```<code>public class MyObject {
  [XmlElement]
  public string MyField { get; set; }
}
</code>```

which generates XSD like this

```<code><xs:complexType name="MyObject">
  <xs:sequence>
    <xs:element minOccurs="0" maxOccurs="1" name="MyField" type="xs:string" />
  </xs:sequence>
</xs:complexType>
</code>```

I want MyField to be generated similar to this (note overridden type and the namespace)

```<code><xs:element minOccurs="0" maxOccurs="1" name="MyField" xmlns:q1="http://my.namespace/" type="q1:MyStringType" />
</code>```

If I add namespace to the XmlElementAttribute,

```<code>[XmlElement(Namespace = "http://my.namespace/")]
</code>```

I get the XSD field as a reference.

```<code><xs:element minOccurs="0" maxOccurs="1" xmlns:q1="http://my.namespace/" ref="q1:MyField" />
</code>```

And if I add DataType (with or without the Namespace)

```<code>[XmlElement(Namespace = "http://my.namespace/", DataType = "MyStringType")]
public string MyField { get; set; }
</code>```

I get exception saying Value 'MyStringType' cannot be used for the XmlElementAttribute.DataType property. The datatype 'http://www.w3.org/2001/XMLSchema:MyStringType' is missing.

Here's the code I'm using to generate schema.

```<code>XmlSchemas xmlSchemas = new XmlSchemas();
XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas);
XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter();

Type[] types = assembly.GetTypes();
foreach (var type in types)
{
    XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type);
    xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);

}
xmlSchemas.Compile(null, fullCompile: false);

using var schemaWriter = new StreamWriter(outputPath, append: false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
foreach (XmlSchema schema in xmlSchemas)
{
    schema.Write(schemaWriter);
}
</code>```

Body:
I have a class from which I generate an XSD schema. The class contains a string property which I need to serialize as a different type (not 'xs:string') into the XSD schema.

I've tried fiddling around with the XmlElementAttribute, setting Namespace and DataType properties, but this either throws an exception or doesn't serialize it correctly.

Here's an example of my class

public class MyObject {
  [XmlElement]
  public string MyField { get; set; }
}

which generates XSD like this

<xs:complexType name="MyObject">
  <xs:sequence>
    <xs:element minOccurs="0" maxOccurs="1" name="MyField" type="xs:string" />
  </xs:sequence>
</xs:complexType>

I want MyField to be generated similar to this (note overridden type and the namespace)

<xs:element minOccurs="0" maxOccurs="1" name="MyField" xmlns:q1="http://my.namespace/" type="q1:MyStringType" />

If I add namespace to the XmlElementAttribute,

[XmlElement(Namespace = "http://my.namespace/")]

I get the XSD field as a reference.

<xs:element minOccurs="0" maxOccurs="1" xmlns:q1="http://my.namespace/" ref="q1:MyField" />

And if I add DataType (with or without the Namespace)

[XmlElement(Namespace = "http://my.namespace/", DataType = "MyStringType")]
public string MyField { get; set; }

I get exception saying Value 'MyStringType' cannot be used for the XmlElementAttribute.DataType property. The datatype 'http://www.w3.org/2001/XMLSchema:MyStringType' is missing.

Here's the code I'm using to generate schema.

XmlSchemas xmlSchemas = new XmlSchemas();
XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas);
XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter();

Type[] types = assembly.GetTypes();
foreach (var type in types)
{
    XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type);
    xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);

}
xmlSchemas.Compile(null, fullCompile: false);

using var schemaWriter = new StreamWriter(outputPath, append: false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
foreach (XmlSchema schema in xmlSchemas)
{
    schema.Write(schemaWriter);
}


问:
Two-Way Routing Service
I have the following requirement:

Client can call the router/relay service, which in turn calls a service on the target server. The target server sends back a result to the relay service which will forward it back to the client.

I've looked at this SO question but I do not think it would suffice my needs because I assume this is only a one-way message from the client, to the relay service and finally to the target server.

I'm fairly new to WCF so I would like to get some insight about this issue so I would focus my research in the right direction.

ContentLicense: CC BY-SA 3.0

Title: Two-Way Routing Service


问:
Need to run schedulers using net/http concurrently
I am working on a project which is built using REST API and can have multiple merchant accounts. We need to run crons for every merchant per 10 mins. The cron urls are our server’s own apis. So I used Golang’s net/http package to fulfil this requirement.
I have thousands of merchants and there was hundreds of bookings per merchant which are going to be completed with the cron, to complete a booking I need to call two more schedulers with http.
I need to call all the schedulers concurrently using go routines.

when i tried to run the code for 1000 merchants, it starts giving EOF error,
Then, I have increased the open file limits to 999000 int my system.

then it starts giving error [dial tcp 127.0.0.1:3333: can't assign requested address], after too many research, I came to a point that, this error is due to the available tcp ports into the system,
it has used all the available tcp ports in the system,

then I have added some delay for the merchants, if all the ports in the system are used, so that further code will be run, whenever there was ports available in the system.

here is the code I am using,

```<code>func TestHttp2(c *gin.Context) {
    fileName := "portlog" + time.Now().String() + ".txt"
    _, e := os.Create(fileName)
    if e != nil {
        fmt.Println(1, e)
    }
    nStr := c.Query("num")
    n, _ := strconv.Atoi(nStr)
    fmt.Println("running")
    var ports int
    for i := 1; i <= n; i++ {
        url := "http://localhost:8000/public/print-test?num=" + strconv.Itoa(i)
    check:
        if i%1000 == 0 {
            ports = PortCheck()
            if ports >= 20000 {
                time.Sleep(10 * time.Second)
                goto check
            }
        }

        go MakeRequest2(url, fileName, ports)
    }
    return
}

/*
 * Function to hit url with get method and close the response body
 */
func MakeRequest2(url, fileName string, port int) {
    data := test{
        FileName: fileName,
        Url:      url,
        Port:     port,
    }
    b, err := json.Marshal(data)
    if err != nil {
        fmt.Println(234234324, err)
    }
    jsonString := string(b)
    client := &http.Client{}
    url2 := url + "?num2="
    req, err := http.NewRequest("GET", url2, bytes.NewBuffer([]byte(jsonString)))
    if err != nil {
        fmt.Println(2, "===========================================", err, "==================================")
        panic(err)
        return
    }
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(1, "===========================================", err, "==================================")
        panic(err)
        return
    }
    io.Copy(ioutil.Discard, resp.Body)
    client.CloseIdleConnections()
    resp.Body.Close()
}

func PortCheck() int {
    cmd := exec.Command("netstat", "-an")
    grep := exec.Command("grep", "8000")
    wc := exec.Command("wc", "-l")
    pipe, _ := cmd.StdoutPipe()
    defer pipe.Close()

    grep.Stdin = pipe
    pipe2, _ := grep.StdoutPipe()
    defer pipe2.Close()
    wc.Stdin = pipe2
    // Run ps first.
    cmd.Start()
    grep.Start()
    out, err := wc.Output()
    if err != nil {
        // if there was any error, print it here
        fmt.Println("could not run command: ", err)
    }
    // otherwise, print the output from running the command
    fmt.Println("Output: ", string(out))
    fmt.Println(cmd)
    wc.Wait()
    ports, err := strconv.Atoi(strings.Split(string(out), "\n")[0])
    if err != nil {
        fmt.Println(err)
    }
    return ports
}

func PrintTest(c *gin.Context) {
    data := test{}
    _ = json.NewDecoder(c.Request.Body).Decode(&data)
    file, err := os.OpenFile(data.FileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(1, err)
        return
    }
    defer file.Close()
    _, err = file.WriteString(time.Now().String() + "==>" + data.Url + " ==> " + strconv.Itoa(data.Port) + "\n")
    if err != nil {
        fmt.Println(err)
        return
    }
    for i := 1; i <= 100; i++ {
        time.Sleep(2 * time.Second)
        url1 := "http://localhost:8000/public/test-func1?num=" + strconv.Itoa(i)
        url2 := "http://localhost:8000/public/test-func2?num=" + strconv.Itoa(i)
        go MakeRequest1(url1)
        go MakeRequest1(url2)
    }
    return
}

type test struct {
    Url      string `json:"url"`
    FileName string `json:"file_name"`
    Port     int    `json:"port"`
}

func TestFunc1(c *gin.Context) {
    time.Sleep(5 * time.Second)
    fmt.Println("test function 1")
}
func TestFunc2(c *gin.Context) {
    time.Sleep(5 * time.Second)
    fmt.Println("test function 2")
}

/*
 * Function to hit url with get method and close the response body
 */
func MakeRequest1(url string) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(3, "===========================================", err, "==================================")
        panic(err)
        return
    }
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(4, "===========================================", err, "==================================")
        panic(err)
        return
    }
    io.Copy(ioutil.Discard, resp.Body)
    client.CloseIdleConnections()
    resp.Body.Close()
    return
}
</code>```

In this I am calling the TestHttp2 functions first, it will run for 5000 merchants, it will check ports after ever 1000 merchants, if ports used are >20000 we will wait for ports to release,
then we are calling PrintTest function using http, in that func we are calling TestFunc1 and TestFunc2 using http command,
Now it starts giving same error

can’t assign requested address

because, we TeseFunc1 and TestFunc2 are consuming the ports, if i am not calling these 2 functions then the code was running perfectly with 2 millions of merchants, but i need to call both functions concurrently,

Then i have added port check condition in PrintTest function too:-

```<code>func PrintTest(c *gin.Context) {
    data := test{}
    _ = json.NewDecoder(c.Request.Body).Decode(&data)
    file, err := os.OpenFile(data.FileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(1, err)
        return
    }
    defer file.Close()
    _, err = file.WriteString(time.Now().String() + "==>" + data.Url + " ==> " + strconv.Itoa(data.Port) + "\n")
    if err != nil {
        fmt.Println(err)
        return
    }
 check:
        ports := PortCheck()
            if ports >= 20000 {
            time.Sleep(10 * time.Second)
            goto check
        }
    for i := 1; i <= 100; i++ {
        time.Sleep(2 * time.Second)
        url1 := "http://localhost:8000/public/test-func1?num=" + strconv.Itoa(i)
        url2 := "http://localhost:8000/public/test-func2?num=" + strconv.Itoa(i)
        go MakeRequest1(url1)
        go MakeRequest1(url2)
    }
    return
}
</code>```

now all the ports of the system are not consumed, but it starts giving error in the last

fork/exec /usr/bin/wc: resource temporarily unavailable

After that I tried to call TestFunc1 and TestFunc2 using curl command:-

```<code>/*
 * Function to hit url with get method and close the response body
 */
func CurlTest(url string) {
    cmd := exec.Command("curl", "-H", "Connection: close", "-H", "--no-keepalive", "-X", "GET", url)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Start()
    if err == nil {
        _ = cmd.Wait()
    }
    // fmt.Println(i, time.Now())
    return
}
func PrintTest(c *gin.Context) {
    data := test{}
    _ = json.NewDecoder(c.Request.Body).Decode(&data)
    file, err := os.OpenFile(data.FileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(1, err)
        return
    }
    defer file.Close()
    _, err = file.WriteString(time.Now().String() + "==>" + data.Url + " ==> " + strconv.Itoa(data.Port) + "\n")
    if err != nil {
        fmt.Println(err)
        return
    }
    for i := 1; i <= 100; i++ {
        time.Sleep(2 * time.Second)
        url1 := "http://localhost:8000/public/test-func1?num=" + strconv.Itoa(i)
        url2 := "http://localhost:8000/public/test-func2?num=" + strconv.Itoa(i)
        go CurlTest(url1)
        go CurlTest(url2)
    }
    return
}
</code>```

If I call the CurlTest func with go routines it was opening too many files in the system, and then it was starting giving error

http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 1s

even i have set the open file limit to around 1 million, it starts giving this error, whenever the open file limit has reached > 1 million.

Please help me to find out best solution of the problem,
I want to call the schedulers with net/http rather than curl, because curl is consuming too much resources.
Please suggest the best architecture for this problem.
can we handle the tcp ports situation in other way rather than adding delays?

Body:
I am working on a project which is built using REST API and can have multiple merchant accounts. We need to run crons for every merchant per 10 mins. The cron urls are our server’s own apis. So I used Golang’s net/http package to fulfil this requirement.
I have thousands of merchants and there was hundreds of bookings per merchant which are going to be completed with the cron, to complete a booking I need to call two more schedulers with http.
I need to call all the schedulers concurrently using go routines.

when i tried to run the code for 1000 merchants, it starts giving EOF error,
Then, I have increased the open file limits to 999000 int my system.

then it starts giving error [dial tcp 127.0.0.1:3333: can't assign requested address], after too many research, I came to a point that, this error is due to the available tcp ports into the system,
it has used all the available tcp ports in the system,

then I have added some delay for the merchants, if all the ports in the system are used, so that further code will be run, whenever there was ports available in the system.

here is the code I am using,

func TestHttp2(c *gin.Context) {
    fileName := "portlog" + time.Now().String() + ".txt"
    _, e := os.Create(fileName)
    if e != nil {
        fmt.Println(1, e)
    }
    nStr := c.Query("num")
    n, _ := strconv.Atoi(nStr)
    fmt.Println("running")
    var ports int
    for i := 1; i <= n; i++ {
        url := "http://localhost:8000/public/print-test?num=" + strconv.Itoa(i)
    check:
        if i%1000 == 0 {
            ports = PortCheck()
            if ports >= 20000 {
                time.Sleep(10 * time.Second)
                goto check
            }
        }

        go MakeRequest2(url, fileName, ports)
    }
    return
}

/*
 * Function to hit url with get method and close the response body
 */
func MakeRequest2(url, fileName string, port int) {
    data := test{
        FileName: fileName,
        Url:      url,
        Port:     port,
    }
    b, err := json.Marshal(data)
    if err != nil {
        fmt.Println(234234324, err)
    }
    jsonString := string(b)
    client := &http.Client{}
    url2 := url + "?num2="
    req, err := http.NewRequest("GET", url2, bytes.NewBuffer([]byte(jsonString)))
    if err != nil {
        fmt.Println(2, "===========================================", err, "==================================")
        panic(err)
        return
    }
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(1, "===========================================", err, "==================================")
        panic(err)
        return
    }
    io.Copy(ioutil.Discard, resp.Body)
    client.CloseIdleConnections()
    resp.Body.Close()
}

func PortCheck() int {
    cmd := exec.Command("netstat", "-an")
    grep := exec.Command("grep", "8000")
    wc := exec.Command("wc", "-l")
    pipe, _ := cmd.StdoutPipe()
    defer pipe.Close()

    grep.Stdin = pipe
    pipe2, _ := grep.StdoutPipe()
    defer pipe2.Close()
    wc.Stdin = pipe2
    // Run ps first.
    cmd.Start()
    grep.Start()
    out, err := wc.Output()
    if err != nil {
        // if there was any error, print it here
        fmt.Println("could not run command: ", err)
    }
    // otherwise, print the output from running the command
    fmt.Println("Output: ", string(out))
    fmt.Println(cmd)
    wc.Wait()
    ports, err := strconv.Atoi(strings.Split(string(out), "\n")[0])
    if err != nil {
        fmt.Println(err)
    }
    return ports
}

func PrintTest(c *gin.Context) {
    data := test{}
    _ = json.NewDecoder(c.Request.Body).Decode(&data)
    file, err := os.OpenFile(data.FileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(1, err)
        return
    }
    defer file.Close()
    _, err = file.WriteString(time.Now().String() + "==>" + data.Url + " ==> " + strconv.Itoa(data.Port) + "\n")
    if err != nil {
        fmt.Println(err)
        return
    }
    for i := 1; i <= 100; i++ {
        time.Sleep(2 * time.Second)
        url1 := "http://localhost:8000/public/test-func1?num=" + strconv.Itoa(i)
        url2 := "http://localhost:8000/public/test-func2?num=" + strconv.Itoa(i)
        go MakeRequest1(url1)
        go MakeRequest1(url2)
    }
    return
}

type test struct {
    Url      string `json:"url"`
    FileName string `json:"file_name"`
    Port     int    `json:"port"`
}

func TestFunc1(c *gin.Context) {
    time.Sleep(5 * time.Second)
    fmt.Println("test function 1")
}
func TestFunc2(c *gin.Context) {
    time.Sleep(5 * time.Second)
    fmt.Println("test function 2")
}

/*
 * Function to hit url with get method and close the response body
 */
func MakeRequest1(url string) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(3, "===========================================", err, "==================================")
        panic(err)
        return
    }
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(4, "===========================================", err, "==================================")
        panic(err)
        return
    }
    io.Copy(ioutil.Discard, resp.Body)
    client.CloseIdleConnections()
    resp.Body.Close()
    return
}

In this I am calling the TestHttp2 functions first, it will run for 5000 merchants, it will check ports after ever 1000 merchants, if ports used are >20000 we will wait for ports to release,
then we are calling PrintTest function using http, in that func we are calling TestFunc1 and TestFunc2 using http command,
Now it starts giving same error

can’t assign requested address

because, we TeseFunc1 and TestFunc2 are consuming the ports, if i am not calling these 2 functions then the code was running perfectly with 2 millions of merchants, but i need to call both functions concurrently,

Then i have added port check condition in PrintTest function too:-

func PrintTest(c *gin.Context) {
    data := test{}
    _ = json.NewDecoder(c.Request.Body).Decode(&data)
    file, err := os.OpenFile(data.FileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(1, err)
        return
    }
    defer file.Close()
    _, err = file.WriteString(time.Now().String() + "==>" + data.Url + " ==> " + strconv.Itoa(data.Port) + "\n")
    if err != nil {
        fmt.Println(err)
        return
    }
 check:
        ports := PortCheck()
            if ports >= 20000 {
            time.Sleep(10 * time.Second)
            goto check
        }
    for i := 1; i <= 100; i++ {
        time.Sleep(2 * time.Second)
        url1 := "http://localhost:8000/public/test-func1?num=" + strconv.Itoa(i)
        url2 := "http://localhost:8000/public/test-func2?num=" + strconv.Itoa(i)
        go MakeRequest1(url1)
        go MakeRequest1(url2)
    }
    return
}

now all the ports of the system are not consumed, but it starts giving error in the last

fork/exec /usr/bin/wc: resource temporarily unavailable

After that I tried to call TestFunc1 and TestFunc2 using curl command:-

/*
 * Function to hit url with get method and close the response body
 */
func CurlTest(url string) {
    cmd := exec.Command("curl", "-H", "Connection: close", "-H", "--no-keepalive", "-X", "GET", url)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Start()
    if err == nil {
        _ = cmd.Wait()
    }
    // fmt.Println(i, time.Now())
    return
}
func PrintTest(c *gin.Context) {
    data := test{}
    _ = json.NewDecoder(c.Request.Body).Decode(&data)
    file, err := os.OpenFile(data.FileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(1, err)
        return
    }
    defer file.Close()
    _, err = file.WriteString(time.Now().String() + "==>" + data.Url + " ==> " + strconv.Itoa(data.Port) + "\n")
    if err != nil {
        fmt.Println(err)
        return
    }
    for i := 1; i <= 100; i++ {
        time.Sleep(2 * time.Second)
        url1 := "http://localhost:8000/public/test-func1?num=" + strconv.Itoa(i)
        url2 := "http://localhost:8000/public/test-func2?num=" + strconv.Itoa(i)
        go CurlTest(url1)
        go CurlTest(url2)
    }
    return
}

If I call the CurlTest func with go routines it was opening too many files in the system, and then it was starting giving error

http: Accept error: accept tcp [::]:8080: accept4: too many open files; retrying in 1s

even i have set the open file limit to around 1 million, it starts giving this error, whenever the open file limit has reached > 1 million.

Please help me to find out best solution of the problem,
I want to call the schedulers with net/http rather than curl, because curl is consuming too much resources.
Please suggest the best architecture for this problem.
can we handle the tcp ports situation in other way rather than adding delays?


问:
Gitlab pipeline: Only run unit tests against code that has been changed
In node.js, I have a monorepo with a number of stubs that use it. At the moment, when code is pushed to gitlab, the pipeline runs the unit tests for ALL stubs. I'd like to set things up so that the tests are only run against the stubs that have been changed.

Is this possible? If so, how can it be done?


问:
Sperating (encapsulating) Pages Using Dialogs In PyQt
I am creating GUI for an app using PyQt... I am currently using the desginer for the basics and coding the more complex stuff... And I thought it would be nice to separate things a bit. So I thought about creating the sign-up and login pages as dialogs, and then just pop them up / mount them as widgets in the app's mainwindow...

The other approach I know of, is fully creating them in a different page using a QStackedWidget, but I feel like it burdens the entire application, because it overflows it with widgets which have the same hierarchy, while I'd prefer it to be more encapsulated... Like mounting complete-page-widgets in different pages of QStackedWidget instead of just creating all of the objects in it (which makes me use prefixes for each page that disgust me...).

So I want to know the correct approach, and any suggestions will be welcomed.

edit_1:

snippet of my current code:

```<code>
class MainWindow(QMainWindow):
...
    self.ui.p2_lw_filetable.setWordWrap(True)
    self.ui.p2_lw_filetable.setIconSize(QtCore.QSize(64,64))
    self.ui.p2_lw_filetable.setFlow(QtWidgets.QListWidget.Flow.LeftToRight)
    self.ui.p2_lw_filetable.setResizeMode(QtWidgets.QListView.ResizeMode.Adjust)
    self.ui.p2_lw_filetable.setLayoutMode(QtWidgets.QListView.LayoutMode.Batched)
    self.ui.p2_lw_filetable.setViewMode(QtWidgets.QListView.ViewMode.IconMode)
...
</code>```

How I want it to be:

```<code>class Page2(QWidget):
...

class MainWindow(QMainWindow):
...
    self.page2 = Page2()
    self.stackedWidget.addWidget(self.page2)
...
</code>```

Basically I want to encapsulate each page as a widget, so it can be defined and setted up on its own, and then add it to the mainwindow in its respectable place in the main QStackedWidget.

By that I hope to achieve clearer code,
but I am not sure if that's the right way to do that.

The Bottom Line:
I need the right way for separating the hierarchy of the widgets in my ui and making it more modular.

An example of how I would like them to be:
self.ui.page2.button...
instead of the prefix way: self.ui.page2_button...

Body:
I am creating GUI for an app using PyQt... I am currently using the desginer for the basics and coding the more complex stuff... And I thought it would be nice to separate things a bit. So I thought about creating the sign-up and login pages as dialogs, and then just pop them up / mount them as widgets in the app's mainwindow...

The other approach I know of, is fully creating them in a different page using a QStackedWidget, but I feel like it burdens the entire application, because it overflows it with widgets which have the same hierarchy, while I'd prefer it to be more encapsulated... Like mounting complete-page-widgets in different pages of QStackedWidget instead of just creating all of the objects in it (which makes me use prefixes for each page that disgust me...).

So I want to know the correct approach, and any suggestions will be welcomed.

edit_1:

snippet of my current code:

class MainWindow(QMainWindow):
...
    self.ui.p2_lw_filetable.setWordWrap(True)
    self.ui.p2_lw_filetable.setIconSize(QtCore.QSize(64,64))
    self.ui.p2_lw_filetable.setFlow(QtWidgets.QListWidget.Flow.LeftToRight)
    self.ui.p2_lw_filetable.setResizeMode(QtWidgets.QListView.ResizeMode.Adjust)
    self.ui.p2_lw_filetable.setLayoutMode(QtWidgets.QListView.LayoutMode.Batched)
    self.ui.p2_lw_filetable.setViewMode(QtWidgets.QListView.ViewMode.IconMode)
...

How I want it to be:

class Page2(QWidget):
...

class MainWindow(QMainWindow):
...
    self.page2 = Page2()
    self.stackedWidget.addWidget(self.page2)
...

Basically I want to encapsulate each page as a widget, so it can be defined and setted up on its own, and then add it to the mainwindow in its respectable place in the main QStackedWidget.

By that I hope to achieve clearer code,
but I am not sure if that's the right way to do that.

The Bottom Line:
I need the right way for separating the hierarchy of the widgets in my ui and making it more modular.

An example of how I would like them to be:
self.ui.page2.button...
instead of the prefix way: self.ui.page2_button...


问:
Using multiple dispatch calls in useEffect
I am using multiple dispatch calls inside useEffect(). Each dispatch call has an async action inside and each async action is making an API call.

Now, the useEffect where all the dispatch calls are happening is obviously inside a component file.

The async actions are in separate .action.tsx files

And the API calls are in service files which are imported in .action.tsx files.

Eg:- if we have CardDetails.tsx as our component where we are calling two dispatch GetCardNumber and GetValidity, then we have two actions file GetCardNumber.action.tsx & GetValidity.action.tsx.

Also, we have two service files GetCardNumber.service.tsx &  GetValidity.service.tsx where we have the APIs.

The useEffect call looks like this -

```<code>useEffect(() => {
 dispatch(GetCardNumber(userId, setLoader));
},[])
</code>```

The action file -

```<code>function GetCardDetails(id,setLoader) {
  return (dispatch) => {
   setLoader(true)
   //call to service file to make an API call
   setLoader(false)
   }
}
</code>```

Now, the issue is that we are passing a loader state as a parameter while doing a dispatch call inside useEffect. The loader is set to true inside each action file before we make a call and is set to false after getting a response.

We came to know that the approach we are following is incorrect because one of the APIs is taking too long to provide response and because of that other APIs are setting the loader state to false and displaying the page.

So, in short, the page is getting loaded even when one of the APIs is in pending state, which is creating a bug.

Is there anyway we can resolve the issue? Many thanks in advance

Body:
I am using multiple dispatch calls inside useEffect(). Each dispatch call has an async action inside and each async action is making an API call.

Now, the useEffect where all the dispatch calls are happening is obviously inside a component file.

The async actions are in separate .action.tsx files

And the API calls are in service files which are imported in .action.tsx files.

Eg:- if we have CardDetails.tsx as our component where we are calling two dispatch GetCardNumber and GetValidity, then we have two actions file GetCardNumber.action.tsx & GetValidity.action.tsx.

Also, we have two service files GetCardNumber.service.tsx &  GetValidity.service.tsx where we have the APIs.

The useEffect call looks like this -

useEffect(() => {
 dispatch(GetCardNumber(userId, setLoader));
},[])

The action file -

function GetCardDetails(id,setLoader) {
  return (dispatch) => {
   setLoader(true)
   //call to service file to make an API call
   setLoader(false)
   }
}

Now, the issue is that we are passing a loader state as a parameter while doing a dispatch call inside useEffect. The loader is set to true inside each action file before we make a call and is set to false after getting a response.

We came to know that the approach we are following is incorrect because one of the APIs is taking too long to provide response and because of that other APIs are setting the loader state to false and displaying the page.

So, in short, the page is getting loaded even when one of the APIs is in pending state, which is creating a bug.

Is there anyway we can resolve the issue? Many thanks in advance


问:
create nested non existing directories javascript
How can I create a nested chain of non existing directories?

```<code>import { writeFileSync, mkdir } from 'fs'
const filename = 'EEE/TTT/moish.txt'
mkdir(filename, { recursive: true }, (err) => {});
writeFileSync(filename, "Hello World");
</code>```

The sub directories EEE and EEE/TTT do not exist.

```<code>$ npx tsc ./main.ts
$ node ./main.js
node:internal/fs/utils:348
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'EEE/TTT/moish.txt'
</code>```

Body:
How can I create a nested chain of non existing directories?

import { writeFileSync, mkdir } from 'fs'
const filename = 'EEE/TTT/moish.txt'
mkdir(filename, { recursive: true }, (err) => {});
writeFileSync(filename, "Hello World");

The sub directories EEE and EEE/TTT do not exist.

$ npx tsc ./main.ts
$ node ./main.js
node:internal/fs/utils:348
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'EEE/TTT/moish.txt'


问:
Pass string into map_dfr to filter using tidyfst
I'm reading data stored in several fst-files using tidyfst and purrr::map_dfr. The following example works as expected.

```<code>library(tidyverse)
library(fst)
library(tidyfst)

# get all fst files in current directory
files_fst <- file.path(list.files(pattern = ".fst"))

df <- map_dfr(files_fst,
              ~ parse_fst(.) %>%
                filter_fst(country == "France")) %>%
  bind_rows()
</code>```

However, using a variable containing the string for which I want to filter does not work:

```<code>country_in <- "France"

df <- map_dfr(files_fst,
              ~ parse_fst(.) %>%
                filter_fst(country == country_in)) %>%
  bind_rows()
</code>```

Any ideas what's the problem here?

Body:
I'm reading data stored in several fst-files using tidyfst and purrr::map_dfr. The following example works as expected.

library(tidyverse)
library(fst)
library(tidyfst)

# get all fst files in current directory
files_fst <- file.path(list.files(pattern = ".fst"))

df <- map_dfr(files_fst,
              ~ parse_fst(.) %>%
                filter_fst(country == "France")) %>%
  bind_rows()

However, using a variable containing the string for which I want to filter does not work:

country_in <- "France"

df <- map_dfr(files_fst,
              ~ parse_fst(.) %>%
                filter_fst(country == country_in)) %>%
  bind_rows()

Any ideas what's the problem here?


问:
Write to Apache MINA session after exception caught?
I have an app that uses apache mina, I would like to write a final object into the session after having an expection caught. But it does not seem to register.

Code:

```<code>@Override
public void exceptionCaught(final IoSession session, final Throwable cause) {

session.write(new RadiusPacket(RadiusPacket.ACCESS_REJECT)); // RadiusPacket.ACCESS_REJECT = 3
session.closeOnFlush();
LOG.error("Radius session closed: {}", session);
</code>```

It does not appear in the session. Any thoughts?

In MINA documentation, it says that "All in all, every time we met an exception while processing a session, this session will be closed.". Does this mean that MINA closes the session before giving control to exceptionCaught()?

I tried several other ways of adding the radius packet to the session, neither worked.

Body:
I have an app that uses apache mina, I would like to write a final object into the session after having an expection caught. But it does not seem to register.

Code:

@Override
public void exceptionCaught(final IoSession session, final Throwable cause) {

session.write(new RadiusPacket(RadiusPacket.ACCESS_REJECT)); // RadiusPacket.ACCESS_REJECT = 3
session.closeOnFlush();
LOG.error("Radius session closed: {}", session);

It does not appear in the session. Any thoughts?

In MINA documentation, it says that "All in all, every time we met an exception while processing a session, this session will be closed.". Does this mean that MINA closes the session before giving control to exceptionCaught()?

I tried several other ways of adding the radius packet to the session, neither worked.


问:
How is a main function in a multi file python program called?
I am quite new to Python and I'm working with a large Python code base consisting of hundreds of files. In a particular file, computation.py, there is a main function:

```<code>@click.command()
@click.option("--arg1", required=True)
def main(arg1, arg2, arg3)
  # definition
</code>```

I am trying to trace where arg1 was passed in, so I need to figure out how main is called. Could someone advise?

Body:
I am quite new to Python and I'm working with a large Python code base consisting of hundreds of files. In a particular file, computation.py, there is a main function:

@click.command()
@click.option("--arg1", required=True)
def main(arg1, arg2, arg3)
  # definition

I am trying to trace where arg1 was passed in, so I need to figure out how main is called. Could someone advise?


问:
Showing error while SonarQube Quality Gate via GitHub Actions,
I just integrated the Sonarqube with Github .. Used Github actions for integration with the sonarqube in which sonarqube quality gate template is used as the pipeline script and the over each pull request the sonarqube will check the code and will give the status.. Error is coming if I run this pipeline in github actions

This is the workflow Pipelines

```<code>name: SonarQube Qualitygate check
on:
  # Trigger analysis when pushing in master or pull requests, and when creating
  # a pull request.
  push:
    branches:
      - development
  pull_request:
      types: [opened, synchronize, reopened]
jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
      with:
        # Disabling shallow clone is recommended for improving relevancy of reporting.
        fetch-depth: 0

    # Triggering SonarQube analysis as results of it are required by Quality Gate check.
    - name: SonarQube Scan
      uses: SonarSource/sonarqube-scan-action@master
      with:
        projectBaseDir: .
      env:
        SONAR_TOKEN: ${{ secrets.TM_SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.TM_SONAR_HOST_URL }}

    # Check the Quality Gate status.
    - name: SonarQube Quality Gate check
      id: sonarqube-quality-gate-check
      uses: SonarSource/sonarqube-quality-gate-action@master
      # Force to fail step after specific time.
      timeout-minutes: 5
      env:
        SONAR_LOGIN: ${{ secrets.TM_SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.TM_SONAR_HOST_URL }}
</code>```

Above is having an error

```<code>Run SonarSource/sonarqube-scan-action@master

32/usr/bin/docker run --name bebb0b4094726a38064eeeb945753_521cb3 --label 290506 --workdir /github/workspace --rm -e "SONAR_TOKEN" -e "SONAR_HOST_URL" -e "INPUT_PROJECTBASEDIR" -e "INPUT_ARGS" -e "HOME" -e "GITHUB_JOB" -e "GITHUB_REF" -e "GITHUB_SHA" -e "GITHUB_REPOSITORY" -e "GITHUB_REPOSITORY_OWNER" -e "GITHUB_RUN_ID" -e "GITHUB_RUN_NUMBER" -e "GITHUB_RETENTION_DAYS" -e "GITHUB_RUN_ATTEMPT" -e "GITHUB_ACTOR" -e "GITHUB_TRIGGERING_ACTOR" -e "GITHUB_WORKFLOW" -e "GITHUB_HEAD_REF" -e "GITHUB_BASE_REF" -e "GITHUB_EVENT_NAME" -e "GITHUB_SERVER_URL" -e "GITHUB_API_URL" -e "GITHUB_GRAPHQL_URL" -e "GITHUB_REF_NAME" -e "GITHUB_REF_PROTECTED" -e "GITHUB_REF_TYPE" -e "GITHUB_WORKSPACE" -e "GITHUB_ACTION" -e "GITHUB_EVENT_PATH" -e "GITHUB_ACTION_REPOSITORY" -e "GITHUB_ACTION_REF" -e "GITHUB_PATH" -e "GITHUB_ENV" -e "GITHUB_STEP_SUMMARY" -e "GITHUB_STATE" -e "GITHUB_OUTPUT" -e "RUNNER_DEBUG" -e "RUNNER_OS" -e "RUNNER_ARCH" -e "RUNNER_NAME" -e "RUNNER_TOOL_CACHE" -e "RUNNER_TEMP" -e "RUNNER_WORKSPACE" -e "ACTIONS_RUNTIME_URL" -e "ACTIONS_RUNTIME_TOKEN" -e "ACTIONS_CACHE_URL" -e GITHUB_ACTIONS=true -e CI=true --entrypoint "/entrypoint.sh" -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/\_temp/\_github_home":"/github/home" -v "/home/runner/work/\_temp/\_github_workflow":"/github/workflow" -v "/home/runner/work/\_temp/\_runner_file_commands":"/github/file_commands" -v "/home/runner/work/tokenmetrics-2.0/tokenmetrics-2.0":"/github/workspace" 290506:793bebb0b4094726a38064eeeb945753

33INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties

34INFO: Project root configuration file: NONE

35INFO: SonarScanner 4.8.0.2856

36INFO: Java 11.0.17 Alpine (64-bit)

37INFO: Linux 5.15.0-1024-azure amd64

38INFO: User cache: /opt/sonar-scanner/.sonar/cache

39ERROR: Failed bootstrap index response: \<!doctype html\>\<html lang="en"\>\<head\>\<meta http-equiv="content-type" content="text/html; charset=UTF-8" charset="UTF-8"/\>\<meta http-equiv="X-UA-Compatible" content="IE=edge"\>\<link rel="apple-touch-icon" href="/apple-touch-icon.png"\>\<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png"\>\<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png"\>\<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png"\>\<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png"\>\<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png"\>\<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png"\>\<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png"\>\<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"\>\<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png"\>\<link rel="icon" type="image/x-icon" href="/favicon.ico"\>\<meta name="application-name" content="SonarQube"/\>\<meta name="msapplication-TileColor" content="#FFFFFF"/\>\<meta name="msapplication-TileImage" content="/mstile-512x512.png"/\>\<title\>SonarQube\</title\>\<style\>\*,:after,:before{margin:0;padding:0}body,html{background-color:#f3f3f3}body{overflow
</code>```

Another syntax I used:

```<code>name: SonarQube Qualitygate check
on:
  # Trigger analysis when pushing in master or pull requests, and when creating
  # a pull request.
  push:
    branches:
      - development
  pull_request:
      types: [opened, synchronize, reopened]
jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
      with:
        # Disabling shallow clone is recommended for improving relevancy of reporting.
        fetch-depth: 0

    - name: SonarQube Quality Gate check
      uses: sonarsource/sonarqube-quality-gate-action@master
      with:
        scanMetadataReportFile: target/sonar/report-task.txt

    # Triggering SonarQube analysis as results of it are required by Quality Gate check.
    - name: SonarQube Scan
      uses: SonarSource/sonarqube-scan-action@master
      with:
        projectBaseDir: .
      env:
        SONAR_TOKEN: ${{ secrets.TM_SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.TM_SONAR_HOST_URL }}

    # Check the Quality Gate status.
    - name: SonarQube Quality Gate check
      id: sonarqube-quality-gate-check
      uses: SonarSource/sonarqube-quality-gate-action@master
      # Force to fail step after specific time.
      timeout-minutes: 5
      env:
        SONAR_TOKEN: ${{ secrets.TM_SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.TM_SONAR_HOST_URL }}
</code>```

Error of console output for this is :

```<code>##[debug]..=> '$GITHUB_ACTION_PATH/script/check-quality-gate.sh {0}'
##[debug]..Evaluating Index:
##[debug]....Evaluating inputs:
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'scanMetadataReportFile'
##[debug]..=> 'target/sonar/report-task.txt'
##[debug]=> '$GITHUB_ACTION_PATH/script/check-quality-gate.sh target/sonar/report-task.txt'
##[debug]Result: '$GITHUB_ACTION_PATH/script/check-quality-gate.sh target/sonar/report-task.txt'
##[debug]Loading env
Run $GITHUB_ACTION_PATH/script/check-quality-gate.sh target/sonar/report-task.txt
  $GITHUB_ACTION_PATH/script/check-quality-gate.sh target/sonar/report-task.txt
  shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0}
##[debug]/usr/bin/bash --noprofile --norc -e -o pipefail /home/runner/work/_temp/e081469c-67c3-4cd2-a060-9cc26d01d502.sh
Set the SONAR_TOKEN env variable.
Error: Process completed with exit code 1.
##[debug]Finished: run
##[debug]Evaluating: steps.quality-gate-check.outputs.quality-gate-status
##[debug]Evaluating Index:
##[debug]..Evaluating Index:
##[debug]....Evaluating Index:
##[debug]......Evaluating steps:
##[debug]......=> Object
##[debug]......Evaluating String:
##[debug]......=> 'quality-gate-check'
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'outputs'
</code>```

Which pipeline have to use?

Body:
I just integrated the Sonarqube with Github .. Used Github actions for integration with the sonarqube in which sonarqube quality gate template is used as the pipeline script and the over each pull request the sonarqube will check the code and will give the status.. Error is coming if I run this pipeline in github actions

This is the workflow Pipelines

name: SonarQube Qualitygate check
on:
  # Trigger analysis when pushing in master or pull requests, and when creating
  # a pull request.
  push:
    branches:
      - development
  pull_request:
      types: [opened, synchronize, reopened]
jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
      with:
        # Disabling shallow clone is recommended for improving relevancy of reporting.
        fetch-depth: 0

    # Triggering SonarQube analysis as results of it are required by Quality Gate check.
    - name: SonarQube Scan
      uses: SonarSource/sonarqube-scan-action@master
      with:
        projectBaseDir: .
      env:
        SONAR_TOKEN: ${{ secrets.TM_SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.TM_SONAR_HOST_URL }}

    # Check the Quality Gate status.
    - name: SonarQube Quality Gate check
      id: sonarqube-quality-gate-check
      uses: SonarSource/sonarqube-quality-gate-action@master
      # Force to fail step after specific time.
      timeout-minutes: 5
      env:
        SONAR_LOGIN: ${{ secrets.TM_SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.TM_SONAR_HOST_URL }}

Above is having an error

Run SonarSource/sonarqube-scan-action@master

32/usr/bin/docker run --name bebb0b4094726a38064eeeb945753_521cb3 --label 290506 --workdir /github/workspace --rm -e "SONAR_TOKEN" -e "SONAR_HOST_URL" -e "INPUT_PROJECTBASEDIR" -e "INPUT_ARGS" -e "HOME" -e "GITHUB_JOB" -e "GITHUB_REF" -e "GITHUB_SHA" -e "GITHUB_REPOSITORY" -e "GITHUB_REPOSITORY_OWNER" -e "GITHUB_RUN_ID" -e "GITHUB_RUN_NUMBER" -e "GITHUB_RETENTION_DAYS" -e "GITHUB_RUN_ATTEMPT" -e "GITHUB_ACTOR" -e "GITHUB_TRIGGERING_ACTOR" -e "GITHUB_WORKFLOW" -e "GITHUB_HEAD_REF" -e "GITHUB_BASE_REF" -e "GITHUB_EVENT_NAME" -e "GITHUB_SERVER_URL" -e "GITHUB_API_URL" -e "GITHUB_GRAPHQL_URL" -e "GITHUB_REF_NAME" -e "GITHUB_REF_PROTECTED" -e "GITHUB_REF_TYPE" -e "GITHUB_WORKSPACE" -e "GITHUB_ACTION" -e "GITHUB_EVENT_PATH" -e "GITHUB_ACTION_REPOSITORY" -e "GITHUB_ACTION_REF" -e "GITHUB_PATH" -e "GITHUB_ENV" -e "GITHUB_STEP_SUMMARY" -e "GITHUB_STATE" -e "GITHUB_OUTPUT" -e "RUNNER_DEBUG" -e "RUNNER_OS" -e "RUNNER_ARCH" -e "RUNNER_NAME" -e "RUNNER_TOOL_CACHE" -e "RUNNER_TEMP" -e "RUNNER_WORKSPACE" -e "ACTIONS_RUNTIME_URL" -e "ACTIONS_RUNTIME_TOKEN" -e "ACTIONS_CACHE_URL" -e GITHUB_ACTIONS=true -e CI=true --entrypoint "/entrypoint.sh" -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/\_temp/\_github_home":"/github/home" -v "/home/runner/work/\_temp/\_github_workflow":"/github/workflow" -v "/home/runner/work/\_temp/\_runner_file_commands":"/github/file_commands" -v "/home/runner/work/tokenmetrics-2.0/tokenmetrics-2.0":"/github/workspace" 290506:793bebb0b4094726a38064eeeb945753

33INFO: Scanner configuration file: /opt/sonar-scanner/conf/sonar-scanner.properties

34INFO: Project root configuration file: NONE

35INFO: SonarScanner 4.8.0.2856

36INFO: Java 11.0.17 Alpine (64-bit)

37INFO: Linux 5.15.0-1024-azure amd64

38INFO: User cache: /opt/sonar-scanner/.sonar/cache

39ERROR: Failed bootstrap index response: \<!doctype html\>\\\<meta http-equiv="content-type" content="text/html; charset=UTF-8" charset="UTF-8"/\>\<meta http-equiv="X-UA-Compatible" content="IE=edge"\>\<link rel="apple-touch-icon" href="/apple-touch-icon.png"\>\<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png"\>\<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png"\>\<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png"\>\<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png"\>\<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png"\>\<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png"\>\<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png"\>\<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"\>\<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png"\>\<link rel="icon" type="image/x-icon" href="/favicon.ico"\>\<meta name="application-name" content="SonarQube"/\>\<meta name="msapplication-TileColor" content="#FFFFFF"/\>\<meta name="msapplication-TileImage" content="/mstile-512x512.png"/\>\<title\>SonarQube\</title\>\


问:
How to target css element behind another, rather than the default, in-font-of behavior with the adjacent sibling combinator
I've searched for hours but can't seem to figure out how to target an element that occurs behind another, rather than in front of.

The css + selector targets an element in front of another.

Example:

HTML:

```<code><div class="apples"></div>
<div class="bananas"></div>
</code>```

CSS:

```<code>.apples + .bananas {
    background-color: blue;
}
</code>```

This will turn the bananas class blue but I want to be able to target the apples class using the bananas class. Seems like the adjacent sibling combinator can't accomplish this. This seems like a mind-bogglingly simple thing to do but there doesn't seem to be an answer for this online. Any help?

What I've tried:
I tried using the adjacent sibling combinator and swapping around the target and the base element but this doesn't work:

HTML:

```<code><div class="apples"></div>
<div class="bananas"></div>
</code>```

CSS:

```<code>.bananas + .apples {
    background-color: blue;
}
</code>```

I'm trying to only add style to an adjacent element that occurs directly before another element based on what classes exist in the the base element. So I only want to add styling to the elements that contain the apples class based on whatever other classes exist in elements that contain the bananas class.

Body:
I've searched for hours but can't seem to figure out how to target an element that occurs behind another, rather than in front of.

The css + selector targets an element in front of another.

Example:

HTML:

CSS:

.apples + .bananas {
    background-color: blue;
}

This will turn the bananas class blue but I want to be able to target the apples class using the bananas class. Seems like the adjacent sibling combinator can't accomplish this. This seems like a mind-bogglingly simple thing to do but there doesn't seem to be an answer for this online. Any help?

What I've tried:
I tried using the adjacent sibling combinator and swapping around the target and the base element but this doesn't work:

HTML:

CSS:

.bananas + .apples {
    background-color: blue;
}

I'm trying to only add style to an adjacent element that occurs directly before another element based on what classes exist in the the base element. So I only want to add styling to the elements that contain the apples class based on whatever other classes exist in elements that contain the bananas class.


问:
How do I color every second row in a table while using Shiny?
I have written a function in my global.R-script, that takes a dataframe and some parameters and returns a datatable to be viewed in my Shiny app. The function works until I try to make every other row in the datatable have the background color '#00ff00' and the other rows have the background color '#0000ff'.

I have tried writing a css-file with the following code in it

```<code>tr:nth-child(even) {background-color: #00ff00;}
tr:nth-child(odd) {background-color: #0000ff;}
</code>```

but that did not affect the colors, probably because Shiny has some default css or javascript code that has priority. My css-file still controls the background color for the Shiny app and the colors in the head of the table, so it does work.

My best attempt so far is the following code:

```<code>  scroll_y <- min(nrow(df)*30+150,650)

  my.rows <- 1:nrow(df)
  my.colors <- ifelse(my.rows %% 2 == 0, '#00ff00', '#0000ff')

  datanames <- names(df)
  df$row <- my.rows
  df <- df[c("row", datanames)]

  t <- DT::datatable(
    df,
    rownames = FALSE,
    # class = "cell-border,"
    # class = "table table-hover",
    class = "table-hover",
    colnames = col_names,
    options = list(
      columnDefs = list(list(className = 'dt-center', targets = 1:(ncol(df) - 1))),
      paging=FALSE,
      searching=FALSE,
      filtering=FALSE,
      ordering=FALSE,
      scrollY=scroll_y,
      dom = 't',
      bSort=FALSE,
      scrollCollapse=FALSE #,
      # rowCallback = DT::JS(
      #   "function(row, data) {",
      #   "  if (data[0] % 2 === 1) {",
      #   "    $(row).css('background-color', '#0000FF');",
      #   "  }else if(data[0] % 2 === 0) {",
      #   "    $(row).css('background-color', '#FF0000');",
      #   "  }",
      #   "}"
      # )
    ),
    escape = TRUE,
    selection = "none",
    fillContainer = TRUE#,
  ) %>%
    DT::formatStyle(
      columns = 'row',
      target = 'row',
      backgroundColor = DT::styleEqual(my.rows, my.colors)
    ) #%>%
    # DT::removeColumn(0)
    # DT::formatStyle(
    #   0,
    #   backgroundColor = DT::styleEqual(c(0,1), c("#f0f0f0", "#ffffff")),
    #   rowIdx = "Mod(row.index, 2)"
    # )
</code>```

I have kept code that was commented out for you to see my other attempts at solving this issue.

I want the code above to display tables with the columns in the dataframe "df", as it looks before I add the column "row", but I cannot remove that column i seems. DT::removeColumn(0) was suggested to me, but that function seems to not exist. I also tried to remove the column "row" by writing t <- t[,"row":=NULL]
or t <- t[, "row", with = FALSE], but I got an error saying ":= can only be used within dynamic dots.".

I have commented out some javascript code that works outside of Shiny, but not in my Shiny app.

If there is a solution that uses a vector that I can calculate my self and giving me full control of the colors of each row, then that would be preferred, since I haven't really worked with javascript or css before and since I might want the last row for example to have another color than the rest of the table rows. Solutions that uses my css-file or that uses javascript are of course still of interest, especially since I can share my css-file with my colleagues easily.

Body:
I have written a function in my global.R-script, that takes a dataframe and some parameters and returns a datatable to be viewed in my Shiny app. The function works until I try to make every other row in the datatable have the background color '#00ff00' and the other rows have the background color '#0000ff'.

I have tried writing a css-file with the following code in it

tr:nth-child(even) {background-color: #00ff00;}
tr:nth-child(odd) {background-color: #0000ff;}

but that did not affect the colors, probably because Shiny has some default css or javascript code that has priority. My css-file still controls the background color for the Shiny app and the colors in the head of the table, so it does work.

My best attempt so far is the following code:

  scroll_y <- min(nrow(df)*30+150,650)

  my.rows <- 1:nrow(df)
  my.colors <- ifelse(my.rows %% 2 == 0, '#00ff00', '#0000ff')

  datanames <- names(df)
  df$row <- my.rows
  df <- df[c("row", datanames)]

  t <- DT::datatable(
    df,
    rownames = FALSE,
    # class = "cell-border,"
    # class = "table table-hover",
    class = "table-hover",
    colnames = col_names,
    options = list(
      columnDefs = list(list(className = 'dt-center', targets = 1:(ncol(df) - 1))),
      paging=FALSE,
      searching=FALSE,
      filtering=FALSE,
      ordering=FALSE,
      scrollY=scroll_y,
      dom = 't',
      bSort=FALSE,
      scrollCollapse=FALSE #,
      # rowCallback = DT::JS(
      #   "function(row, data) {",
      #   "  if (data[0] % 2 === 1) {",
      #   "    $(row).css('background-color', '#0000FF');",
      #   "  }else if(data[0] % 2 === 0) {",
      #   "    $(row).css('background-color', '#FF0000');",
      #   "  }",
      #   "}"
      # )
    ),
    escape = TRUE,
    selection = "none",
    fillContainer = TRUE#,
  ) %>%
    DT::formatStyle(
      columns = 'row',
      target = 'row',
      backgroundColor = DT::styleEqual(my.rows, my.colors)
    ) #%>%
    # DT::removeColumn(0)
    # DT::formatStyle(
    #   0,
    #   backgroundColor = DT::styleEqual(c(0,1), c("#f0f0f0", "#ffffff")),
    #   rowIdx = "Mod(row.index, 2)"
    # )

I have kept code that was commented out for you to see my other attempts at solving this issue.

I want the code above to display tables with the columns in the dataframe "df", as it looks before I add the column "row", but I cannot remove that column i seems. DT::removeColumn(0) was suggested to me, but that function seems to not exist. I also tried to remove the column "row" by writing t <- t[,"row":=NULL]
or t <- t[, "row", with = FALSE], but I got an error saying ":= can only be used within dynamic dots.".

I have commented out some javascript code that works outside of Shiny, but not in my Shiny app.

If there is a solution that uses a vector that I can calculate my self and giving me full control of the colors of each row, then that would be preferred, since I haven't really worked with javascript or css before and since I might want the last row for example to have another color than the rest of the table rows. Solutions that uses my css-file or that uses javascript are of course still of interest, especially since I can share my css-file with my colleagues easily.


问:
How to pass dynamic value inside Request body
I have two tokens one is brandwiseBearerToken which is a string and another is thirdPartyPaymentGatewayToken it belongs form my POJO class, and I want to pass these two values as dynamic. but in my case, I pass as hard-coded how I can make it dynamic. for your reference, I share my code.

I want to dynamic exact at this point

String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson);
```
<p>I don't want to pass hard-coded data</p>
<pre class="lang-java prettyprint-override"><code> public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
         throws AuthenticationException, UnknownHostException, BadRequestException {
         String brandwiseBearerToken = authenticationToken();
         String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

         RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
         Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
                                    .post(body)
                                    .addHeader("Content-Type", "application/json")
                                    .addHeader("Bearer", brandwiseBearerToken)
                                    .build();

         Response response = client.newCall(request).execute();
         ResponseBody responseBody = response.body();

         JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
         JsonElement error = jsonObject.get("Message");

         }
         ```
```

Body:
I have two tokens one is brandwiseBearerToken which is a string and another is thirdPartyPaymentGatewayToken it belongs form my POJO class, and I want to pass these two values as dynamic. but in my case, I pass as hard-coded how I can make it dynamic. for your reference, I share my code.

I want to dynamic exact at this point

String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson);

I don't want to pass hard-coded data

 public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
         throws AuthenticationException, UnknownHostException, BadRequestException {
         String brandwiseBearerToken = authenticationToken();
         String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

         RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
         Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
                                    .post(body)
                                    .addHeader("Content-Type", "application/json")
                                    .addHeader("Bearer", brandwiseBearerToken)
                                    .build();

         Response response = client.newCall(request).execute();
         ResponseBody responseBody = response.body();

         JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
         JsonElement error = jsonObject.get("Message");

         }
         ```