问:
How to deserialize root JSON dynamic property name in C#?
I'm trying to deserialize the following JSON object in C#. I'm having trouble because the "0a6888c9-86c5-48e7-a6d9-da3cc39db1a0" is dynamic

{
  "0a6888c9-86c5-48e7-a6d9-da3cc39db1a0": {
    "minPricePerNft": "100000000000000000",
    "amountForSale": "1",
    "loopringSaleInfo": {
      "minPricePerNftInWei": "100000000000000000",
      "amountForSale": "1"
    },
    "likeCount": 4
  }
}
```
<p>I've tried making the following c# classes to no avail...:</p>
<pre class="lang-cs prettyprint-override"><code>   public class LoopringSaleInfo
    {
        public string? minPricePerNftInWei { get; set; }
        public string? amountForSale { get; set; }
    }

    public class Value
    {
        public string? minPricePerNft { get; set; }
        public string? amountForSale { get; set; }
        public LoopringSaleInfo? loopringSaleInfo { get; set; }
        public int likeCount { get; set; }
    }
    public class GameStopNftListing
    {
        public string? @class { get; set; }
        public Value? value { get; set; }
    }
</code>```

Any tips?

The difference between this and other similar questions on here is the root property is dynamic. All the other answers I see start with a non dynamic root property...

Body:
I'm trying to deserialize the following JSON object in C#. I'm having trouble because the "0a6888c9-86c5-48e7-a6d9-da3cc39db1a0" is dynamic

{
  "0a6888c9-86c5-48e7-a6d9-da3cc39db1a0": {
    "minPricePerNft": "100000000000000000",
    "amountForSale": "1",
    "loopringSaleInfo": {
      "minPricePerNftInWei": "100000000000000000",
      "amountForSale": "1"
    },
    "likeCount": 4
  }
}

I've tried making the following c# classes to no avail...:

   public class LoopringSaleInfo
    {
        public string? minPricePerNftInWei { get; set; }
        public string? amountForSale { get; set; }
    }

    public class Value
    {
        public string? minPricePerNft { get; set; }
        public string? amountForSale { get; set; }
        public LoopringSaleInfo? loopringSaleInfo { get; set; }
        public int likeCount { get; set; }
    }
    public class GameStopNftListing
    {
        public string? @class { get; set; }
        public Value? value { get; set; }
    }

Any tips?

The difference between this and other similar questions on here is the root property is dynamic. All the other answers I see start with a non dynamic root property...


来源: stackexchange

问:
System.Data.SqlClient.SqlException: Local Database Runtime error occurred. The specified LocalDB instance does not exist
I have this weird issue where i try to access data ('woningen') but it throws an error saying *System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.*

It is weird because when i access my other data ('klanten'), it works fine and loads perfectly. I have already searched online and tried several solutions but none worked for me.

The error gets thrown here:

ImmoWinConnectedRepository.cs

public IEnumerable<Woning> GetWoningen()
        {
            return new Woningen(
                _context.Woningen
                .Include(k => k.Eigenaar)
                .Include(k => k.Adres)
                .Include(k => k.Prijs)
                .ToList());
        }
```
<p>Here is my dbcontext class:</p>
<p><strong>ImmoWinContext.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class ImmoWinContext : DbContext
    {
        #region Fields & properties

        public DbSet<Adres> Adressen { get; set; }
        public DbSet<Appartement> Appartementen { get; set; }
        public DbSet<Huis> Huizen { get; set; }
        public DbSet<Klant> Klanten { get; set; }
        public DbSet<Persoon> Personen { get; set; }
        public DbSet<Woning> Woningen { get; set; }

        #endregion

        #region Constructors

        public ImmoWinContext() : this(null)
        { }
        public ImmoWinContext(Action<String> logger) : base("dbImmoWin")
        {
            if (logger != null)
                Database.Log = logger;
            Database.SetInitializer(new ImmoWinContextDropCreateDatabaseAlways());
            //Database.SetInitializer(new ImmoWinContextDropCreateDatabaseIfModelChanges());
        }

        #endregion

        #region Methods

        #endregion
    }
</code>```

Some extra info:

The database has been created and is connected.

Code editor Visual Studio 2022

.NET version is 4.8

WPF Project using MVVM

Thank you for any help. Much appreciated!

I have tried checking the services, .NET versions and checking the connection to the db.

ContentLicense: CC BY-SA 4.0

Body:
I have this weird issue where i try to access data ('woningen') but it throws an error saying *System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.*

It is weird because when i access my other data ('klanten'), it works fine and loads perfectly. I have already searched online and tried several solutions but none worked for me.

The error gets thrown here:

ImmoWinConnectedRepository.cs

public IEnumerable<Woning> GetWoningen()
        {
            return new Woningen(
                _context.Woningen
                .Include(k => k.Eigenaar)
                .Include(k => k.Adres)
                .Include(k => k.Prijs)
                .ToList());
        }

Here is my dbcontext class:

ImmoWinContext.cs

public class ImmoWinContext : DbContext
    {
        #region Fields & properties

        public DbSet<Adres> Adressen { get; set; }
        public DbSet<Appartement> Appartementen { get; set; }
        public DbSet<Huis> Huizen { get; set; }
        public DbSet<Klant> Klanten { get; set; }
        public DbSet<Persoon> Personen { get; set; }
        public DbSet<Woning> Woningen { get; set; }

        #endregion

        #region Constructors

        public ImmoWinContext() : this(null)
        { }
        public ImmoWinContext(Action<String> logger) : base("dbImmoWin")
        {
            if (logger != null)
                Database.Log = logger;
            Database.SetInitializer(new ImmoWinContextDropCreateDatabaseAlways());
            //Database.SetInitializer(new ImmoWinContextDropCreateDatabaseIfModelChanges());
        }

        #endregion

        #region Methods

        #endregion
    }

Some extra info:

The database has been created and is connected.

Code editor Visual Studio 2022

.NET version is 4.8

WPF Project using MVVM

Thank you for any help. Much appreciated!

I have tried checking the services, .NET versions and checking the connection to the db.


问:
nested exception is feign.codec.DecodeException:Could not extract response: no suitable HttpMessageConverter found for response type [application/xml]
I'm learning to work with feign. When the requests were in the "json" format, all the responses came fine, but when I needed to get a response in the "xml" format, it gives this error. How can I solve it?

@GetMapping("/link") CorporateItemsDto getCorporationDepartments( @RequestParam(value = "key") String key );

I tried RestTemplate, but it didn't work


问:
C++ YOLOv5: Failed to parse onnx model in function 'cv::dnn::dnn4_v20190621::ONNXImporter::ONNXImporter'
I want to use YOLOv5 for object detection Using C++ and OpenCV's DNN.
I'm using Windows 10, and VS 2019.

However, the following line of code:

```<code>#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("yolov5s.onnx");

    return 0;
}
</code>```

causes the following error:

```<code> OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:57: error: (-210:Unsupported format or combination of formats) Failed to parse onnx model in function 'cv::dnn::dnn4_v20190621::ONNXImporter::ONNXImporter'

Press any key to continue . . .
</code>```

EDIT:

Seems there was a problem with the path.

After I wrote the full path to the full .onnx file path, as follows:

```<code>#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("C:/Users/hedey/source/repos/Road_Defects_Detector/yolov5s.onnx");

    return 0;
}
</code>```

Now, I'm getting the following error:

```<code>OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:320: error: (-204:Requested object was not found) Blob  not found in const blobs in function 'cv::dnn::dnn4_v20190621::ONNXImporter::getBlob'

Press any key to continue . . .
</code>```

Body:
I want to use YOLOv5 for object detection Using C++ and OpenCV's DNN.
I'm using Windows 10, and VS 2019.

However, the following line of code:

#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("yolov5s.onnx");

    return 0;
}

causes the following error:

 OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:57: error: (-210:Unsupported format or combination of formats) Failed to parse onnx model in function 'cv::dnn::dnn4_v20190621::ONNXImporter::ONNXImporter'

Press any key to continue . . .

EDIT:

Seems there was a problem with the path.

After I wrote the full path to the full .onnx file path, as follows:

#include <opencv2/opencv.hpp>

int main(int, char **)
{
    auto net = cv::dnn::readNet("C:/Users/hedey/source/repos/Road_Defects_Detector/yolov5s.onnx");

    return 0;
}

Now, I'm getting the following error:

OpenCV(4.1.1) C:\opencv-4.1.1\modules\dnn\src\onnx\onnx_importer.cpp:320: error: (-204:Requested object was not found) Blob  not found in const blobs in function 'cv::dnn::dnn4_v20190621::ONNXImporter::getBlob'

Press any key to continue . . .


问:
Named outlets not displaying content
I'm attempting to use a named router outlet like so:

```<code>// Proposal_Year_Root_Component
<router-outlet name='popup'></router-outlet>

<ng-container *ngIf=is_ready>
  <div fxLayout=row>
    ...blah blah
</code>```

My routes look like this:

```<code>const routes: Routes = [
  {
    path: '',
    component: Proposal_Routing_Component,
    children: [
      {
        path: '',
        component: Proposals_Root_Component,
      },
      {
        path: ':proposal_id',
        component: Proposal_Root_Component,
        children: [
          {
            path: 'years/:year_id',
            component: Proposal_Year_Root_Component,
            children: [
              {
                path: 'scale',
                outlet: 'popup',
                loadChildren: () => import('../scale/scale.module').then(m => m.Scale_Module)
              }
            ]
          },
        ]
      },

    ]
  }
]
</code>```

This route works and is visible in the URL:

```<code>...Y7BsIwXMzEGNmm7a2U4K/years/Gr1THwjaofVaB0aeRtFm/(popup:scale)
</code>```

The only problem is that the component from the Scale_Module does not load as intended. This is the router outlet inside the Proposal_Year_Root_Component:

I've included an imported routing module with the Scale_Module, and a basic component at the '' path, so the component should be displaying.

```<code>// Scale_Module
import { Common_Module } from '@app/modules'
import { NgModule } from '@angular/core';

import { Scale_Component } from './scale.component'
import { Scale_Routing_Module } from './scale.routing.module'

@NgModule({
  declarations: [Scale_Component],
  imports: [
    Common_Module,
    Scale_Routing_Module,
  ],
})
export class Scale_Module { }

// Scale_Routing_Module
import { Scale_Component } from './scale.component'
import { RouterModule, Routes } from '@angular/router'
import { NgModule } from '@angular/core'

const routes: Routes = [
  {
    path: '',
    component: Scale_Component,
  }
]

@NgModule({
  imports: [RouterModule.forChild(routes)],
})
export class Scale_Routing_Module { }

</code>```

Any idea what I'm doing wrong?

EDIT: another clue - the Scale_Module is loaded in the network tab upon lazy loading. So, it's loading, it's just not displaying in the named outlet.

Title: Named outlets not displaying content

Body:
I'm attempting to use a named router outlet like so:

// Proposal_Year_Root_Component
<router-outlet name='popup'></router-outlet>

<ng-container *ngIf=is_ready>

    ...blah blah

My routes look like this:

const routes: Routes = [
  {
    path: '',
    component: Proposal_Routing_Component,
    children: [
      {
        path: '',
        component: Proposals_Root_Component,
      },
      {
        path: ':proposal_id',
        component: Proposal_Root_Component,
        children: [
          {
            path: 'years/:year_id',
            component: Proposal_Year_Root_Component,
            children: [
              {
                path: 'scale',
                outlet: 'popup',
                loadChildren: () => import('../scale/scale.module').then(m => m.Scale_Module)
              }
            ]
          },
        ]
      },

    ]
  }
]

This route works and is visible in the URL:

...Y7BsIwXMzEGNmm7a2U4K/years/Gr1THwjaofVaB0aeRtFm/(popup:scale)

The only problem is that the component from the Scale_Module does not load as intended. This is the router outlet inside the Proposal_Year_Root_Component:

I've included an imported routing module with the Scale_Module, and a basic component at the '' path, so the component should be displaying.

// Scale_Module
import { Common_Module } from '@app/modules'
import { NgModule } from '@angular/core';

import { Scale_Component } from './scale.component'
import { Scale_Routing_Module } from './scale.routing.module'

@NgModule({
  declarations: [Scale_Component],
  imports: [
    Common_Module,
    Scale_Routing_Module,
  ],
})
export class Scale_Module { }

// Scale_Routing_Module
import { Scale_Component } from './scale.component'
import { RouterModule, Routes } from '@angular/router'
import { NgModule } from '@angular/core'

const routes: Routes = [
  {
    path: '',
    component: Scale_Component,
  }
]

@NgModule({
  imports: [RouterModule.forChild(routes)],
})
export class Scale_Routing_Module { }

Any idea what I'm doing wrong?

EDIT: another clue - the Scale_Module is loaded in the network tab upon lazy loading. So, it's loading, it's just not displaying in the named outlet.


问:
Prevent CRLF text being converted to LF text when downloading file with HttpClient.GetStreamAsync
I want to download a file from Github and save it to a specific folder.

The code below works, but it converts the line endings in my file from CRLF to LF.

I want to keep the CRLF line endings.

When I download the file manually from Github, the file’s line endings remain as CRLF.

Here's my code for calling the text file:

string AlinktofileCM = destinationOnGithub + "mytext.txt";
string linktofileCM = destinationOnMyPc + "mytext.txt";

using (var client = new HttpClient())
{
    using (var s = client.GetStreamAsync(AlinktofileCM))
    {
        using (var fs = new FileStream(linktofileCM, FileMode.OpenOrCreate))
        {
            s.Result.CopyTo(fs);
        }
    }
}
```

All the solutions I have found are related to webclient, I don't want to use it!

Body:
I want to download a file from Github and save it to a specific folder.

The code below works, but it converts the line endings in my file from CRLF to LF.

I want to keep the CRLF line endings.

When I download the file manually from Github, the file’s line endings remain as CRLF.

Here's my code for calling the text file:

string AlinktofileCM = destinationOnGithub + "mytext.txt";
string linktofileCM = destinationOnMyPc + "mytext.txt";

using (var client = new HttpClient())
{
    using (var s = client.GetStreamAsync(AlinktofileCM))
    {
        using (var fs = new FileStream(linktofileCM, FileMode.OpenOrCreate))
        {
            s.Result.CopyTo(fs);
        }
    }
}

All the solutions I have found are related to webclient, I don't want to use it!


问:
how to write Matrix mlm spillover algorithm?
I wonder how to write a matrix spillover algorithm(C# or Nodejs).
this algorithm is used in marketing companies to incentivize customer.

the first levels of this matrix is easy and we can print it with a simple function, but as Matrix goes deeper, things gets hard.
here is my algorithm, but it only works until level 5, after that the structure goes wrong.

```<code>    var bigstep = total branches count of level / 3
    var smallstep = bigstep /3
    var middlestep = smallstep /3
    var headstep = middlestep /3
    var roll = every three user adds 1 to roll
    var round = every 3 rolls adds +1 round
    var totalround = every 3 round adds +1 totalround
    var place = 0 // when there is no room in tree branch, this place adds +1 and everythings resets
    // now everytime new roll adds up
    Next Branch = (smallstep*roll) + (middlestep*round) + (headstep*totalround) + place

    every time totalround is equal to 3, headstep/3
    also when round is 3 for first time, headstep = middlestep /3
</code>```

I've been on this for a long time, i'm not asking for doing homeworks but if you have any clue or article on how to solve this Matrix Structure, it would be useful.

here is a correct sample of first 5 levels.
as you can see, in every level, within each branch moving steps are broken by 3

Body:
I wonder how to write a matrix spillover algorithm(C# or Nodejs).
this algorithm is used in marketing companies to incentivize customer.

the first levels of this matrix is easy and we can print it with a simple function, but as Matrix goes deeper, things gets hard.
here is my algorithm, but it only works until level 5, after that the structure goes wrong.

    var bigstep = total branches count of level / 3
    var smallstep = bigstep /3
    var middlestep = smallstep /3
    var headstep = middlestep /3
    var roll = every three user adds 1 to roll
    var round = every 3 rolls adds +1 round
    var totalround = every 3 round adds +1 totalround
    var place = 0 // when there is no room in tree branch, this place adds +1 and everythings resets
    // now everytime new roll adds up
    Next Branch = (smallstep*roll) + (middlestep*round) + (headstep*totalround) + place

    every time totalround is equal to 3, headstep/3
    also when round is 3 for first time, headstep = middlestep /3

I've been on this for a long time, i'm not asking for doing homeworks but if you have any clue or article on how to solve this Matrix Structure, it would be useful.

here is a correct sample of first 5 levels.
as you can see, in every level, within each branch moving steps are broken by 3


问:
TypeScript, WebComponent - components deriving from different native elements, with custom base class
I just want to be able to have base custom class for components, but class for specific should deriving from specific hmtlelement.

Ideally, the solution to my problem would be as follows:

```<code>abstract class ComponentBase<TBase extends HTMLElement = HTMLElement> extends TBase {...}

class FirstComponent<HTMLDivElement> {...}
class SecondComponent<HTMLInputElement> {...}
</code>```

I tried to do it with mixins but didn't find a working solution. Also mixins can't have private/protected properties which would be very handy.

Maybe someone knows a better approach.

Body:
I just want to be able to have base custom class for components, but class for specific should deriving from specific hmtlelement.

Ideally, the solution to my problem would be as follows:

abstract class ComponentBase<TBase extends HTMLElement = HTMLElement> extends TBase {...}

class FirstComponent<HTMLDivElement> {...}
class SecondComponent<HTMLInputElement> {...}

I tried to do it with mixins but didn't find a working solution. Also mixins can't have private/protected properties which would be very handy.

Maybe someone knows a better approach.


问:
Use of Google Activity Recognition API
Have been trying to use Google Activity Recognition API, but until now, can't get a single result.

I have this function in Main Activity

```<code>private void requestTransactionsUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) !=
                PackageManager.PERMISSION_GRANTED) {
            return;
        }

        List transitions = new ArrayList<>();

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

        Intent intent = new Intent(ActivityTransitionReceiver.TRANSITION_ACTION_RECEIVER);
        mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        mTransitionsReceiver = new ActivityTransitionReceiver();
        registerReceiver(mTransitionsReceiver,
                new IntentFilter(ActivityTransitionReceiver.TRANSITION_ACTION_RECEIVER));

        Task<Void> task =
                ActivityRecognition.getClient(this)
                        .requestActivityTransitionUpdates(request, mPendingIntent);
        task.addOnSuccessListener(
                result -> {

                });
        task.addOnFailureListener(
                e -> {

                });

    }
</code>```

and created a Receiver class

```<code>public class ActivityTransitionReceiver extends BroadcastReceiver {

    public static final String TRANSITION_ACTION_RECEIVER =
            BuildConfig.APPLICATION_ID + "TRANSITION_ACTION_RECEIVER";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (TRANSITION_ACTION_RECEIVER == intent.getAction()) {
            Log.d("DetectActivityReceiver", "Received an unsupported action.");
            return;
        }

        if (ActivityTransitionResult.hasResult(intent)){
            ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
            for (ActivityTransitionEvent event : result.getTransitionEvents()){
                System.out.println(event.toString());
            }
        }
    }
}
</code>```

also added the receiver in Manifest.xml.

Expected to get the event in Receiver class, but didn't.

Title: Use of Google Activity Recognition API

Body:
Have been trying to use Google Activity Recognition API, but until now, can't get a single result.

I have this function in Main Activity

private void requestTransactionsUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) !=
                PackageManager.PERMISSION_GRANTED) {
            return;
        }

        List transitions = new ArrayList<>();

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                        .build());

        transitions.add(
                new ActivityTransition.Builder()
                        .setActivityType(DetectedActivity.WALKING)
                        .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                        .build());

        ActivityTransitionRequest request = new ActivityTransitionRequest(transitions);

        Intent intent = new Intent(ActivityTransitionReceiver.TRANSITION_ACTION_RECEIVER);
        mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        mTransitionsReceiver = new ActivityTransitionReceiver();
        registerReceiver(mTransitionsReceiver,
                new IntentFilter(ActivityTransitionReceiver.TRANSITION_ACTION_RECEIVER));

        Task<Void> task =
                ActivityRecognition.getClient(this)
                        .requestActivityTransitionUpdates(request, mPendingIntent);
        task.addOnSuccessListener(
                result -> {

                });
        task.addOnFailureListener(
                e -> {

                });

    }

and created a Receiver class

public class ActivityTransitionReceiver extends BroadcastReceiver {

    public static final String TRANSITION_ACTION_RECEIVER =
            BuildConfig.APPLICATION_ID + "TRANSITION_ACTION_RECEIVER";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (TRANSITION_ACTION_RECEIVER == intent.getAction()) {
            Log.d("DetectActivityReceiver", "Received an unsupported action.");
            return;
        }

        if (ActivityTransitionResult.hasResult(intent)){
            ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
            for (ActivityTransitionEvent event : result.getTransitionEvents()){
                System.out.println(event.toString());
            }
        }
    }
}

also added the receiver in Manifest.xml.

Expected to get the event in Receiver class, but didn't.


问:
What is the stucture of the elgato wavelink 1.6.2 websocket
I what to use the Wavelink WebSocket but because of the new version of Wavelink all SDKs are broken.

I already tried connecting to the WebSocket and what I found by doing this is that there are a few events that can be triggered by changing stuff in Wavelink.

Outputs

outputMuteChanged

outputVolumeChanged

selectedOutputChanged

Inputs

inputsChanged

inputMuteChanged

inputVolumeChanged

Filter

filterAdded

filterChanged

filterRemoved

But what I did not find out is what commands you can send.

I learned that you can see what commands are sent between the WebSocket and the client using Wireshark. The problem is that I don't have any device like the Elgato Stream Deck that sends Commands to the Wavelink Software.


问:
Error: Cannot find module when trying to find yarn --version. It thinks it's in anaconda3
I've installed yarn via npm through npm install --global yarn.

When I try to check the version it's looking for it in an anaconda3 related path which is weird. This conflicting path doesn't show up in the system or user environment variables. I checked for the correct path of yarn and it is in my user environment variables. So this conflicting path seems to be the issue?

I'm not sure how to address this because I believe there was some specific setup when initializing vscode to recognize anaconda.

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

Error: Cannot find module 'C:\Users\deerr\anaconda3\Library\c\Users\deerr\AppData\Roaming\npm\node_modules\yarn\bin\yarn.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
</code>```

Body:
I've installed yarn via npm through npm install --global yarn.

When I try to check the version it's looking for it in an anaconda3 related path which is weird. This conflicting path doesn't show up in the system or user environment variables. I checked for the correct path of yarn and it is in my user environment variables. So this conflicting path seems to be the issue?

I'm not sure how to address this because I believe there was some specific setup when initializing vscode to recognize anaconda.

$ yarn --version
node:internal/modules/cjs/loader:998
  throw err;
  ^

Error: Cannot find module 'C:\Users\deerr\anaconda3\Library\c\Users\deerr\AppData\Roaming\npm\node_modules\yarn\bin\yarn.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at Module._load (node:internal/modules/cjs/loader:841:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}


问:
Nginx TLS Passthrough (111: Connection refused) while connecting to upstream
What I am trying do is to configure NGINX to forward https requests to corresponding containers (by hostnames) running on the same machine with TLS passthrough so TLS termination will be done at the containers. As right now, I only have bw.domain.com

Here is my nginx config that I try to config:

```<code>stream {
    map $ssl_preread_server_name $name {
        bw.domain.com    bw;
    }

    upstream bw {
        server  127.0.0.1:4443;
    }

    server {
        listen  443;
        proxy_pass  $name;
        ssl_preread on;
    }
}
</code>```

Here is the nginx config generated by self-host bitwarden (upstream):

```<code>#######################################################################
# WARNING: This file is generated. Do not make changes to this file.  #
# They will be overwritten on update. You can manage various settings #
# used in this file from the ./bwdata/config.yml file for your        #
# installation.                                                       #
#######################################################################

server {
  listen 8080 default_server;
  listen [::]:8080 default_server;
  server_name bw.domain.com;

  return 301 https://bw.domain.com$request_uri;
}

server {
  listen 8443 ssl http2;
  listen [::]:8443 ssl http2;
  server_name bw.domain.com;

  ssl_certificate /etc/ssl/fullchain.pem;
  ssl_certificate_key /etc/ssl/privkey.pem;
  ssl_session_timeout 30m;
  ssl_session_cache shared:SSL:20m;
  ssl_session_tickets off;

  # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
  ssl_dhparam /etc/ssl/dhparam.pem;

  ssl_protocols TLSv1.2;
  ssl_ciphers "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256";
  # Enables server-side protection from BEAST attacks
  ssl_prefer_server_ciphers on;

  # OCSP Stapling ---
  # Fetch OCSP records from URL in ssl_certificate and cache them
  ssl_stapling on;
  ssl_stapling_verify on;

  # Verify chain of trust of OCSP response using Root CA and Intermediate certs
  ssl_trusted_certificate /etc/ssl/fullchain.pem;
  resolver 1.1.1.1 1.0.0.1 9.9.9.9 149.112.112.112 valid=300s;

  include /etc/nginx/security-headers-ssl.conf;
  include /etc/nginx/security-headers.conf;

  location / {
    proxy_pass http://web:5000/;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://haveibeenpwned.com https://www.gravatar.com; child-src 'self' https://*.duosecurity.com https://*.duofederal.com; frame-src 'self' https://*.duosecurity.com https://*.duofederal.com; connect-src 'self' wss://bw.domain.com https://api.pwnedpasswords.com https://2fa.directory; object-src 'self' blob:;";
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Robots-Tag "noindex, nofollow";
  }

  location /alive {
    return 200 'alive';
    add_header Content-Type text/plain;
  }

  location = /app-id.json {
    proxy_pass http://web:5000/app-id.json;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    proxy_hide_header Content-Type;
    add_header Content-Type $fido_content_type;
  }

  location = /duo-connector.html {
    proxy_pass http://web:5000/duo-connector.html;
  }

  location = /webauthn-connector.html {
    proxy_pass http://web:5000/webauthn-connector.html;
  }

  location = /webauthn-fallback-connector.html {
    proxy_pass http://web:5000/webauthn-fallback-connector.html;
  }

  location = /sso-connector.html {
    proxy_pass http://web:5000/sso-connector.html;
  }

  location /attachments/ {
    proxy_pass http://attachments:5000/;
  }

  location /api/ {
    proxy_pass http://api:5000/;
  }

  location /icons/ {
    proxy_pass http://icons:5000/;
  }

  location /notifications/ {
    proxy_pass http://notifications:5000/;
  }

  location /notifications/hub {
    proxy_pass http://notifications:5000/hub;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
  }

  location /events/ {
    proxy_pass http://events:5000/;
  }

  location /sso {
    proxy_pass http://sso:5000;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header X-Frame-Options SAMEORIGIN;
  }

  location /identity {
    proxy_pass http://identity:5000;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header X-Frame-Options SAMEORIGIN;
  }

  location /admin {
    proxy_pass http://admin:5000;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header X-Frame-Options SAMEORIGIN;
  }

}
</code>```

Right now, it throws this error when I use Firefox:

Secure Connection Failed

An error occurred during a connection to bw.domain.com.
PR_END_OF_FILE_ERROR

Error code: PR_END_OF_FILE_ERROR

Here is the logs of the NGINX

2023/01/07 23:09:37 [error] 28#28: *1 connect() failed (111:
Connection refused) while connecting to upstream, client: 172.16.1.1,
server: 0.0.0.0:443, upstream: "127.0.0.1:4443", bytes from/to
client:0/0, bytes from/to upstream:0/0

Body:
What I am trying do is to configure NGINX to forward https requests to corresponding containers (by hostnames) running on the same machine with TLS passthrough so TLS termination will be done at the containers. As right now, I only have bw.domain.com

Here is my nginx config that I try to config:

stream {
    map $ssl_preread_server_name $name {
        bw.domain.com    bw;
    }

    upstream bw {
        server  127.0.0.1:4443;
    }

    server {
        listen  443;
        proxy_pass  $name;
        ssl_preread on;
    }
}

Here is the nginx config generated by self-host bitwarden (upstream):

#######################################################################
# WARNING: This file is generated. Do not make changes to this file.  #
# They will be overwritten on update. You can manage various settings #
# used in this file from the ./bwdata/config.yml file for your        #
# installation.                                                       #
#######################################################################

server {
  listen 8080 default_server;
  listen [::]:8080 default_server;
  server_name bw.domain.com;

  return 301 https://bw.domain.com$request_uri;
}

server {
  listen 8443 ssl http2;
  listen [::]:8443 ssl http2;
  server_name bw.domain.com;

  ssl_certificate /etc/ssl/fullchain.pem;
  ssl_certificate_key /etc/ssl/privkey.pem;
  ssl_session_timeout 30m;
  ssl_session_cache shared:SSL:20m;
  ssl_session_tickets off;

  # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
  ssl_dhparam /etc/ssl/dhparam.pem;

  ssl_protocols TLSv1.2;
  ssl_ciphers "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256";
  # Enables server-side protection from BEAST attacks
  ssl_prefer_server_ciphers on;

  # OCSP Stapling ---
  # Fetch OCSP records from URL in ssl_certificate and cache them
  ssl_stapling on;
  ssl_stapling_verify on;

  # Verify chain of trust of OCSP response using Root CA and Intermediate certs
  ssl_trusted_certificate /etc/ssl/fullchain.pem;
  resolver 1.1.1.1 1.0.0.1 9.9.9.9 149.112.112.112 valid=300s;

  include /etc/nginx/security-headers-ssl.conf;
  include /etc/nginx/security-headers.conf;

  location / {
    proxy_pass http://web:5000/;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://haveibeenpwned.com https://www.gravatar.com; child-src 'self' https://*.duosecurity.com https://*.duofederal.com; frame-src 'self' https://*.duosecurity.com https://*.duofederal.com; connect-src 'self' wss://bw.domain.com https://api.pwnedpasswords.com https://2fa.directory; object-src 'self' blob:;";
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Robots-Tag "noindex, nofollow";
  }

  location /alive {
    return 200 'alive';
    add_header Content-Type text/plain;
  }

  location = /app-id.json {
    proxy_pass http://web:5000/app-id.json;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    proxy_hide_header Content-Type;
    add_header Content-Type $fido_content_type;
  }

  location = /duo-connector.html {
    proxy_pass http://web:5000/duo-connector.html;
  }

  location = /webauthn-connector.html {
    proxy_pass http://web:5000/webauthn-connector.html;
  }

  location = /webauthn-fallback-connector.html {
    proxy_pass http://web:5000/webauthn-fallback-connector.html;
  }

  location = /sso-connector.html {
    proxy_pass http://web:5000/sso-connector.html;
  }

  location /attachments/ {
    proxy_pass http://attachments:5000/;
  }

  location /api/ {
    proxy_pass http://api:5000/;
  }

  location /icons/ {
    proxy_pass http://icons:5000/;
  }

  location /notifications/ {
    proxy_pass http://notifications:5000/;
  }

  location /notifications/hub {
    proxy_pass http://notifications:5000/hub;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
  }

  location /events/ {
    proxy_pass http://events:5000/;
  }

  location /sso {
    proxy_pass http://sso:5000;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header X-Frame-Options SAMEORIGIN;
  }

  location /identity {
    proxy_pass http://identity:5000;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header X-Frame-Options SAMEORIGIN;
  }

  location /admin {
    proxy_pass http://admin:5000;
    include /etc/nginx/security-headers-ssl.conf;
    include /etc/nginx/security-headers.conf;
    add_header X-Frame-Options SAMEORIGIN;
  }

}

Right now, it throws this error when I use Firefox:

Secure Connection Failed

An error occurred during a connection to bw.domain.com.
PR_END_OF_FILE_ERROR

Error code: PR_END_OF_FILE_ERROR

Here is the logs of the NGINX

2023/01/07 23:09:37 [error] 28#28: *1 connect() failed (111:
Connection refused) while connecting to upstream, client: 172.16.1.1,
server: 0.0.0.0:443, upstream: "127.0.0.1:4443", bytes from/to
client:0/0, bytes from/to upstream:0/0


问:
What wont this simple functional component example work?
I have this React child component....

```<code>const MainLink = ({linkText}) => {

  return (
    <h1>{linkText}</h1>
  )
}
export default MainLink
</code>```

I have this Parent component that calls the child component...

```<code>import MainLink from "./MainLink"
const MainLinks = () => {

    return (
        <>
        <MainLink key='1' linkText={"Home"}/>
        <MainLink key='2' linkText="Home"/>
        </>
    )
  }
  export default MainLinks

</code>```

I can't seem to pass any value for "linkText" to the child component. It always comes up

{linkText: undefined}

and the output is

I thought one of these would work. What am I missing here?

Body:
I have this React child component....

const MainLink = ({linkText}) => {

  return (

{linkText}

  )
}
export default MainLink

I have this Parent component that calls the child component...

import MainLink from "./MainLink"
const MainLinks = () => {

    return (
        <>
        <MainLink key='1' linkText={"Home"}/>
        <MainLink key='2' linkText="Home"/>
        </>
    )
  }
  export default MainLinks

I can't seem to pass any value for "linkText" to the child component. It always comes up

{linkText: undefined}

and the output is

I thought one of these would work. What am I missing here?


问:
Apple Contacts share box doesn't show my app when exporting a vCard
I've added the support for vCard vcf in my info.plist.

If I save a vCard, say in iCloud drive, then tap on the share button, a box appears with my app icon, and I can easily import the vCard. Perfect.

However, like 90% of the time, people will want to share a contact card directly from the native Apple Contacts app to mine (without saving the vCard somewhere first).

My problem is that specifically with the Apple Contacts App, my app doesn't show in the sharing box.

Do you know why? Is it because at this stage the vCard has not been created yet? If so, what UTTypeIdentifier should I use?

Here is my info.plist:

```<code><key>CFBundleDocumentTypes</key>
           <array>
               <dict>
                   <key>CFBundleTypeExtensions</key>
                   <array>
                       <string>vcf</string>
                   </array>
                   <key>CFBundleTypeIconFile</key>
                   <string>app.icns</string>
                   <key>CFBundleTypeName</key>
                   <string>public.vcard</string>
                   <key>CFBundleTypeRole</key>
                   <string>Viewer</string>
                   <key>LSHandlerRank</key>
                   <string>Alternate</string>
                   <key>LSItemContentTypes</key>
                   <array>
                       <string>public.vcard</string>
                   </array>
               </dict>
           </array>
           <key>LSRequiresIPhoneOS</key>
           <true/>
           <key>LSSupportsOpeningDocumentsInPlace</key>
           <true/>
           <key>UTImportedTypeDeclarations</key>
           <array>
               <dict>
                   <key>UTTypeConformsTo</key>
                   <array>
                       <string>public.data</string>
                   </array>
                   <key>UTTypeIdentifier</key>
                   <string>public.vcard</string>
                   <key>UTTypeTagSpecification</key>
                   <dict>
                       <key>com.apple.ostype</key>
                       <string>VCF</string>
                       <key>public.filename-extension</key>
                       <array>
                           <string>vcf</string>
                       </array>
                       <key>public.mime-type</key>
                       <string>text/x-vcard</string>
                   </dict>
               </dict>
           </array>
</code>```

Tried to dig into Apple's doc https://developer.apple.com/documentation/uniformtypeidentifiers/uttypecontact but nothing about how to solve my problem.

Body:
I've added the support for vCard vcf in my info.plist.

If I save a vCard, say in iCloud drive, then tap on the share button, a box appears with my app icon, and I can easily import the vCard. Perfect.

However, like 90% of the time, people will want to share a contact card directly from the native Apple Contacts app to mine (without saving the vCard somewhere first).

My problem is that specifically with the Apple Contacts App, my app doesn't show in the sharing box.

Do you know why? Is it because at this stage the vCard has not been created yet? If so, what UTTypeIdentifier should I use?

Here is my info.plist:

<key>CFBundleDocumentTypes</key>
           <array>
               <dict>
                   <key>CFBundleTypeExtensions</key>
                   <array>
                       <string>vcf</string>
                   </array>
                   <key>CFBundleTypeIconFile</key>
                   <string>app.icns</string>
                   <key>CFBundleTypeName</key>
                   <string>public.vcard</string>
                   <key>CFBundleTypeRole</key>
                   <string>Viewer</string>
                   <key>LSHandlerRank</key>
                   <string>Alternate</string>
                   <key>LSItemContentTypes</key>
                   <array>
                       <string>public.vcard</string>
                   </array>
               </dict>
           </array>
           <key>LSRequiresIPhoneOS</key>
           <true/>
           <key>LSSupportsOpeningDocumentsInPlace</key>
           <true/>
           <key>UTImportedTypeDeclarations</key>
           <array>
               <dict>
                   <key>UTTypeConformsTo</key>
                   <array>
                       <string>public.data</string>
                   </array>
                   <key>UTTypeIdentifier</key>
                   <string>public.vcard</string>
                   <key>UTTypeTagSpecification</key>
                   <dict>
                       <key>com.apple.ostype</key>
                       <string>VCF</string>
                       <key>public.filename-extension</key>
                       <array>
                           <string>vcf</string>
                       </array>
                       <key>public.mime-type</key>
                       <string>text/x-vcard</string>
                   </dict>
               </dict>
           </array>

Tried to dig into Apple's doc https://developer.apple.com/documentation/uniformtypeidentifiers/uttypecontact but nothing about how to solve my problem.


问:
Running the AppBundle from Xcode crashes, but succeeds when run from Terminal
I wrote a program in C++/wxWidgets, and it is successfully building inside my Mac laptop. The program consists of 1 main executable and a couple of dylibs as well as wxWidgets.

I also made a script that after the build succeeds, copies ALL dylibs and resources inside the AppBundle. The script also executes fine and succeeds.

I'm building both wxWidgets and the application on OSX 10.13.6 with Xcode 9.4.1.

Then I tried to run the application from the Terminal by doing "open myapp.app" and it executed fine. No issues, no crashes.

Then I tried to go back to Xcode and tried run the program by pressing "Command" + R. The program starts, but then crashes when I hit the button at the toolbar which needs to lad one of my dylibs. As said - the same thing executed fine when I run the program from the Terminal.

Next, I enabled the Debug Console inside Xcode and tried to run the program again from Xcode. When I get the crash I inspected the content of such Console and I saw couple of messages like:

```<code>2023-01-06 18:25:48.403647-0600 dbhandler[34132:2466387] dynamic_cast error 1: Both of the following type_info's should have public visibility.  At least one of them is hidden. 8wxWindow, 12DatabaseType.
</code>```

wxWindow is a class from wxWidgets and DatabaseType - is a class inside the dylib that is public. However it is declared/defined in 2 big cpp/h files alone with some other classes.

Those classes are part of the Wizard-like window.

I am not sure what to do from here. Searching the SO for that message gave me that its possible the program is using multiple versions of the same library. This is not the case here, because the program executes from the Terminal successfully.

Can anyone offer a suggestion of what to do here?

The program is not designed for iPhone/iPad - it is Desktop software.

P.S.: I have a complete log from the Console, however, it's too big to post here. So I'm just looking for a suggestion on how to approach such crashes.

Body:
I wrote a program in C++/wxWidgets, and it is successfully building inside my Mac laptop. The program consists of 1 main executable and a couple of dylibs as well as wxWidgets.

I also made a script that after the build succeeds, copies ALL dylibs and resources inside the AppBundle. The script also executes fine and succeeds.

I'm building both wxWidgets and the application on OSX 10.13.6 with Xcode 9.4.1.

Then I tried to run the application from the Terminal by doing "open myapp.app" and it executed fine. No issues, no crashes.

Then I tried to go back to Xcode and tried run the program by pressing "Command" + R. The program starts, but then crashes when I hit the button at the toolbar which needs to lad one of my dylibs. As said - the same thing executed fine when I run the program from the Terminal.

Next, I enabled the Debug Console inside Xcode and tried to run the program again from Xcode. When I get the crash I inspected the content of such Console and I saw couple of messages like:

2023-01-06 18:25:48.403647-0600 dbhandler[34132:2466387] dynamic_cast error 1: Both of the following type_info's should have public visibility.  At least one of them is hidden. 8wxWindow, 12DatabaseType.

wxWindow is a class from wxWidgets and DatabaseType - is a class inside the dylib that is public. However it is declared/defined in 2 big cpp/h files alone with some other classes.

Those classes are part of the Wizard-like window.

I am not sure what to do from here. Searching the SO for that message gave me that its possible the program is using multiple versions of the same library. This is not the case here, because the program executes from the Terminal successfully.

Can anyone offer a suggestion of what to do here?

The program is not designed for iPhone/iPad - it is Desktop software.

P.S.: I have a complete log from the Console, however, it's too big to post here. So I'm just looking for a suggestion on how to approach such crashes.


问:
How do I connect my .NET API to my react native mobile API
While building an ecommerce I decided to write the backend where I keep all my products in C# using the .NET API. I connected the back-end & front-end with CORS:

```<code>app.UseCors(opt =>
{
    opt.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins("http://localhost:19006");
});
</code>```

I use fetch API & React Native on the  client side to receive the products

```<code>useEffect(() => {
  fetch('http://localhost:5000/api/products')
      .then(response => response.json())
      .then(data => setProducts(data))
}, [])
</code>```

When I enter npm expo start --web in the terminal, I can see that I'm successful. The problem occurs when I run the same app on my phone using regular npm start & connecting my phone to expo. I don't get the products from the app, I get this error:

I believe this is happening because it is no longer running on localhost, it says it's running on exp://127.0.0.1:19002 . The problem is I have no idea how to connect to that. Some help would be really appreciated.

Body:
While building an ecommerce I decided to write the backend where I keep all my products in C# using the .NET API. I connected the back-end & front-end with CORS:

app.UseCors(opt =>
{
    opt.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins("http://localhost:19006");
});

I use fetch API & React Native on the  client side to receive the products

useEffect(() => {
  fetch('http://localhost:5000/api/products')
      .then(response => response.json())
      .then(data => setProducts(data))
}, [])

When I enter npm expo start --web in the terminal, I can see that I'm successful. The problem occurs when I run the same app on my phone using regular npm start & connecting my phone to expo. I don't get the products from the app, I get this error:

I believe this is happening because it is no longer running on localhost, it says it's running on exp://127.0.0.1:19002 . The problem is I have no idea how to connect to that. Some help would be really appreciated.


问:
Calling my API Key from server side and declaring it a global variable on client side
I am trying to hide my paystack API key from being editable on the client side. I have JSON string it but it just won't work. The paystack function doesn't recognize the data received. I hope someone can put me through on this. Below are the client and server side codes. I hope to also learn how to parse a global variable to client side the correct way.

CLIENT SIDE JS

```<code><script>

const paymentForm = document.getElementById('paymentForm');
function getPaystackKey(){
  google.script.run.withSuccessHandler(payWithPaystack, data => {
    const parsedData = JSON.parse(data)
    const liveKey = parsedData.values.liveKey
    const testKey = parsedData.values.testKey
    const tester = parsedData.tester
  }).withFailureHandler(er => {
    // alert("fail")
    //alert(er)
  }).getDataFromSpreadsheet()
    //do onload work
}
if(window.addEventListener) {
    window.addEventListener('submit',payWithPaystack,false); //W3C
} else {
    window.attachEvent('onload',payWithPaystack); //IE
}

function payWithPaystack(e, parsedData) {
  e.preventDefault();
    const liveKey = parsedData.values.liveKey
    const testKey = parsedData.values.testKey
    const tester = parsedData.tester

  let handler = PaystackPop.setup({
    key: testKey // Replace with your public key
    email: document.getElementById("email").value,
    amount: document.getElementById("totalAmount").value * 100,
    ref: document.getElementById("reference").value,
    //ref: ''+Math.floor((Math.random() * 1000000000) + 1), // generates a pseudo-unique reference. Please replace with a reference you generated. Or remove the line entirely so our API will generate one for you
    // label: "Optional string that replaces customer email"
    onClose: function(){
      alert('Window closed.');
      document.getElementById("paymentForm").reset();
    },
    callback: function(response){
      let message = 'Payment complete! Reference: ' + response.reference;
      alert(message);
      document.getElementById("paymentForm").reset();
    }
  });

  handler.openIframe();
}

</script>
</code>```

SERVER SIDE JS

```<code>function getDataFromSpreadsheet(){
  const ss= SpreadsheetApp.openByUrl(url);
  const ws = ss.getSheetByName("PRIVATE");
  const liveKey = ws.getRange("A2").getValue()
  const testKey = ws.getRange("B2").getValue()
  const tester = "'pk_test_70366345d1f9ef32f81b6449'"
  Logger.log(tester);

  return JSON.stringify({tester: tester ,values: {liveKey: liveKey, testKey: testKey}})
};
</code>```

Body:
I am trying to hide my paystack API key from being editable on the client side. I have JSON string it but it just won't work. The paystack function doesn't recognize the data received. I hope someone can put me through on this. Below are the client and server side codes. I hope to also learn how to parse a global variable to client side the correct way.

CLIENT SIDE JS

SERVER SIDE JS

function getDataFromSpreadsheet(){
  const ss= SpreadsheetApp.openByUrl(url);
  const ws = ss.getSheetByName("PRIVATE");
  const liveKey = ws.getRange("A2").getValue()
  const testKey = ws.getRange("B2").getValue()
  const tester = "'pk_test_70366345d1f9ef32f81b6449'"
  Logger.log(tester);

  return JSON.stringify({tester: tester ,values: {liveKey: liveKey, testKey: testKey}})
};


问:
console.log does not show in Backend when trying to use Vercel/Railway?
This is my code structure:

First, I want to say that my code works locally, it only causes problems why I try to deploy on Vercel or Railway.
Backend --> first sends user to login page --> goes back to backend to /authorize, then is sent to /callback --> sends user to dashboard.html.

I have an interesting issue where the user ALWAYS MAKES IT to the dashboard.html, but NONE of the console.log in the backend are shown? Even the two console.log right before the last line of code which sends user to dashboard.html.

I have no idea why NO console.log show up???? I have a few in the FRONTEND that ALWAYS show up????? No idea why

I have this piece of backend code:

```<code>//authorize the user by getting a code
app.get("/authorize", (req, res) => {
console.log("poopy");
  var auth_query_parameters = new URLSearchParams({
    response_type: "code",
    client_id: client_id,
    scope: "user-top-read",
    redirect_uri: redirect_uri,
  });

  res.redirect(
    "https://accounts.spotify.com/authorize?" + auth_query_parameters.toString()
  );

});

app.get("/callback", (req, res) => {
  const code = req.query.code; //this is from url
  console.log(code);
  console.log("ops");

  var body = new URLSearchParams({
    code: code,
    redirect_uri: redirect_uri,
    grant_type: "authorization_code",
  });
  console.log(client_id + "client id");
  console.log(client_secret + "client secret");
  request.post({
    url: "https://accounts.spotify.com/api/token",
    form: body,
    headers: {
      "Content-type": "application/x-www-form-urlencoded",
      "Authorization":
        "Basic " +
        Buffer.from(client_id + ":" + client_secret).toString("base64"),
    }
    // json: true
  },
  (error, response, body) => {
      const data = JSON.parse(body);
      global.access_token = data.access_token;
      console.log(data + "data");
      console.log(global.access_token  + "access token");

      res.sendFile(path.join(__dirname, "frontend", "dashboard.html"));
  });
});
</code>```

Tried debugging, but never got anywhere? The console when I inspect just doesn't show any of the console.log

Body:
This is my code structure:

First, I want to say that my code works locally, it only causes problems why I try to deploy on Vercel or Railway.
Backend --> first sends user to login page --> goes back to backend to /authorize, then is sent to /callback --> sends user to dashboard.html.

I have an interesting issue where the user ALWAYS MAKES IT to the dashboard.html, but NONE of the console.log in the backend are shown? Even the two console.log right before the last line of code which sends user to dashboard.html.

I have no idea why NO console.log show up???? I have a few in the FRONTEND that ALWAYS show up????? No idea why

I have this piece of backend code:

//authorize the user by getting a code
app.get("/authorize", (req, res) => {
console.log("poopy");
  var auth_query_parameters = new URLSearchParams({
    response_type: "code",
    client_id: client_id,
    scope: "user-top-read",
    redirect_uri: redirect_uri,
  });

  res.redirect(
    "https://accounts.spotify.com/authorize?" + auth_query_parameters.toString()
  );

});

app.get("/callback", (req, res) => {
  const code = req.query.code; //this is from url
  console.log(code);
  console.log("ops");

  var body = new URLSearchParams({
    code: code,
    redirect_uri: redirect_uri,
    grant_type: "authorization_code",
  });
  console.log(client_id + "client id");
  console.log(client_secret + "client secret");
  request.post({
    url: "https://accounts.spotify.com/api/token",
    form: body,
    headers: {
      "Content-type": "application/x-www-form-urlencoded",
      "Authorization":
        "Basic " +
        Buffer.from(client_id + ":" + client_secret).toString("base64"),
    }
    // json: true
  },
  (error, response, body) => {
      const data = JSON.parse(body);
      global.access_token = data.access_token;
      console.log(data + "data");
      console.log(global.access_token  + "access token");

      res.sendFile(path.join(__dirname, "frontend", "dashboard.html"));
  });
});

Tried debugging, but never got anywhere? The console when I inspect just doesn't show any of the console.log


问:
Use the same instance of Object0 in different methods of Object1?
I'm trying to make a program that uses Robot but want to be able to set some parameters for that instance to use (delay between actions) every time it is used by the methods but cannot seem to figure it out.

```<code>import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.*;
import org.sikuli.script.*;

public class Functions {
    static Robot robot;
    static Screen screen;

    public static void main(String[] args) throws Exception, IOException, AWTException, InterruptedException {
        Robot robot = new Robot();
        robot.setAutoDelay(50);
    }

    public static void build(Monkey monkey) throws Exception {
        robot.mouseMove(monkey.getX(), monkey.getY());
        robot.getAutoDelay();
    }
}
</code>```

I've tried having

```<code>Robot robot = new Robot();
robot.setAutoDelay(50);
</code>```

in the build method but then I would need to assign a new Robot for every method (I assume). Is there another way?

Body:
I'm trying to make a program that uses Robot but want to be able to set some parameters for that instance to use (delay between actions) every time it is used by the methods but cannot seem to figure it out.

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.*;
import org.sikuli.script.*;

public class Functions {
    static Robot robot;
    static Screen screen;

    public static void main(String[] args) throws Exception, IOException, AWTException, InterruptedException {
        Robot robot = new Robot();
        robot.setAutoDelay(50);
    }

    public static void build(Monkey monkey) throws Exception {
        robot.mouseMove(monkey.getX(), monkey.getY());
        robot.getAutoDelay();
    }
}

I've tried having

Robot robot = new Robot();
robot.setAutoDelay(50);

in the build method but then I would need to assign a new Robot for every method (I assume). Is there another way?


问:
PyTorch Dataloader ignores FOR loop
I have a custom Pytorch dataset and its corresponding dataloader. However, when I iterate over the dataloader, it seems like it skips the loop entirely. I have checked that the length of the dataloader is not 0.

I have a custom dataset which only given a folder lists all the images in the folder, and then returns the image and the filepath each time it is called.

```<code>class BBoxDataset(Dataset):

    def __init__(self, path_list):
        super().__init__()

        self.img_dirs = path_list
        self.update_img_paths()

    def update_img_paths(self):
        self.img_paths = []
        for img_dir in self.img_dirs:
            files = glob.glob(os.path.join(img_dir, "*.jpg"))
            for file in files:
                self.img_paths.append(file)

    def __len__(self):
        return len(self.img_paths)

    def __getitem__(self, idx):
        filepath = self.img_paths[idx]
        img = Image.open(filepath).convert("RGB")
        return img, filepath
</code>```

I have created a custom dataloader for the same and a function to return the constructed dataloader.

```<code>def get_dataloader(image_paths, batch_size: int, shuffle: bool = dataset_settings.random_shuffle,
                    num_workers: int = 0, phase: str = 'infer', sampler: Sampler = None) -> None:
    dataset = BBoxDataset(path_list=image_paths)
    drop_last = False if phase == 'infer' else True
    shuffle = False if phase == 'infer' else True
    kwargs_dl = dict(num_workers=num_workers, batch_size=batch_size, pin_memory=True, shuffle=shuffle, drop_last=drop_last, sampler=sampler)
    if sampler is not None:
        kwargs_dl['sampler'] = sampler(dataset, shuffle=shuffle)
        del kwargs_dl['shuffle']
    dataloader = DataLoader(dataset, **kwargs_dl)
    return dataloader
</code>```

However, when I import the try to loop through the dataloader, it does not even enter the loop. In my case, the "MLN" is not printed, neither is the data from the batch.

```<code>infer_dataloader = get_dataloader(dataset_path, batch_size=1)
for batch, batch_data in enumerate(infer_dataloader):
    print("MLN")
    image, filepath = batch_data
    print(image, filepath)
</code>```

I am not sure where I am going wrong. Can anyone help?

Title: PyTorch Dataloader ignores FOR loop

Body:
I have a custom Pytorch dataset and its corresponding dataloader. However, when I iterate over the dataloader, it seems like it skips the loop entirely. I have checked that the length of the dataloader is not 0.

I have a custom dataset which only given a folder lists all the images in the folder, and then returns the image and the filepath each time it is called.

class BBoxDataset(Dataset):

    def __init__(self, path_list):
        super().__init__()

        self.img_dirs = path_list
        self.update_img_paths()

    def update_img_paths(self):
        self.img_paths = []
        for img_dir in self.img_dirs:
            files = glob.glob(os.path.join(img_dir, "*.jpg"))
            for file in files:
                self.img_paths.append(file)

    def __len__(self):
        return len(self.img_paths)

    def __getitem__(self, idx):
        filepath = self.img_paths[idx]
        img = Image.open(filepath).convert("RGB")
        return img, filepath

I have created a custom dataloader for the same and a function to return the constructed dataloader.

def get_dataloader(image_paths, batch_size: int, shuffle: bool = dataset_settings.random_shuffle,
                    num_workers: int = 0, phase: str = 'infer', sampler: Sampler = None) -> None:
    dataset = BBoxDataset(path_list=image_paths)
    drop_last = False if phase == 'infer' else True
    shuffle = False if phase == 'infer' else True
    kwargs_dl = dict(num_workers=num_workers, batch_size=batch_size, pin_memory=True, shuffle=shuffle, drop_last=drop_last, sampler=sampler)
    if sampler is not None:
        kwargs_dl['sampler'] = sampler(dataset, shuffle=shuffle)
        del kwargs_dl['shuffle']
    dataloader = DataLoader(dataset, **kwargs_dl)
    return dataloader

However, when I import the try to loop through the dataloader, it does not even enter the loop. In my case, the "MLN" is not printed, neither is the data from the batch.

infer_dataloader = get_dataloader(dataset_path, batch_size=1)
for batch, batch_data in enumerate(infer_dataloader):
    print("MLN")
    image, filepath = batch_data
    print(image, filepath)

I am not sure where I am going wrong. Can anyone help?


问:
Find all nodes up to distance K from target node
I have an undirected, acyclic graph with N nodes and N-1 edges. I have a function where I get a node, A. I need to update all nodes which are at distance D or less away from A (for example, if D is 2, I need to update all nodes which can be reached from A in at most 2 edges). As updating a node changes the value of the node, I also need to make sure that I only update each node once.

Currently, I'm doing this with a recursive function and an adjacency list. However, once N starts to get bigger than 1000 (I need to do this function several times) it becomes too slow (since the whole program needs to run in under 4 seconds and there are several calls to update different sets of nodes). Is there a different way to do this?

My current recursive function in C++:

```<code>void update(int parent_node, int current_node, int dist) {
    update the node

    if (dist == 0) return;
    dist--;
    for (int next_node : adjList[current_node]) {
        if (next_node == parent_node) continue;
        update(current_node, next_node, dist);
    }
}
</code>```

Body:
I have an undirected, acyclic graph with N nodes and N-1 edges. I have a function where I get a node, A. I need to update all nodes which are at distance D or less away from A (for example, if D is 2, I need to update all nodes which can be reached from A in at most 2 edges). As updating a node changes the value of the node, I also need to make sure that I only update each node once.

Currently, I'm doing this with a recursive function and an adjacency list. However, once N starts to get bigger than 1000 (I need to do this function several times) it becomes too slow (since the whole program needs to run in under 4 seconds and there are several calls to update different sets of nodes). Is there a different way to do this?

My current recursive function in C++:

void update(int parent_node, int current_node, int dist) {
    update the node

    if (dist == 0) return;
    dist--;
    for (int next_node : adjList[current_node]) {
        if (next_node == parent_node) continue;
        update(current_node, next_node, dist);
    }
}


问:
Bar plot and line plot shifts away from each other when using twinx()
I am dealing a CDF4 data using xarray to open it. I want to plot a line and a bar in just one figure, so I used twinx(). The problem is the xticks of the line and bar plot are not matched to each other. The xticks of the line plot is shifted one unit (one month) to the right when compared to those of the bar plot.

```<code>ERA5_land = xr.open('Era5landmon2001_2021nc.sec')

prec = ERA5_land.tp.groupby('time.month').sum().sel(longitude = 8.4, latitude = 49) #calculate the sum of precipitation at (49, 8.4)
temp = ERA5_land.t2m.groupby('time.month').mean().sel(longitude = 8.4, latitude = 49) #calculate the mean of temperature at (49, 8.4)

f,ax1 = plt.subplots()
prec.to_series().plot.bar(ax = ax1,)

ax2 = ax1.twinx()
temp.plot( ax = ax2)

</code>```

The data can be downloaded from here: ERA5-Land hourly data from 1950 to present. The variables are '2m temperature' and 'total precipitation', measured from 2001 to 2021. All the 12 months in a year were taken into account.

My result:
Time shift of the line plot

I tried to set ax2.set_xticks(ticks = ax1.get_xticks() and ax2.set_xticks(ticks = range(1,13) but nothing was success.

```<code>f,ax1 = plt.subplots()
prec.to_series().plot.bar(ax = ax1)

ax2 = ax1.twinx()
a2.set_xticks(ticks = ax1.get_xticks())
temp.plot( ax = ax2)
</code>```

I also know that the xticks of the two plots are different, but I don't know to do match them.

Body:
I am dealing a CDF4 data using xarray to open it. I want to plot a line and a bar in just one figure, so I used twinx(). The problem is the xticks of the line and bar plot are not matched to each other. The xticks of the line plot is shifted one unit (one month) to the right when compared to those of the bar plot.

ERA5_land = xr.open('Era5landmon2001_2021nc.sec')

prec = ERA5_land.tp.groupby('time.month').sum().sel(longitude = 8.4, latitude = 49) #calculate the sum of precipitation at (49, 8.4)
temp = ERA5_land.t2m.groupby('time.month').mean().sel(longitude = 8.4, latitude = 49) #calculate the mean of temperature at (49, 8.4)

f,ax1 = plt.subplots()
prec.to_series().plot.bar(ax = ax1,)

ax2 = ax1.twinx()
temp.plot( ax = ax2)

The data can be downloaded from here: ERA5-Land hourly data from 1950 to present. The variables are '2m temperature' and 'total precipitation', measured from 2001 to 2021. All the 12 months in a year were taken into account.

My result:
Time shift of the line plot

I tried to set ax2.set_xticks(ticks = ax1.get_xticks() and ax2.set_xticks(ticks = range(1,13) but nothing was success.

f,ax1 = plt.subplots()
prec.to_series().plot.bar(ax = ax1)

ax2 = ax1.twinx()
a2.set_xticks(ticks = ax1.get_xticks())
temp.plot( ax = ax2)

I also know that the xticks of the two plots are different, but I don't know to do match them.


问:
NetCDF variable extraction at specific coordinates using arrays does not work - python
I am trying to extract two variables values of a netCDF file at specific coordinates. From what I have seen from various posts on StackOverflow, the best way to achieve that is to work with arrays.

I have tried to use this method but it does not work and I am struggling finding out why.

The code I used is the following:

import xarray as xr
file = "input.nc"
lon=24.2
lat=17.8

da = xr.open_dataset(file)
ts = da.sel(lon=lon, lat=lat, method="nearest")   #I also tried da["variable1"].sel(lon=lon, lat=lat, method="nearest") but same outcome.
```
<p>But it raised this error:</p>
```KeyError: 'lon is not a valid dimension or coordinate'
```
<p>I then tried to set lon and lat as coordinates (<code>da.set_coords(("lat", "lon"))</code>) but it still raised an error:</p>
```KeyError: 'no index found for coordinate lon'
```
<p>I have very rarely worked with arrays so I don't understand what is wrong here. Here are more details of my netCDF:</p>
```xarray.Dataset
Dimensions: south_north: 63, west_east: 69, vcoord_dim: 8, Time: 25, bottom_top: 8
Coordinates: (0)  # For some reasons lon and lat are Data variables and not Coordinates in this netCDF.
Data variables: (216)
```

I also tried a more mannual extraction method (validated answer here) but it gave an index value way out of bound for the j that I can also not explain.

So, to summarize, what I want is extract the values of some Data variables at specific lon/lat values for all the timesteps of the netCDF.

I looked everywhere for answers but nothing helped me understand what was wrong. Any tips and advices would be greatly appreciated.

Body:
I am trying to extract two variables values of a netCDF file at specific coordinates. From what I have seen from various posts on StackOverflow, the best way to achieve that is to work with arrays.

I have tried to use this method but it does not work and I am struggling finding out why.

The code I used is the following:

import xarray as xr
file = "input.nc"
lon=24.2
lat=17.8

da = xr.open_dataset(file)
ts = da.sel(lon=lon, lat=lat, method="nearest")   #I also tried da["variable1"].sel(lon=lon, lat=lat, method="nearest") but same outcome.

But it raised this error:

KeyError: 'lon is not a valid dimension or coordinate'

I then tried to set lon and lat as coordinates (da.set_coords(("lat", "lon"))) but it still raised an error:

KeyError: 'no index found for coordinate lon'

I have very rarely worked with arrays so I don't understand what is wrong here. Here are more details of my netCDF:

xarray.Dataset
Dimensions: south_north: 63, west_east: 69, vcoord_dim: 8, Time: 25, bottom_top: 8
Coordinates: (0)  # For some reasons lon and lat are Data variables and not Coordinates in this netCDF.
Data variables: (216)

I also tried a more mannual extraction method (validated answer here) but it gave an index value way out of bound for the j that I can also not explain.

So, to summarize, what I want is extract the values of some Data variables at specific lon/lat values for all the timesteps of the netCDF.

I looked everywhere for answers but nothing helped me understand what was wrong. Any tips and advices would be greatly appreciated.


问:
possible to run PCA in R assuming columns are samples and rows are variables?
I have a file with 500K variables (DNA changes) and 60K samples.

I am finding reading "wide" files typically takes longer that "long" files, so it would be better is I could read in my data with samples as columns

as I understand it prcomp assumes samples are rows and variables are columns, but is there a way to make it assume samples are columns and variables are rows?


问:
Accessing RXSpreadsheet data for further manipulation?
I am making a Shiny app that should have an empty spreadsheet (like excel), where I can paste some data, which can be further processed to get some desired output.

How can I access the data from the spreadsheet for further manipulation in my app?

In the code below, I successfully load an empty spreadsheet that is editable, I can also paste whatever I want into it, but I don't know how to manipulate the data further. I tried to at least load it like a DT table just to see if I managed to convert it to data.frame.

```<code>
library(shiny)
library(RXSpreadsheet)

ui <- fluidPage(
  tabsetPanel(
    tabPanel(
      "Spreadsheet",
      RXSpreadsheet("table"),
      RXSpreadsheetOutput("spreadsheet")
    ),
    tabPanel(
      "Tabela",
      DT::dataTableOutput("dataframe")
    )
  )
)

server <- function(input, output) {

  data <- reactive({
    input$table
  })

  output$spreadsheet <- renderRXSpreadsheet({
    data()
  })

  data_2 <- reactive({
    as.data.frame(data())
  })

  output$dataframe <- DT::renderDT({
    data_2()
  })

}

shinyApp(ui, server)

</code>```

Body:
I am making a Shiny app that should have an empty spreadsheet (like excel), where I can paste some data, which can be further processed to get some desired output.

How can I access the data from the spreadsheet for further manipulation in my app?

In the code below, I successfully load an empty spreadsheet that is editable, I can also paste whatever I want into it, but I don't know how to manipulate the data further. I tried to at least load it like a DT table just to see if I managed to convert it to data.frame.

library(shiny)
library(RXSpreadsheet)

ui <- fluidPage(
  tabsetPanel(
    tabPanel(
      "Spreadsheet",
      RXSpreadsheet("table"),
      RXSpreadsheetOutput("spreadsheet")
    ),
    tabPanel(
      "Tabela",
      DT::dataTableOutput("dataframe")
    )
  )
)

server <- function(input, output) {

  data <- reactive({
    input$table
  })

  output$spreadsheet <- renderRXSpreadsheet({
    data()
  })

  data_2 <- reactive({
    as.data.frame(data())
  })

  output$dataframe <- DT::renderDT({
    data_2()
  })

}

shinyApp(ui, server)


问:
I'm getting a 403 Forbidden response when using axios instance in react to access my api endpoint in Django rest framework
I am working on a blog project, following a certain tutorial, using django 4.1.4, DRF-3.14, React 18.2, and using drf-social-oauth2 1.2.1 module for social logins
When I use postman or that DRF API Interface to make request to the api everything is working fine, I can do all the request when authenticated but when I use exios instance I keep getting the 403 Forbidden error.

Here is axios file:

```<code>    import axios from 'axios';

    const baseURL = 'http://127.0.0.1:8000/api/';

    const token = localStorage.getItem('access_token')

    console.log(token);

    const axiosInstance = axios.create({
        baseURL: baseURL,
        timeout: 5000,
        headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'multipart/form-data',
            accept: 'application/json',
        },
    });

    axiosInstance.interceptors.response.use(
        (response) => {
            return response;
        },
         async function (error) {
            const originalRequest = error.config;

            if (typeof error.response === 'undefined') {
                alert(
                    'A server/network error occurred. ' +
                        'Looks like CORS might be the problem. ' +
                        'Sorry about this - we will get it fixed shortly.'
                );
                return Promise.reject(error);
            }

            if (
                error.response.status === 401 &&
                originalRequest.url === baseURL + 'token/refresh/'
            ) {
                window.location.href = '/login/';
                return Promise.reject(error);
            }

            if (
                error.response.data.code === 'token_not_valid' &&
                error.response.status === 401 &&
                error.response.statusText === 'Unauthorized'
            ) {
                const refreshToken = localStorage.getItem('refresh_token');

                if (refreshToken) {
                    const tokenParts = JSON.parse(atob(refreshToken.split('.')[1]));

                    // exp date in token is expressed in seconds, while now() returns
    milliseconds:
                    const now = Math.ceil(Date.now() / 1000);
                    console.log(tokenParts.exp);

                    if (tokenParts.exp > now) {
                       return axiosInstance
                           .post('/token/refresh/', {
                                refresh: refreshToken,
                           })
                           .then((response) => {
                               localStorage.setItem('access_token',
    response.data.access_token);
                                localStorage.setItem('refresh_token',
    response.data.refresh_token);
                                return axiosInstance(originalRequest);
                           })
                            .catch((err) => {
                                console.log(err);
                            });
                    } else {
                        console.log('Refresh token is expired', tokenParts.exp, now);
                        window.location.href = '/login/';
                    }
                } else {
                    console.log('Refresh token not available.');
                    window.location.href = '/login/';
                }
            }

            // specific error handling done elsewhere
            return Promise.reject(error);
    }
    );

    export default axiosInstance;

</code>```

API Views file:

```<code>from rest_framework import generics
from posts.models import Post
from . serializers import PostSerializer
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import SAFE_METHODS, IsAuthenticated, BasePermission,
IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework import filters
from rest_framework import status

class PostUserWritrPermission(BasePermission):

    message = 'Editing post is restricted to the author only.'

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        return obj.author.user == request.user

class PostList(generics.ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

class PostDetail(generics.RetrieveAPIView):
    serializer_class = PostSerializer

    def get_object(self, queryset=None, **kwargs):
        slug = self.kwargs.get('pk')
        return get_object_or_404(Post, slug=slug)

class PostListDetailFilter(generics.ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['^slug']

class CreatePost(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, format=None):
        print(request.data)
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class AdminPostDetail(generics.RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class EditPost(generics.UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

class DeletePost(generics.RetrieveDestroyAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()
</code>```

Part of the Settings file:

```<code>MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

AUTHENTICATION_BACKENDS = [
    'drf_social_oauth2.backends.DjangoOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'drf_social_oauth2.authentication.SocialAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

CORS_ALLOW_ALL_ORIGINS = True

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "http://localhost:8000",
    "http://127.0.0.1:8000",
]
</code>```

Body:
I am working on a blog project, following a certain tutorial, using django 4.1.4, DRF-3.14, React 18.2, and using drf-social-oauth2 1.2.1 module for social logins
When I use postman or that DRF API Interface to make request to the api everything is working fine, I can do all the request when authenticated but when I use exios instance I keep getting the 403 Forbidden error.

Here is axios file:

    import axios from 'axios';

    const baseURL = 'http://127.0.0.1:8000/api/';

    const token = localStorage.getItem('access_token')

    console.log(token);

    const axiosInstance = axios.create({
        baseURL: baseURL,
        timeout: 5000,
        headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'multipart/form-data',
            accept: 'application/json',
        },
    });

    axiosInstance.interceptors.response.use(
        (response) => {
            return response;
        },
         async function (error) {
            const originalRequest = error.config;

            if (typeof error.response === 'undefined') {
                alert(
                    'A server/network error occurred. ' +
                        'Looks like CORS might be the problem. ' +
                        'Sorry about this - we will get it fixed shortly.'
                );
                return Promise.reject(error);
            }

            if (
                error.response.status === 401 &&
                originalRequest.url === baseURL + 'token/refresh/'
            ) {
                window.location.href = '/login/';
                return Promise.reject(error);
            }

            if (
                error.response.data.code === 'token_not_valid' &&
                error.response.status === 401 &&
                error.response.statusText === 'Unauthorized'
            ) {
                const refreshToken = localStorage.getItem('refresh_token');

                if (refreshToken) {
                    const tokenParts = JSON.parse(atob(refreshToken.split('.')[1]));

                    // exp date in token is expressed in seconds, while now() returns
    milliseconds:
                    const now = Math.ceil(Date.now() / 1000);
                    console.log(tokenParts.exp);

                    if (tokenParts.exp > now) {
                       return axiosInstance
                           .post('/token/refresh/', {
                                refresh: refreshToken,
                           })
                           .then((response) => {
                               localStorage.setItem('access_token',
    response.data.access_token);
                                localStorage.setItem('refresh_token',
    response.data.refresh_token);
                                return axiosInstance(originalRequest);
                           })
                            .catch((err) => {
                                console.log(err);
                            });
                    } else {
                        console.log('Refresh token is expired', tokenParts.exp, now);
                        window.location.href = '/login/';
                    }
                } else {
                    console.log('Refresh token not available.');
                    window.location.href = '/login/';
                }
            }

            // specific error handling done elsewhere
            return Promise.reject(error);
    }
    );

    export default axiosInstance;

API Views file:

from rest_framework import generics
from posts.models import Post
from . serializers import PostSerializer
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import SAFE_METHODS, IsAuthenticated, BasePermission,
IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework import filters
from rest_framework import status

class PostUserWritrPermission(BasePermission):

    message = 'Editing post is restricted to the author only.'

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        return obj.author.user == request.user

class PostList(generics.ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

class PostDetail(generics.RetrieveAPIView):
    serializer_class = PostSerializer

    def get_object(self, queryset=None, **kwargs):
        slug = self.kwargs.get('pk')
        return get_object_or_404(Post, slug=slug)

class PostListDetailFilter(generics.ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['^slug']

class CreatePost(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, format=None):
        print(request.data)
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class AdminPostDetail(generics.RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    queryset = Post.objects.all()
    serializer_class = PostSerializer

class EditPost(generics.UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

class DeletePost(generics.RetrieveDestroyAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

Part of the Settings file:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

AUTHENTICATION_BACKENDS = [
    'drf_social_oauth2.backends.DjangoOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'drf_social_oauth2.authentication.SocialAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

CORS_ALLOW_ALL_ORIGINS = True

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "http://localhost:8000",
    "http://127.0.0.1:8000",
]


问:
How to position 4 images as well as one line of text correctly on top of each other?
So Ive been having problems with figuring out which code would work for these images on my site. Im an extremley new coder but I know the answer is probably very simple, Its just I havent been able to find exactly the kind of answer Im looking for. Basically I need 4 images stacked nicely on top of each other,
All I know is a parent div and divs added to the image class will be a right fit, Its just I don't know how to position the images properly.

 This is how Id like it to look,
I'd also like the rainbow to be slightly strecthed like the first link compared to:

how it currently looks.

Heres the current code;

HTML code:

```<code><div class="container">
  <img src="https://fyunky.neocities.org/Images!/BORDERTITLE2.png" alt="Purple Border Image with bubbles :3" style="width:40%;">
  <div class="centered"><h2>!!!Welcome!!!</h2></div>
</div>
</code>```

css code:

```<code>.container {
  font-family: 'chewy';
  position: relative;
  text-align: center;
  color: #fbd3ff;
}
.centered {
  position: absolute;
  top: 50%;
  left: 49.40%;
  transform: translate(-50%, -49.40%);
}
</code>```

as you can see the clouds aren't added yet, and I only have css code for the border image and the text, also I need the images to be in the center and top of the page. The only thing I don't know is positioning, because I haven't been able to figure out exactly how it works, sorry if what I wrote was confusing and please let me know how I would do this. Thx for reading! <3 <3 <3

Body:
So Ive been having problems with figuring out which code would work for these images on my site. Im an extremley new coder but I know the answer is probably very simple, Its just I havent been able to find exactly the kind of answer Im looking for. Basically I need 4 images stacked nicely on top of each other,
All I know is a parent div and divs added to the image class will be a right fit, Its just I don't know how to position the images properly.

 This is how Id like it to look,
I'd also like the rainbow to be slightly strecthed like the first link compared to:

how it currently looks.

Heres the current code;

HTML code:

!!!Welcome!!!

css code:

.container {
  font-family: 'chewy';
  position: relative;
  text-align: center;
  color: #fbd3ff;
}
.centered {
  position: absolute;
  top: 50%;
  left: 49.40%;
  transform: translate(-50%, -49.40%);
}

as you can see the clouds aren't added yet, and I only have css code for the border image and the text, also I need the images to be in the center and top of the page. The only thing I don't know is positioning, because I haven't been able to figure out exactly how it works, sorry if what I wrote was confusing and please let me know how I would do this. Thx for reading! <3 <3 <3


问:
Is there a faster way to do ZigZag encoding in JavaScript that works with large numbers?
I am attempting to perform ZigZag encoding for numbers in JavaScript that are within the safe bounds of JavaScript integers

These functions seem to work up to 2^30 - 1 only because JavaScript bit-wise operators only work with 32 bit numbers:

function encodeZigzag(value) {
  return ((value << 1) ^ (value >> 31));
}

function decodeZigzag(encoded) {
  return (encoded >> 1) ^ -((encoded & 1));
}

console.log(decodeZigzag(encodeZigzag(0)));
console.log(decodeZigzag(encodeZigzag(-1)));
console.log(decodeZigzag(encodeZigzag(2)));
console.log(decodeZigzag(encodeZigzag(-2)));
console.log(decodeZigzag(encodeZigzag(1073741823)));
console.log(decodeZigzag(encodeZigzag(1073741824))); // breaks```
</div>
</div>
</p>
<p>Anyways, I was looking for a pair of alternate functions that worked up to a larger upper-bound (2^53 or so). I came up with these, which seem to work, but I was wondering if there was a more elegant / performant way:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function bigEncodeZigzag(v) {
  const shift = v * 2;

  return v >= 0 ? shift : -shift - 1;
}

function bigDecodeZigzag(v) {
  const shift = Math.floor(v / 2);

  return v % 2 === 0 ? shift : -shift - 1;
}

console.log(bigDecodeZigzag(bigEncodeZigzag(0)));
console.log(bigDecodeZigzag(bigEncodeZigzag(-1)));
console.log(bigDecodeZigzag(bigEncodeZigzag(2)));
console.log(bigDecodeZigzag(bigEncodeZigzag(-2)));
console.log(bigDecodeZigzag(bigEncodeZigzag(1073741823)));
console.log(bigDecodeZigzag(bigEncodeZigzag(1073741824))); // works</code>```

Body:
I am attempting to perform ZigZag encoding for numbers in JavaScript that are within the safe bounds of JavaScript integers

These functions seem to work up to 2^30 - 1 only because JavaScript bit-wise operators only work with 32 bit numbers:

function encodeZigzag(value) {
  return ((value << 1) ^ (value >> 31));
}

function decodeZigzag(encoded) {
  return (encoded >> 1) ^ -((encoded & 1));
}

console.log(decodeZigzag(encodeZigzag(0)));
console.log(decodeZigzag(encodeZigzag(-1)));
console.log(decodeZigzag(encodeZigzag(2)));
console.log(decodeZigzag(encodeZigzag(-2)));
console.log(decodeZigzag(encodeZigzag(1073741823)));
console.log(decodeZigzag(encodeZigzag(1073741824))); // breaks

Anyways, I was looking for a pair of alternate functions that worked up to a larger upper-bound (2^53 or so). I came up with these, which seem to work, but I was wondering if there was a more elegant / performant way:

function bigEncodeZigzag(v) {
  const shift = v * 2;

  return v >= 0 ? shift : -shift - 1;
}

function bigDecodeZigzag(v) {
  const shift = Math.floor(v / 2);

  return v % 2 === 0 ? shift : -shift - 1;
}

console.log(bigDecodeZigzag(bigEncodeZigzag(0)));
console.log(bigDecodeZigzag(bigEncodeZigzag(-1)));
console.log(bigDecodeZigzag(bigEncodeZigzag(2)));
console.log(bigDecodeZigzag(bigEncodeZigzag(-2)));
console.log(bigDecodeZigzag(bigEncodeZigzag(1073741823)));
console.log(bigDecodeZigzag(bigEncodeZigzag(1073741824))); // works


问:
Finding the next closest point from a series of latitudes and longitudes
I have been given a list of 133 locations by latitude and longitude. I need a way to find the next closest point to each point independtly in miles or kilometers.

I've already found a way to find the distance between two points. (haversine formula) I've also already found a way to find the distance between each point and a known location. What I'm struggling with is how to find the distance between a point and the next closest point.

Any ideas on how to accomplish this? Everything i'm researching indicates that I need a known point from which to start the comparison and I can't find the distance to a point within the data itself.

So far we've only tried the haversine formula to find the distance between two points. I'm note sure where to start with this formula.