问:
NullReferenceException when calling method of a service in Index page in Blazor
My Index page has the @code block calling a service method:

@using BlazingPizza.Services

@inject PizzaService PizzaService

...

@code {
    private List<Pizza> specials = new List<Pizza>();

    protected override async Task OnInitializedAsync()
    {
        specials = await PizzaService.GetPizzasAsync();
    }
}
```
<p>The service is already registered in <code>Program.cs</code>:</p>
<pre class="lang-cs prettyprint-override"><code>builder.Services.AddSingleton<PizzaService>();
</code>```

I also tried injecting the interface and declaring the following:

builder.Services.AddSingleton<IPizzaService, PizzaService>();
```
<p>But whenever I call <code>GetPizzasAsync</code>, the exception happens.</p>
```NullReferenceException: Object reference not set to an instance of an object.
BlazingPizza.Pages.Index.OnInitializedAsync() in Index.razor
+
        specials = await PizzaService.GetPizzasAsync();
```

What am I missing? I am following official's tutorials.

答:
Use
builder.Services.AddSingleton<IPizzaService, PizzaService>(); but inject the Interface instead of the Class:

```<code>@inject IPizzaService PizzaService
</code>```

Now PizzaService is implemented correctly and the GetPizzaAsync() method can be used to populate your specials list.

Body:
My Index page has the @code block calling a service method:

@using BlazingPizza.Services

@inject PizzaService PizzaService

...

@code {
    private List<Pizza> specials = new List<Pizza>();

    protected override async Task OnInitializedAsync()
    {
        specials = await PizzaService.GetPizzasAsync();
    }
}

The service is already registered in Program.cs:

builder.Services.AddSingleton<PizzaService>();

I also tried injecting the interface and declaring the following:

builder.Services.AddSingleton<IPizzaService, PizzaService>();

But whenever I call GetPizzasAsync, the exception happens.

NullReferenceException: Object reference not set to an instance of an object.
BlazingPizza.Pages.Index.OnInitializedAsync() in Index.razor
+
        specials = await PizzaService.GetPizzasAsync();

What am I missing? I am following official's tutorials.

Body:
Use
builder.Services.AddSingleton<IPizzaService, PizzaService>(); but inject the Interface instead of the Class:

@inject IPizzaService PizzaService

Now PizzaService is implemented correctly and the GetPizzaAsync() method can be used to populate your specials list.


来源: stackexchange

问:
How to install the Bumblebee 2021.1.1 Android Studio Patch?
When I open Android Studio I receive a notification saying that an update is available:

```<code>The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes
</code>```

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.

答: Download and install JetBrains Toolbox. Android studio patch update will show in the toolbox list. Update through this. Hope its helpful.</p>

ContentLicense: CC BY-SA 4.0

Body:
When I open Android Studio I receive a notification saying that an update is available:

The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.


问:
Why doesn't build_runner generate files when serializing JSON in dart/flutter
I'm just trying to generate my files with the same command i stored like 3 months ago (i'm not very good with backend and devops) and now it doesn't generate the files anymore.
It tells me to use the delete command which i don't remember but even using that one my files still won't be generated.
This is what my log looks like, and below you can find the code for a simple class.

One of my guesses would be this has something to do with me changing my github account, since there's the permission issue mentioned.

Im using vs code in windows 10.

log file:

```<code>E:\1 Work\flutter_pilot> flutter pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 336ms

[WARNING] Deleted previous snapshot due to missing asset graph.
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 12.5s

[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 787ms

[INFO] Checking for unexpected pre-existing outputs....
[INFO] Found 13 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
[SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/models/advisory-service-item.g.dart
lib/models/advisory-service.g.dart
lib/models/auth.g.dart
lib/models/contract.g.dart
lib/models/contributor.g.dart
lib/models/exact-cost-values.g.dart
lib/models/exact-cost.g.dart
lib/models/expert.g.dart
lib/models/paginator-info.g.dart
lib/models/person.g.dart
lib/models/project.g.dart
lib/models/system-country.g.dart
lib/models/user.g.dart
pub failed (78)
</code>```

class file:

```<code>import 'package:json_annotation/json_annotation.dart';
part 'organisation.g.dart';

@JsonSerializable()
class Organisation {
  final String name;
  Organisation({this.name});

  factory Organisation.fromJson(Map<String, dynamic> json) => _$OrganisationFromJson(json);

  Map<String, dynamic> toJson() => _$OrganisationToJson(this);
}
</code>```

答: In my case the build_runner process was successful but the .g files weren't produced. I had to restart the IDE (vscode) before I start seeing the .g files.</p>

Body:
I'm just trying to generate my files with the same command i stored like 3 months ago (i'm not very good with backend and devops) and now it doesn't generate the files anymore.
It tells me to use the delete command which i don't remember but even using that one my files still won't be generated.
This is what my log looks like, and below you can find the code for a simple class.

One of my guesses would be this has something to do with me changing my github account, since there's the permission issue mentioned.

Im using vs code in windows 10.

log file:

E:\1 Work\flutter_pilot> flutter pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 336ms

[WARNING] Deleted previous snapshot due to missing asset graph.
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 12.5s

[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 787ms

[INFO] Checking for unexpected pre-existing outputs....
[INFO] Found 13 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
[SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/models/advisory-service-item.g.dart
lib/models/advisory-service.g.dart
lib/models/auth.g.dart
lib/models/contract.g.dart
lib/models/contributor.g.dart
lib/models/exact-cost-values.g.dart
lib/models/exact-cost.g.dart
lib/models/expert.g.dart
lib/models/paginator-info.g.dart
lib/models/person.g.dart
lib/models/project.g.dart
lib/models/system-country.g.dart
lib/models/user.g.dart
pub failed (78)

class file:

import 'package:json_annotation/json_annotation.dart';
part 'organisation.g.dart';

@JsonSerializable()
class Organisation {
  final String name;
  Organisation({this.name});

  factory Organisation.fromJson(Map<String, dynamic> json) => _$OrganisationFromJson(json);

  Map<String, dynamic> toJson() => _$OrganisationToJson(this);
}


问:
Create a csv file in from a python list
I have a list like the following with the \n separating each new lines

```<code>['Data,9,record,timestamp,"896018545",s,position_lat,"504719750",semicircles,position_long,"-998493490",semicircles,distance,"10.87",m,altitude,"285.79999999999995",m,speed,"1.773",m/s,unknown,"3929",,unknown,"1002",,enhanced_altitude,"285.79999999999995",m,enhanced_speed,"1.773",m/s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\n', 'Data,9,record,timestamp,"896018560",s,position_lat,"504717676",semicircles,position_long,"-998501870",semicircles,distance,"71.85",m,altitude,"285.0",m,speed,"5.533",m/s,unknown,"3924",,unknown,"1001",,enhanced_altitude,"285.0",m,enhanced_speed,"5.533",m/s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]
</code>```

This is hard to read, so I need to extract the following out of this list into a CSV file in python in the below format without using pandas:

```<code>timestamp, position_lat,altitude
"896018545","504719750","285.79999999999995"
"896018560","504717676","285.0"
</code>```

I have the following, but I am confused about how to add the data into the CSV file:

```<code>header = ['timestamp','latitude','altitude']
with open('target.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    # write the header
    writer.writerow(header)
    # write the data
</code>```

Title: Create a csv file in from a python list

Body:
I have a list like the following with the \n separating each new lines

['Data,9,record,timestamp,"896018545",s,position_lat,"504719750",semicircles,position_long,"-998493490",semicircles,distance,"10.87",m,altitude,"285.79999999999995",m,speed,"1.773",m/s,unknown,"3929",,unknown,"1002",,enhanced_altitude,"285.79999999999995",m,enhanced_speed,"1.773",m/s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\n', 'Data,9,record,timestamp,"896018560",s,position_lat,"504717676",semicircles,position_long,"-998501870",semicircles,distance,"71.85",m,altitude,"285.0",m,speed,"5.533",m/s,unknown,"3924",,unknown,"1001",,enhanced_altitude,"285.0",m,enhanced_speed,"5.533",m/s,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]

This is hard to read, so I need to extract the following out of this list into a CSV file in python in the below format without using pandas:

timestamp, position_lat,altitude
"896018545","504719750","285.79999999999995"
"896018560","504717676","285.0"

I have the following, but I am confused about how to add the data into the CSV file:

header = ['timestamp','latitude','altitude']
with open('target.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    # write the header
    writer.writerow(header)
    # write the data

Body:
If I'm understanding your question correctly, all you need to do is write additional rows that include your data.

...
    ...
    writer.writerow(["896018545","504719750","285.79999999999995"])
    writer.writerow(["896018560","504717676","285.0"])

# alternatively,

data = [["896018545","504719750","285.79999999999995"],
["896018560","504717676","285.0"]]
...
    ...
    for row in data:
        writer.writerow(row)


问:
Is it safe to use fclose() on a temporary file created by tmpfile()?
According to this documentation, the temporary file created by tmpfile() is closed and deleted when the program exits normally. So far, I have not found any details regarding the use of fclose() on such file.

答:
Is it safe to use fclose() on a temporary file created by tmpfile()?

Yes, OK to close.

The tmpfile function creates a temporary binary file that is different from any other existing file and that will automatically be removed when it is closed or at program termination. If the program terminates abnormally, whether an open temporary file is removed is implementation-defined.

C17dr § 7.21.4.3 2


问:
How do I give specific users access to specific websites in PHP?
I'm building a login system. My database looks like this

Lets say, after loggin in, the code recognizes who is currently logged in and sends them to a specific website, based on the content in their KURS field.

So user yyy would be send to lets say TG111.php

And user uuu would be send to lets say TG112.php

TG111.php looks like this

<?php
session_start();

    $sess = $_SESSION['KURS'];

    if ($sess !== 'TG111') {
      if ($sess !== 'TG112') {
        if ($sess !== 'TG113') {
          header("Location: index.php");
          exit();
        }
        else {
          header("Location: TG113.php");
          exit();
        }
      }
      else {
        header("Location: TG112.php");
        exit();
      }
    }
    else {
      header('Location: TG111.php');
      exit();
    }

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Hello</title>

    Abmelden

```

But this doesn't work...

答:
I'm not sure what you're looking for? but you can try to debug it to see what the problem, you can try using this in your if statement</p>
```<code>if($sess == 'TG111') {
    header('Location: TG111.php');
    exit();
} elseif ($sess == 'TG112') {
    header("Location: TG112.php");
    exit();
} elseif ($sess == 'TG113') {
    header("Location: TG113.php");
    exit();
} else {
    header("Location: index.php");
    exit();
}
</code>```

Body:
I'm building a login system. My database looks like this

Lets say, after loggin in, the code recognizes who is currently logged in and sends them to a specific website, based on the content in their KURS field.

So user yyy would be send to lets say TG111.php

And user uuu would be send to lets say TG112.php

TG111.php looks like this

<?php
session_start();

    $sess = $_SESSION['KURS'];

    if ($sess !== 'TG111') {
      if ($sess !== 'TG112') {
        if ($sess !== 'TG113') {
          header("Location: index.php");
          exit();
        }
        else {
          header("Location: TG113.php");
          exit();
        }
      }
      else {
        header("Location: TG112.php");
        exit();
      }
    }
    else {
      header('Location: TG111.php');
      exit();
    }

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Hello</title>

    Abmelden

But this doesn't work...

Body:
I'm not sure what you're looking for? but you can try to debug it to see what the problem, you can try using this in your if statement

if($sess == 'TG111') {
    header('Location: TG111.php');
    exit();
} elseif ($sess == 'TG112') {
    header("Location: TG112.php");
    exit();
} elseif ($sess == 'TG113') {
    header("Location: TG113.php");
    exit();
} else {
    header("Location: index.php");
    exit();
}


问:
Cannot validate argument on parameter 'Container'. The argument is null or empty
I’m working on triggering an on-demand backup for my machines. But while running ps script it shows the below error.
"Cannot validate argument on parameter 'Container'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again".

```<code>$vault = Get-AzRecoveryServicesVault -ResourceGroupName "xxxx" -Name "xxxx"
Set-AzRecoveryServicesVaultContext -Vault $vault
$backupcontainer = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -FriendlyName "testvm"
$item = Get-AzRecoveryServicesBackupItem -Container $backupcontainer -WorkloadType "AzureVM"
</code>```

the above code was working fine couple of months ago. I have tried using different vm names in -FriendlyName but no luck.

Please suggest

答:
The PowerShell response is that Get-AzRecoveryServicesBackupContainer do not respond a valid container object but $null.
Why I don't know.

But you should test the return values of the CmdLets you call before using them in other CmdLets.

Body:
I’m working on triggering an on-demand backup for my machines. But while running ps script it shows the below error.
"Cannot validate argument on parameter 'Container'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again".

$vault = Get-AzRecoveryServicesVault -ResourceGroupName "xxxx" -Name "xxxx"
Set-AzRecoveryServicesVaultContext -Vault $vault
$backupcontainer = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -FriendlyName "testvm"
$item = Get-AzRecoveryServicesBackupItem -Container $backupcontainer -WorkloadType "AzureVM"

the above code was working fine couple of months ago. I have tried using different vm names in -FriendlyName but no luck.

Please suggest


问:
What is the usage of guard let self = self else { return }
I just learned how to use the Result type recently from Sean Allen's video, and I get the idea of using it. However, while I was writing a code, there is a line I don't understand.

The line is 87 in the picture (or this -> guard let self = self else { return } )
At first, I was just doing the same stuff as he did, but I wonder why he add the line in the code. I think he wrote it because the self can be nil and wanted to make sure if the self is not nil and return from the function if it gets nil.

And my question is

when or in which situation the self can be nil?
and

if self gets nil, I think it won't trigger the following line (the one for checking the result), so both of the updateUI function and presentGFAlert... function won't be triggered and nothing shows up on the screen, right?

答:
Your concern is correct. Because getFollowers is an async task, user could go back to previous screen while the task is running. In that case, self could be nil and the return is okay.

On the other hand, to make sure there's no problem with completion block of getFollowers task, self will be captured as strong reference, that could cause memory leak even if user already leave that screen.
He uses weak self to prevent that happens.


问:
how to check null value of Integer type field in ASP.NET MVC view?
I have integer type field in database which is having property "Not Null".

when i create a view & do a validation, if i left that field blank, it will consider it as 0 so i can not compare it with 0 because if someone insert a value 0 then it will be considered as error!

one another problem is that i am using Model error as described in the book "ASP.NET MVC 1.0" @ Scott Gu blog.  And I am checking the value in partial class of object (created by LINQ-To-SQL). i.e

```<code>public partial class Person
{
    public bool IsValid
    {
        get { return (GetRuleViolations().Count() == 0); }
    }
    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name))
            yield return new RuleViolation("Name is Required", "Name");
        if (Age == 0)
            yield return new RuleViolation("Age is Required", "Age");
        yield break;
    }
    partial void OnValidate(ChangeAction action)
    {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }
}
</code>```

There is also problem with range.

Like in database if i declared as smallint i.e. short in c#, now if i exceed that range then it gives error as "A Value is reguired".

so finally is there any best way for validation in ASP.NET MVC?

答:
you can change your code with a nullable type?</p>

```<code>    Dim i As Nullable(Of Integer)

    MsgBox(i.HasValue)
    'result is false

    i = 1
    MsgBox(i.HasValue)
    'result is true

    i = Nothing
    MsgBox(i.HasValue)
    'result is false
</code>```

OwnerDisplayName: Vikas

ContentLicense: CC BY-SA 2.5

Body:
I have integer type field in database which is having property "Not Null".

when i create a view & do a validation, if i left that field blank, it will consider it as 0 so i can not compare it with 0 because if someone insert a value 0 then it will be considered as error!

one another problem is that i am using Model error as described in the book "ASP.NET MVC 1.0" @ Scott Gu blog.  And I am checking the value in partial class of object (created by LINQ-To-SQL). i.e

public partial class Person
{
    public bool IsValid
    {
        get { return (GetRuleViolations().Count() == 0); }
    }
    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name))
            yield return new RuleViolation("Name is Required", "Name");
        if (Age == 0)
            yield return new RuleViolation("Age is Required", "Age");
        yield break;
    }
    partial void OnValidate(ChangeAction action)
    {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }
}

There is also problem with range.

Like in database if i declared as smallint i.e. short in c#, now if i exceed that range then it gives error as "A Value is reguired".

so finally is there any best way for validation in ASP.NET MVC?

Body:
you can change your code with a nullable type?

    Dim i As Nullable(Of Integer)

    MsgBox(i.HasValue)
    'result is false

    i = 1
    MsgBox(i.HasValue)
    'result is true

    i = Nothing
    MsgBox(i.HasValue)
    'result is false

OwnerDisplayName: Fredou


问:
Set a html form with javascript
I've been playing with the PayPal code:

```<code>                <form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="paypal">
                <input type="hidden" name="cmd" value="_cart">
                <input type="hidden" name="upload" value="1">
                <input type="hidden" name="currency_code" value="GBP">
                <input type="hidden" name="business" value="test@test.org">
                <input type="hidden" name="item_name_1" value="Item1">
                <input type="hidden" name="amount_1" value="1.00">
                <input type="hidden" name="item_name_2" value="Item2">
                <input type="hidden" name="amount_2" value="2.00">
                <input type="submit" value="PayPal">
                </form>
</code>```

And I want to set the value of item_name_1 and amount_1 via javascript when a button is pressed elsewhere so when that form is submitted the values are all set:

So I have this function run when the add to cart is clicked:

```<code><script type='text/javascript'>
function addtocart(){
paypal.item_name_2.value="Hello!";
}
 </script>
</code>```

I feel I'm on the right tracks but no joy. Help please! TIA

答:
Try this</p>

```<code>document.forms["paypal"].item_name_2.value="heelo";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Set a html form with javascript

Body:
I've been playing with the PayPal code:

                <form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="paypal">
                <input type="hidden" name="cmd" value="_cart">
                <input type="hidden" name="upload" value="1">
                <input type="hidden" name="currency_code" value="GBP">
                <input type="hidden" name="business" value="test@test.org">
                <input type="hidden" name="item_name_1" value="Item1">
                <input type="hidden" name="amount_1" value="1.00">
                <input type="hidden" name="item_name_2" value="Item2">
                <input type="hidden" name="amount_2" value="2.00">
                <input type="submit" value="PayPal">
                </form>

And I want to set the value of item_name_1 and amount_1 via javascript when a button is pressed elsewhere so when that form is submitted the values are all set:

So I have this function run when the add to cart is clicked:

I feel I'm on the right tracks but no joy. Help please! TIA

Body:
Try this

document.forms["paypal"].item_name_2.value="heelo";


问:
Render 2 micro-frontend on the same page (root)
I'm struggling with the following scenario when using micro-frontend architecture :

I have a first micro-frontend used to do some search (by exemple I look for persons), I have another micro-frontend used to display the detail of a selected person (reusable with other micro-frontend). both are written in Angular and have their own routing.

I tried to use a framework like single-spa.js to make a "root" where we inject the first app (search app) and a bootstrap modal with the detail (app2), the communication between both is made with a shared state in redux. But both routing enter in conflict, when both app start, they want to route to their default route and it crashed (kind of infinite loop).

Did someone already succeed this scenario may be by using WebComponents, so that all angular app can run independently and that both routing are separate and does not interact with the other app ? and of course without using iFrames ;)

Regards,

答:
I think https://www.npmjs.com/package/@angular-architects/module-federation could be useful in your use case.

Webpack 5 give the very good capability to federate your modules and compose multiple micro app in one and share resources


问:
Accidentally deleted my test folder in Spring boot application
As the title says I accidentally deleted my test folder in Spring boot application and created a folder named test under src folder. But now I can't create java class in test folder.IDE does not recognize it as a java class. What can I do to fix this?</p>

答: Create the java in the test directory. If you use IDEA, right-click the java and choose Mark Directory as->Test Resources Root from the shortcut menu. Put your test classes in the java.


问:
Jenkins Copy Artifacts from Upstream Job to Downstream and back
I have Job A that call to another Job B

Job B know copy from Job A the artifact.

How I can do copy back of another artifact from Job B to Job A?

```<code>Job A
//////////

 stage('Validation'){
                'Binary Scan':{
                    build job: 'JOB_B'
                },
           )
        }

Job B
/////////

stage('Copy Artifacts from Job A'){

copyArtifacts filter: 'testz.zip',
fingerprintArtifacts: true,
projectName: currentBuild.upstreamBuilds[0].fullProjectName,
selector: upstream()

}

stage('Do something'){
}

stage('Copy Artifacts back to Job A'){

/////?????????
}
</code>```

答:
From within a project, you can't normally execute arbitrary code into a different project.

What you can do is for the Job B to use archiveArtifacts, and when it completes, the calling job (Job A) can retrieve the artifacts from the instance of Job B it triggered.
The build command will return a job 'handle' that has enough information to let you build a copyArtifacts command.

```<code>job A
//////////

stage('Produce artifacts'){
     // First, produce some artifacts for Job B and archive them so that they are available to Job B
     archiveArtifacts artifacts: "testz.zip"
}

stage('Validation'){
     // Invoke Job B (blocks until job B completes)
     def jobB = build job: "JOB_B"

     // Retrieve artifacts from Job B after it completes
     final String artifactsFilter = "build/*.csv"
     copyArtifacts filter: artifactsFilter, projectName: "JOB_B", selector: specific("${jobB.number}")
     // re-attach the same artifacts to Job A (now that they have been copied back into Job A workspace)
     archiveArtifacts artifacts: artifactsFilter
}

Job B
/////////

stage('Copy Artifacts from Job A'){
    copyArtifacts filter: 'testz.zip', fingerprintArtifacts: true,
                projectName: currentBuild.upstreamBuilds[0].fullProjectName,
                selector: upstream()
}
stage('Do something'){
}
stage('Archive Artifacts for Job A'){
    // Archive desired artifacts
    archiveArtifacts artifacts: "build/**.csv"
}
</code>```

Body:
I have Job A that call to another Job B

Job B know copy from Job A the artifact.

How I can do copy back of another artifact from Job B to Job A?

Job A
//////////

 stage('Validation'){
                'Binary Scan':{
                    build job: 'JOB_B'
                },
           )
        }

Job B
/////////

stage('Copy Artifacts from Job A'){

copyArtifacts filter: 'testz.zip',
fingerprintArtifacts: true,
projectName: currentBuild.upstreamBuilds[0].fullProjectName,
selector: upstream()

}

stage('Do something'){
}

stage('Copy Artifacts back to Job A'){

/////?????????
}

Body:
From within a project, you can't normally execute arbitrary code into a different project.

What you can do is for the Job B to use archiveArtifacts, and when it completes, the calling job (Job A) can retrieve the artifacts from the instance of Job B it triggered.
The build command will return a job 'handle' that has enough information to let you build a copyArtifacts command.

job A
//////////

stage('Produce artifacts'){
     // First, produce some artifacts for Job B and archive them so that they are available to Job B
     archiveArtifacts artifacts: "testz.zip"
}

stage('Validation'){
     // Invoke Job B (blocks until job B completes)
     def jobB = build job: "JOB_B"

     // Retrieve artifacts from Job B after it completes
     final String artifactsFilter = "build/*.csv"
     copyArtifacts filter: artifactsFilter, projectName: "JOB_B", selector: specific("${jobB.number}")
     // re-attach the same artifacts to Job A (now that they have been copied back into Job A workspace)
     archiveArtifacts artifacts: artifactsFilter
}

Job B
/////////

stage('Copy Artifacts from Job A'){
    copyArtifacts filter: 'testz.zip', fingerprintArtifacts: true,
                projectName: currentBuild.upstreamBuilds[0].fullProjectName,
                selector: upstream()
}
stage('Do something'){
}
stage('Archive Artifacts for Job A'){
    // Archive desired artifacts
    archiveArtifacts artifacts: "build/**.csv"
}


问:
Snakemake integrate the multiple command lines in a rule
The output of my first command line "bcftools query -l {input.invcf} | head -n 1" prints the name of the first individual of vcf file (i.e. IND1). I want to use that output in selectvariants GATK in -sn IND1 option. How is it possible to integrate the 1st comamnd line in snakemake in order to use it's output in the next one?

```<code>rule selectvar:
    input:
        invcf="{family}_my.vcf"
    params:
        ind= ???
        ref="ref.fasta"
    output:
        out="{family}.dn.vcf"
    shell:
        """
        bcftools query -l {input.invcf} | head -n 1 > {params.ind}
        gatk --java-options "-Xms2G -Xmx2g -XX:ParallelGCThreads=2" SelectVariants -R {params.ref} -V {input.invcf} -sn {params.ind} -O {output.out}
        """
</code>```

答:
When I have to do these things I prefer to use run instead of shell, and then shell out only at the end.
The reason for this is because it makes it possible for snakemake to lint the run statement, and to exit early if something goes wrong instead of following through with a broken shell command.</p>
```<code>rule selectvar:
    input:
        invcf="{family}_my.vcf"
    params:
        ref="ref.fasta"
        gatk_opts='--java-options "-Xms2G -Xmx2g -XX:ParallelGCThreads=2" SelectVariants'
    output:
        out="{family}.dn.vcf"
    run:
        opts = "{params.gatk_opts} -R {params.ref} -V {input.invcf} -O {output.out}"
        sn_parameter = shell("bcftools query -l {input.invcf} | head -n 1")
        # we could add a sanity check here if necessary, before shelling out
        shell(f"gatk {options} {sn_parameter}")
        """
</code>```

Body:
The output of my first command line "bcftools query -l {input.invcf} | head -n 1" prints the name of the first individual of vcf file (i.e. IND1). I want to use that output in selectvariants GATK in -sn IND1 option. How is it possible to integrate the 1st comamnd line in snakemake in order to use it's output in the next one?

rule selectvar:
    input:
        invcf="{family}_my.vcf"
    params:
        ind= ???
        ref="ref.fasta"
    output:
        out="{family}.dn.vcf"
    shell:
        """
        bcftools query -l {input.invcf} | head -n 1 > {params.ind}
        gatk --java-options "-Xms2G -Xmx2g -XX:ParallelGCThreads=2" SelectVariants -R {params.ref} -V {input.invcf} -sn {params.ind} -O {output.out}
        """

Body:
When I have to do these things I prefer to use run instead of shell, and then shell out only at the end.
The reason for this is because it makes it possible for snakemake to lint the run statement, and to exit early if something goes wrong instead of following through with a broken shell command.

rule selectvar:
    input:
        invcf="{family}_my.vcf"
    params:
        ref="ref.fasta"
        gatk_opts='--java-options "-Xms2G -Xmx2g -XX:ParallelGCThreads=2" SelectVariants'
    output:
        out="{family}.dn.vcf"
    run:
        opts = "{params.gatk_opts} -R {params.ref} -V {input.invcf} -O {output.out}"
        sn_parameter = shell("bcftools query -l {input.invcf} | head -n 1")
        # we could add a sanity check here if necessary, before shelling out
        shell(f"gatk {options} {sn_parameter}")
        """


问:
Select first row in each GROUP BY group?

As the title suggests, I'd like to select the first row of each set of rows grouped with a GROUP BY.

Specifically, if I've got a purchases table that looks like this:

SELECT * FROM purchases;
```
<p><strong>My Output:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>customer</th>
<th>total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Joe</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>Joe</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Sally</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I'd like to query for the <code>id</code> of the largest purchase (<code>total</code>) made by each <code>customer</code>. Something like this:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT FIRST(id), customer, FIRST(total)
FROM  purchases
GROUP BY customer
ORDER BY total DESC;
</code>```

Expected Output:

FIRST(id)
customer
FIRST(total)

1
Joe
5

2
Sally
3

答:
This is how we can achieve this by using windows function:

```<code>    create table purchases (id int4, customer varchar(10), total integer);
    insert into purchases values (1, 'Joe', 5);
    insert into purchases values (2, 'Sally', 3);
    insert into purchases values (3, 'Joe', 2);
    insert into purchases values (4, 'Sally', 1);

    select ID, CUSTOMER, TOTAL from (
    select ID, CUSTOMER, TOTAL,
    row_number () over (partition by CUSTOMER order by TOTAL desc) RN
    from purchases) A where RN = 1;
</code>```

Body:
As the title suggests, I'd like to select the first row of each set of rows grouped with a GROUP BY.

Specifically, if I've got a purchases table that looks like this:

SELECT * FROM purchases;

My Output:

id
customer
total

1
Joe
5

2
Sally
3

3
Joe
2

4
Sally
1

I'd like to query for the id of the largest purchase (total) made by each customer. Something like this:

SELECT FIRST(id), customer, FIRST(total)
FROM  purchases
GROUP BY customer
ORDER BY total DESC;

Expected Output:

FIRST(id)
customer
FIRST(total)

1
Joe
5

2
Sally
3

Body:
This is how we can achieve this by using windows function:

    create table purchases (id int4, customer varchar(10), total integer);
    insert into purchases values (1, 'Joe', 5);
    insert into purchases values (2, 'Sally', 3);
    insert into purchases values (3, 'Joe', 2);
    insert into purchases values (4, 'Sally', 1);

    select ID, CUSTOMER, TOTAL from (
    select ID, CUSTOMER, TOTAL,
    row_number () over (partition by CUSTOMER order by TOTAL desc) RN
    from purchases) A where RN = 1;


问:
How to add spacing between columns in Bootstrap 5?
screenshot

i want like this

As you can see in the picture, I can't put a space between the red and blue columns. I tried many Bootstrap classes, but I couldn't get the result I wanted. I added m-4 to the Navbar, Header and the sections below. When I add a few divs in the row, the left and right length (in m-4 equal) is distorted. I want to keep the left and right spacing fixed and adjust the spacing of the columns inside. How will I do this?

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

            example

            example

            example

            example

            example

            example

```

答:
With some template changes you can achieve this.

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

                example

                example

                example

                example

                example

                example

```

Body:
With some template changes you can achieve this.

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<header>
    <div class="m-4 px-4" style="background-color: white; border-radius: 10px;"></div>
</header>

<section id="first">
    <div class="m-4 px-4 py-5 smashinglogo" style="border-radius: 10px;"></div>
</section>
<section>
    <div class="m-4 row" style="background-color: white; border-radius: 10px;">
        <div class="col-lg-6 p-1">
            <div class="p-4" style="background-color: red; border-radius: 10px;">
                example
            </div>
        </div>
        <div class="col-lg-6 p-1">
            <div class="p-4" style="background-color: blue; border-radius: 10px;">
                example
            </div>
        </div>
    </div>
    <div class="m-4 row" style="background-color: white; border-radius: 10px;">
        <div class="col-lg-3 p-1">

            <div class="p-4" style="background-color: red; border-radius: 10px;">
                example
            </div>
        </div>
        <div class="col-lg-3 p-1">
            <div class="p-4" style="background-color: red; border-radius: 10px;">
                example
            </div>
        </div>
        <div class="col-lg-3 p-1">
            <div class="p-4" style="background-color: blue; border-radius: 10px;">
                example
            </div>
        </div>
        <div class="col-lg-3 p-1">
            <div class="p-4" style="background-color: blue; border-radius: 10px;">
                example
            </div>
        </div>
    </div>
</section>


问:
Why does comparing using greater than and less than always return true?
I am trying to compare command-line input to check whether or not it is between and including 0 and 2. Am I misunderstanding the &&(and) operator?

```<code>#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]){
  if ((argc >= 0) && (argc <= 2))
    printf("True\n");
  else
    printf("False\n");
  }
</code>```

No matter what value I input, I always get True.

```<code>[jpuyear]$ ./test 1
True
[jpuyear]$ ./test 0
True
[jpuyear]$ ./test 2
True
[jpuyear]$ ./test 3
True
[jpuyear]$ ./test 4
True

</code>```

答:
argc is the count of how many arguments you have.  Each time you enter one argument, so argc is 2 (one for the program name and one for the argument passed in) and the condition is true.

argv contains the strings which are the actual arguments.  So first make sure that argc is at least 2, and if so use atoi to convert argv[1] to an integer and check that.

Body:
I am trying to compare command-line input to check whether or not it is between and including 0 and 2. Am I misunderstanding the &&(and) operator?

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]){
  if ((argc >= 0) && (argc <= 2))
    printf("True\n");
  else
    printf("False\n");
  }

No matter what value I input, I always get True.

[jpuyear]$ ./test 1
True
[jpuyear]$ ./test 0
True
[jpuyear]$ ./test 2
True
[jpuyear]$ ./test 3
True
[jpuyear]$ ./test 4
True


问:
not able to mute someone in discord.js - node.js
I want to mute someone manually in discord.js
by adding:

if(message.author == /*muted list*/){
message.delete();
return;
}
```
<p>and I need to extract the list from a json file (and I did)</p>
<pre class="lang-json prettyprint-override"><code>{
  "muted":[
    //someone's ID,
    //someone else's ID
    ]
}
</code>```

I got the the IDs in a variable.
and logged it into console to see if I did it correct
console output:

[  some id , some else id ]
```

so I put the variable in the /*muted list*/  in the js file.
but it did nothing.
help pls

答:
Try

if (<muted.json>.find(x => x.id == message.author.id)) {
    message.delete();
    return;
}
```

Body:
I want to mute someone manually in discord.js
by adding:

if(message.author == /*muted list*/){
message.delete();
return;
}

and I need to extract the list from a json file (and I did)

{
  "muted":[
    //someone's ID,
    //someone else's ID
    ]
}

I got the the IDs in a variable.
and logged it into console to see if I did it correct
console output:

[  some id , some else id ]

so I put the variable in the /*muted list*/  in the js file.
but it did nothing.
help pls


问:
need to add a column to my query results output and update that column with conditional values from another column in the same query table
I want to add a new column (see site AS Location) in my query results where the values are based off of what is in the 'site' column.  For example when 'site' = 'test' THEN SET Location = 'test1'.

I keep getting the error that Location does not exist.

I need assistance in adding the column named 'Location' to my query results and not ALTER the actual tables.

```<code>SELECT DISTINCT ON (accessionnumber)
           id,
           accessionnumber,
           patientname,
           patientid,
           patientdateofbirth,
           patientsex,
           studydescription,
           studydate,
           referringphysician,
           organization,
           peerreviewanalyticsview.comment,
           status,
           reviewedon,
           reviewedby,
           type,
           procedurecode,
           modalities,
           reportingradiologist,
           site,
           site AS Location,
           peerreviewid
FROM   workflowquality.peerreviewanalyticsview
       LEFT OUTER JOIN workflowquality.peerreviewscore
                    ON workflowquality.peerreviewanalyticsview.id =
                       workflowquality.peerreviewscore.peerreviewid
</code>```

答:
You need to use the CASE...WHEN statement in your select query, like below.

```<code>SELECT DISTINCT ON (accessionnumber) Id, accessionnumber, column2,....
site, CASE WHEN site ='test' THEN 'test1'
         END Location, peerreviewid FROM table1...<join clause>
</code>```

You can add multiple WHEN segments, and also there is an ELSE part if none of the conditions match.

Body:
I want to add a new column (see site AS Location) in my query results where the values are based off of what is in the 'site' column.  For example when 'site' = 'test' THEN SET Location = 'test1'.

I keep getting the error that Location does not exist.

I need assistance in adding the column named 'Location' to my query results and not ALTER the actual tables.

SELECT DISTINCT ON (accessionnumber)
           id,
           accessionnumber,
           patientname,
           patientid,
           patientdateofbirth,
           patientsex,
           studydescription,
           studydate,
           referringphysician,
           organization,
           peerreviewanalyticsview.comment,
           status,
           reviewedon,
           reviewedby,
           type,
           procedurecode,
           modalities,
           reportingradiologist,
           site,
           site AS Location,
           peerreviewid
FROM   workflowquality.peerreviewanalyticsview
       LEFT OUTER JOIN workflowquality.peerreviewscore
                    ON workflowquality.peerreviewanalyticsview.id =
                       workflowquality.peerreviewscore.peerreviewid

Body:
You need to use the CASE...WHEN statement in your select query, like below.

SELECT DISTINCT ON (accessionnumber) Id, accessionnumber, column2,....
site, CASE WHEN site ='test' THEN 'test1'
         END Location, peerreviewid FROM table1...<join clause>

You can add multiple WHEN segments, and also there is an ELSE part if none of the conditions match.


问:
err_connection_timed_out and PHP Warning: mysqli_connect():(HY000/2002):Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
Recently, from few weeks ago I got err_connection_timed_out just sometimes while working with my website.

and i am sure, my users get this error too.
When i see at error log, there are a few of message like below

PHP Warning:mysqli_connect(): (HY000/2002): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock

I changed 'localhost' to '127.0.0.1' for TCP connection instead of Unix socket, but no success.

My server host admin do not accept any problem at server side (like always!).

I asked them to restart Mysql, but they do not accept because it is a share server.

It is a Directadmin server and they recommend switch to Cpanel as the last chance.

Do you have any experience and solution for this problem?

EDIT: The main problem is err_connection_timed_out which i get in browser and i don't know if it relates to Mysql connection error in log file.

答:
Normally this problem is caused due to MySQL server timing-out database connections is faster than the Stash connection pool can notice. This exhausts the Stash connection pool as it will keep its connections open while the MySQL side of the connections is already closed.

Easiest solution.
You can fix it by simply change this parameter (wait_timeout) at the Mysql config.

More difficult but better
Also you can close all connections in your code after you got the values. And finally you can change your connection to your database in order to reuse an existing connections.

And last but not least
Try a vps you got out there too many oferts, even for free. You wouldn't be able to change anything in a shared host sorry. :(


问:
How to restart a java program within the program
I'm working on a small Java game using Swing for school, and we need to implement a button that "starts a new game" when pressed. The problem is, the game takes multiple parameters from String[] args, so I can't just call the "main" function (where everything is instansiated) again from another class. Any way to do this?</p>

答:
You have to lauch your program before exit it.
Runtime rs = Runtime. getRuntime(); try { rs. exec("java -jar your_restartable_program.jar"); }


问:
Avoid & Count non-numerical values computing basic statistics in Mathematica
Please consider:

```<code>dalist={{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
       {2.88`, 2.04`, 4.64`,0.56`, 4.92`, 2.06`, 3.46`, 2.68`, 2.72`,0.820},
       {"Laura1", "Laura1", "Laura1", "Laura1", "Laura1",
       "Laura1", "Laura1", "Laura1", "Laura1","Laura1"},
       {"RIGHT", 0, 1, 15.1`, 0.36`, 505, 20.059375`,15.178125`, ".", "."}}
</code>```

The actual dataset is about 6 000 rows and 147 columns. However the above reflects its content. I would like to compute some basic statistics, such as the mean. My attempt:

```<code>Table[Mean@dalist[[colNO]], {colNO, 1, 4}]
</code>```

How could I create a function such as to:

Avoid non-numerical values and

Count the number of non numerical values found in each lists.

I have not succeeded in finding the right pattern mechanism yet.

答:
Here is a variation of Verbeia's answer that you may consider.

Assuming that this is a rectangular array (all rows are the same length), then setting d to the row length (which can be found with Dimensions):

```<code>d = 10;

{d - Length@#, Mean@#} &@Select[#, NumericQ] & /@ dalist
</code>```

```(* Out: *) {{0, 11/2}, {0, 2.678}, {10, Mean[{}]}, {3, 79.5282}}```

That is, pairs of {number_of_non-numeric, average}.

Mean[{}] appears where there are no numeric values to average.  This could be removed from the list with DeleteCases but the results would no longer align with the rows of dalist.  I think it would be better to use something like: /. Mean[{}] -> "NO AVERAGE" if needed.

Body:
Please consider:

dalist={{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
       {2.88`, 2.04`, 4.64`,0.56`, 4.92`, 2.06`, 3.46`, 2.68`, 2.72`,0.820},
       {"Laura1", "Laura1", "Laura1", "Laura1", "Laura1",
       "Laura1", "Laura1", "Laura1", "Laura1","Laura1"},
       {"RIGHT", 0, 1, 15.1`, 0.36`, 505, 20.059375`,15.178125`, ".", "."}}

The actual dataset is about 6 000 rows and 147 columns. However the above reflects its content. I would like to compute some basic statistics, such as the mean. My attempt:

Table[Mean@dalist[[colNO]], {colNO, 1, 4}]

How could I create a function such as to:

Avoid non-numerical values and

Count the number of non numerical values found in each lists.

I have not succeeded in finding the right pattern mechanism yet.

Body:
Here is a variation of Verbeia's answer that you may consider.

Assuming that this is a rectangular array (all rows are the same length), then setting d to the row length (which can be found with Dimensions):

d = 10;

{d - Length@#, Mean@#} &@Select[#, NumericQ] & /@ dalist

(* Out: *) {{0, 11/2}, {0, 2.678}, {10, Mean[{}]}, {3, 79.5282}}

That is, pairs of {number_of_non-numeric, average}.

Mean[{}] appears where there are no numeric values to average.  This could be removed from the list with DeleteCases but the results would no longer align with the rows of dalist.  I think it would be better to use something like: /. Mean[{}] -> "NO AVERAGE" if needed.


问:
sudoers - Google Compute Engine - no access to root
I have a Google Compute Engine VM instance with a Asterisk Server running on it. I get this message when I try to run sudo:

```<code>sudo: parse error in /etc/sudoers near line 21
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin
</code>```

Is there a password for root so I can try to change it there? Any suggestions on this?

答:
I got a Permission denied error when trying to ssh to the problem instance via gcloud. Using a startup script as mentioned above by @Jorick works. Instructions for it are here. You will have to stop and restart the VM instance for the startup script to get executed. I modified the script slightly:

```<code>rm -f /etc/sudoers.d/google_sudoers >& /tmp/startup.log
</code>```

After the restart, launch an SSH session from the cloud console and check that you are able to view the file contents (with sudo more /etc/sudoers.d/google_sudoers for example). If that works your problem has been solved.

Body:
I have a Google Compute Engine VM instance with a Asterisk Server running on it. I get this message when I try to run sudo:

sudo: parse error in /etc/sudoers near line 21
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

Is there a password for root so I can try to change it there? Any suggestions on this?

Body:
I got a Permission denied error when trying to ssh to the problem instance via gcloud. Using a startup script as mentioned above by @Jorick works. Instructions for it are here. You will have to stop and restart the VM instance for the startup script to get executed. I modified the script slightly:

rm -f /etc/sudoers.d/google_sudoers >& /tmp/startup.log

After the restart, launch an SSH session from the cloud console and check that you are able to view the file contents (with sudo more /etc/sudoers.d/google_sudoers for example). If that works your problem has been solved.


问:
Where to configure jest in a monorepo?
I am setting up a monorepo in which I am building a react app where I will be using typescript. We want to use jest to test backend features and React-Testing-Library to test frontend features. Should I install jest and add the config file in root or directly in the ''backend'' package?

What would be the advantage / disadvantages of doing one over the other?

Thank you for your help.

答:
Just install the jest package in the root. Then, add projects [array<string | ProjectConfig>]
 configuration in jest.config.js file:

Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time.

My project uses lerna to manage mono repos.

Folder structure:

⚡  tree -L 2 -I 'node_modules|examples'
.
├── LICENSE
├── coverage
│   ├── clover.xml
│   ├── coverage-final.json
│   ├── lcov-report
│   └── lcov.info
├── jest.config.js
├── jest.setup.js
├── lerna.json
├── package-lock.json
├── package.json
├── packages
│   ├── redux-saga-examples
│   └── redux-toolkit-example
└── tsconfig.json

5 directories, 10 files
```
<p>There are two packages: <code>redux-saga-examples</code> and <code>redux-toolkit-example</code>. There are many test files in these packages.</p>
<p>The <code>package.json</code> in the root:</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "root",
  "private": true,
  "scripts": {
    "bootstrap": "lerna bootstrap",
    "clean": "lerna clean",
    "test": "jest"
  },
  "devDependencies": {
    "@types/jest": "^26.0.24",
    "lerna": "^4.0.0",
    "jest": "^27.0.6",
    "ts-jest": "^27.0.4",
    "ts-node": "^9.1.1",
    "typescript": "^4.3.5",
    "prettier": "^2.3.1"
  },
  "dependencies": {
    "axios": "^0.21.4"
  }
}
</code>```

jest.config.js:

const reduxSagaExamplesPkg = require('./packages/redux-saga-examples/package.json');
const RTKExamplesPkg = require('./packages/redux-toolkit-example/package.json');

module.exports = {
  verbose: true,
  projects: [
    {
      preset: 'ts-jest/presets/js-with-ts',
      testEnvironment: 'jsdom',
      setupFilesAfterEnv: ['./jest.setup.js'],
      displayName: reduxSagaExamplesPkg.name,
      testMatch: ['<rootDir>/packages/redux-saga-examples/**/?(*.)+(spec|test).[jt]s?(x)'],
    },
    {
      preset: 'ts-jest/presets/js-with-ts',
      testEnvironment: 'jsdom',
      setupFilesAfterEnv: ['./jest.setup.js'],
      displayName: RTKExamplesPkg.name,
      testMatch: ['<rootDir>/packages/redux-toolkit-example/**/?(*.)+(spec|test).[jt]s?(x)'],
    },
  ],
};
```

Now, you can run npm t npm script in the root of the project to run all tests.

Title: Where to configure jest in a monorepo?

Body:
Just install the jest package in the root. Then, add projects [array<string | ProjectConfig>]
 configuration in jest.config.js file:

Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time.

My project uses lerna to manage mono repos.

Folder structure:

⚡  tree -L 2 -I 'node_modules|examples'
.
├── LICENSE
├── coverage
│   ├── clover.xml
│   ├── coverage-final.json
│   ├── lcov-report
│   └── lcov.info
├── jest.config.js
├── jest.setup.js
├── lerna.json
├── package-lock.json
├── package.json
├── packages
│   ├── redux-saga-examples
│   └── redux-toolkit-example
└── tsconfig.json

5 directories, 10 files

There are two packages: redux-saga-examples and redux-toolkit-example. There are many test files in these packages.

The package.json in the root:

{
  "name": "root",
  "private": true,
  "scripts": {
    "bootstrap": "lerna bootstrap",
    "clean": "lerna clean",
    "test": "jest"
  },
  "devDependencies": {
    "@types/jest": "^26.0.24",
    "lerna": "^4.0.0",
    "jest": "^27.0.6",
    "ts-jest": "^27.0.4",
    "ts-node": "^9.1.1",
    "typescript": "^4.3.5",
    "prettier": "^2.3.1"
  },
  "dependencies": {
    "axios": "^0.21.4"
  }
}

jest.config.js:

const reduxSagaExamplesPkg = require('./packages/redux-saga-examples/package.json');
const RTKExamplesPkg = require('./packages/redux-toolkit-example/package.json');

module.exports = {
  verbose: true,
  projects: [
    {
      preset: 'ts-jest/presets/js-with-ts',
      testEnvironment: 'jsdom',
      setupFilesAfterEnv: ['./jest.setup.js'],
      displayName: reduxSagaExamplesPkg.name,
      testMatch: ['<rootDir>/packages/redux-saga-examples/**/?(*.)+(spec|test).[jt]s?(x)'],
    },
    {
      preset: 'ts-jest/presets/js-with-ts',
      testEnvironment: 'jsdom',
      setupFilesAfterEnv: ['./jest.setup.js'],
      displayName: RTKExamplesPkg.name,
      testMatch: ['<rootDir>/packages/redux-toolkit-example/**/?(*.)+(spec|test).[jt]s?(x)'],
    },
  ],
};

Now, you can run npm t npm script in the root of the project to run all tests.


问:
How to activate/deactivate a selection of a clicked element?
I have 3 headings Administration, Market, DTA.

The selection color  is on Administration,

When, the user clicks on an other heading for example Market.
The selection color  is always on Administration.

I would like the color to be activated on a single heading.

dashboard.component.html

```<code><ul class="nav-links" *ngFor="let menu of menus; let i = index">
    <li [ngClass]="{ selected: selectedTab === menu.route }">
      <a
        routerLink="{{ menu.route }}"
        routerLinkActive="active"
        (click)="toggleMenu(i); selectedTab = menu.route"
      >
        <i class="{{ menu.class }}"></i>
        <span class="links_name"> {{ menu.item }} </span>
        <i
          class="{{ menu.arrowDown }} iconArrow"
          *ngIf="selectedTab !== menu.route || !showSubmenu[i]"
        ></i>
        <i
          class="{{ menu.arrowUp }} iconArrow "
          *ngIf="selectedTab === menu.route && showSubmenu[i]"
        ></i>
      </a>
    </li>

    <ng-container *ngFor="let submenu of menu.submenus; let j = index">
      <li *ngIf="showSubmenu[i]">
        <a routerLink="{{ submenu.route }}">
          <i class="{{ submenu.class }}"></i>
          <span class="links_name"> {{ submenu.item }} </span>
        </a>
      </li>
    </ng-container>
</code>```

I can share you my code here.

The pseudo is toto and the password 1234.

答:
Headers' route settings are not routing properly. First of all, remove slash from redirect routes of modules and change them with appropriate route. For example, route setting for the market module route can be as follows:

```<code>{
     path: '',
     pathMatch: 'full',
     redirectTo: 'indice',
},
</code>```

Second, add also routerLinkActive="active" to submenus routes.

Stackblitz

Body:
I have 3 headings Administration, Market, DTA.

The selection color  is on Administration,

When, the user clicks on an other heading for example Market.
The selection color  is always on Administration.

I would like the color to be activated on a single heading.

dashboard.component.html

         {{ menu.item }}

    <ng-container *ngFor="let submenu of menu.submenus; let j = index">

           {{ submenu.item }}

    </ng-container>

I can share you my code here.

The pseudo is toto and the password 1234.

Body:
Headers' route settings are not routing properly. First of all, remove slash from redirect routes of modules and change them with appropriate route. For example, route setting for the market module route can be as follows:

{
     path: '',
     pathMatch: 'full',
     redirectTo: 'indice',
},

Second, add also routerLinkActive="active" to submenus routes.

Stackblitz


问:
Equivalent in C++ to the pack function in PHP pack('H*', $tagIdAsHex);
I have this PHP code:

$tagId = 1;    // the original value of tag
$tagIdAsHex = sprintf("%02X", $tagId);    // the tag value in hex format
$tagAsHexBytes = pack('H*', $tagIdAsHex);  // the packed hex value of tag packed into string as a conversion
```
<p>How can I translate that to C++?</p>
<pre class="lang-cpp prettyprint-override"><code>byte tagId = 1;
auto hexedTag = IntToHex(tagId); //C++ Builder
??
</code>```

答:
The PHP code shown is simply converting the integer 1 into a hex-encoded string containing "01", and is then parsing that hex string into a binary string holding a single byte 0x01.

In C, you can use sscanf() in a loop to parse a hex string.

In standard C++, you can use std::hex and std::setw() to parse a hex string from any std::istream, such as std::istringstream, using operator>> in a loop.

In C++Builder specifically, you can use its RTL's HexToBin() function to parse a hex string into a pre-allocated byte array.

Body:
I have this PHP code:

$tagId = 1;    // the original value of tag
$tagIdAsHex = sprintf("%02X", $tagId);    // the tag value in hex format
$tagAsHexBytes = pack('H*', $tagIdAsHex);  // the packed hex value of tag packed into string as a conversion

How can I translate that to C++?

byte tagId = 1;
auto hexedTag = IntToHex(tagId); //C++ Builder
??


问:
Changing the kotlin version results in change in compilesdkversion for some reasons
I cloned a flutter project, and tried to run it on an android device. But I ran into this error:

Execution failed for task ':app:checkDebugAarMetadata'.
Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.window:window-java:1.0.0-beta04.
AAR metadata file: C:\Users\Harshit.gradle\caches\transforms-2\files-2.1\ac98fb722099a50563f635966aedbe29\jetified-window-java-1.0.0-beta04\META-INF\com\android\build\gradle\a
ar-metadata.properties.

The error mentions that the current compileSdkVersion is 30, but some dependency works only with 31.

So, I just changed compileSdkVersion and targetSdkVersion from 30 to 31, in my app-level build.gradle, then I tried to run it again, and I ran into another error:

Task :location:compileDebugKotlin
e: Incompatible classes were found in dependencies. Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors
e: C:/Users/Harshit/.gradle/caches/transforms-2/files-2.1/1028a8ca100cbb0fda6fd6257a450fc1/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

After a quick google search, I found a fix, that I need to mention the latest kotlin version in android/build.gradle file, so I changed this:

```<code>ext.kotlin_version = '1.3.50'
</code>```

to this:

```<code>ext.kotlin_version = '1.6.0'
</code>```

and downloaded the respective kotlin plugin. Then I tried to run the project again, and I ran into this error:

Execution failed for task ':google_maps_flutter:checkDebugUnitTestAarMetadata'.
Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-29).
Dependency: androidx.window:window-java:1.0.0-beta04.
AAR metadata file: C:\Users\Harshit.gradle\caches\transforms-2\files-2.1\9d7a6c54f576894d03496d57f9d5a318\jetified-window-java-1.0.0-beta04\META-INF\com\android\build\gradle\a
ar-metadata.properties.

This error is identical to the first error, except here it mentions that the current compileSdkVersion is 29, even though I didn't change it after setting it to 31.

So, for some reason, upgrading the version of kotlin results in compileSdkVersin being set to 29 automatically, and I have no idea why.

How can I get rid of this error which says the current compileSdkVersion is 29, even though I have it set to 31?

And why does changing kotlin version tricks it into believing that compileSdkVersion is 29, even though its value is set to 31 in build.gradle?

android/build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.6.0'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app/build.gradle:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.pranshupandya.locus_stalker"
        minSdkVersion 20
        targetSdkVersion 31
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:28.2.0')
    implementation 'com.google.firebase:firebase-analytics'
    def multidex_version = "2.0.1"
    implementation "androidx.multidex:multidex:$multidex_version"
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
```<code>android {
    compileSdkVersion 31  // update to 31 from 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.ryx.mallties"
        minSdkVersion 21
        targetSdkVersion 31  // update to 31 from 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

</code>```

Body:
I cloned a flutter project, and tried to run it on an android device. But I ran into this error:

Execution failed for task ':app:checkDebugAarMetadata'.
Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.window:window-java:1.0.0-beta04.
AAR metadata file: C:\Users\Harshit.gradle\caches\transforms-2\files-2.1\ac98fb722099a50563f635966aedbe29\jetified-window-java-1.0.0-beta04\META-INF\com\android\build\gradle\a
ar-metadata.properties.

The error mentions that the current compileSdkVersion is 30, but some dependency works only with 31.

So, I just changed compileSdkVersion and targetSdkVersion from 30 to 31, in my app-level build.gradle, then I tried to run it again, and I ran into another error:

Task :location:compileDebugKotlin
e: Incompatible classes were found in dependencies. Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors
e: C:/Users/Harshit/.gradle/caches/transforms-2/files-2.1/1028a8ca100cbb0fda6fd6257a450fc1/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

After a quick google search, I found a fix, that I need to mention the latest kotlin version in android/build.gradle file, so I changed this:

ext.kotlin_version = '1.3.50'

to this:

ext.kotlin_version = '1.6.0'

and downloaded the respective kotlin plugin. Then I tried to run the project again, and I ran into this error:

Execution failed for task ':google_maps_flutter:checkDebugUnitTestAarMetadata'.
Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-29).
Dependency: androidx.window:window-java:1.0.0-beta04.
AAR metadata file: C:\Users\Harshit.gradle\caches\transforms-2\files-2.1\9d7a6c54f576894d03496d57f9d5a318\jetified-window-java-1.0.0-beta04\META-INF\com\android\build\gradle\a
ar-metadata.properties.

This error is identical to the first error, except here it mentions that the current compileSdkVersion is 29, even though I didn't change it after setting it to 31.

So, for some reason, upgrading the version of kotlin results in compileSdkVersin being set to 29 automatically, and I have no idea why.

How can I get rid of this error which says the current compileSdkVersion is 29, even though I have it set to 31?

And why does changing kotlin version tricks it into believing that compileSdkVersion is 29, even though its value is set to 31 in build.gradle?

android/build.gradle:

buildscript {
    ext.kotlin_version = '1.6.0'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app/build.gradle:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.pranshupandya.locus_stalker"
        minSdkVersion 20
        targetSdkVersion 31
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:28.2.0')
    implementation 'com.google.firebase:firebase-analytics'
    def multidex_version = "2.0.1"
    implementation "androidx.multidex:multidex:$multidex_version"
}
apply plugin: 'com.google.gms.google-services'


问:
AWS Lambda Connecting to Local Postgres in Docker
I'm attempting to connect to a local Postgres server running as a docker container from my Lambda function.

I'm using the sam local invoke call to do so.

For some reason, it seems that outgoing connection from SAM's docker container for the function is disabled.

I'm getting this error message:

```<code>"errorMessage": "(psycopg2.OperationalError) could not connect to server: Connection refused\n\tIs the server running on host \"localhost\" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\ncould not connect to server: Cannot assign requested address\n\tIs the server running on host \"localhost\" (::1) and accepting\n\tTCP/IP connections on port 5432?\n\n(Background on this error at: http://sqlalche.me/e/e3q8)",
</code>```

Is there a way to enable a Lambda function call to a local docker database?

I have no issues running the connection code outside the Lambda function as standard Python code - so I'm sure my database is up, my code works, etc.

答:
I resolve this by replacing localhost with host.docker.internal.

For example if you use psycopg2

```<code>conn = psycopg2.connect(host="host.docker.internal",port=5432, ...)
</code>```

Body:
I'm attempting to connect to a local Postgres server running as a docker container from my Lambda function.

I'm using the sam local invoke call to do so.

For some reason, it seems that outgoing connection from SAM's docker container for the function is disabled.

I'm getting this error message:

"errorMessage": "(psycopg2.OperationalError) could not connect to server: Connection refused\n\tIs the server running on host \"localhost\" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\ncould not connect to server: Cannot assign requested address\n\tIs the server running on host \"localhost\" (::1) and accepting\n\tTCP/IP connections on port 5432?\n\n(Background on this error at: http://sqlalche.me/e/e3q8)",

Is there a way to enable a Lambda function call to a local docker database?

I have no issues running the connection code outside the Lambda function as standard Python code - so I'm sure my database is up, my code works, etc.

Body:
I resolve this by replacing localhost with host.docker.internal.

For example if you use psycopg2

conn = psycopg2.connect(host="host.docker.internal",port=5432, ...)


问:
Flutter - Can't seem to order a list and i've no clue why
I have a model which defines some JSON from an Api.

```<code>abstract class ITrainingExerciseListingProvider with Store {
  @observable
  List exerciseList = [];

  @observable
  List<ExerciseModel> exerciseModelList = [];
</code>```

If i try and put a
exerciseList.sort(); itgives a constructor error.

I'm trying to get this listview to order on the length but i'm stuck!

```<code>ListView.separated(
                              // itemCount: 14,
                              itemCount: sl<ITrainingExerciseListingProvider>()
                                  ?.exerciseModelList
                                  ?.length,
</code>```

Any suggestions are appreciated.

答:
Did you try this?</p>
```<code>exerciseList.sort((o1, o2) {
                // handle the sort logic here
                return 1;
              });
</code>```

Body:
I have a model which defines some JSON from an Api.

abstract class ITrainingExerciseListingProvider with Store {
  @observable
  List exerciseList = [];

  @observable
  List<ExerciseModel> exerciseModelList = [];

If i try and put a
exerciseList.sort(); itgives a constructor error.

I'm trying to get this listview to order on the length but i'm stuck!

ListView.separated(
                              // itemCount: 14,
                              itemCount: sl<ITrainingExerciseListingProvider>()
                                  ?.exerciseModelList
                                  ?.length,

Any suggestions are appreciated.

Body:
Did you try this?

exerciseList.sort((o1, o2) {
                // handle the sort logic here
                return 1;
              });


问:
Getting Notified on "Ethernet cable plugged in" events in linux
I am writing a Python Application running on linux. I want to be able to register and be notified by the system if a network cable is plugged in/ out.

I am already using pyUdev (python bindings for libUdev) in order to get notified for USB plug in events. However, because the network eth0 module (for example) always remains loaded (regardless of the cable being plugged in) , I dont get the information I require. It only works for if up/down events.

I have read a lot of posts on Windows WMI providing this functionality but none on linux. Am I looking in the right direction?

A python way of doing this (a python library) would be ideal as I want to integrate this with my program.

答: Have you looked into netplugd command, I am not sure if a python wrapper exists but it should not be hard to parse the output </p>


问:
How to update json value with dropdown list
Can anyone teach me how can I update json value using the the dropdown list.
In JavaScript

HTML:

<select id="currency" onchange="getSelectValue();">
    <option value="Singapore Dollar">Singapore Dollar</option>
    <option value="USD">USD</option>
    <option value="Malaysia Riggit">Malaysia Riggit</option>
</select>
```
<p>JSON :</p>
<pre class="lang-js prettyprint-override"><code>{
"products": [
    {
       "name": "Apple",
        "price": "2.50",
        "code": "SGD"
    },
    {
       "name": "Orange",
        "price": "2.50",
        "code": "SGD"
    }
]
}
</code>```

答:
Here is the code sample.</p>
```<code>var json=JSON.parse( "Your json which you mentioned above");

var products= json.products;

string selectlist="";

if(products.length>0)
{

    selectlist += "<select>";
    for(var i = 0; i < products.length; i++) {

        var currency = json[i];

            selectlist += "<option value="+currency.code+"> "+currency.code+"  </option>";
    }
    selectlist += "</select>"
if("body").append(selectlist);
}
</code>```

Body:
Can anyone teach me how can I update json value using the the dropdown list.
In JavaScript

HTML:

<select id="currency" onchange="getSelectValue();">
    <option value="Singapore Dollar">Singapore Dollar</option>
    <option value="USD">USD</option>
    <option value="Malaysia Riggit">Malaysia Riggit</option>
</select>

JSON :

{
"products": [
    {
       "name": "Apple",
        "price": "2.50",
        "code": "SGD"
    },
    {
       "name": "Orange",
        "price": "2.50",
        "code": "SGD"
    }
]
}

Body:
Here is the code sample.

var json=JSON.parse( "Your json which you mentioned above");

var products= json.products;

string selectlist="";

if(products.length>0)
{

    selectlist += "<select>";
    for(var i = 0; i < products.length; i++) {

        var currency = json[i];

            selectlist += "<option value="+currency.code+"> "+currency.code+"  </option>";
    }
    selectlist += "</select>"
if("body").append(selectlist);
}


问:
AttributeError after sorting through elementtree values
I'm trying to take elementtree elements picked from an XML and sort them through alphabetical order. Since there's multiple XMLs I'm sorting through (keys are defined in the platforms list), I'm first storing the values in a dictionary with the key and then sorting them.

I've tried the following:

```<code>titles = {}

for platform in platforms:
    for title in self.databases[platform][1].findall("game"):
        if title.find("locale", {"lang": "EN"}) is not None:
            titles[title.find("locale", {"lang": "EN"}).find("title").text + " - " + platform] = title
            print(title.find("region").text) # this works

for key, title in sorted(titles.items()):
    for s in title:
        t = s.find("region").text
</code>```

However, I'm getting AttributeError: 'NoneType' object has no attribute 'text' with the last line of the code, which doesn't make sense because I'm able to print the XML value in the loop where I assign the values to a dictionary.

2 questions:

Is there a better way to do this? I'm sure that this can be optimized in a better way. Maybe elementtree or Python has a nice little function that can sort when the items are stored as elements?

Why am I getting an AttributeError? Is something breaking after I store them in a dictionary?

答: With regard to question 2. Why the line "for s in title" (is title an iterator)?  While title.find(region) has a text attribute it is not clear that s.find("region")  does</p>

Body:
I'm trying to take elementtree elements picked from an XML and sort them through alphabetical order. Since there's multiple XMLs I'm sorting through (keys are defined in the platforms list), I'm first storing the values in a dictionary with the key and then sorting them.

I've tried the following:

titles = {}

for platform in platforms:
    for title in self.databases[platform][1].findall("game"):
        if title.find("locale", {"lang": "EN"}) is not None:
            titles[title.find("locale", {"lang": "EN"}).find("title").text + " - " + platform] = title
            print(title.find("region").text) # this works

for key, title in sorted(titles.items()):
    for s in title:
        t = s.find("region").text

However, I'm getting AttributeError: 'NoneType' object has no attribute 'text' with the last line of the code, which doesn't make sense because I'm able to print the XML value in the loop where I assign the values to a dictionary.

2 questions:

Is there a better way to do this? I'm sure that this can be optimized in a better way. Maybe elementtree or Python has a nice little function that can sort when the items are stored as elements?

Why am I getting an AttributeError? Is something breaking after I store them in a dictionary?


问:
Laravel cannot find public dir
I worked on a team and then clone the laravel/php codes from our repository. When I serve the laravel on localhost, it cannot find all the file inside the public directory and throw an error on the terminal:

[404]: GET /public/css/style.css - No such file or directory
```
<p>Many answers to similar issues advise me to change the codes in the <code>blade.php</code> file. The problem is that I can't edit the <code>blade.php</code> because it works fine on other team members even though we have the same ubuntu, PHP, and laravel version and <code>.env</code> file.</p>
<p>What I have tried:</p>
<ul>
<li>Run <code>composer install</code> and <code>composer update</code></li>
<li>Try different browsers such as firefox and chromium-based browsers</li>
<li>Run <code>php artisan storage:link</code></li>
<li>Restart apache2</li>
<li>Run <code>npm install</code> and <code>npm run dev</code></li>
</ul>
<p>I think there is some package or something missing.</p>
<p>List of paths I get from <code>dd($__data)</code>:</p>
```"path" => "/project-directory/project-name/app"
"path.base" => "/project-directory/project-name"
"path.lang" => "/project-directory/project-name/resources/lang"
"path.config" => "/project-directory/project-name/config"
"path.public" => "/project-directory/project-name/public"
"path.storage" => "/project-directory/project-name/storage"
"path.database" => "/project-directory/project-name/database"
"path.resources" => "/project-directory/project-name/resources"
"path.bootstrap" => "/project-directory/project-name/bootstrap"
```

答:
Have you tried?</p>
```<code>php artisan storage:link
</code>```

Title: Laravel cannot find public dir

Body:
I worked on a team and then clone the laravel/php codes from our repository. When I serve the laravel on localhost, it cannot find all the file inside the public directory and throw an error on the terminal:

[404]: GET /public/css/style.css - No such file or directory

Many answers to similar issues advise me to change the codes in the blade.php file. The problem is that I can't edit the blade.php because it works fine on other team members even though we have the same ubuntu, PHP, and laravel version and .env file.

What I have tried:

Run composer install and composer update

Try different browsers such as firefox and chromium-based browsers

Run php artisan storage:link

Restart apache2

Run npm install and npm run dev

I think there is some package or something missing.

List of paths I get from dd($__data):

"path" => "/project-directory/project-name/app"
"path.base" => "/project-directory/project-name"
"path.lang" => "/project-directory/project-name/resources/lang"
"path.config" => "/project-directory/project-name/config"
"path.public" => "/project-directory/project-name/public"
"path.storage" => "/project-directory/project-name/storage"
"path.database" => "/project-directory/project-name/database"
"path.resources" => "/project-directory/project-name/resources"
"path.bootstrap" => "/project-directory/project-name/bootstrap"

Body:
Have you tried?

php artisan storage:link


问:
What are the 'rules' for names with getters/settings in a class?
What are the restrictions on using getters and setters in javascript? For example, here are a few scenarios I've seen when just doing trial-and-error:

class User {

    // 1 - must have an alias somewhere or will get loop
    constructor(name) {
        this.name = name;
    }

    get name() {
        console.log('--- Getter ---');
        return this.name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this.name = name;
    }
}

const user = new User('David');
console.log(user.name);```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class User {

    name;

    // 2 - setter/getter must have a property with exact name in constructor?
    constructor(name) {
        this._name = name;
    }
    get name() {
        console.log('--- Getter ---');
        return this._name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this._name = name;
    }
}

const user = new User('David');
console.log(user.name);
user.name = 'Keith';
console.log(user.name);</code>```

Is a correct understanding of a setter/getter that:

The name must be aliased.

The setter/getter must have that exact name defined in the constructor.

Finally, putting it all togther, does the following seem like a good pattern to hide fields when user a getter/setter, as it seems like #name (private) and name (public) act like two different variables.

class User {
    #name;
    constructor(name) {
        this.name = name;
    }
    get name() {
        console.log('-getter-');
        return this.#name;
    }
    set name(name) {
        console.log('-setter-');
        this.#name = name
    }
}
bob = new User('Bob');
bob.name = 'Bobby';
console.log(bob.name);```

答:
A backing field is not a requirement, needless to say a backing field with the same name. You don't even need setter and getter if all you do is just setting and getting a backing field, since there would be functionally no difference than a normal field.

Getter and Setter are usually used when

the property is a computed property, e.g. derived from other properties/state.

you want to do extra work when accessing the field, e.g. notifying a property is changed

Example for case 1:

class Foo
{
  constructor(bar)
  {
    this.bar = bar;
  }

  get barSquare()
  {
    return this.bar * this.bar;
  }

  set barSquare(x)
  {
    this.bar = Math.sqrt(x);
  }
}

let foo = new Foo(4);
console.log(foo.barSquare);
foo.barSquare = 25;
console.log(foo.bar);```
</div>
</div>
</p>
<p>Example for case 2:</p>
<p>You do need a backing field in this case, though the name of the backing field can be anything except the setter/getter name.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Foo
{
  constructor(bar)
  {
    this._bar = bar;
  }

  get bar()
  {
    return this._bar;
  }

  set bar(x)
  {
    console.log(`bar is changed to ${x}!`);
    this._bar = x;
  }
}

let foo = new Foo(4);
console.log(foo.bar);
foo.bar = 5;
console.log(foo.bar);</code>```

Finally, the parameter name (bar) defined in constructor(bar) is totally unrelated. It can be any legal variable name. It is scoped to the constructor block. For example, it can be

class Foo
{
  constructor(totallyRandomName)
  {
    this.someBackingFieldName = totallyRandomName;
  }

  get bar()
  {
    return this.someBackingFieldName;
  }

  set bar(x)
  {
    console.log(`bar is changed to ${x}!`);
    this.someBackingFieldName = x;
  }
}

let foo = new Foo(4);
console.log(foo.bar);
foo.bar = 5;
console.log(foo.bar);```

Body:
What are the restrictions on using getters and setters in javascript? For example, here are a few scenarios I've seen when just doing trial-and-error:

class User {

    // 1 - must have an alias somewhere or will get loop
    constructor(name) {
        this.name = name;
    }

    get name() {
        console.log('--- Getter ---');
        return this.name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this.name = name;
    }
}

const user = new User('David');
console.log(user.name);

class User {

    name;

    // 2 - setter/getter must have a property with exact name in constructor?
    constructor(name) {
        this._name = name;
    }
    get name() {
        console.log('--- Getter ---');
        return this._name;
    }
    set name(name) {
        console.log('--- Setter --- ');
        this._name = name;
    }
}

const user = new User('David');
console.log(user.name);
user.name = 'Keith';
console.log(user.name);

Is a correct understanding of a setter/getter that:

The name must be aliased.

The setter/getter must have that exact name defined in the constructor.

Finally, putting it all togther, does the following seem like a good pattern to hide fields when user a getter/setter, as it seems like #name (private) and name (public) act like two different variables.

class User {
    #name;
    constructor(name) {
        this.name = name;
    }
    get name() {
        console.log('-getter-');
        return this.#name;
    }
    set name(name) {
        console.log('-setter-');
        this.#name = name
    }
}
bob = new User('Bob');
bob.name = 'Bobby';
console.log(bob.name);

Body:
A backing field is not a requirement, needless to say a backing field with the same name. You don't even need setter and getter if all you do is just setting and getting a backing field, since there would be functionally no difference than a normal field.

Getter and Setter are usually used when

the property is a computed property, e.g. derived from other properties/state.

you want to do extra work when accessing the field, e.g. notifying a property is changed

Example for case 1:

class Foo
{
  constructor(bar)
  {
    this.bar = bar;
  }

  get barSquare()
  {
    return this.bar * this.bar;
  }

  set barSquare(x)
  {
    this.bar = Math.sqrt(x);
  }
}

let foo = new Foo(4);
console.log(foo.barSquare);
foo.barSquare = 25;
console.log(foo.bar);

Example for case 2:

You do need a backing field in this case, though the name of the backing field can be anything except the setter/getter name.

class Foo
{
  constructor(bar)
  {
    this._bar = bar;
  }

  get bar()
  {
    return this._bar;
  }

  set bar(x)
  {
    console.log(`bar is changed to ${x}!`);
    this._bar = x;
  }
}

let foo = new Foo(4);
console.log(foo.bar);
foo.bar = 5;
console.log(foo.bar);

Finally, the parameter name (bar) defined in constructor(bar) is totally unrelated. It can be any legal variable name. It is scoped to the constructor block. For example, it can be

class Foo
{
  constructor(totallyRandomName)
  {
    this.someBackingFieldName = totallyRandomName;
  }

  get bar()
  {
    return this.someBackingFieldName;
  }

  set bar(x)
  {
    console.log(`bar is changed to ${x}!`);
    this.someBackingFieldName = x;
  }
}

let foo = new Foo(4);
console.log(foo.bar);
foo.bar = 5;
console.log(foo.bar);