问:
How to read a single row or of multiple txt files in python
I am trying to open a txt file from a folder which contains several txt files. But I want to choose the file as a user input- means the user should put the txt file name and the output will be the data in that respective txt file. Can someone help me with this?

I tried like this:

import os
os.chdir(r"D:\Thesis\data\new_data\HKSS")
filelist=os.listdir(r"D:\Thesis\data\new_data\HKSS")
mylines=[]
for file in filelist:
   with open("241Pu.txt", "rt") as myfile:
      for i in myfile:
         mylines.append(i.strip("\n"))
      tup=(mylines[0], mylines[1])
      str="".join(tup)
      print(str)
      myfile.close()
```
<p>But the output is coming like:</p>
```E(MeV)   N(/fission)
```

There are values under E and N which I am not sure how to get through the above program. Any suggestions will be helpful.

Body:
I am trying to open a txt file from a folder which contains several txt files. But I want to choose the file as a user input- means the user should put the txt file name and the output will be the data in that respective txt file. Can someone help me with this?

I tried like this:

import os
os.chdir(r"D:\Thesis\data\new_data\HKSS")
filelist=os.listdir(r"D:\Thesis\data\new_data\HKSS")
mylines=[]
for file in filelist:
   with open("241Pu.txt", "rt") as myfile:
      for i in myfile:
         mylines.append(i.strip("\n"))
      tup=(mylines[0], mylines[1])
      str="".join(tup)
      print(str)
      myfile.close()

But the output is coming like:

E(MeV)   N(/fission)

There are values under E and N which I am not sure how to get through the above program. Any suggestions will be helpful.


来源: stackexchange

问:
Vue.js: Update second property during calculation of computed property
Example: Based on a list of nodes and edges I want to calculate a graph object. Also I am interested in the longest path of the calculated graph. For my understanding a straight-forward implmentation would be:

```<code>Vue.createApp({
    data() {
        return {
            myNodes: {/*list of nodes*/},
            myEdges: {/*list of edges*/}
    },
    methods: {
        calculateGraph(nodes, edges) {/* complex calculation */},
        calculateLongestPath(graph) {/* more complex calculation */}
    }
    computed: {
        myGraph: function {
            return calculateGraph(this.myNodes,this.myEdges)
        }
        myLongestPath: function {
            return calculateLongestPath(this.myGraph)
        }
    }
}
</code>```

However, assuming the longest path could be calculated directly during the construction of the graph (for performance), the code could look like this:

```<code>Vue.createApp({
    data() {
        return {
            myNodes: {/*list of nodes*/},
            myEdges: {/*list of edges*/},
            myLongestPath: null
    },
    methods: {
        calculateGraph(nodes, edges) {
            /* complex calculation */
            this.myLongestPath = /* calculated value */
        }
    }
    computed: {
        myGraph: function {
            return calculateGraph(this.myNodes,this.myEdges)
        }
    }
}
</code>```

Is the second implementation good practise in Vue.js? Is there a better third option between readability (1) and unnecessary complex function calculateLongestPath (2)?

ContentLicense: CC BY-SA 4.0

Body:
Example: Based on a list of nodes and edges I want to calculate a graph object. Also I am interested in the longest path of the calculated graph. For my understanding a straight-forward implmentation would be:

Vue.createApp({
    data() {
        return {
            myNodes: {/*list of nodes*/},
            myEdges: {/*list of edges*/}
    },
    methods: {
        calculateGraph(nodes, edges) {/* complex calculation */},
        calculateLongestPath(graph) {/* more complex calculation */}
    }
    computed: {
        myGraph: function {
            return calculateGraph(this.myNodes,this.myEdges)
        }
        myLongestPath: function {
            return calculateLongestPath(this.myGraph)
        }
    }
}

However, assuming the longest path could be calculated directly during the construction of the graph (for performance), the code could look like this:

Vue.createApp({
    data() {
        return {
            myNodes: {/*list of nodes*/},
            myEdges: {/*list of edges*/},
            myLongestPath: null
    },
    methods: {
        calculateGraph(nodes, edges) {
            /* complex calculation */
            this.myLongestPath = /* calculated value */
        }
    }
    computed: {
        myGraph: function {
            return calculateGraph(this.myNodes,this.myEdges)
        }
    }
}

Is the second implementation good practise in Vue.js? Is there a better third option between readability (1) and unnecessary complex function calculateLongestPath (2)?


问:
Error in `[.data.frame`(., df1$Sample.ID, !df1$Sample.ID %in% df2$Sample.ID) : undefined columns selected
I am trying to extract the samples ids that only exist in a dataframe. Initially, I am removing the duplicates and then pipe the results to get the samples ids that are not common to both dataframes.

I am using the above code:

```<code>df1 %>% distinct(Sample.ID, .keep_all = TRUE) %>%
  df1$Sample.ID[!df1$Sample.ID %in% df2$Sample.ID]
</code>```

Then I read, and I tried:

```<code>df1 %>% distinct(Sample.ID, .keep_all = TRUE) %>%
  df1$Sample.ID[!df1$Sample.ID %in% df2$Sample.ID,]
</code>```

My example dataframe:

```<code>df <- data.frame(Sample.ID=c("H22","H33","H44", "H55","H22","H33","H44", "H55),
                  sample.no=c(1,3,3,4))
df2 <- data.frame(Sample.ID=c("H33","H55"), pane=c(5,6))
</code>```

I am use the package "tidyverse"

I expect to get;

```<code>Sample.ID
H22
H44
</code>```

It works if I don't pipe but I have to assign them to new dataframes but that is not ideal.

Body:
I am trying to extract the samples ids that only exist in a dataframe. Initially, I am removing the duplicates and then pipe the results to get the samples ids that are not common to both dataframes.

I am using the above code:

df1 %>% distinct(Sample.ID, .keep_all = TRUE) %>%
  df1$Sample.ID[!df1$Sample.ID %in% df2$Sample.ID]

Then I read, and I tried:

df1 %>% distinct(Sample.ID, .keep_all = TRUE) %>%
  df1$Sample.ID[!df1$Sample.ID %in% df2$Sample.ID,]

My example dataframe:

df <- data.frame(Sample.ID=c("H22","H33","H44", "H55","H22","H33","H44", "H55),
                  sample.no=c(1,3,3,4))
df2 <- data.frame(Sample.ID=c("H33","H55"), pane=c(5,6))

I am use the package "tidyverse"

I expect to get;

Sample.ID
H22
H44

It works if I don't pipe but I have to assign them to new dataframes but that is not ideal.


问:
Git: calculate code breakdown between two commits
I have two commits, and I would like to calculate the code breakdown for them:

NewLines: new lines of code

RefactoredLines: lines of code that were modified/deleted and their last modification was more than 30 days ago

ReworkedLines: lines of code that were modified/deleted and their last modification was less than 30 days ago

This is for the purpose of calculation this stats for any PR's to main/master branch

I know that there is git diff <commitId> <commitId> --stat/numstat/shortstatBut it only shows insertion/deletion and does not have a context of the last known modification for a given line.

Is there any way to achieve this?


问:
Gulp error: Error: Cannot find module 'undertaker'
I am trying to run gulp in my WordPress theme but I am getting an error that the module "undertaker" is not found. I have that package installed so I am not sure why I am getting this error message.

Error message:

```<code>node:internal/modules/cjs/loader:998
  throw err;
  ^

Error: Cannot find module 'undertaker'
</code>```

My gulpfile.js:

```<code>const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');

// SASS Task
function scssTask() {
    return src(['assets/sass/*.scss', 'assets/sass/**/*.scss'], { sourcemaps: true })
    .pipe(sass())
    .pipe(postcss([cssnano()]))
    .pipe(dest('assets/css', {sourcemaps: '.' }));
}

// JavaScript Task
function jsTask() {
    return src('assets/js/*.js', { sourcemaps: true })
    .pipe(terser())
    .pipe(dest('dist/js', { sourcemaps: '.' }));
}

function watchTask() {
    watch(['*.php', 'assets/sass/**/*.scss', 'assets/js/*.js'], series(scssTask, jsTask));
}

// Default Gulp Task
exports.default = series(
    scssTask,
    jsTask,
    watchTask
);
</code>```

Body:
I am trying to run gulp in my WordPress theme but I am getting an error that the module "undertaker" is not found. I have that package installed so I am not sure why I am getting this error message.

Error message:

node:internal/modules/cjs/loader:998
  throw err;
  ^

Error: Cannot find module 'undertaker'

My gulpfile.js:

const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');

// SASS Task
function scssTask() {
    return src(['assets/sass/*.scss', 'assets/sass/**/*.scss'], { sourcemaps: true })
    .pipe(sass())
    .pipe(postcss([cssnano()]))
    .pipe(dest('assets/css', {sourcemaps: '.' }));
}

// JavaScript Task
function jsTask() {
    return src('assets/js/*.js', { sourcemaps: true })
    .pipe(terser())
    .pipe(dest('dist/js', { sourcemaps: '.' }));
}

function watchTask() {
    watch(['*.php', 'assets/sass/**/*.scss', 'assets/js/*.js'], series(scssTask, jsTask));
}

// Default Gulp Task
exports.default = series(
    scssTask,
    jsTask,
    watchTask
);


问:
Generic interface implementation
Let's say we have GeneralRequest class with no properties. Every specific request class extends this class. For example:

```<code>public class GeneralRequest
{
}
</code>```

And:

```<code>public class UserInsertRequest : GeneralRequest
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
public class UserUpdateRequest : GeneralRequest
{
   public string FirstName { get; set; }
}
</code>```

Also there is interface IGeneralService like this:

```<code>public interface IGeneralService
{
   public Task Insert(GeneralRequest request);
   public Task Update(GeneralRequest request);
}
</code>```

With specific user service interface that implements it:

```<code>public interface IUsersInterface : GeneralInterface
{
    public Task FindByFirstName(String FirstName);
}
</code>```

And specific service class that implements it:

```<code>public class UserService: IUsersInterface
{
    public async Task Insert(UserInsertRequest request)
    {
      //implementation
    }

    public async Task Update(UserUpdateRequest request)
    {
      //implementation
    }

    public Task FindByFirstName(String FirstName)
    {
      //implementation
    }
}
</code>```

The problem is that UserService's Insert and Update is not IGeneralService's Insert and Update method implementation (different method signature). But, is there a way to make this logic work?

I tried something like this

```<code>public interface IGeneralService<T> where T:GeneralRequest
{
   public Task Insert(T request);
   public Task Update(T request);
}
</code>```

But in that case I need to specify the type parameter when implementing IGeneralService, and there are multiple. I'm so confused !

My goal is to have general service interface that every service class implements it, and specific interface for specific service class.

Title: Generic interface implementation

Body:
Let's say we have GeneralRequest class with no properties. Every specific request class extends this class. For example:

public class GeneralRequest
{
}

And:

public class UserInsertRequest : GeneralRequest
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
public class UserUpdateRequest : GeneralRequest
{
   public string FirstName { get; set; }
}

Also there is interface IGeneralService like this:

public interface IGeneralService
{
   public Task Insert(GeneralRequest request);
   public Task Update(GeneralRequest request);
}

With specific user service interface that implements it:

public interface IUsersInterface : GeneralInterface
{
    public Task FindByFirstName(String FirstName);
}

And specific service class that implements it:

public class UserService: IUsersInterface
{
    public async Task Insert(UserInsertRequest request)
    {
      //implementation
    }

    public async Task Update(UserUpdateRequest request)
    {
      //implementation
    }

    public Task FindByFirstName(String FirstName)
    {
      //implementation
    }
}

The problem is that UserService's Insert and Update is not IGeneralService's Insert and Update method implementation (different method signature). But, is there a way to make this logic work?

I tried something like this

public interface IGeneralService<T> where T:GeneralRequest
{
   public Task Insert(T request);
   public Task Update(T request);
}

But in that case I need to specify the type parameter when implementing IGeneralService, and there are multiple. I'm so confused !

My goal is to have general service interface that every service class implements it, and specific interface for specific service class.


问:
FFmpeg concat demuxer and keyframes
I am trying to use to the concat protocol but I have troubles with keyframes

I use this ffprobe command to visualize the keyframes pts of my videos:

ffprobe -loglevel error -select_streams v:0 -show_entries packet=pts_time,flags -of csv=print_section=0 inout.mp4  | awk -F',' '/K/ {print $1}'

Here is my process: I have the original video, with these keyframes:

0.000000 5.000000 9.760000 14.240000  18.440000 ...

I trim the first 5 seconds, so the output has these keyframes:

0.000000 4.760000 9.240000 13.440000 ...

I create a 5 seconds video by looping an image, with the same parameters/codec... that were used to produce the original video. This video just has one keyframe at 0.000000

Then I concat this video with the trimmed video like this:

ffmpeg -f concat -safe 0 -i list.txt -c copy -shortest  output.mp4 -y

But when I look for the keyframes of the output video, I get this:

0.021016 5.035000 9.795000 14.275000 ...

Is this behavior normal? Should I add a parameter to handle keyframes during concatenation? Thanks

Title: FFmpeg concat demuxer and keyframes


问:
Memory Error when loading a txt file for an ML model
I am trying to run the code below

```<code>from transformers import pipeline

question_answerer = pipeline("question-answering", model='distilbert-base-uncased-distilled-squad')

with open('output_file.txt', 'r', encoding='utf-8') as file:

    context = file.read()

    question = input("Type your question: ")

    print("Calculating answer, please wait.")

    result = question_answerer(question=question, context=context)

    print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}")
</code>```

but I get MemoryError, since the input text file is too large (>100GB).

Are there any techniques to read such files?

I can imagine there are others with the same issue. What is a standard approach in situations as such?

Body:
I am trying to run the code below

from transformers import pipeline

question_answerer = pipeline("question-answering", model='distilbert-base-uncased-distilled-squad')

with open('output_file.txt', 'r', encoding='utf-8') as file:

    context = file.read()

    question = input("Type your question: ")

    print("Calculating answer, please wait.")

    result = question_answerer(question=question, context=context)

    print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}")

but I get MemoryError, since the input text file is too large (>100GB).

Are there any techniques to read such files?

I can imagine there are others with the same issue. What is a standard approach in situations as such?


问:
Failed to dial target host "kong-proxy-service-external-ip:443": context deadline exceeded
I am trying to use Kong API Gateway with Using Ingress with gRPC but getting below error.

Failed to dial target host "kong-proxy-service-external-ip:443": context deadline exceeded

I am using minikube cluster for deplyment.

I followed all the steps mentioned here - https://docs.konghq.com/kubernetes-ingress-controller/latest/guides/using-ingress-with-grpc/ but when I tried to run grpcurl -v -d '{"greeting": "Kong Hello world!"}' -insecure $PROXY_IP:443 hello.HelloService.SayHello
I got the error Failed to dial target host

If I use port forwarding on service with command kubectl port-forward service/grpcbin 9001:9001 then this works so that mean the issue is somewhere with ingress or some configuration issue.

Request you to help me with this issue.


问:
CSS: Which is more efficient, Inline styles or Css classes with !important to override styles
I am building a widget on React with CRA and parcel to bundle, which can be added to other websites via a small JS script in index HTML. Used CSS modules for styling the components. I try adding this widget to a WordPress website, the CSS from WP pages override the CSS styles of the components.

I could think about two solutions to retain my styles:

Inline styles to all components

Adding !important to all CSS properties in CSS classes (recommended to be used sparingly)

Will there be a performance hit due to increase in page size due to inline styles
Also worried about not being able to use pseudo elements or media queries if I go with inline styles

I hope there some way to achieve this, some packages in react will helpful.


问:
How can I find out what features the total score returned from products is based on on Solr?
How can I find out what features the total score returned from products is based on on Solr? I'll print these scores one by one elsewhere.

I want to see what the total scores of the products returned from Solr are based on.


问:
My UserClaimsPrincipalFactory does not generate claims during login. (Dotnet 6.0.5)
I am trying to build a login system combining Microsoft.Identity and AzureAD login integration. Currently, the user is able to login with their Microsoft account through the AD portal, but during this process my customized UserClaimsPrincipalFactory is never reached (I've checked with breakpoints during debugging with Visual Studio 2022, and checked the data from the results of the login).

My current setup is as following:

```<code>builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddRoles<IdentityRole>()
        .AddUserManager<UserManager<ApplicationUser>>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddRoleStore<RoleStore<IdentityRole, UserAppContext>>()
        .AddClaimsPrincipalFactory<ApplicationUserClaimsFactory>()
        .AddEntityFrameworkStores<UserAppContext>();
</code>```

I have also tried to not use "AddClaimsPrincipalFactory" or any add function besides "AddEntityFrameworkStores()" and initialize them through AddScoped instead, but the result remains the same.

My UserClaimsPrincipalFactory looks as following

```<code>public class ApplicationUserClaimsFactory: UserClaimsPrincipalFactory<ApplicationUser>
{
    public ApplicationUserClaimsFactory(
        UserManager<ApplicationUser> userManager,
        IOptions<IdentityOptions> optionsAccessor)
        : base(userManager, optionsAccessor)
    {

    }
    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        var identity = (ClaimsIdentity)principal.Identity;

        var claims = new List<Claim>
        {
            new Claim("Test", "true")
        };
        identity.AddClaims(claims);
        return principal;
    }
    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        ClaimsIdentity claims = await base.GenerateClaimsAsync(user);
        claims.AddClaim(new Claim("name", "Aris"));
        claims.AddClaim(new Claim("Test", "true"));
        return claims;
    }
}
</code>```

Nothing I've tried using UserClaimsPrincipalFactory works. I've been able to assign new claims using the IClaimsTransformation interface, but I want to be able to pull data from a database and use that data to determine which claims to assign a given user.

Body:
I am trying to build a login system combining Microsoft.Identity and AzureAD login integration. Currently, the user is able to login with their Microsoft account through the AD portal, but during this process my customized UserClaimsPrincipalFactory is never reached (I've checked with breakpoints during debugging with Visual Studio 2022, and checked the data from the results of the login).

My current setup is as following:

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddRoles<IdentityRole>()
        .AddUserManager<UserManager<ApplicationUser>>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddRoleStore<RoleStore<IdentityRole, UserAppContext>>()
        .AddClaimsPrincipalFactory<ApplicationUserClaimsFactory>()
        .AddEntityFrameworkStores<UserAppContext>();

I have also tried to not use "AddClaimsPrincipalFactory" or any add function besides "AddEntityFrameworkStores()" and initialize them through AddScoped instead, but the result remains the same.

My UserClaimsPrincipalFactory looks as following

public class ApplicationUserClaimsFactory: UserClaimsPrincipalFactory<ApplicationUser>
{
    public ApplicationUserClaimsFactory(
        UserManager<ApplicationUser> userManager,
        IOptions<IdentityOptions> optionsAccessor)
        : base(userManager, optionsAccessor)
    {

    }
    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        var identity = (ClaimsIdentity)principal.Identity;

        var claims = new List<Claim>
        {
            new Claim("Test", "true")
        };
        identity.AddClaims(claims);
        return principal;
    }
    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        ClaimsIdentity claims = await base.GenerateClaimsAsync(user);
        claims.AddClaim(new Claim("name", "Aris"));
        claims.AddClaim(new Claim("Test", "true"));
        return claims;
    }
}

Nothing I've tried using UserClaimsPrincipalFactory works. I've been able to assign new claims using the IClaimsTransformation interface, but I want to be able to pull data from a database and use that data to determine which claims to assign a given user.


问:
OpsWorks and Chef recipes
I've been playing with AWS OpsWorks lately and I would just like to hear the opinion of someone with Chef programming experience about a recipe that I'm trying to run on Windows Server 2012.

The snippet is the following:

```<code>powershell_script 'Install Application Routing Request (ARR)' do
  code <<-EOH
    cd 'C:\\Program Files'
    wget https://download.microsoft.com/download/E/9/8/E9849D6A-020E-47E4-9FD0-A023E99B54EB/requestRouter_amd64.msi -OutFile requestRouter_amd64.msi
    Start-Process 'C:\\Program Files\\requestRouter_amd64.msi' '/qn' -PassThru | Wait-Process
    C:\\Windows\\system32\\inetsrv\\appcmd set config  -section:system.webServer/proxy /enabled:"True"  /commit:apphost
  EOH
  guard_interpreter :powershell_script
end
</code>```

Does that look all right?

I'm trying to install ARR by directly downloading it from Microsoft using wget command, as the old recipe I was using is not working anymore starting 1st of January 2023, because the WebPI feed has been removed from the servers and the product installers have been pulled from the Microsoft download center.

For reference, the old recipe I was using is this:

```<code>Install Application Routing Request (ARR) IIS Module and enable proxy mode

powershell_script 'Install Application Routing Request (ARR)' do
  code <<-EOH

    Start-Process 'C:\\chef\\cookbooks\\setup\\WebPlatformInstaller_x64_en-US-2.msi' '/qn' -PassThru | Wait-Process
    cd 'C:\\Program Files\\Microsoft\\Web Platform Installer'; .\\WebpiCmd.exe /Install /Products:'ARRv3_0' /AcceptEULA /Log:'C:\\WebpiCmd.log'
    C:\\Windows\\system32\\inetsrv\\appcmd set config  -section:system.webServer/proxy /enabled:"True"  /commit:apphost
  EOH
    guard_interpreter :powershell_script
end
</code>```

Basically, the config section of the script returns an error because WebpiCmd.exe is not able to download and install ARR anymore.

Thank you,

Diego

Title: OpsWorks and Chef recipes

Body:
I've been playing with AWS OpsWorks lately and I would just like to hear the opinion of someone with Chef programming experience about a recipe that I'm trying to run on Windows Server 2012.

The snippet is the following:

powershell_script 'Install Application Routing Request (ARR)' do
  code <<-EOH
    cd 'C:\\Program Files'
    wget https://download.microsoft.com/download/E/9/8/E9849D6A-020E-47E4-9FD0-A023E99B54EB/requestRouter_amd64.msi -OutFile requestRouter_amd64.msi
    Start-Process 'C:\\Program Files\\requestRouter_amd64.msi' '/qn' -PassThru | Wait-Process
    C:\\Windows\\system32\\inetsrv\\appcmd set config  -section:system.webServer/proxy /enabled:"True"  /commit:apphost
  EOH
  guard_interpreter :powershell_script
end

Does that look all right?

I'm trying to install ARR by directly downloading it from Microsoft using wget command, as the old recipe I was using is not working anymore starting 1st of January 2023, because the WebPI feed has been removed from the servers and the product installers have been pulled from the Microsoft download center.

For reference, the old recipe I was using is this:

Install Application Routing Request (ARR) IIS Module and enable proxy mode

powershell_script 'Install Application Routing Request (ARR)' do
  code <<-EOH

    Start-Process 'C:\\chef\\cookbooks\\setup\\WebPlatformInstaller_x64_en-US-2.msi' '/qn' -PassThru | Wait-Process
    cd 'C:\\Program Files\\Microsoft\\Web Platform Installer'; .\\WebpiCmd.exe /Install /Products:'ARRv3_0' /AcceptEULA /Log:'C:\\WebpiCmd.log'
    C:\\Windows\\system32\\inetsrv\\appcmd set config  -section:system.webServer/proxy /enabled:"True"  /commit:apphost
  EOH
    guard_interpreter :powershell_script
end

Basically, the config section of the script returns an error because WebpiCmd.exe is not able to download and install ARR anymore.

Thank you,

Diego


问:
Fabric connection to an extender
I wanted to connect to a extender for a Wi-Fi project, but I don't know if I can connect to an extender using the Fabric module for Python...

I was trying to connect to a server using it's name, but I'm sure that the name is wrong, but I don't know if I'm connecting wrong. Here is my code:

```<code>from fabric import Connection
node = Connection('KIN-AP23')
letsgo = node.run('help')
</code>```

I don't know how to connect since I got this error:

```<code>Traceback (most recent call last):
  File "main.py", line 5, in <module>
    letsgo = node.run('help')
  File "<decorator-gen-3>", line 2, in run
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/fabric/connection.py", line 29, in opens
    self.open()
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/fabric/connection.py", line 636, in open
    self.client.connect(**kwargs)
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/paramiko/client.py", line 349, in connect
    to_try = list(self._families_and_addresses(hostname, port))
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/paramiko/client.py", line 203, in _families_and_addresses
    addrinfos = socket.getaddrinfo(
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
</code>```

I know for sure that's not the right name but is there any extra stuff I have to do, if so tell me, if not still tell me how to do it!

Title: Fabric connection to an extender

Body:
I wanted to connect to a extender for a Wi-Fi project, but I don't know if I can connect to an extender using the Fabric module for Python...

I was trying to connect to a server using it's name, but I'm sure that the name is wrong, but I don't know if I'm connecting wrong. Here is my code:

from fabric import Connection
node = Connection('KIN-AP23')
letsgo = node.run('help')

I don't know how to connect since I got this error:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    letsgo = node.run('help')
  File "<decorator-gen-3>", line 2, in run
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/fabric/connection.py", line 29, in opens
    self.open()
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/fabric/connection.py", line 636, in open
    self.client.connect(**kwargs)
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/paramiko/client.py", line 349, in connect
    to_try = list(self._families_and_addresses(hostname, port))
  File "/home/runner/FLIPPER1/venv/lib/python3.8/site-packages/paramiko/client.py", line 203, in _families_and_addresses
    addrinfos = socket.getaddrinfo(
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

I know for sure that's not the right name but is there any extra stuff I have to do, if so tell me, if not still tell me how to do it!


问:
How to sort & limit mongo $lookup without applying the filter on every result?
Items collection, divided on categories, a single category could be +100k documents ranging many items.
Collection of orders, an item can have many orders, either sell or bid orders.

For every item, find the lowest sell order and the highest bid order
$sort by lowest sell order and $limit results to first 20 (so a pagination is possible).

To do so, I have tried many ways via $lookup & aggregation usage, but I'm forced to fetch the lowest sell order for every item to be able to sort them all and limit the final results to the first 20, thereby the response time is huge, as this $lookup is being applied on every matching result rather than just the first 20.

How is this pattern doable without a complete category $lookup?

I cannot think of a way that doesn't apply the filter on all the results to later on, sort & limit the results to just 20.

I'm using the latest mongoose version for node.js


问:
Linux-- How do I force my custom cursor to take priority in a remote server?
I use GeForce Now Cloud Gaming to game.
I also have vision issues in one eye.
In windows I use a cursor app called CursorNode.
With GeForce Now when you start it it take over your mouse and switched it 2 times.
First to the desktop cursor on the remote server, and Second to the game cursor.
With CursorNode on Windows, you can force your custom cursor to work no matter what.
Is there a way to do something similar in linux? Force custom cursor use on remote servers/in games that switch your cursor.

I used a variety of custom cursors, but that is not the issue. Having persistence and priority and the ability to cast the custom cursor over a remote server's and game cursor is the key.
I have seen some github ideas for locating cursor/casting a color over it using xlib that might have some efficacy, but  I am ignorant on this topic.


问:
What the real difference between Mocks and Stubs?
I am learnig about test doubles, but I'm a little confused about the difference between Mocks and Stubs.

So, looking for some references about this topic, I found this article (is a good article, but some examples are a little bit confusing)

Then, I was following the examples in my IDE, however, the examples about Mocks and Stubs are the same.

Stubs example:

class A
{
    public function calculate() {    }
}

class B
{
    private A $a;
    public $value;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function setValue()
    {
        $this->value = $this->a->calculate();
    }
}

class StubsTest extends \PHPUnit\Framework\TestCase
{
    public function testValueCorrect()
    {
        $a = $this->createStub(A::class);
        $a
            ->method('calculate')
            ->willReturn(10);

        $b = new B($a);
        $b->setValue();

        $this->assertEquals(10, $b->value);
    }
}
```
<p><strong>Mock example:</strong></p>
<pre class="lang-php prettyprint-override"><code>use PHPUnit\Framework\TestCase;

class A {
    public function calculate() {    }
    public function doSomething() {    }
}

class B {

    private $a;
    public $value;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function setValue()
    {
        $this->value = $this->a->calculate();
    }

    public function doSomethingWithA()
    {
        $this->a->doSomething();
    }
}

class MockTest extends TestCase
{
    public function testValueCorrect()
    {
        $a = $this->createStub(A::class);
        $a
            ->method('calculate')
            ->willReturn(10);

        $b = new B($a);
        $b->setValue();

        $this->assertEquals(10, $b->value);
    }
}

</code>```

What the real difference between both? These code examples above are valid?

Body:
I am learnig about test doubles, but I'm a little confused about the difference between Mocks and Stubs.

So, looking for some references about this topic, I found this article (is a good article, but some examples are a little bit confusing)

Then, I was following the examples in my IDE, however, the examples about Mocks and Stubs are the same.

Stubs example:

class A
{
    public function calculate() {    }
}

class B
{
    private A $a;
    public $value;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function setValue()
    {
        $this->value = $this->a->calculate();
    }
}

class StubsTest extends \PHPUnit\Framework\TestCase
{
    public function testValueCorrect()
    {
        $a = $this->createStub(A::class);
        $a
            ->method('calculate')
            ->willReturn(10);

        $b = new B($a);
        $b->setValue();

        $this->assertEquals(10, $b->value);
    }
}

Mock example:

use PHPUnit\Framework\TestCase;

class A {
    public function calculate() {    }
    public function doSomething() {    }
}

class B {

    private $a;
    public $value;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function setValue()
    {
        $this->value = $this->a->calculate();
    }

    public function doSomethingWithA()
    {
        $this->a->doSomething();
    }
}

class MockTest extends TestCase
{
    public function testValueCorrect()
    {
        $a = $this->createStub(A::class);
        $a
            ->method('calculate')
            ->willReturn(10);

        $b = new B($a);
        $b->setValue();

        $this->assertEquals(10, $b->value);
    }
}

What the real difference between both? These code examples above are valid?


问:
Flutter: SvgPicture/png Image gets pixelated
Any solution to fix the pixelated issue on flutter? Here is my code.

Code

```<code>Image.asset(
            'assets/logo.png',
          ),
</code>```
```<code>SvgPicture.asset(
            'assets/logo.svg',
          ),
</code>```

Even i tried to solve it with filterQuality but i didn't find this as a solution.

filterQuality: FilterQuality.medium,

filterQuality: FilterQuality.high,

Body:
Any solution to fix the pixelated issue on flutter? Here is my code.

Code

Image.asset(
            'assets/logo.png',
          ),

SvgPicture.asset(
            'assets/logo.svg',
          ),

Even i tried to solve it with filterQuality but i didn't find this as a solution.

filterQuality: FilterQuality.medium,

filterQuality: FilterQuality.high,


问:
Prettier showing unfixable errors after saving
I am making a simple NEXTJS application to study.

I am trying to make a configuration of Prettier and ESLint.

However, while the format on save is working according to the rules I set up, Prettier still shows these errors that are impossible to fix.

Image showing Prettier Error

It asks me to delete space, but a. this is not according to the format and b. even If I do delete de space, the error continues to show up.

This is happening through the entire file.

Details of the configuration:

Versions:

"next": "9.4.4"

"react": "16.13.1"

"react-dom": "16.13.1"

"eslint": "^7.3.1"

"eslint-config-prettier": "^6.11.0"

"eslint-plugin-prettier": "^3.1.4"

"prettier": "^2.0.5"

The .eslintrc file

```<code>{
  "env": {
    "browser": true,
    "es2020": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 11,
    "sourceType": "module"
  },
  "plugins": ["react", "react-hooks", "@typescript-eslint"],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react/prop-types": "off",
    "react/react-in-jsx-scope": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off"
  }
}
</code>```

The prettierrc file

```<code>{
  "trailingComma": "none",
  "semi": false,
  "singleQuote": true
}
</code>```

The only VSCode extension that I have is the ESLint one. VSCode version is 1.74.3

I uninstalled the Prettier VS Code Plugin. I also tried to change to a newer Prettier version. I tried to unable prettier in .eslintrc file, and while that worked and I got rid of the errors, it isn't the result I wanted (it is not formatting anymore). I also tried to change de .prettierrc file in a number of ways, even deleting it, but the result was the same. I then try to follow this tutorial, but the result was that I ended up with no formatting at all.

Body:
I am making a simple NEXTJS application to study.

I am trying to make a configuration of Prettier and ESLint.

However, while the format on save is working according to the rules I set up, Prettier still shows these errors that are impossible to fix.

Image showing Prettier Error

It asks me to delete space, but a. this is not according to the format and b. even If I do delete de space, the error continues to show up.

This is happening through the entire file.

Details of the configuration:

Versions:

"next": "9.4.4"

"react": "16.13.1"

"react-dom": "16.13.1"

"eslint": "^7.3.1"

"eslint-config-prettier": "^6.11.0"

"eslint-plugin-prettier": "^3.1.4"

"prettier": "^2.0.5"

The .eslintrc file

{
  "env": {
    "browser": true,
    "es2020": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 11,
    "sourceType": "module"
  },
  "plugins": ["react", "react-hooks", "@typescript-eslint"],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react/prop-types": "off",
    "react/react-in-jsx-scope": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off"
  }
}

The prettierrc file

{
  "trailingComma": "none",
  "semi": false,
  "singleQuote": true
}

The only VSCode extension that I have is the ESLint one. VSCode version is 1.74.3

I uninstalled the Prettier VS Code Plugin. I also tried to change to a newer Prettier version. I tried to unable prettier in .eslintrc file, and while that worked and I got rid of the errors, it isn't the result I wanted (it is not formatting anymore). I also tried to change de .prettierrc file in a number of ways, even deleting it, but the result was the same. I then try to follow this tutorial, but the result was that I ended up with no formatting at all.


问:
select2 was not applied to all dropdowns; it only applied to the last record of data
In one of my applications, I want to update the data when someone changes the value in a dropdown. I did that thing with turbo_stream. I have a lot of values in my dropdown, and I'd like to search through them as well. Hence, I am using the select2 rails gem. But when I applied select2, then I was facing some issues, like select2 being applied to only the last dropdown item. If I have ten data, it skips the first nine and only applies to the last dropdown.

Note : Update functionality with turbo_stream is working fine.

Working Configuration :

rails - 7.0.4

ruby - 3.1.2

Here I am adding dropdown code in which I changed the value using turbo_stream,

Before Adding select2,

```<code><div data-controller="devdropdownbox">
  <%= f.select :status, Developer.developer_stauses(developer.id).map {|key, value| [key.humanize, value]}, data: { action: 'change->dropdownvalues#changeStatus', turbo_frame: :assign_interview_modal}, class: "bg-primary" %>
</div>
</code>```

After Adding select2

To apply select2, I have added an autosuggest class to the dropdown and written some JavaScript code.

```<code><div data-controller="devdropdownbox">
  <%= f.select :status, Developer.developer_stauses(developer.id).map {|key, value| [key.humanize, value]}, data: { action: 'change->dropdownvalues#changeDeveloperStatus', turbo_frame: :assign_interview_modal}, class: "bg-primary autosuggest" %>
</div>
</code>```

JavaScript for autosuggest,

```<code><script>
  $(document).ready(function() {
    $('.autosuggest').select2({
    });
  });
</script>
</code>```

Javascript is executed when the page DOM is ready.

So, after adding this, all of the values continue to update properly, but as I previously stated, select2 is only applied to the last set of data. I also added some styling.

I am attaching a screenshot of the problem to explain it in a better way

Screenshot of problem :

Body:
In one of my applications, I want to update the data when someone changes the value in a dropdown. I did that thing with turbo_stream. I have a lot of values in my dropdown, and I'd like to search through them as well. Hence, I am using the select2 rails gem. But when I applied select2, then I was facing some issues, like select2 being applied to only the last dropdown item. If I have ten data, it skips the first nine and only applies to the last dropdown.

Note : Update functionality with turbo_stream is working fine.

Working Configuration :

rails - 7.0.4

ruby - 3.1.2

Here I am adding dropdown code in which I changed the value using turbo_stream,

Before Adding select2,

  <%= f.select :status, Developer.developer_stauses(developer.id).map {|key, value| [key.humanize, value]}, data: { action: 'change->dropdownvalues#changeStatus', turbo_frame: :assign_interview_modal}, class: "bg-primary" %>

After Adding select2

To apply select2, I have added an autosuggest class to the dropdown and written some JavaScript code.

  <%= f.select :status, Developer.developer_stauses(developer.id).map {|key, value| [key.humanize, value]}, data: { action: 'change->dropdownvalues#changeDeveloperStatus', turbo_frame: :assign_interview_modal}, class: "bg-primary autosuggest" %>

JavaScript for autosuggest,

Javascript is executed when the page DOM is ready.

So, after adding this, all of the values continue to update properly, but as I previously stated, select2 is only applied to the last set of data. I also added some styling.

I am attaching a screenshot of the problem to explain it in a better way

Screenshot of problem :


问:
Traefik ingress with External-DNS Statuscode=409
i'm using aks cluster and traefik ingress and i'm using external-dns to update my records .
i installed my traefik ingress and he's working fine
this my variables for helm :

```<code>additionalArguments:
  - "--accesslog=true"
  - "--accesslog.format=json"
  - "--log.level=DEBUG"

deployment:
  replicas: 1

service:
  spec:
    loadBalancerIP: 20.151.201.38
  annotations:
    "service.beta.kubernetes.io/azure-load-balancer-resource-group": "aks-test"

kubernetesIngress:
  publishedService:
    enabled: true
</code>```

and this is my ingress manifest :

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
  namespace: default
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.ingress.kubernetes.io/router.entrypoints: web
    external-dns.alpha.kubernetes.io/hostname: app.juicyreviewz.com
    external-dns.alpha.kubernetes.io/target: juicyreviewz.com
spec:
  rules:
  - host: app.juicyreviewz.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: app1-nginx-service
            port:
              number: 80
</code>```

and after running this manifests the record is created but i got this error from external-dns pod :

```<code>time="2023-01-11T14:49:57Z" level=info msg="All records are already up to date"
time="2023-01-11T14:50:57Z" level=info msg="Updating CNAME record named 'app' to 'juicyreviewz.com' for Azure DNS zone 'juicyreviewz.com'."
time="2023-01-11T14:50:58Z" level=info msg="Updating TXT record named 'app' to '\"heritage=external-dns,external-dns/owner=default,external-dns/resource=ingress/default/my-ingress\"' for Azure DNS zone 'juicyreviewz.com'."
time="2023-01-11T14:51:00Z" level=error msg="Failed to update TXT record named 'app' to '\"heritage=external-dns,external-dns/owner=default,external-dns/resource=ingress/default/my-ingress\"' for DNS zone 'juicyreviewz.com': dns.RecordSetsClient#CreateOrUpdate: Failure sending request: StatusCode=409 -- Original Error: autorest/azure: Service returned an error. Status=<nil> <nil>"
</code>```

and this is the output of kubectl get ingress :

```<code>NAME         CLASS    HOSTS                  ADDRESS   PORTS   AGE
my-ingress   <none>   app.juicyreviewz.com             80      9m57s
</code>```

Body:
i'm using aks cluster and traefik ingress and i'm using external-dns to update my records .
i installed my traefik ingress and he's working fine
this my variables for helm :

additionalArguments:
  - "--accesslog=true"
  - "--accesslog.format=json"
  - "--log.level=DEBUG"

deployment:
  replicas: 1

service:
  spec:
    loadBalancerIP: 20.151.201.38
  annotations:
    "service.beta.kubernetes.io/azure-load-balancer-resource-group": "aks-test"

kubernetesIngress:
  publishedService:
    enabled: true

and this is my ingress manifest :

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
  namespace: default
  annotations:
    kubernetes.io/ingress.class: traefik
    traefik.ingress.kubernetes.io/router.entrypoints: web
    external-dns.alpha.kubernetes.io/hostname: app.juicyreviewz.com
    external-dns.alpha.kubernetes.io/target: juicyreviewz.com
spec:
  rules:
  - host: app.juicyreviewz.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: app1-nginx-service
            port:
              number: 80

and after running this manifests the record is created but i got this error from external-dns pod :

time="2023-01-11T14:49:57Z" level=info msg="All records are already up to date"
time="2023-01-11T14:50:57Z" level=info msg="Updating CNAME record named 'app' to 'juicyreviewz.com' for Azure DNS zone 'juicyreviewz.com'."
time="2023-01-11T14:50:58Z" level=info msg="Updating TXT record named 'app' to '\"heritage=external-dns,external-dns/owner=default,external-dns/resource=ingress/default/my-ingress\"' for Azure DNS zone 'juicyreviewz.com'."
time="2023-01-11T14:51:00Z" level=error msg="Failed to update TXT record named 'app' to '\"heritage=external-dns,external-dns/owner=default,external-dns/resource=ingress/default/my-ingress\"' for DNS zone 'juicyreviewz.com': dns.RecordSetsClient#CreateOrUpdate: Failure sending request: StatusCode=409 -- Original Error: autorest/azure: Service returned an error. Status=<nil> <nil>"

and this is the output of kubectl get ingress :

NAME         CLASS    HOSTS                  ADDRESS   PORTS   AGE
my-ingress   <none>   app.juicyreviewz.com             80      9m57s


问:
vscode list.expandAll
In VS Code, we can collapse all nodes in the file tree (explorer window) using list.collapseAll shortcut.

But, is there a way to do the reverse? Couldn't find any list.expandAll functionality. Any idea?

Title: vscode list.expandAll


问:
Mockito does not inject Mocks for Fields that are defined as Generics within the class that we want to inject in
I Have the following structure of a class:

```<code>public class MyClass <T extends InterfaceA & InterfaceB> {
private final T someOtherClass;

public MyClass(T someOtherClass){
 this.someOtherClass = someOtherClass;
 }
}
</code>```

Now I want to test this class and for that I need to mock the someOtherClass.
Here is what I have for my tests:

```<code>@ExtendWith(MockitoExtension.class)
public class MyeTest {
//NewClass implements both interfaces: InterfaceA and InterfaceB
@Mock
private NewClass newClass;

@InjectMocks
private MyClass<NewClass> myClass;

@Test
void someTest() {
//...
}
</code>```

Error Message that I get:
org.mockito.exceptions.misusing.InjectMocksException:
Cannot instantiate @InjectMocks field named 'myClass' of type MyClass.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null

Within test I tried to add a new empty interface that extends both InterfaceA and InterfaceB, and use it instead of a NewClass that implements both interfaces, like that:

```<code>@Mock
private InterfaceAandB someName;
@InjectMocks
private MyClass<InterfaceAandB> myClass;
</code>```

But I still get the same error message.

Body:
I Have the following structure of a class:

public class MyClass <T extends InterfaceA & InterfaceB> {
private final T someOtherClass;

public MyClass(T someOtherClass){
 this.someOtherClass = someOtherClass;
 }
}

Now I want to test this class and for that I need to mock the someOtherClass.
Here is what I have for my tests:

@ExtendWith(MockitoExtension.class)
public class MyeTest {
//NewClass implements both interfaces: InterfaceA and InterfaceB
@Mock
private NewClass newClass;

@InjectMocks
private MyClass<NewClass> myClass;

@Test
void someTest() {
//...
}

Error Message that I get:
org.mockito.exceptions.misusing.InjectMocksException:
Cannot instantiate @InjectMocks field named 'myClass' of type MyClass.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null

Within test I tried to add a new empty interface that extends both InterfaceA and InterfaceB, and use it instead of a NewClass that implements both interfaces, like that:

@Mock
private InterfaceAandB someName;
@InjectMocks
private MyClass<InterfaceAandB> myClass;

But I still get the same error message.


问:
AssemblyBinding Redirect in app.config with linkedConfiguration-Element
I have several .net-ConsoleApplications with a lot of app.config-Files.

In each app.config I have the following section:

```<code>   <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</code>```

This works fine, but now I have updated the nuget-packages and have to update all binding redirects. This is a lot of manual work.

I've read in the internet of the linkedConfiguration-Element where I can move the bindingRedirects to another file. So I replaced the above code with the following:

```<code>  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <linkedConfiguration href="file://D:\Sources\AssemblyBindingRedirects.xml"/>
  </assemblyBinding>
  <runtime>

  </runtime>
</code>```

and the AssemblyBindingRedirects.xml is:

```<code><?xml version="1.0"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

In the web.config of an IIS-Application this just works fine. Unfortunately in my app.Config-Files this doesn't work. I get an error that the Newtonsoft.Json.dll in the Verison 6.0.0.0 could not be found.

What am I doing wrong here?

Body:
I have several .net-ConsoleApplications with a lot of app.config-Files.

In each app.config I have the following section:

   <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

This works fine, but now I have updated the nuget-packages and have to update all binding redirects. This is a lot of manual work.

I've read in the internet of the linkedConfiguration-Element where I can move the bindingRedirects to another file. So I replaced the above code with the following:

  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <linkedConfiguration href="file://D:\Sources\AssemblyBindingRedirects.xml"/>
  </assemblyBinding>
  <runtime>

  </runtime>

and the AssemblyBindingRedirects.xml is:

<?xml version="1.0"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

In the web.config of an IIS-Application this just works fine. Unfortunately in my app.Config-Files this doesn't work. I get an error that the Newtonsoft.Json.dll in the Verison 6.0.0.0 could not be found.

What am I doing wrong here?


问:
VSCode closes immediately after opening
My VSCode keeps closing immediately when opened, I can't define the exact cause but this started to come around after I did some changes in my registry to fix my memory usage issues. The following keys are the keys that I modified when I was fixing my memory issue, I don't know if any of these caused the problem.

Modified Registry Keys:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> ClearPageFileAtShutdown
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> DisablePagingExecutive
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> LargeSystemCache
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> NonPagedPoolSize
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> PagedPoolSize
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> PhysicalAddressExtension
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> SessionPoolSize
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> SessionViewSize

How my vsc problem looks like:
vsc problem preview

I reinstalled the app several twice and searched for solutions but no luck.

----- Edit 1 -----

After executing code in the command prompt, it logged the following:

```<code> 1: 00007FF6E3472EE6 node::Buffer::New+50054
 2: 00007FF6E3462D33 node::InitializeNodeWithArgs+2371
 3: 00007FF6E1BB77E9 std::__1::__vector_base<v8::CpuProfileDeoptFrame,std::__1::allocator<v8::CpuProfileDeoptFrame> >::__end_cap+22297
 4: 00007FF6E19EECCE std::__1::vector<v8::CpuProfileDeoptInfo,std::__1::allocator<v8::CpuProfileDeoptInfo> >::vector<v8::CpuProfileDeoptInfo,std::__1::allocator<v8::CpuProfileDeoptInfo> >+49406
 5: 00007FF6E54869A2 Cr_z_crc32+4171922
 6: 00007FFFCA8826BD BaseThreadInitThunk+29
 7: 00007FFFCBDCDFB8 RtlUserThreadStart+40
</code>```

----- Edit 2 -----

Somehow, I got it back working. All I did was delete the folder C:\Users\Me\.vscode, what is the reason that this fixed it?

Title: VSCode closes immediately after opening

Body:
My VSCode keeps closing immediately when opened, I can't define the exact cause but this started to come around after I did some changes in my registry to fix my memory usage issues. The following keys are the keys that I modified when I was fixing my memory issue, I don't know if any of these caused the problem.

Modified Registry Keys:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> ClearPageFileAtShutdown
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> DisablePagingExecutive
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> LargeSystemCache
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> NonPagedPoolSize
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> PagedPoolSize
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> PhysicalAddressExtension
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> SessionPoolSize
Computer\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Memory Management -> SessionViewSize

How my vsc problem looks like:
vsc problem preview

I reinstalled the app several twice and searched for solutions but no luck.

----- Edit 1 -----

After executing code in the command prompt, it logged the following:

 1: 00007FF6E3472EE6 node::Buffer::New+50054
 2: 00007FF6E3462D33 node::InitializeNodeWithArgs+2371
 3: 00007FF6E1BB77E9 std::__1::__vector_base<v8::CpuProfileDeoptFrame,std::__1::allocator<v8::CpuProfileDeoptFrame> >::__end_cap+22297
 4: 00007FF6E19EECCE std::__1::vector<v8::CpuProfileDeoptInfo,std::__1::allocator<v8::CpuProfileDeoptInfo> >::vector<v8::CpuProfileDeoptInfo,std::__1::allocator<v8::CpuProfileDeoptInfo> >+49406
 5: 00007FF6E54869A2 Cr_z_crc32+4171922
 6: 00007FFFCA8826BD BaseThreadInitThunk+29
 7: 00007FFFCBDCDFB8 RtlUserThreadStart+40

----- Edit 2 -----

Somehow, I got it back working. All I did was delete the folder C:\Users\Me\.vscode, what is the reason that this fixed it?


问:
How to save a record in a controller to two different tables in go
People, I am trying to save an employee in the employee table, it already saves and everything is fine, the problem is when I try to save the schedule that is related to another table where schedule_id is the foreign of the employee table and is related to the id of the time table, this is the code:

Controlador

```<code>func Save(writer http.ResponseWriter, request *http.Request) {
    employe := models.Employe{}

    db := common.GetConnection()

    error := json.NewDecoder(request.Body).Decode(&employe)

    if error != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusBadRequest)
        return
    }

    randomBytes := make([]byte, 2)
    _, err := rand.Read(randomBytes)
    if err != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusBadRequest)
        return
    }

    employe.PinEmploye = hex.EncodeToString(randomBytes)

    horary := models.Employe{Arrival: employe.Arrival, Departure: employe.Departure}
    error = db.Save(&horary).Error

    if error != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusInternalServerError)
        return
    }

    employe.ScheduleId = horary.ID

    error = db.Save(&employe).Error

    if error != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusInternalServerError)
        return
    }
    json, _ := json.Marshal(employe)
    common.SendResponse(writer, http.StatusCreated, json)
    fmt.Println(employe)
}
</code>```

structs

```<code>type Employe struct {
    ID         int    `json:"id" gorm:"primary_key;auto_increment"`
    PinEmploye string `json:"pinEmploye" gorm:"FOREIGNKEY:PinEmploye" `
    FirstName  string `json:"first_name" `
    LastName   string `json:"last_name"`
    Company    string `json:"company"`
    Position   string `json:"position"`
    ScheduleId int    `json:"schedule_id"`
    // Arrival    time.Time `json:"arrival"`
    // Departure  time.Time `json:"departure"`
    CreatedAt time.Time `json:"fechacreacion"`
}
</code>```

Horary:

```<code>type Horary struct {
    ID        int       `json:"id" gorm:"primary_key;auto_increment"`
    Arrival   time.Time `json:"arrival"`
    Departure time.Time `json:"departure"`
}
</code>```

I tried to do it with entities but I still don't know very well about the subject

```<code>type Employe struct {
    ID         int       `json:"id" gorm:"primary_key;auto_increment"`
    PinEmploye string    `json:"pinEmploye" gorm:"FOREIGNKEY:PinEmploye" `
    FirstName  string    `json:"first_name" `
    LastName   string    `json:"last_name"`
    Company    string    `json:"company"`
    Position   string    `json:"position"`
    ScheduleId int       `json:"schedule_id"`
    CreatedAt  time.Time `json:"fechacreacion"`
}
</code>```

I have tried with entity model but still can't do it, I tried to do it with chatGPT but still can't

Body:
People, I am trying to save an employee in the employee table, it already saves and everything is fine, the problem is when I try to save the schedule that is related to another table where schedule_id is the foreign of the employee table and is related to the id of the time table, this is the code:

Controlador

func Save(writer http.ResponseWriter, request *http.Request) {
    employe := models.Employe{}

    db := common.GetConnection()

    error := json.NewDecoder(request.Body).Decode(&employe)

    if error != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusBadRequest)
        return
    }

    randomBytes := make([]byte, 2)
    _, err := rand.Read(randomBytes)
    if err != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusBadRequest)
        return
    }

    employe.PinEmploye = hex.EncodeToString(randomBytes)

    horary := models.Employe{Arrival: employe.Arrival, Departure: employe.Departure}
    error = db.Save(&horary).Error

    if error != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusInternalServerError)
        return
    }

    employe.ScheduleId = horary.ID

    error = db.Save(&employe).Error

    if error != nil {
        log.Fatal(error)
        common.SendError(writer, http.StatusInternalServerError)
        return
    }
    json, _ := json.Marshal(employe)
    common.SendResponse(writer, http.StatusCreated, json)
    fmt.Println(employe)
}

structs

type Employe struct {
    ID         int    `json:"id" gorm:"primary_key;auto_increment"`
    PinEmploye string `json:"pinEmploye" gorm:"FOREIGNKEY:PinEmploye" `
    FirstName  string `json:"first_name" `
    LastName   string `json:"last_name"`
    Company    string `json:"company"`
    Position   string `json:"position"`
    ScheduleId int    `json:"schedule_id"`
    // Arrival    time.Time `json:"arrival"`
    // Departure  time.Time `json:"departure"`
    CreatedAt time.Time `json:"fechacreacion"`
}

Horary:

type Horary struct {
    ID        int       `json:"id" gorm:"primary_key;auto_increment"`
    Arrival   time.Time `json:"arrival"`
    Departure time.Time `json:"departure"`
}

I tried to do it with entities but I still don't know very well about the subject

type Employe struct {
    ID         int       `json:"id" gorm:"primary_key;auto_increment"`
    PinEmploye string    `json:"pinEmploye" gorm:"FOREIGNKEY:PinEmploye" `
    FirstName  string    `json:"first_name" `
    LastName   string    `json:"last_name"`
    Company    string    `json:"company"`
    Position   string    `json:"position"`
    ScheduleId int       `json:"schedule_id"`
    CreatedAt  time.Time `json:"fechacreacion"`
}

I have tried with entity model but still can't do it, I tried to do it with chatGPT but still can't


问:
kotlin, android, json serialization
i'm using google gson converter to serialize an json response from an api call into an kotlin object,

one of the json field is a json object

so this didn'T work:

```<code>@Expose
@SerializedName("properties")
val properties: List<ThingProperty>,
</code>```

i got the following error:
Api call failed: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1

but this work fine:

```<code>@Expose
@SerializedName("properties")
val properties: JsonObject,
</code>```

but i then received a JsonObject and not a list of "second level" kotlin object

So the question is, using serialization or something like that,

how can i just received the original json and convert it properly, for this field, into a list of object based on the jsonObject

note, i received my data using retrofit2

Edit:

there is a json example for this item:

```<code>"properties":{
        "ActiveEvent":{
            "name":"ActiveEvent",
            "value":false,
            "visible":true,
            "title":"Active Event",
            "type":"boolean",
            "@type":"BooleanProperty",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/ActiveEvent"
                }]
            },
        "PreHeatEvent":{
            "name":"PreHeatEvent",
            "value":false,
            "visible":true,
            "title":"Pre-Heat Event",
            "type":"boolean",
            "@type":"BooleanProperty",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/PreHeatEvent"
                }]
            },
        "PostHeatEvent":{
            "name":"PostHeatEvent",
            "value":false,
            "visible":true,
            "title":"Post-Heat Event",
            "type":"boolean",
            "@type":"BooleanProperty",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/PostHeatEvent"
                }]
            },
        "NextEvent":{
            "name":"NextEvent",
            "value":null,
            "visible":true,
            "title":"Next Event",
            "type":"string",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/NextEvent"
                }]
            },
</code>```

Title: kotlin, android, json serialization

Body:
i'm using google gson converter to serialize an json response from an api call into an kotlin object,

one of the json field is a json object

so this didn'T work:

@Expose
@SerializedName("properties")
val properties: List<ThingProperty>,

i got the following error:
Api call failed: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1

but this work fine:

@Expose
@SerializedName("properties")
val properties: JsonObject,

but i then received a JsonObject and not a list of "second level" kotlin object

So the question is, using serialization or something like that,

how can i just received the original json and convert it properly, for this field, into a list of object based on the jsonObject

note, i received my data using retrofit2

Edit:

there is a json example for this item:

"properties":{
        "ActiveEvent":{
            "name":"ActiveEvent",
            "value":false,
            "visible":true,
            "title":"Active Event",
            "type":"boolean",
            "@type":"BooleanProperty",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/ActiveEvent"
                }]
            },
        "PreHeatEvent":{
            "name":"PreHeatEvent",
            "value":false,
            "visible":true,
            "title":"Pre-Heat Event",
            "type":"boolean",
            "@type":"BooleanProperty",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/PreHeatEvent"
                }]
            },
        "PostHeatEvent":{
            "name":"PostHeatEvent",
            "value":false,
            "visible":true,
            "title":"Post-Heat Event",
            "type":"boolean",
            "@type":"BooleanProperty",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/PostHeatEvent"
                }]
            },
        "NextEvent":{
            "name":"NextEvent",
            "value":null,
            "visible":true,
            "title":"Next Event",
            "type":"string",
            "readOnly":true,
            "links":[{
                "rel":"property",
                "href":"/things/hydroqc-Maison/properties/NextEvent"
                }]
            },


问:
How can I save the data from my Django crispy form
This is how my form looks like:

When I press submit and go to the page where the post should be rendered, then I cannot see the post I just have created.

This is the page where I have my form: 'anzeige_new.html'

```<code>  {% load crispy_forms_tags %}
  {% block content %}
        <div class="content-section">
            <form method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Inserat erstellen</legend>
                    {{ form|crispy }}
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info" type="submit">Post</button>
                </div>
            </form>
        </div>
  {% endblock content %}
</code>```

This is where it should be rendered: "angebote.html"

```<code>{% block content %}
{% for post in posts %}
  <p>Inside for loop</p>
  <a class="mr-2" href="#">{{ Post.objects.all }}</a>
  <article class="media content-section">
    <img class="rounded-circle article-img" src="{{ post.author.profile.image.url">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2" href="#">{{ post.author }}</a>
        <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
      </div>
      <h2><a class="article-title">{{ post.title }}</a></h2>
      <p class="article-content">{{ post.content }}</p>
    </div>
  </article>
{% endfor %}
{% endblock content %}
</code>```

forms.py

```<code>class PostForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)

        # If you pass FormHelper constructor a form instance
        # It builds a default layout with all its fields
        self.helper = FormHelper(self)

        # You can dynamically adjust your layout
        self.helper.layout.append(Submit('save', 'save'))

    class Meta:
        model = Post
        fields = ('title', 'category', 'weekday')
</code>```

models.py

```<code>class Post(models.Model):
    title = models.CharField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    post = models.CharField(max_length=100, default='SOME STRING')

    weekday_choices = (
        ('Monday', 'Monday'),
        ('Tuesday', 'Tuesday'),
        ('Wednesday', 'Wednesday'),
        ('Thursday', 'Thursday'),
        ('Friday', 'Friday'),
        ('Saturday', 'Saturday'),
        ('Sunday', 'Sunday'),
    )

    weekday = models.CharField(max_length=15, choices=weekday_choices, default=0)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})
</code>```

views.py

```<code>class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'category', 'weekday']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostListView(ListView):
    model = Post
    template_name = 'vereinsapp/angebote.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']  # ordering posts from latest to oldest

class CreateView(TemplateView):
    template_name = 'vereinsapp/anzeige_new.html'
    print("Inside Create View")
    def post(self, request):
        form = PostForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['post']
            post = form.save()
            post.save()
            form = PostForm()
            post = form.save()
            return redirect('post:posts')

        args = {'form': form}
        return render(request, self.template_name, args)
</code>```

urls.py

```<code>urlpatterns = [
    path('', views.index, name='index'),
    path('vereinsapp/', views.index, name='index'),
    path('angebote/', views.angebote),
    path('angebotsprofil/', views.angebotsprofil),
    path('vereinsmarketing/', views.vereinsmarketing),
    path('anzeige_new/', views.anzeige_new),
    path('nutzerprofil/', views.nutzerprofil),

    path('posts/', PostListView.as_view(), name='posts'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
]
</code>```

Why is it still not saving?

UPDATE/EDIT:

```<code>class PostListView(ListView):
    model = Post
    template_name = 'vereinsapp/angebote.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']  # ordering posts from latest to oldest
    queryset = Post.objects.all()
</code>```

angebote.html

```<code>{% block content %}
{% for post in posts %}
  <p>Inside for loop</p>
  <a class="mr-2" href="#">{{ post }}</a>
  <article class="media content-section">
    <img class="rounded-circle article-img" src="{{ post.author.profile.image.url">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2" href="#">{{ post.author }}</a>
        <small class="text-muted">{{ post.weekday }}</small>
      </div>
      <h2><a class="article-title">{{ post.title }}</a></h2>
      <p class="article-content">{{ post.category }}</p>
    </div>
  </article>
{% endfor %}
{% endblock content %}
</code>```

Body:
This is how my form looks like:

When I press submit and go to the page where the post should be rendered, then I cannot see the post I just have created.

This is the page where I have my form: 'anzeige_new.html'

  {% load crispy_forms_tags %}
  {% block content %}

            <form method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Inserat erstellen</legend>
                    {{ form|crispy }}
                </fieldset>

                    <button class="btn btn-outline-info" type="submit">Post</button>

            </form>

  {% endblock content %}

This is where it should be rendered: "angebote.html"

{% block content %}
{% for post in posts %}

Inside for loop

  {{ Post.objects.all }}

        {{ post.author }}
        {{ post.date_posted|date:"F d, Y" }}

{{ post.title }}

{{ post.content }}

{% endfor %}
{% endblock content %}

forms.py

class PostForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)

        # If you pass FormHelper constructor a form instance
        # It builds a default layout with all its fields
        self.helper = FormHelper(self)

        # You can dynamically adjust your layout
        self.helper.layout.append(Submit('save', 'save'))

    class Meta:
        model = Post
        fields = ('title', 'category', 'weekday')

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    post = models.CharField(max_length=100, default='SOME STRING')

    weekday_choices = (
        ('Monday', 'Monday'),
        ('Tuesday', 'Tuesday'),
        ('Wednesday', 'Wednesday'),
        ('Thursday', 'Thursday'),
        ('Friday', 'Friday'),
        ('Saturday', 'Saturday'),
        ('Sunday', 'Sunday'),
    )

    weekday = models.CharField(max_length=15, choices=weekday_choices, default=0)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

views.py

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'category', 'weekday']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostListView(ListView):
    model = Post
    template_name = 'vereinsapp/angebote.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']  # ordering posts from latest to oldest

class CreateView(TemplateView):
    template_name = 'vereinsapp/anzeige_new.html'
    print("Inside Create View")
    def post(self, request):
        form = PostForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['post']
            post = form.save()
            post.save()
            form = PostForm()
            post = form.save()
            return redirect('post:posts')

        args = {'form': form}
        return render(request, self.template_name, args)

urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('vereinsapp/', views.index, name='index'),
    path('angebote/', views.angebote),
    path('angebotsprofil/', views.angebotsprofil),
    path('vereinsmarketing/', views.vereinsmarketing),
    path('anzeige_new/', views.anzeige_new),
    path('nutzerprofil/', views.nutzerprofil),

    path('posts/', PostListView.as_view(), name='posts'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
]

Why is it still not saving?

UPDATE/EDIT:

class PostListView(ListView):
    model = Post
    template_name = 'vereinsapp/angebote.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']  # ordering posts from latest to oldest
    queryset = Post.objects.all()

angebote.html

{% block content %}
{% for post in posts %}

Inside for loop

  {{ post }}

        {{ post.author }}
        {{ post.weekday }}

{{ post.title }}

{{ post.category }}

{% endfor %}
{% endblock content %}


问:
Amp-accordion's animation removes the outline in animation/transition
   .focusOutline:focus-visible { outline: 3px solid green; outline-offset:5px; z-index:99; }

I have added an outline and animation to the amp-accordion. During the animation/transition the outline outside of the accordion disappears.

   https://codepen.io/wilson-ruan/pen/yLjwyNO

Can the outline not disappear?


问:
simplesamlphp behind a load balancer
I have an application load balancer in AWS listening on 443 with an ACM ssl certificate. It forwards to EC2 instance listening port 80. I call https://ec2instancedomain.com and everything works, ssl is accepted.

But after installing simplesamlphp I get the error:
Requester: Unknown AssertionConsumerServiceURL http://ec2instancedomain.com/simplesaml/module.php/saml/sp/saml2-acs.php/default-sp
(missing the https)

...my service provider insists on https being in the AssertionConsumerServiceURL. I am using saml20_idp_remote and there seems to be no way of overriding the communicated. communicated assertion url.
So my service provider expects https, but the request is sending http, how can I override this?

Title: simplesamlphp behind a load balancer


问:
R-package dll not generated during installation
I am writing an example of an R-package that uses C++ to call a C-function from an external library (I used the chron.dll from the R-package chron).
The version of R is R-4.2.2. On my machine (Windows 10) rtools42 is installed in C:/Program Files aka C:/PROGRA~1.
Since this is not the standard location I am running

```<code>Sys.setenv(PATH = paste("C:/PROGRA~1/rtools42/bin/", Sys.getenv("PATH"), sep=";"))
Sys.setenv(BINPREF = "C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/")
</code>```

prior to the build. Then I check the build with devtools::check() and it seems that compilation and linking works but the installation
fails. The 00install.out file is as follows:

```<code>* installing *source* package 'PackageExample' ...
** using staged installation
** libs
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c RcppExports.cpp -o RcppExports.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c callchron.cpp -o callchron.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c matrix.cpp -o matrix.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c rcpp_hello_world.cpp -o rcpp_hello_world.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c vector.cpp -o vector.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++ -shared -s -static-libgcc -o PackageExample.dll tmp.def RcppExports.o callchron.o matrix.o rcpp_hello_world.o vector.o -L../chron/libs/x64 -lchron -LC:/Programme/rtools42/x86_64-w64-mingw32.static.posix/lib/x64 -LC:/Programme/rtools42/x86_64-w64-mingw32.static.posix/lib -LC:/PROGRA~1/R/R-42~1.2/bin/x64 -lR
installing to C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/00LOCK-PACKAG~1/00new/PackageExample/libs/x64
** R
** byte-compile and prepare package for lazy loading
Reading Tests.R.
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
Error: loading of pakckage or namespace 'PackageExample' in inDL(x, as.logical(local), as.logical(now), ...): failed
cannot load shared object 'C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/00LOCK-PACKAG~1/00new/PackageExample/libs/x64/PackageExample.dll':
LoadLibrary failure:  the referenced module was not found.

Error: loading failed
Execution terminated
ERROR: loading failed
* removing 'C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/PackageExample'
</code>```

(Some error messages translatd from German).
Interestingly the folder
C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/
contains files foo.dll, foo.o.

It looks like the PackageExample.dll is not put into

```<code>'C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/00LOCK- PACKAG~1/00new/PackageExample/libs/x64/
</code>```

and instead foo.dll and foo.o are generated. What might be the problem?

Body:
I am writing an example of an R-package that uses C++ to call a C-function from an external library (I used the chron.dll from the R-package chron).
The version of R is R-4.2.2. On my machine (Windows 10) rtools42 is installed in C:/Program Files aka C:/PROGRA~1.
Since this is not the standard location I am running

Sys.setenv(PATH = paste("C:/PROGRA~1/rtools42/bin/", Sys.getenv("PATH"), sep=";"))
Sys.setenv(BINPREF = "C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/")

prior to the build. Then I check the build with devtools::check() and it seems that compilation and linking works but the installation
fails. The 00install.out file is as follows:

* installing *source* package 'PackageExample' ...
** using staged installation
** libs
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c RcppExports.cpp -o RcppExports.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c callchron.cpp -o callchron.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c matrix.cpp -o matrix.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c rcpp_hello_world.cpp -o rcpp_hello_world.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++  -std=gnu++11 -I"C:/PROGRA~1/R/R-42~1.2/include" -DNDEBUG -I../chron/include -I. -I'C:/Users/JohnDoe/PROJECTS/R/libraries/Rcpp/include'   -I"C:/Programme/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c vector.cpp -o vector.o
C:/PROGRA~1/rtools42/x86_64-w64-mingw32.static.posix/bin/g++ -shared -s -static-libgcc -o PackageExample.dll tmp.def RcppExports.o callchron.o matrix.o rcpp_hello_world.o vector.o -L../chron/libs/x64 -lchron -LC:/Programme/rtools42/x86_64-w64-mingw32.static.posix/lib/x64 -LC:/Programme/rtools42/x86_64-w64-mingw32.static.posix/lib -LC:/PROGRA~1/R/R-42~1.2/bin/x64 -lR
installing to C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/00LOCK-PACKAG~1/00new/PackageExample/libs/x64
** R
** byte-compile and prepare package for lazy loading
Reading Tests.R.
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
Error: loading of pakckage or namespace 'PackageExample' in inDL(x, as.logical(local), as.logical(now), ...): failed
cannot load shared object 'C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/00LOCK-PACKAG~1/00new/PackageExample/libs/x64/PackageExample.dll':
LoadLibrary failure:  the referenced module was not found.

Error: loading failed
Execution terminated
ERROR: loading failed
* removing 'C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/PackageExample'

(Some error messages translatd from German).
Interestingly the folder
C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/
contains files foo.dll, foo.o.

It looks like the PackageExample.dll is not put into

'C:/Users/JohnDoe/AppData/Local/Temp/Rtmpg9Wn7W/file43d46e066097/PackageExample.Rcheck/00LOCK- PACKAG~1/00new/PackageExample/libs/x64/

and instead foo.dll and foo.o are generated. What might be the problem?


问:
Reload PM2 from New Directory
I'm wondering if it is possible to reload a pm2 process from a different directory. The reason for this is that I am using self-hosted Github actions to pull and build the project. However, while the build is running, the build folder is replaced with a new build folder, causing some requests to return a 500 status. If I could build and reload the application in a different directory, that would be ideal. Is it possible?</p>

Title: Reload PM2 from New Directory


问:
Excel lookup using multiple criteria
How can I make Timesheet!C2 display $10 and Timesheet!C3 display $20?

So far I have this:

```<code>=VLOOKUP("base", Rates!A2:D4, 4, FALSE)
</code>```

but I need it to also check that Punch-in from Timesheet falls in between Start and End from the Rates sheet.

I am totally open to abandoning the VLOOKUP() function so all suggestions are welcomed.

Data provided for easy copying.

Punch-in
Punch-out
Hourly

11/21/2022 14:00
11/21/2022 22:00

1/10/2023 10:00
1/10/2023 18:00

Key
Start
End
Value

base
1/1/2022 0:00
12/31/2022 23:59
$10.00

base
1/1/2023 0:00
12/31/2023 23:59
$20.00

OT
1/1/2010 0:00
12/31/2050 23:59
$30.00

Title: Excel lookup using multiple criteria

Body:
How can I make Timesheet!C2 display $10 and Timesheet!C3 display $20?

So far I have this:

=VLOOKUP("base", Rates!A2:D4, 4, FALSE)

but I need it to also check that Punch-in from Timesheet falls in between Start and End from the Rates sheet.

I am totally open to abandoning the VLOOKUP() function so all suggestions are welcomed.

Data provided for easy copying.

Punch-in
Punch-out
Hourly

11/21/2022 14:00
11/21/2022 22:00

1/10/2023 10:00
1/10/2023 18:00

Key
Start
End
Value

base
1/1/2022 0:00
12/31/2022 23:59
$10.00

base
1/1/2023 0:00
12/31/2023 23:59
$20.00

OT
1/1/2010 0:00
12/31/2050 23:59
$30.00


问:
Returning a byte array from a GET call on ASP.NET API
I have been trying to recreate an existing API for testing purposes.
Original API is returning a XML presented as an array of bytes.

I have already modeled my GET response XML to look like the original and am now trying to display it as a byte array but the problem I am encountering is while calling my API from Postman the result is a Base64Encoded string.

My GET method is reading rows from an SQL table via Dapper into a model I made.

My current code:

```<code>    //[Produces("application/xml")]
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {
        [Route("{employeeID?}")]
        [HttpGet]
        public byte[] Get(int? employeeID = null)
        {
            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                con.Open();

                employees = con.Query<Employee, EmploymentData, Employee>(query, (emp, empData) => {
                    emp.EmploymentData = empData;
                    return emp;
                }, splitOn: "CompanyID");
            }

            GetResponse response = new GetResponse()
            {
                Employees = (List<Employee>)employees,
                ErrorCode = null,
                ErrorMessage = null,
                InputParameterErrors = null,
                ResultInfo = new ResultInfo()
                {
                    ResultDateTime = DateTime.Now,
                    EmployeeCount = employees.Count()
                }
            };

            byte[] bytes = ObjectToByteArray(response);
            return bytes;
        }

        public static byte[] ObjectToByteArray(Object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
        }
</code>```

I have already tried [Produces("application/octet-stream")] instead of application/xml but I get 406 Not Acceptable in Postman.

Body:
I have been trying to recreate an existing API for testing purposes.
Original API is returning a XML presented as an array of bytes.

I have already modeled my GET response XML to look like the original and am now trying to display it as a byte array but the problem I am encountering is while calling my API from Postman the result is a Base64Encoded string.

My GET method is reading rows from an SQL table via Dapper into a model I made.

My current code:

    //[Produces("application/xml")]
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {
        [Route("{employeeID?}")]
        [HttpGet]
        public byte[] Get(int? employeeID = null)
        {
            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                con.Open();

                employees = con.Query<Employee, EmploymentData, Employee>(query, (emp, empData) => {
                    emp.EmploymentData = empData;
                    return emp;
                }, splitOn: "CompanyID");
            }

            GetResponse response = new GetResponse()
            {
                Employees = (List<Employee>)employees,
                ErrorCode = null,
                ErrorMessage = null,
                InputParameterErrors = null,
                ResultInfo = new ResultInfo()
                {
                    ResultDateTime = DateTime.Now,
                    EmployeeCount = employees.Count()
                }
            };

            byte[] bytes = ObjectToByteArray(response);
            return bytes;
        }

        public static byte[] ObjectToByteArray(Object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
        }

I have already tried [Produces("application/octet-stream")] instead of application/xml but I get 406 Not Acceptable in Postman.