问:
Kotlin Apollo GraphQL - How to modify normalized cached item with ApolloStore API?
I'm using Apollo GraphQL for my Kotlin Android Application.
My Normalized Cache has for example this item:

```<code> "Post:247" : {
    "__typename" : Post
    "id" : 247
    "name" : testname
    "favorites" : 4                                                                                }
</code>```

How can I edit this item in cache using ApolloStore API and increment the favorites count by 1 so that all my watchers get notified?

The official ApolloStore Docs are not helpful at all.

Body:
I'm using Apollo GraphQL for my Kotlin Android Application.
My Normalized Cache has for example this item:

 "Post:247" : {
    "__typename" : Post
    "id" : 247
    "name" : testname
    "favorites" : 4                                                                                }

How can I edit this item in cache using ApolloStore API and increment the favorites count by 1 so that all my watchers get notified?

The official ApolloStore Docs are not helpful at all.


来源: stackexchange

问:
Angular html custom element from typescript
I'm a bit new to Angular and this problem seems nquite easy but I didn't find any solution on the web...

Here is what I want :
I have a component, named PageComponent (for example), and I want its html template to come from the back-end.
It works fine for classic html elements ; for instance :

page-component.html :

```<code><div [innerHtml]="content"></div>
</code>```

page-component.ts :

```<code>// [...]
export class PageComponent implements OnInit {
   this.content = ""
   // [...]

   ngOnInit() {
      this.content = "<p>Hello world !</p>"
   }
}
</code>```

So, it works fine here. The problem comes when I want to "inject" some custom elements, namely some material elements, such as the material tab group.

In short, I want the same feature as before but with a content like the following :

```<code>this.content = "<mat-tab-group><mat-tab label='label'><p>hello world</p></mat-tab></mat-tab-group>"
</code>```

I know custom elements don't work for the 'innerHtml' property ; when I look at the web inspector (F12 -> inspector) on the html file it shows the right content (i.e. the mat tab group element and the rest) but it doesn't actually display it on the GUI.

Actually, "this.content" is assigned to a string coming from the back end.
I don't know much about DOM manipulation and Angular preprocessing, maybe it's really easy ^^

'npm --version' gives me 8.19.2
angular core, cdk are v14, material is v13.3.9

So is there a way to inject custom elements in a html in Angular, like the 'innerHtml' property ?

Thanks !

First, I have tried to copy and paste the raw string on the html file of the component (page-component.html) and it works (the GUI shows the tabs like I want), so the problem doesn't come from Material (I have imported MatTabsModule).

I have tried different things such as content projection (https://angular.io/guide/content-projection), dynamic components (https://falconsoft.github.io/ngx-dynamic-components/), dynamic hooks (https://github.com/MTobisch/ngx-dynamic-hooks#3-what-it-does), the deprecated compontentFactoryResolver (and the features that replace it) but it handles components, and I want to handle raw strings.
I've also seen some threads mentioning directives and since it doesn't seem to be the right way either I didn't look further.

I've also seen elementRef, embeddedView, templateRef (and ) and other contents like this (https://angular.io/api/core/ViewContainerRef) but I didn't find a solution.

I must admit I have seen so much features I am quite lost and don't really know how to properly tackle this problem.

As I wrote, I tried the 'innerHtml' with native html elements, and I'm looking for the same feature working with material elements.

I have seen this stackoverflow thread : Angular 6 Custom Element inside InnerHtml Keeps Reloading, but it is not exactly the same problem, and there is no answer yet.

When I tried the aforementioned features I had one of the following result :
-the html file in the web inspector is '' (no )
-the html file is good but the GUI is not good (blank page, or it just shows the content of the tabs without the tabs, here "hello world")

ContentLicense: CC BY-SA 4.0

Body:
I'm a bit new to Angular and this problem seems nquite easy but I didn't find any solution on the web...

Here is what I want :
I have a component, named PageComponent (for example), and I want its html template to come from the back-end.
It works fine for classic html elements ; for instance :

page-component.html :

page-component.ts :

// [...]
export class PageComponent implements OnInit {
   this.content = ""
   // [...]

   ngOnInit() {
      this.content = "
Hello world !
"
   }
}

So, it works fine here. The problem comes when I want to "inject" some custom elements, namely some material elements, such as the material tab group.

In short, I want the same feature as before but with a content like the following :

this.content = "<mat-tab-group><mat-tab label='label'>
hello world
</mat-tab></mat-tab-group>"

I know custom elements don't work for the 'innerHtml' property ; when I look at the web inspector (F12 -> inspector) on the html file it shows the right content (i.e. the mat tab group element and the rest) but it doesn't actually display it on the GUI.

Actually, "this.content" is assigned to a string coming from the back end.
I don't know much about DOM manipulation and Angular preprocessing, maybe it's really easy ^^

'npm --version' gives me 8.19.2
angular core, cdk are v14, material is v13.3.9

So is there a way to inject custom elements in a html in Angular, like the 'innerHtml' property ?

Thanks !

First, I have tried to copy and paste the raw string on the html file of the component (page-component.html) and it works (the GUI shows the tabs like I want), so the problem doesn't come from Material (I have imported MatTabsModule).

I have tried different things such as content projection (https://angular.io/guide/content-projection), dynamic components (https://falconsoft.github.io/ngx-dynamic-components/), dynamic hooks (https://github.com/MTobisch/ngx-dynamic-hooks#3-what-it-does), the deprecated compontentFactoryResolver (and the features that replace it) but it handles components, and I want to handle raw strings.
I've also seen some threads mentioning directives and since it doesn't seem to be the right way either I didn't look further.

I've also seen elementRef, embeddedView, templateRef (and ) and other contents like this (https://angular.io/api/core/ViewContainerRef) but I didn't find a solution.

I must admit I have seen so much features I am quite lost and don't really know how to properly tackle this problem.

As I wrote, I tried the 'innerHtml' with native html elements, and I'm looking for the same feature working with material elements.

I have seen this stackoverflow thread : Angular 6 Custom Element inside InnerHtml Keeps Reloading, but it is not exactly the same problem, and there is no answer yet.

When I tried the aforementioned features I had one of the following result :
-the html file in the web inspector is '' (no )
-the html file is good but the GUI is not good (blank page, or it just shows the content of the tabs without the tabs, here "hello world")


问:
Can't exclude debug traffic from Realtime reports Google Analytics 4
The problem:

I want to be able to debug GA4 without polluting my data. I can't seem to do that without removing my internal traffic filter, and then my presence on the app gets reported in Realtime reporting (and only Realtime reporting so far, but i suspect after 48 hours it will show everywhere in Reports).

First, is this expected behavior? Is Realtime reporting 'special'? Does it display dev traffic while other reports don't? If so, ignore the rest.

What I've tried:

I used google chrome with the GA debug extension from here: ga debugger ext to review my website (on localhost).

When my Internal Traffic filter is deactivated and my Developer Traffic filter is activated, Realtime reports show my presence on my app (boo). But I do see data in the debug view (yay).

When both are activated no data is shown in the Realtime reports area (yay), but also no data is shown in the debug view (boo).

Some Code:

```<code>import ReactGA from "react-ga4";

function App() {

  useEffect(() => {
      ReactGA.initialize("G-blablabla");
      ReactGA.send("pageview");
    },
    []
  )

  let location = useLocation();
  useEffect(() => {
    ReactGA.send({ hitType: "pageview", page: location });
  }, [location]);

  const GenerateAppRoutes = () => {
    return (
      <>
        <Route path="/" element={
            <Landing/>
          }
        />
        <Route path="/blog/design" element={
          <BlogPillar
            imgSrc={sampleImg}
            topicTitle='Design'
            articles={
              [
                {'link': '/blog/design/materials', 'title': 'Materials'},
                {'link': '/blog/design/fasteners', 'title': 'Screws'},
              ]
            }
            imgAlt=""
          />
        }/>
      </>
    )
  }

  const AppRoutes = GenerateAppRoutes();
  const appRouteObjects = createRoutesFromChildren(AppRoutes);
  const GeneratedRoutes = useRoutes(appRouteObjects);
  return (
    <>
      <NavBarComponent/>
      {GeneratedRoutes}
    </>
  )
}

export default App;
</code>```

Body:
The problem:

I want to be able to debug GA4 without polluting my data. I can't seem to do that without removing my internal traffic filter, and then my presence on the app gets reported in Realtime reporting (and only Realtime reporting so far, but i suspect after 48 hours it will show everywhere in Reports).

First, is this expected behavior? Is Realtime reporting 'special'? Does it display dev traffic while other reports don't? If so, ignore the rest.

What I've tried:

I used google chrome with the GA debug extension from here: ga debugger ext to review my website (on localhost).

When my Internal Traffic filter is deactivated and my Developer Traffic filter is activated, Realtime reports show my presence on my app (boo). But I do see data in the debug view (yay).

When both are activated no data is shown in the Realtime reports area (yay), but also no data is shown in the debug view (boo).

Some Code:

import ReactGA from "react-ga4";

function App() {

  useEffect(() => {
      ReactGA.initialize("G-blablabla");
      ReactGA.send("pageview");
    },
    []
  )

  let location = useLocation();
  useEffect(() => {
    ReactGA.send({ hitType: "pageview", page: location });
  }, [location]);

  const GenerateAppRoutes = () => {
    return (
      <>
        <Route path="/" element={
            <Landing/>
          }
        />
        <Route path="/blog/design" element={
          <BlogPillar
            imgSrc={sampleImg}
            topicTitle='Design'
            articles={
              [
                {'link': '/blog/design/materials', 'title': 'Materials'},
                {'link': '/blog/design/fasteners', 'title': 'Screws'},
              ]
            }
            imgAlt=""
          />
        }/>
      </>
    )
  }

  const AppRoutes = GenerateAppRoutes();
  const appRouteObjects = createRoutesFromChildren(AppRoutes);
  const GeneratedRoutes = useRoutes(appRouteObjects);
  return (
    <>
      <NavBarComponent/>
      {GeneratedRoutes}
    </>
  )
}

export default App;


问:
Pass control prop to child component in react hook form
I'm trying to pass the control prop to my custom component that comes from react-hook-form but it tells that the control is undefined

I did the same thing written in document. I used FormProvider like this:

```<code><FormProvider {...methods}>
        <form
          style={{
            height: "auto",
            width: "90%",
            padding: "2em",
            paddingTop: "0",
            textAlign: "center",
            backgroundColor: "white",
            borderRadius: "10px",
          }}
          onSubmit={methods.handleSubmit((data) => console.log(data))}
        >
          <IconButton
            color="error"
            onClick={() => setRecordControl({ stat: "" })}
          >
            <Cancel fontSize="large" />
          </IconButton>
          <h3 style={{ marginBottom: "10px", textAlign: "center" }}>
            saving records
          </h3>
          {filtered.ListColumnInfo.map(
            (detail) =>
              detail.VisibleColumn && (
                <div key={uuidV4()}>
                  <CustomTextBoxComponent
                    filtered={detail}
                  />
                </div>
              )
          )}

          <Button
            variant="contained"
            fullWidth
            color="success"
            sx={{ mt: "1em" }}
            type="submit"
          >
            save
          </Button>
        </form>
      </FormProvider>

</code>```

and I tried to retrieve the control inside of my CustomTextBoxComponent like this:

```<code>const CustomTextBoxComponent = ({ filtered }) => {
  const { control } = useFormContext();
  return (
    <Controller
      name="input"
      render={({ field }) => (
        <TextField
          fullWidth
          placeholder={
            filtered.ElsRecord.PersianName !== ""
              ? filtered.ElsRecord.PersianName
              : filtered.ElsRecord.Name
          }

          sx={{ marginBlock: "1em" }}
          {...control}
          {...field}
        />
      )}
      defaultValue=""
    />
  );
};
</code>```

it didn't work. always says the method is null

the picture of Error

how can I solve it?

Body:
I'm trying to pass the control prop to my custom component that comes from react-hook-form but it tells that the control is undefined

I did the same thing written in document. I used FormProvider like this:

<FormProvider {...methods}>
        <form
          style={{
            height: "auto",
            width: "90%",
            padding: "2em",
            paddingTop: "0",
            textAlign: "center",
            backgroundColor: "white",
            borderRadius: "10px",
          }}
          onSubmit={methods.handleSubmit((data) => console.log(data))}
        >
          <IconButton
            color="error"
            onClick={() => setRecordControl({ stat: "" })}
          >
            <Cancel fontSize="large" />
          </IconButton>

            saving records

          {filtered.ListColumnInfo.map(
            (detail) =>
              detail.VisibleColumn && (

                  <CustomTextBoxComponent
                    filtered={detail}
                  />

              )
          )}

          <Button
            variant="contained"
            fullWidth
            color="success"
            sx={{ mt: "1em" }}
            type="submit"
          >
            save
          </Button>
        </form>
      </FormProvider>

and I tried to retrieve the control inside of my CustomTextBoxComponent like this:

const CustomTextBoxComponent = ({ filtered }) => {
  const { control } = useFormContext();
  return (
    <Controller
      name="input"
      render={({ field }) => (
        <TextField
          fullWidth
          placeholder={
            filtered.ElsRecord.PersianName !== ""
              ? filtered.ElsRecord.PersianName
              : filtered.ElsRecord.Name
          }

          sx={{ marginBlock: "1em" }}
          {...control}
          {...field}
        />
      )}
      defaultValue=""
    />
  );
};

it didn't work. always says the method is null

the picture of Error

how can I solve it?


问:
How to get which ID is similar after cv2.BFMatcher.knnMatch() implementation?
I have 2 cameras that see the similar objects from different perspective. First I detected the objects with their tracking ids, then find the feature descriptors for each detected objects. You can see the table that contains values for both cam1 and cam2. Normally, id1 on cam1 is the same object id2 on the cam2.

My code is :

```<code>if feature_data_cam1.shape != () and feature_data_cam2.shape != () :

            matches = self.bf.knnMatch(feature_data_cam1,feature_data_cam2,k=2)

            # Apply ratio test to eliminate undesirable matches
            good = []
            for m,n in matches:
                if m.distance < 0.75*n.distance:
                    good.append([m])

            print(matches)
</code>```

As an output, I got cv2.DMatch that gives me the matched keypoints. I would like to know, which ID is similar.(like : ID1 on cam1 is the same object called ID2 on cam2.) How can I get this information from Dmatches?

Body:
I have 2 cameras that see the similar objects from different perspective. First I detected the objects with their tracking ids, then find the feature descriptors for each detected objects. You can see the table that contains values for both cam1 and cam2. Normally, id1 on cam1 is the same object id2 on the cam2.

My code is :

if feature_data_cam1.shape != () and feature_data_cam2.shape != () :

            matches = self.bf.knnMatch(feature_data_cam1,feature_data_cam2,k=2)

            # Apply ratio test to eliminate undesirable matches
            good = []
            for m,n in matches:
                if m.distance < 0.75*n.distance:
                    good.append([m])

            print(matches)

As an output, I got cv2.DMatch that gives me the matched keypoints. I would like to know, which ID is similar.(like : ID1 on cam1 is the same object called ID2 on cam2.) How can I get this information from Dmatches?


问:
Is "Scalable dp" the best choice for supporting every different screen size in android?
I have been searching for information to define dimens.xml for every different screen size so that I can have different values for different screen sizes. I have seen that is really difficult because I would have to make a different dimens file for every different screen size. While searching for a possible solution to this, I have found this library: https://github.com/intuit/sdp

Is that library the best solution nowadays to support all the different android devices according to the screen size? I would appreciate other alternatives if using "scalable dp" library is not a good option.

In my case, the purpose of having different values according to the screen size is because I have a ConstraintLayout with some items that have Top and Bottom margin. To let you understand, imagine that both Top and Bottom margin is 10dp. I can see so much difference of margin between device 1: 480x800px (4" and screen density= hdpi) and device 2: 480x800px(3.7" and screen density= hdpi). As you can see both devices have same screen density and same px, so I have to use some other attribute or tool to distinguish that different screen size...


问:
Does anyone knows what does mysql erro code ECONNREFUSED mean?
So I use nodejs, I have remote hosted mysql server. I also have user seted with % host, I can even login into mysql-workbench, but when i try to connect with node it throw this err on me:

```<code> errno: -111,
 code: 'ECONNREFUSED',
</code>```

my connection code looks like this:

```<code>    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME,
})
</code>```

I tried to search but even when I tried everything I could find it doesn't work.
As a server i use ubuntu 20.04
Anyone here know what to do?

Body:
So I use nodejs, I have remote hosted mysql server. I also have user seted with % host, I can even login into mysql-workbench, but when i try to connect with node it throw this err on me:

 errno: -111,
 code: 'ECONNREFUSED',

my connection code looks like this:

    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME,
})

I tried to search but even when I tried everything I could find it doesn't work.
As a server i use ubuntu 20.04
Anyone here know what to do?


问:
Fix TypeScript error in a function that groups an array of objects by multiple keys
I created a function that groups an array of objects by multiple keys:

export function groupByMulti<T>(dataset: T[], keys: Array<keyof T>) {
  if (keys.length === 0) {
    return dataset
  }
  const byFirst = groupBy(dataset, keys[0])
  const rest = keys.slice(1)
  for (const prop in byFirst) {
    // HERE there is a TypeScript error
    // Type 'T[] | Dictionary<T[]>' is not assignable to type 'T[]'
    byFirst[prop] = groupByMulti(byFirst[prop], rest)
  }
  return byFirst
}
```

How can I solve this error? I absolutely don't want to use a ts-ignore

Body:
I created a function that groups an array of objects by multiple keys:

export function groupByMulti<T>(dataset: T[], keys: Array<keyof T>) {
  if (keys.length === 0) {
    return dataset
  }
  const byFirst = groupBy(dataset, keys[0])
  const rest = keys.slice(1)
  for (const prop in byFirst) {
    // HERE there is a TypeScript error
    // Type 'T[] | Dictionary<T[]>' is not assignable to type 'T[]'
    byFirst[prop] = groupByMulti(byFirst[prop], rest)
  }
  return byFirst
}

How can I solve this error? I absolutely don't want to use a ts-ignore


问:
Why is nested tidyr function inconsistently generating error?
I have written two functions (one nested in the other), one of which is inconsistently throwing an error, such that I've struggling to identity where to even begin with troubleshooting.

To describe each function briefly:

importJSON() has been written to use jsonlite::fromJSON() and tidyverse:: functions to scrape data from individual .json files containing multiple observations of day-level data about a person, within which there are several observations of 30-sec epoch event-level data, which are then returned in a tidied data frame; it's not intended to be called directly by users

scrapePerson() is intended to be called directly by users, and deploys importJSON() on a particular person's folder of data, scraping the data day-level and event-level data (which requiring unnesting), and using rbind() to combine all the data frames (for each .json file) into one tidied data frame

importJSON() seems to work on all cases I tested it on, and scrapePerson(), likewise, has worked on most. For one folder of data, however, the function has thrown the following error:

Error in list_unchop(): ! Can't combine x[[36]] <data.frame> and
x[[37]] .

--- Backtrace:

snoozr::scrapePerson(...)

snoozr::importJSON(newpath, level1 = TRUE)
at snoozr/R/scrapePerson.R:82:6

tidyr:::unnest.data.frame(fjson.df, levels.shortData, names_sep = ".")

tidyr::unchop(data, any_of(cols), keep_empty = keep_empty, ptype = ptype)

tidyr:::df_unchop(cols, ptype = ptype, keep_empty = keep_empty)

vctrs::vec_unchop(col, ptype = col_ptype)

vctrs::list_unchop(...)

Being a largely self-trained programmer, I tried to debug this the only way I know how: the painstakingly monotonous way, applying importJSON() individually to each of the 66 .json files in the problematic folder, and using rbind() to iteratively stitch them together into one data frame, in the same manner the scrapePerson() function would.

To my surprise, this worked without any error (e.g., my expectations had been that it might struggle to combine data from the 37th .json to the rbind()'ed 1-36th .json files).

Does anyone have an intuition of what might be happening here? The interior of importJSON() seems to be working just fine on the files in the problematic directory when I manually "iterate", but when I use a for() loop (in scrapePerson(), it errors out (and only for this directory, of the directories I've tried). I appreciate any insights and/or intuitions of where to get started!


问:
In next-auth, how to you ensure that session details have not be tampered with by the client?
In NextAuth, you can add some additional logic in the session callback which allows you to expose some extra fields which are available on the JWT to the session which is visible to the client. Imagine a scenario where I set a new field on the session called "fieldx" in the session callback.

```<code>session.fieldx = "user"
</code>```

Later on, I want to protect an API route and ensure that I only return a result if the session.fieldx value = "admin", so I use unstable_getServerSession.

I check session.fieldx of the returned session before returning the result.

So how specifically is it enforced here that the client does not tamper with the cookie which is storing the session? If a bad actor managed to change fieldx on their session to "admin", despite having it originally set to "user" in the session callback, what behaviour would be observed when I call unstable_getServerSession?

I have not observed any abnormal behaviour, I just want to confirm that it is working as expected.

Body:
In NextAuth, you can add some additional logic in the session callback which allows you to expose some extra fields which are available on the JWT to the session which is visible to the client. Imagine a scenario where I set a new field on the session called "fieldx" in the session callback.

session.fieldx = "user"

Later on, I want to protect an API route and ensure that I only return a result if the session.fieldx value = "admin", so I use unstable_getServerSession.

I check session.fieldx of the returned session before returning the result.

So how specifically is it enforced here that the client does not tamper with the cookie which is storing the session? If a bad actor managed to change fieldx on their session to "admin", despite having it originally set to "user" in the session callback, what behaviour would be observed when I call unstable_getServerSession?

I have not observed any abnormal behaviour, I just want to confirm that it is working as expected.


问:
ChainedTokenCredential authentication failed
```<code>``const { DefaultAzureCredential } = require('@azure/identity');
const { BlobServiceClient } = require("@azure/storage-blob");
const { v1: uuidv1 } = require("uuid");
require("dotenv").config();

async function main() {
try {
console.log("Azure Blob storage v12 - JavaScript quickstart sample");

     } catch (err) {
    console.err(`Error: ${err.message}`);

}
// Quick start code goes here
const accountName = process.env.demostorageaccount2023;
//if (!accountName) throw Error('Azure Storage accountName not found');

const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
new DefaultAzureCredential()
);
// Create a unique name for the container
const containerName = 'quickstart' + u`your text`uidv1();

console.log('\\nCreating container...');
console.log('\\t', containerName);

// Get a reference to a container
const containerClient = blobServiceClient.getContainerClient(containerName);
// Create the container
const createContainerResponse = await containerClient.create();
console.log(
`Container was created successfully.\n\trequestId:${createContainerResponse.requestId}\n\tURL:         ${containerClient.url}`
);
}

main()
.then(() =\> console.log("Done"))
.catch((ex) =\> console.log(ex.message));`
</code>```

`
I am trying to connect to Azure storage account and create a blob container.

I am logged in VS as global admin on the tenant. The account has "storage account contributor" and "Blob data owner" rights. I have also created a user managed identity and gave that "storage account contributor" access rights.

In addition, I run Az Login and re-enter my creds before I run node index.js in the VS terminal window. It fails to create the blobs with the below error message....

ChainedTokenCredential authentication failed.
CredentialUnavailableError: EnvironmentCredential is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.

CredentialUnavailableError: ManagedIdentityCredential: Authentication failed. Message ManagedIdentityCredential - No MSI credential available
CredentialUnavailableError: ERROR: AADSTS50079: Due to a configuration change made by your administrator, or because you moved to a new location, you must enroll in multi-factor authentication to access 'e406a681-f3d4-42a8-90b6-c2b029497af1'.
Trace ID: 88ea514a-ad3b-4905-b019-e11e2c92dc00
Correlation ID: dfe36549-0b86-4e4f-be5b-505a111ee3a4
Timestamp: 2022-12-17 20:37:40Z
Interactive authentication is needed. Please run:
az login --scope https://storage.azure.com/.default

Login to VS with a global admin account
User-managed identity with access rights on the storage account
AZ Login- re-enter the global admin account

```<code></code>```

Body:
``const { DefaultAzureCredential } = require('@azure/identity');
const { BlobServiceClient } = require("@azure/storage-blob");
const { v1: uuidv1 } = require("uuid");
require("dotenv").config();

async function main() {
try {
console.log("Azure Blob storage v12 - JavaScript quickstart sample");

     } catch (err) {
    console.err(`Error: ${err.message}`);

}
// Quick start code goes here
const accountName = process.env.demostorageaccount2023;
//if (!accountName) throw Error('Azure Storage accountName not found');

const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
new DefaultAzureCredential()
);
// Create a unique name for the container
const containerName = 'quickstart' + u`your text`uidv1();

console.log('\\nCreating container...');
console.log('\\t', containerName);

// Get a reference to a container
const containerClient = blobServiceClient.getContainerClient(containerName);
// Create the container
const createContainerResponse = await containerClient.create();
console.log(
`Container was created successfully.\n\trequestId:${createContainerResponse.requestId}\n\tURL:         ${containerClient.url}`
);
}

main()
.then(() =\> console.log("Done"))
.catch((ex) =\> console.log(ex.message));`

`
I am trying to connect to Azure storage account and create a blob container.

I am logged in VS as global admin on the tenant. The account has "storage account contributor" and "Blob data owner" rights. I have also created a user managed identity and gave that "storage account contributor" access rights.

In addition, I run Az Login and re-enter my creds before I run node index.js in the VS terminal window. It fails to create the blobs with the below error message....

ChainedTokenCredential authentication failed.
CredentialUnavailableError: EnvironmentCredential is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.

CredentialUnavailableError: ManagedIdentityCredential: Authentication failed. Message ManagedIdentityCredential - No MSI credential available
CredentialUnavailableError: ERROR: AADSTS50079: Due to a configuration change made by your administrator, or because you moved to a new location, you must enroll in multi-factor authentication to access 'e406a681-f3d4-42a8-90b6-c2b029497af1'.
Trace ID: 88ea514a-ad3b-4905-b019-e11e2c92dc00
Correlation ID: dfe36549-0b86-4e4f-be5b-505a111ee3a4
Timestamp: 2022-12-17 20:37:40Z
Interactive authentication is needed. Please run:
az login --scope https://storage.azure.com/.default

Login to VS with a global admin account
User-managed identity with access rights on the storage account
AZ Login- re-enter the global admin account


问:
How to declare user variable of type "firebase.User" with AngularFireAuth?
In my Angular project, I import AngularFireAuth, and then use signInWithEmailAndPassword,
VSCode says the type returned by signInwithEmailAndPassword is firebase.auth.Usercredential.  I can't seem to import this type.

Similarly AngularFireAuth.currentUser returns a firebase.User.  Not clear how to import that type either.  What is the preferred way to store the current user, and how to import the type?

```<code>import {AngularFireAuth } from '@angular/fire/compat/auth`

class MyClass {

  constructor(private afAuth : AngularFireAuth){}

  async login(email : string, pw: string) {
    let user = await this.afAuth.signInWithEmailAndPassword(email,pw);
    //user is of type firebase.auth.UserCredential
    let currentUser = this.afAuth.currentUser;
    //currentUser is of type firebase.User;
  }
</code>```

But if I try to either declare the variables types rather than infer them, I can't do it:

```<code>   async login(email : string, pw: string) {
      let user : firebase.auth.UserCredential;
      //produces syntax error `..firebase.compat.index has no exported member 'auth'
      let user : firebase.User;
      //produces syntax error '../firebase.compat.index has no exported member 'User"

   }
</code>```

I've tried to import from various different sources but none seem to work propertly.

How to import the class of object returned either by 'signInWithEmaila/ndPassword()' or
the currentUser property of AngularFireAuth?

Body:
In my Angular project, I import AngularFireAuth, and then use signInWithEmailAndPassword,
VSCode says the type returned by signInwithEmailAndPassword is firebase.auth.Usercredential.  I can't seem to import this type.

Similarly AngularFireAuth.currentUser returns a firebase.User.  Not clear how to import that type either.  What is the preferred way to store the current user, and how to import the type?

import {AngularFireAuth } from '@angular/fire/compat/auth`

class MyClass {

  constructor(private afAuth : AngularFireAuth){}

  async login(email : string, pw: string) {
    let user = await this.afAuth.signInWithEmailAndPassword(email,pw);
    //user is of type firebase.auth.UserCredential
    let currentUser = this.afAuth.currentUser;
    //currentUser is of type firebase.User;
  }

But if I try to either declare the variables types rather than infer them, I can't do it:

   async login(email : string, pw: string) {
      let user : firebase.auth.UserCredential;
      //produces syntax error `..firebase.compat.index has no exported member 'auth'
      let user : firebase.User;
      //produces syntax error '../firebase.compat.index has no exported member 'User"

   }

I've tried to import from various different sources but none seem to work propertly.

How to import the class of object returned either by 'signInWithEmaila/ndPassword()' or
the currentUser property of AngularFireAuth?


问:
The type initializer for '[Modulename]' threw an exception
i am using visual studio 2022
if i run the program from IDE, it runs, creates the SQLite database
and all funtions work as expectd.

if i create an installation through VS installer program and run the
program, i get the following error

"The type initializer for '[Modulename]' threw an exception"

here is the code in my module.
error occurs no matter were i place this

```<code>
</code>```

#Region "Declarations"

```<code>'Find users Roaming location
'Get the path to the Application Data folder
Public appData1 As String = GetFolderPath(SpecialFolder.ApplicationData)

Public location As String = appData1 & "\RJ Enterprize\" & Application.ProductName
Public fileName As String = "Password2023.rjd"
Public fullPath As String = System.IO.Path.Combine(location, fileName)

Public connectonString As String = String.Format("Data Source = {0}", fullPath)

Public SqlConn As New SQLiteConnection(connectonString)
</code>```

#End Region

```<code></code>```
```<code>

tried in various modules and forms
</code>```

Body:
i am using visual studio 2022
if i run the program from IDE, it runs, creates the SQLite database
and all funtions work as expectd.

if i create an installation through VS installer program and run the
program, i get the following error

"The type initializer for '[Modulename]' threw an exception"

here is the code in my module.
error occurs no matter were i place this

#Region "Declarations"

'Find users Roaming location
'Get the path to the Application Data folder
Public appData1 As String = GetFolderPath(SpecialFolder.ApplicationData)

Public location As String = appData1 & "\RJ Enterprize\" & Application.ProductName
Public fileName As String = "Password2023.rjd"
Public fullPath As String = System.IO.Path.Combine(location, fileName)

Public connectonString As String = String.Format("Data Source = {0}", fullPath)

Public SqlConn As New SQLiteConnection(connectonString)

#End Region

tried in various modules and forms


问:
Web Setup Project on Visual Studio 2022 - Unable to open project error
Good evening,

I have created a Web Form using Visual Studio 2022, and I have created a Web Setup project to help our customers to install the site on their server. I used the official extension that allows to create Setup projects in VS2022 (Microsoft Visual Studio Installer Projects); everything worked fine until some days ago, when VS2022 started to show the following error when trying to load the installer project:

"Unable to open project .../Setup.vdproj".

This is the error I am getting when I try to open/create a Web Setup project

I tried to open it also with VS2019, which I still had installed on my computer, but I got the same error.

At the beginning I thought it was an issue related to the project (maybe for some reasons some files had been corrrupted), so I tried to create a new Web Setup project, both on VS2022 and VS2019. Again, the same error appeared, on both versions of VS. At this point I tried to load the already existing project on another computer, and on the other computer everything worked perfectly, the project was loaded immediatly and no issues have been detected.
I tried to unistall and re-install the Microsoft Visual Studio Installer Projects extension, it didn't solve the problem; I tried to repair VS2022, it didn't solve the problem; I tried to completely uninstall VS2022 and VS2019 and re-install only VS2022, and guess what? It didn't solve the problem.

Does anyone know how to fix this problem, and what is the reason why I am unable to neither load nor create Web Setup projects?

Thank you,
Giacomo


问:
SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2396)') during performance testing in Locust for the upload PUT request
Test execution is in Locust based on HttpUser on MacOS. I'm receiving that kind of error during the upload of file testing, for the file with ~10 MB. The error appears only for more users than 40, rps rate is always equal to users.
I reviewed many topics about SSL errors, I've upgraded all packages related to OpenSSL, also I installed packages related to httpsclient, but it didn't solve the issue, still, for a few PUT requests I'm receiving

```<code>PUT doc_upload_bigSize_PUT_method: SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2396)')
</code>```

I'm not so experienced in performance tests, so maybe the fault is on my side, but still, it is strange that a lot of requests are passing, but 2-3 of them are returning SSLEOF.

This is how it looks from a script perspective:
upload method:

```<code>@staticmethod
def file_upl_pdf(dirname, file_name):
    upload = open(f"{dirname}/{file_name}", "rb")
    return upload
</code>```

Test script:

```<code>def upload_big_size_doc(self):
    file_name = "test_file_big_size.pdf"
    res = self.client.post("/documents", data=json.dumps(data)), name='doc_upload_bigSize_POST_method')
    json_response = json.loads(res.text)
    document_id = jsonpath.jsonpath(json_response, "documentId")[0]
    url_upload = jsonpath.jsonpath(json_response, "url")[0]
    self.client.put(url=url_upload, data=ResourceUtils.file_upl_pdf(dirname="../test_files/big_size", file_name=file_name),
                    headers={'Content-Type': 'application/pdf'},
                    name='doc_upload_bigSize_PUT_method')
</code>```

here I'm running a test:

```<code>@task
def perf_test(self):
    self.upload_big_size_doc()
</code>```

I would like to see rather errors coming from load tests about infra like timeout or something, but SSLEOF seems to me like a bad behaviour of my scripts or config.

Body:
Test execution is in Locust based on HttpUser on MacOS. I'm receiving that kind of error during the upload of file testing, for the file with ~10 MB. The error appears only for more users than 40, rps rate is always equal to users.
I reviewed many topics about SSL errors, I've upgraded all packages related to OpenSSL, also I installed packages related to httpsclient, but it didn't solve the issue, still, for a few PUT requests I'm receiving

PUT doc_upload_bigSize_PUT_method: SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2396)')

I'm not so experienced in performance tests, so maybe the fault is on my side, but still, it is strange that a lot of requests are passing, but 2-3 of them are returning SSLEOF.

This is how it looks from a script perspective:
upload method:

@staticmethod
def file_upl_pdf(dirname, file_name):
    upload = open(f"{dirname}/{file_name}", "rb")
    return upload

Test script:

def upload_big_size_doc(self):
    file_name = "test_file_big_size.pdf"
    res = self.client.post("/documents", data=json.dumps(data)), name='doc_upload_bigSize_POST_method')
    json_response = json.loads(res.text)
    document_id = jsonpath.jsonpath(json_response, "documentId")[0]
    url_upload = jsonpath.jsonpath(json_response, "url")[0]
    self.client.put(url=url_upload, data=ResourceUtils.file_upl_pdf(dirname="../test_files/big_size", file_name=file_name),
                    headers={'Content-Type': 'application/pdf'},
                    name='doc_upload_bigSize_PUT_method')

here I'm running a test:

@task
def perf_test(self):
    self.upload_big_size_doc()

I would like to see rather errors coming from load tests about infra like timeout or something, but SSLEOF seems to me like a bad behaviour of my scripts or config.


问:
How Can I Close My Hamburger Menu After Clicking On A Link?
I have a hamburger menu that's made with pure CSS. It works well, but I'd like to be able to have it closed after clicking on one of the links inside it.

```<code><div class="cp_cont">
<input id="cp_toggle03" type="checkbox">
<div class="cp_mobilebar">
<label for="cp_toggle03" class="cp_menuicon">
<span></span>
</label>
</div>
<label id="h-menu_black" class="cp_toggle03" for="cp_menuicon"></label>
<div id="body" class="noscroll"></div>

<header class="cp_offcm03">

<nav>
<ul style="text-align: center; margin-left: 210px; overflow: hidden;">

<li style="border-bottom: 1px solid lightgray;"><a href="../../../../../Home_English.html">Home</a></li>
<li style="border-bottom: 1px solid lightgray;"><a href="../../../../../Blog_English.html">Blog</a></li>
<li style="border-bottom: 1px solid lightgray;"><a href="../../../../../About_English.html">About This Website</a></li>
<li style="border-bottom: 1px solid lightgray;"><a href="../../../../../Bibliography_English.html">Bibliography</a></li>
</code>```

I've tried to add a closeNav(); function, but haven't been able to get it working. I’d like it so that if I were to go back to a page where the hamburger menu had been opened and used to navigate to another page then it would be closed. If anyone knows how I could close the menu when clicking on a link inside of it I'd appreciate you sharing your knowledge with me. Thank you.

This is my CSS.

```<code>.body{background-color: white;
      font-family: sans-serif;}

 .searchbar{float: right;}

 .image{text-align: center;}

 .setsumei{margin-left: 20px;
           margin-right: 20px;}

 .footer{width: 100%;
           height: 40px;
           text-align: center;
           border-top: 1px solid black;
           position: absolute;
           bottom: 0;
           padding: 10px;}

 .page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -40px;
}

 .page-wrap:after {
  content: "";
  display: block;
  }

 .site-footer, .page-wrap:after {
  /* .push must be the same height as footer */
  height: 20px;
}

 .site-footer {
  text-align: center;
  border-top: 1px solid black;
  padding: 10px;
}

 *, *:before, *:after {
    padding-left: 0;
    margin: 0;
    box-sizing: border-box;

}

 ol, ul {
    list-style: none;
}

 a {
    text-decoration: none;
    color: black;
}

 .cp_cont {
    height: auto;
}

/* menu */
 .cp_offcm03 {
    position: relative;
    z-index: 5000;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
    width: 100%;
    height: auto;
    padding-top: 0;
    -webkit-transition: transform 0.3s ease-in;
            transition: transform 0.3s ease-in;
    text-align: center;
    color: black;
    background-color: white;
}
 .cp_offcm03 nav,
 .cp_offcm03 ul {
    height: 100%;
}

 .cp_offcm03 li {
    display: inline-block;
    margin-right: -6px;
}

 .cp_offcm03 a {
    display: block;
    padding: 15px 45px;
    margin-bottom: -5px;
    -webkit-transition: background-color .3s ease-in;
            transition: background-color .3s ease-in;
}

 .cp_offcm03 a:hover {
    background-color: lightgray;
}

/* menu toggle */
 #cp_toggle03 {
    display: none;
}

 #cp_toggle03:checked ~ .cp_offcm03 {
    -webkit-transform: translateX(0);
                    transform: translateX(0);
}

 #cp_toggle03:checked ~ .cp_container {
    -webkit-transform: translateX(0);
                    transform: translateX(0);
}

 .cp_mobilebar {
    display: none;

}

/* content */
 .cp_container {
    position: relative;
    top: 0;
    padding: 35px auto;
    -webkit-transition: transform .3s ease-in;
            transition: transform .3s ease-in;
}

 .cp_content {
    margin: 0 auto;
    padding: 20px;
    height: 65vh;
    text-align: center;

}

@media (max-width: 1130px)and (min-width: 280px) {
/* menu */
 .cp_offcm03 {
        position: fixed;
        left: -250px;
        overflow-y: hidden;
        width: 250px;
        height: 100%;
        padding-top: 40px;
        color: black;
        background-color: white;
        z-index: 1000;
    }

 .cp_offcm03 nav {
        background: white;
        border-right: 0.5px solid lightgray;
        margin-left: -210px;
    }

 .cp_offcm03 li {
        display: block;
        margin-right: 0;}

 .cp_offcm03 a {
        padding: 20px;

    }

/* menu toggle */
 .cp_mobilebar {
        display: block;
        z-index: 2000;
        position: relative;
        top: 0;
        left: 0;
        padding: 0 25px;
        width: 100%;
        height: 40px;
        background-color: white;
        border-bottom: .05px solid lightgray;

    }

 .cp_menuicon {
        display: block;
        position: relative;
        width: 25px;
        height: 100%;
        cursor: pointer;
        -webkit-transition: transform .3s ease-in;
                transition: transform .3s ease-in;
    }
 .cp_menuicon > span {
        display: block;
        position: absolute;
        top: 55%;
        margin-top: -0.3em;
        width: 100%;
        height: 0.2em;
        border-radius: 1px;
        background-color: black;
        -webkit-transition: transform .3s ease;
                transition: transform .3s ease;
    }
 .cp_menuicon > span:before,
 .cp_menuicon > span:after {
        content: "";
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: 1px;
        background-color: black;
        -webkit-transition: transform .3s ease-in;
                transition: transform .3s ease-in;
    }

 .cp_menuicon > span:before {
        -webkit-transform: translateY(-0.6em);
                transform: translateY(-0.6em);
    }

 .cp_menuicon > span:after {
        -webkit-transform: translateY(0.6em);
                transform: translateY(0.6em);
    }

 #cp_toggle03:checked + .cp_mobilebar .cp_menuicon {
        -webkit-transform: rotate(45deg);
                transform: rotate(45deg);
    }

 #cp_toggle03:checked + .cp_mobilebar span:before,
 #cp_toggle03:checked + .cp_mobilebar span:after {
        -webkit-transform: rotate(90deg);
                transform: rotate(90deg);
    }

 #cp_toggle03:checked ~ .cp_offcm03 {
        -webkit-transform: translateX(100%);
                transform: translateX(100%);
    }

 #cp_toggle03:checked ~ .cp_container {
        -webkit-transform: translateX(250px);
                transform: translateX(250px);
    }

 input:checked ~ #h-menu_black {
    display: block;/*カバーを表示*/
    opacity: .6;
}

 #h-menu_black {
    display: none;
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: black;
    opacity: 0;
    transition: .7s ease-in-out;
}

/* content */
 .cp_container {
        top: 60px;
        height: 92vh;
        text-align: center;
    }

 .noscroll{
        overflow: hidden;
        position: fixed;
    }
</code>```

Body:
I have a hamburger menu that's made with pure CSS. It works well, but I'd like to be able to have it closed after clicking on one of the links inside it.

<input id="cp_toggle03" type="checkbox">

Home

Blog

About This Website

Bibliography

I've tried to add a closeNav(); function, but haven't been able to get it working. I’d like it so that if I were to go back to a page where the hamburger menu had been opened and used to navigate to another page then it would be closed. If anyone knows how I could close the menu when clicking on a link inside of it I'd appreciate you sharing your knowledge with me. Thank you.

This is my CSS.

.body{background-color: white;
      font-family: sans-serif;}

 .searchbar{float: right;}

 .image{text-align: center;}

 .setsumei{margin-left: 20px;
           margin-right: 20px;}

 .footer{width: 100%;
           height: 40px;
           text-align: center;
           border-top: 1px solid black;
           position: absolute;
           bottom: 0;
           padding: 10px;}

 .page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -40px;
}

 .page-wrap:after {
  content: "";
  display: block;
  }

 .site-footer, .page-wrap:after {
  /* .push must be the same height as footer */
  height: 20px;
}

 .site-footer {
  text-align: center;
  border-top: 1px solid black;
  padding: 10px;
}

 *, *:before, *:after {
    padding-left: 0;
    margin: 0;
    box-sizing: border-box;

}

 ol, ul {
    list-style: none;
}

 a {
    text-decoration: none;
    color: black;
}

 .cp_cont {
    height: auto;
}

/* menu */
 .cp_offcm03 {
    position: relative;
    z-index: 5000;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
    width: 100%;
    height: auto;
    padding-top: 0;
    -webkit-transition: transform 0.3s ease-in;
            transition: transform 0.3s ease-in;
    text-align: center;
    color: black;
    background-color: white;
}
 .cp_offcm03 nav,
 .cp_offcm03 ul {
    height: 100%;
}

 .cp_offcm03 li {
    display: inline-block;
    margin-right: -6px;
}

 .cp_offcm03 a {
    display: block;
    padding: 15px 45px;
    margin-bottom: -5px;
    -webkit-transition: background-color .3s ease-in;
            transition: background-color .3s ease-in;
}

 .cp_offcm03 a:hover {
    background-color: lightgray;
}

/* menu toggle */
 #cp_toggle03 {
    display: none;
}

 #cp_toggle03:checked ~ .cp_offcm03 {
    -webkit-transform: translateX(0);
                    transform: translateX(0);
}

 #cp_toggle03:checked ~ .cp_container {
    -webkit-transform: translateX(0);
                    transform: translateX(0);
}

 .cp_mobilebar {
    display: none;

}

/* content */
 .cp_container {
    position: relative;
    top: 0;
    padding: 35px auto;
    -webkit-transition: transform .3s ease-in;
            transition: transform .3s ease-in;
}

 .cp_content {
    margin: 0 auto;
    padding: 20px;
    height: 65vh;
    text-align: center;

}

@media (max-width: 1130px)and (min-width: 280px) {
/* menu */
 .cp_offcm03 {
        position: fixed;
        left: -250px;
        overflow-y: hidden;
        width: 250px;
        height: 100%;
        padding-top: 40px;
        color: black;
        background-color: white;
        z-index: 1000;
    }

 .cp_offcm03 nav {
        background: white;
        border-right: 0.5px solid lightgray;
        margin-left: -210px;
    }

 .cp_offcm03 li {
        display: block;
        margin-right: 0;}

 .cp_offcm03 a {
        padding: 20px;

    }

/* menu toggle */
 .cp_mobilebar {
        display: block;
        z-index: 2000;
        position: relative;
        top: 0;
        left: 0;
        padding: 0 25px;
        width: 100%;
        height: 40px;
        background-color: white;
        border-bottom: .05px solid lightgray;

    }

 .cp_menuicon {
        display: block;
        position: relative;
        width: 25px;
        height: 100%;
        cursor: pointer;
        -webkit-transition: transform .3s ease-in;
                transition: transform .3s ease-in;
    }
 .cp_menuicon > span {
        display: block;
        position: absolute;
        top: 55%;
        margin-top: -0.3em;
        width: 100%;
        height: 0.2em;
        border-radius: 1px;
        background-color: black;
        -webkit-transition: transform .3s ease;
                transition: transform .3s ease;
    }
 .cp_menuicon > span:before,
 .cp_menuicon > span:after {
        content: "";
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: 1px;
        background-color: black;
        -webkit-transition: transform .3s ease-in;
                transition: transform .3s ease-in;
    }

 .cp_menuicon > span:before {
        -webkit-transform: translateY(-0.6em);
                transform: translateY(-0.6em);
    }

 .cp_menuicon > span:after {
        -webkit-transform: translateY(0.6em);
                transform: translateY(0.6em);
    }

 #cp_toggle03:checked + .cp_mobilebar .cp_menuicon {
        -webkit-transform: rotate(45deg);
                transform: rotate(45deg);
    }

 #cp_toggle03:checked + .cp_mobilebar span:before,
 #cp_toggle03:checked + .cp_mobilebar span:after {
        -webkit-transform: rotate(90deg);
                transform: rotate(90deg);
    }

 #cp_toggle03:checked ~ .cp_offcm03 {
        -webkit-transform: translateX(100%);
                transform: translateX(100%);
    }

 #cp_toggle03:checked ~ .cp_container {
        -webkit-transform: translateX(250px);
                transform: translateX(250px);
    }

 input:checked ~ #h-menu_black {
    display: block;/*カバーを表示*/
    opacity: .6;
}

 #h-menu_black {
    display: none;
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: black;
    opacity: 0;
    transition: .7s ease-in-out;
}

/* content */
 .cp_container {
        top: 60px;
        height: 92vh;
        text-align: center;
    }

 .noscroll{
        overflow: hidden;
        position: fixed;
    }


问:
I need to change the link for a specific button above 768px width with jQuery
I have an issue with a facebook button on my wordpress site, in mobile it was opening browsers instead of opening the fb app, so I changed the link to a fb:// but now on desktop it throws a message before heading to the facebook page to "open AddressUrlForwarder" before letting you in. I want to keep the button as is for 768px resolutions and below because thats my breakpoint, and above just have the regular facebook www. url. At first I thought a media query could solve it but I realized there must be a much simpler way with jQuery, a replacewith with and if maybe, Im just not very keen on the syntax. Thanks for the help

All I've done is change with jQuery the default www.facebook.com/... to the fb://..., the button is set automatically when the url is written in the theme, so I had to change the link type with jQuery. As of that moment I was expecting it not to be a problem on desktop, but when I tried it, it showed the "open AddressUrlForwarder" message.


问:
User defined cross entropy and built-in cross entropy of KERAS gives same loss but different gradients
When i train a simple NN architecture with cross entropy i get same loss when using the built-in keras crossentropy loss and user defined crossentropy while the gradients are different for the different implementation ...

Important to mention that this issue is comes up when my "target" is not categorical variable (As it happening in policy gradients). When i define the target to be 0 or 1 the gradient and losses are the same.

I made some public google colab notebook so you can see and run the example link

Also attaching the code and the results here.
I run the the code twice for the built-in and the manual cross entropy. once with categorical target , in order to show that the results are the same. and once with non categorical target.

from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow import constant ,GradientTape, math
import numpy as np

def get_loss_and_grads(function,
                       y_true,
                       y_pred):

  with GradientTape() as gr:
    gr.watch(y_pred)

    loss = function(y_true = y_true,
                    y_pred = y_pred)

  dy_dx = gr.gradient(loss, y_pred)
  return loss, dy_dx

def udf_loss(y_true, y_pred):
  loss = - math.log(y_pred) * y_true
  return loss

# Define predicted and actual target variables
y_true = constant(np.array([1.]))
y_pred = constant(np.array([0.5]))

# Run for built in keras cross entropy
loss, dy_dx = get_loss_and_grads(function = BinaryCrossentropy(from_logits=False) ,
                                 y_true = y_true,
                                 y_pred = y_pred)

print(f"\n\n-- ==  built in cross entropy -  y_true = {y_true} , y_pred = {y_pred} == --\n")
print("loss ", loss)
print("dy_dx ", dy_dx)

# Run for user defined cross entropy
loss, dy_dx = get_loss_and_grads(function = udf_loss ,
                                 y_true = y_true,
                                 y_pred = y_pred)

print(f"\n-- ==  user defined cross entropy - y_true = {y_true} , y_pred = {y_pred} == --\n")
print("loss ", loss)
print("dy_dx ", dy_dx)

# Define predicted and actual target variables
y_true = constant(np.array([5.]))
y_pred = constant(np.array([0.5]))

# Run for built in keras cross entropy
loss, dy_dx = get_loss_and_grads(function = BinaryCrossentropy(from_logits=False) ,
                                 y_true = y_true,
                                 y_pred = y_pred)

print(f"\n\n-- ==  built in cross entropy -  y_true = {y_true} , y_pred = {y_pred} == --\n")
print("loss ", loss)
print("dy_dx ", dy_dx)

# Run for user defined cross entropy
loss, dy_dx = get_loss_and_grads(function = udf_loss ,
                                 y_true = y_true,
                                 y_pred = y_pred)

print(f"\n-- ==  user defined cross entropy - y_true = {y_true} , y_pred = {y_pred} == --\n")
print("loss ", loss)
print("dy_dx ", dy_dx)

-- ==  built in cross entropy -  y_true = [1.] , y_pred = [0.5] == --

loss  tf.Tensor(0.6931469805599654, shape=(), dtype=float64)
dy_dx  tf.Tensor([-1.9999996], shape=(1,), dtype=float64)

-- ==  user defined cross entropy - y_true = [1.] , y_pred = [0.5] == --

loss  tf.Tensor([0.69314718], shape=(1,), dtype=float64)
dy_dx  tf.Tensor([-2.], shape=(1,), dtype=float64)

-- ==  built in cross entropy -  y_true = [5.] , y_pred = [0.5] == --

loss  tf.Tensor(0.6931469805599653, shape=(), dtype=float64)
dy_dx  tf.Tensor([-17.9999964], shape=(1,), dtype=float64)

-- ==  user defined cross entropy - y_true = [5.] , y_pred = [0.5] == --

loss  tf.Tensor([3.4657359], shape=(1,), dtype=float64)
dy_dx  tf.Tensor([-10.], shape=(1,), dtype=float64)```


问:
How to run Nest+React app with docker-compose if both containers work fine separately
I try to run both React and Nest apps with docker-compose up, but it fails while running the server.
However, there is not problems when starting 2 containers separately.

The error is:

```<code>server  | Unknown command: "start:dev"
server  |
server  | Did you mean one of these?
server  |     npm run start:dev # run the "start:dev" package script
</code>```

docker-compose.yml:

```<code>version: "3"
services:
    client:
        container_name: client
        build:
            context: ./client
            dockerfile: Dockerfile
        image: client
        ports:
            - "3000:3000"
        volumes:
            - ./client:/app
    server:
        container_name: server
        build:
            context: ./server
            dockerfile: Dockerfile
        image: server
        ports:
            - "8080:8080"
        volumes:
            - ./server:/app
</code>```

Server Dockerfile:

```<code>FROM node:16

WORKDIR ./app

COPY package.json ./

RUN npm install

COPY . .

ENV PORT=8080

EXPOSE 8080

CMD ["npm", "run", "start:dev"]
</code>```

Client Dockerfile:

```<code>FROM node:16

WORKDIR ./app

COPY package.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]
</code>```

The issue is with docker-compose.yml, but I can't see if it's connected to nest or docker.
Thank you for the help in advance.

Body:
I try to run both React and Nest apps with docker-compose up, but it fails while running the server.
However, there is not problems when starting 2 containers separately.

The error is:

server  | Unknown command: "start:dev"
server  |
server  | Did you mean one of these?
server  |     npm run start:dev # run the "start:dev" package script

docker-compose.yml:

version: "3"
services:
    client:
        container_name: client
        build:
            context: ./client
            dockerfile: Dockerfile
        image: client
        ports:
            - "3000:3000"
        volumes:
            - ./client:/app
    server:
        container_name: server
        build:
            context: ./server
            dockerfile: Dockerfile
        image: server
        ports:
            - "8080:8080"
        volumes:
            - ./server:/app

Server Dockerfile:

FROM node:16

WORKDIR ./app

COPY package.json ./

RUN npm install

COPY . .

ENV PORT=8080

EXPOSE 8080

CMD ["npm", "run", "start:dev"]

Client Dockerfile:

FROM node:16

WORKDIR ./app

COPY package.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

The issue is with docker-compose.yml, but I can't see if it's connected to nest or docker.
Thank you for the help in advance.


问:
Add element to own c++ template class with overloading operator+=
I have to write a header file to an existing cpp with making an own template class. There is a simple add method but I have to overload the operator+= function.
If I try to add the elements separately, like this:

```<code>ls += lmb;
ls += lmc;
</code>```

than it works well, but if I try to do it like in the cpp file:

```<code>(ls += lmb) += lmc;
</code>```

than it doesn't work, it only add one element.

It's important: I can't change the cpp file!

The cpp look like this:

```<code>#include <iostream>
#include "mapalign.h"
#include <string>
#include <algorithm>
#include <map>
#include "mapalign.h"

struct string_size_less
{

  bool operator()( const std::string& a,
                   const std::string& b ) const
  {
    return a.size() < b.size();
  }

};

const int max = 1000;

bool check()
{

  std::map<std::string, int> sma;
  std::map<std::string, int> smb;
  std::map<std::string, int> smc;

  map_aligner<std::string, int> sa;
  sa.add( sma );
  sa.add( smb );
  sa.add( smc );

  sma[ "C++" ] = 1;
  smb[ "Ada" ] = 2;
  smc[ "C" ] = 3;
  smc[ "Python" ] = 4;
  smc[ "Ada"] = 5;

  sa.align();

  std::map<int, double> ima;
  std::map<int, double> imb;
  for( int i = 0; i < max; ++i )
  {
    if ( 0 == i % 2 )
    {
      ima[ i ] = max - i;
    }
    else
    {
      imb[ i ] = max;
    }
  }

  map_aligner<int, double> ia;
  ia.add( ima );
  ia.add( imb );

  ia.align();

  if ( ( 4 != sma.size() && 1 != imb.count( 0 )) || max * 1U != ima.size() ||
       1 != smc.count( "C++" ) || "Ada" != sma.begin()->first ||
       0 != sma.begin()->second ||  4 != smc.size() ||
       1 != smb.count( "Python" ) || 0 != imb.begin()->first ||
       0.8 <= imb.begin()->second || 1 != imb.count( max / 2 ) )
  {
    return false;
  }

  sma[ "Pascal" ] = 5;
  sa.set_filler( max );
  sa.align();

  std::map<std::string, std::string> langsa;
  langsa[ "C++" ] = "<3";
  langsa[ "Python" ] = ":|";
  std::map<std::string, std::string> langsb;
  langsb[ "Brainfuck" ] = ":S";
  langsb[ "Python" ] = ":/";
  langsb[ "C" ] = ":)";

  map_aligner<std::string, std::string> lsa;
  lsa.add( langsa );
  lsa.add( langsb );

  lsa.align();
  lsa.erase( "Python" );

  if ( 0 != langsa.count( "Python" ) || max != smc[ "Pascal" ] ||
       !langsa.begin()->second.empty() || max != smb[ "Pascal" ] ||
       2 * 1U != langsb.begin()->second.size() ||
       0 != langsb.count( "Python" ) || 1 != langsb.count( "C++" ) )
  {
    return false;
  }

  std::map<std::string, std::string, string_size_less> lma;
  std::map<std::string, std::string, string_size_less> lmb;
  std::map<std::string, std::string, string_size_less> lmc;

  lma[ "C++" ] = ":D";
  lmb[ "Eiffel" ] = ":P";
  lmc[ "C" ] = "8-)";
  lmc[ "Ada" ] = "!";

  map_aligner<std::string, std::string, string_size_less> ls;
  ls.add( lma );
  (ls += lmb) += lmc;

  ls.align();

  std::cout << ls.count() << "\n";
  std::cout << lmb.size() << "\n";

  std::cout << (3 == ls.count()) << (1 == lmc.count( "Ada" )) <<
       (3 * 1U == lmb.size()) << (1 == lma.count( "Python" )) <<
       (2 == lsa.count()) << (2 == ia.count()) << "\n" ;

  return ( 3 == ls.count() && 1 == lmc.count( "Ada" ) &&
       3 * 1U == lmb.size() && 1 == lma.count( "Python" ) &&
       2 == lsa.count() && 2 == ia.count() );
}

int main()
{
  std::cout
    << "Your solution is "
    << (check() ? "" : "not ")
    << "ready for submission."
    << std::endl;
}

</code>```

This is my operator+= function now:

```<code>            map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
                maps_.push_back(&m);
                map_aligner ma = *this;
                return ma;
            }
</code>```

The whole header look like this:

```<code>#ifndef MAPALIGN_H
#define MAPALIGN_H

#include <vector>
#include <map>
#include <typeinfo>

template<typename KEY, typename VALUE, typename COMPARE = std::less<KEY>>
class map_aligner{

    public:
            typedef typename std::map<KEY, VALUE, COMPARE>::size_type size_type;

            map_aligner() {}

            void add(std::map<KEY, VALUE, COMPARE>& m) {
                maps_.push_back(&m);
            }

            map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
                maps_.push_back(&m);
                map_aligner ma = *this;
                return ma;
            }

            size_type count() const {
                return maps_.size();
            }

            void align(){
                for(int i = 0; i != (int)maps_.size(); i++ ){
                    std::map<KEY, VALUE, COMPARE>* first_map = maps_.at(i);
                    for(typename std::map<KEY, VALUE, COMPARE>::iterator j = first_map->begin(); j !=first_map->end(); j++ ){
                        for(int h = 0; h != (int)maps_.size(); h++ ){
                            std::map<KEY, VALUE, COMPARE>* second_map = maps_.at(h);
                            if(first_map != second_map && notContainsPair(second_map, j)){
                                second_map->insert(std::make_pair(j->first, filler_));
                            }
                        }
                    }
                }
            }

            bool notContainsPair(std::map<KEY, VALUE, COMPARE>* map,typename std::map<KEY, VALUE, COMPARE>::iterator it){
                for(typename std::map<KEY, VALUE, COMPARE>::iterator g = map->begin(); g != map->end(); g++ ){
                    if(it->first != g->first){
                        return true;
                    }
                }
                return false;
            }

            void set_filler(VALUE filler){
                filler_ = filler;
            }

            void erase(KEY key){
                for(int h = 0; h != (int)maps_.size(); h++ ){
                    std::map<KEY, VALUE>* map = maps_.at(h);
                    typename std::map<KEY, VALUE, COMPARE>::iterator it;
                    map->erase(key);
                    if(typeid(it->first) == typeid(it->second)){
                        for(it = map->begin(); it != map->end(); it++){
                            if(key == it->second){
                                map->erase(it->first);
                            }
                        }
                    }
                }
            }

    private:
        std::vector<std::map<KEY, VALUE, COMPARE>*> maps_;
        VALUE filler_ = VALUE();
};

#endif
</code>```

Body:
I have to write a header file to an existing cpp with making an own template class. There is a simple add method but I have to overload the operator+= function.
If I try to add the elements separately, like this:

ls += lmb;
ls += lmc;

than it works well, but if I try to do it like in the cpp file:

(ls += lmb) += lmc;

than it doesn't work, it only add one element.

It's important: I can't change the cpp file!

The cpp look like this:

#include <iostream>
#include "mapalign.h"
#include <string>
#include <algorithm>
#include <map>
#include "mapalign.h"

struct string_size_less
{

  bool operator()( const std::string& a,
                   const std::string& b ) const
  {
    return a.size() < b.size();
  }

};

const int max = 1000;

bool check()
{

  std::map<std::string, int> sma;
  std::map<std::string, int> smb;
  std::map<std::string, int> smc;

  map_aligner<std::string, int> sa;
  sa.add( sma );
  sa.add( smb );
  sa.add( smc );

  sma[ "C++" ] = 1;
  smb[ "Ada" ] = 2;
  smc[ "C" ] = 3;
  smc[ "Python" ] = 4;
  smc[ "Ada"] = 5;

  sa.align();

  std::map<int, double> ima;
  std::map<int, double> imb;
  for( int i = 0; i < max; ++i )
  {
    if ( 0 == i % 2 )
    {
      ima[ i ] = max - i;
    }
    else
    {
      imb[ i ] = max;
    }
  }

  map_aligner<int, double> ia;
  ia.add( ima );
  ia.add( imb );

  ia.align();

  if ( ( 4 != sma.size() && 1 != imb.count( 0 )) || max * 1U != ima.size() ||
       1 != smc.count( "C++" ) || "Ada" != sma.begin()->first ||
       0 != sma.begin()->second ||  4 != smc.size() ||
       1 != smb.count( "Python" ) || 0 != imb.begin()->first ||
       0.8 <= imb.begin()->second || 1 != imb.count( max / 2 ) )
  {
    return false;
  }

  sma[ "Pascal" ] = 5;
  sa.set_filler( max );
  sa.align();

  std::map<std::string, std::string> langsa;
  langsa[ "C++" ] = "<3";
  langsa[ "Python" ] = ":|";
  std::map<std::string, std::string> langsb;
  langsb[ "Brainfuck" ] = ":S";
  langsb[ "Python" ] = ":/";
  langsb[ "C" ] = ":)";

  map_aligner<std::string, std::string> lsa;
  lsa.add( langsa );
  lsa.add( langsb );

  lsa.align();
  lsa.erase( "Python" );

  if ( 0 != langsa.count( "Python" ) || max != smc[ "Pascal" ] ||
       !langsa.begin()->second.empty() || max != smb[ "Pascal" ] ||
       2 * 1U != langsb.begin()->second.size() ||
       0 != langsb.count( "Python" ) || 1 != langsb.count( "C++" ) )
  {
    return false;
  }

  std::map<std::string, std::string, string_size_less> lma;
  std::map<std::string, std::string, string_size_less> lmb;
  std::map<std::string, std::string, string_size_less> lmc;

  lma[ "C++" ] = ":D";
  lmb[ "Eiffel" ] = ":P";
  lmc[ "C" ] = "8-)";
  lmc[ "Ada" ] = "!";

  map_aligner<std::string, std::string, string_size_less> ls;
  ls.add( lma );
  (ls += lmb) += lmc;

  ls.align();

  std::cout << ls.count() << "\n";
  std::cout << lmb.size() << "\n";

  std::cout << (3 == ls.count()) << (1 == lmc.count( "Ada" )) <<
       (3 * 1U == lmb.size()) << (1 == lma.count( "Python" )) <<
       (2 == lsa.count()) << (2 == ia.count()) << "\n" ;

  return ( 3 == ls.count() && 1 == lmc.count( "Ada" ) &&
       3 * 1U == lmb.size() && 1 == lma.count( "Python" ) &&
       2 == lsa.count() && 2 == ia.count() );
}

int main()
{
  std::cout
    << "Your solution is "
    << (check() ? "" : "not ")
    << "ready for submission."
    << std::endl;
}

This is my operator+= function now:

            map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
                maps_.push_back(&m);
                map_aligner ma = *this;
                return ma;
            }

The whole header look like this:

#ifndef MAPALIGN_H
#define MAPALIGN_H

#include <vector>
#include <map>
#include <typeinfo>

template<typename KEY, typename VALUE, typename COMPARE = std::less<KEY>>
class map_aligner{

    public:
            typedef typename std::map<KEY, VALUE, COMPARE>::size_type size_type;

            map_aligner() {}

            void add(std::map<KEY, VALUE, COMPARE>& m) {
                maps_.push_back(&m);
            }

            map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
                maps_.push_back(&m);
                map_aligner ma = *this;
                return ma;
            }

            size_type count() const {
                return maps_.size();
            }

            void align(){
                for(int i = 0; i != (int)maps_.size(); i++ ){
                    std::map<KEY, VALUE, COMPARE>* first_map = maps_.at(i);
                    for(typename std::map<KEY, VALUE, COMPARE>::iterator j = first_map->begin(); j !=first_map->end(); j++ ){
                        for(int h = 0; h != (int)maps_.size(); h++ ){
                            std::map<KEY, VALUE, COMPARE>* second_map = maps_.at(h);
                            if(first_map != second_map && notContainsPair(second_map, j)){
                                second_map->insert(std::make_pair(j->first, filler_));
                            }
                        }
                    }
                }
            }

            bool notContainsPair(std::map<KEY, VALUE, COMPARE>* map,typename std::map<KEY, VALUE, COMPARE>::iterator it){
                for(typename std::map<KEY, VALUE, COMPARE>::iterator g = map->begin(); g != map->end(); g++ ){
                    if(it->first != g->first){
                        return true;
                    }
                }
                return false;
            }

            void set_filler(VALUE filler){
                filler_ = filler;
            }

            void erase(KEY key){
                for(int h = 0; h != (int)maps_.size(); h++ ){
                    std::map<KEY, VALUE>* map = maps_.at(h);
                    typename std::map<KEY, VALUE, COMPARE>::iterator it;
                    map->erase(key);
                    if(typeid(it->first) == typeid(it->second)){
                        for(it = map->begin(); it != map->end(); it++){
                            if(key == it->second){
                                map->erase(it->first);
                            }
                        }
                    }
                }
            }

    private:
        std::vector<std::map<KEY, VALUE, COMPARE>*> maps_;
        VALUE filler_ = VALUE();
};

#endif


问:
How to cast both sides of Either?
I am trying to have Either<Failure, Concrete> where Concrete extends Abstract class, but I cannot get it to work. If I try to cast the left side I get the error:

```<code>type 'Right<Failure, Concrete>' is not a subtype of type 'Either<Failure, Abstract>' in type cast
</code>```

if I try for the right side I get:

```<code>type 'Left<Object, Concrete>' is not a subtype of type 'Either<Failure, Concrete>' in type cast
</code>```

And bimap does not seems to solve it. Is there an easy way to do it? tks

Title: How to cast both sides of Either?

Body:
I am trying to have Either<Failure, Concrete> where Concrete extends Abstract class, but I cannot get it to work. If I try to cast the left side I get the error:

type 'Right<Failure, Concrete>' is not a subtype of type 'Either<Failure, Abstract>' in type cast

if I try for the right side I get:

type 'Left<Object, Concrete>' is not a subtype of type 'Either<Failure, Concrete>' in type cast

And bimap does not seems to solve it. Is there an easy way to do it? tks


问:
'LXC launch' gives 'Error: Failed instance creation'
Trying to run this:

```<code>ros@ros-Virtualbox:/$ sudo lxc launch -p row ubuntu:20.04 turtlebot
Creating turtlebot

Error: Failed instance creation: Failed creating instance record: Failed initialising instance: Failed getting root disk: No root device could be found

ros@ros-Virtualbox:/$
</code>```

But the above error is shown.

Made sure LXC was installed

Removed version from 'ubuntu'; ubuntu:20.04

Body:
Trying to run this:

ros@ros-Virtualbox:/$ sudo lxc launch -p row ubuntu:20.04 turtlebot
Creating turtlebot

Error: Failed instance creation: Failed creating instance record: Failed initialising instance: Failed getting root disk: No root device could be found

ros@ros-Virtualbox:/$

But the above error is shown.

Made sure LXC was installed

Removed version from 'ubuntu'; ubuntu:20.04


问:
Android studio, solve problem with missing local.properties file after cloning git repo
I want to work on my project on several devices, hence I'm using git clone. However, after doing so I always get an error with incorrect sdk.dir path (missing local.properties). As far as I know adding it manually is dangerous, so my question is how can I solve this conveniently, without any issues?</p>


问:
Azure Search API throws CORS error even when CORS is enabled
I have an Azure search index called users that has CORS configured to * (for now) to allow all origins. When I make a GET request to it programmatically using fetch or axios, I get a CORS error:

Access to XMLHttpRequest  at 'https://MY_SEARCH_SERVICE.search.windows.net/indexes/users/docs?api-version=2021-04-30-Preview&%24top=5&search=matt*&%24searchFields=name&%24select=id%2Cname%2Cemail&api-key=MY_API_KEY' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

However, if I put the same GET URL into a browser, it returns the list of expected results with no errors.

Here's my code (to run, create a Svelte app and put this in App.svelte or use the Svelte  REPL. You must also have an Azure Search service set up, and you'll need to replace the placeholder variables MY_SEARCH_SERVICE and MY_API_KEY with your own, along with an index on which you want to try this):

```


问:
.net 7 redirect unknown cultures, getting 404 when not supplying culture
When i route to a page and supply the culture it works as intended
ie. localhost/en-us/page/index.cshtml.

but when i go to localhost/folder/page.cshtml I get a 404.
I would like to know if its possible to still navigate to localhost/{Culture}/folder/page but instead of have to supply the culture get the current users culture.

in my program.cs

```<code>builder.Services.Configure<RequestLocalizationOptions>(ops =>
{
    var cultures = new CultureInfo[] { new CultureInfo("en-US"), new CultureInfo("en-AU")
        , new CultureInfo("en-GB")
        , new CultureInfo("es-US")
         , new CultureInfo("en-CA")
          , new CultureInfo("fr-CA")
         , new CultureInfo("en-ZA")

    };
    ops.SupportedCultures = cultures;
    ops.SupportedUICultures = cultures;
    ops.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US");
    ops.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
    ops.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider { Options = ops });
});
</code>```

have also added manual routes as well

```<code>builder.Services.AddRazorPages()
                .AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/{FromIata:length(3)}-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/to-{ToIata:length(3)}-{CityName}");

                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/{FromIata:length(3)?}/{ToIata:length(3)?}");

               ;
</code>```

on my /page/index.cshtml

```<code>@page "/flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
@using Microsoft.AspNetCore.Localization;
@using System.Globalization;
</code>```

any advice would be greatly appreciated
thanks in advance.

Body:
When i route to a page and supply the culture it works as intended
ie. localhost/en-us/page/index.cshtml.

but when i go to localhost/folder/page.cshtml I get a 404.
I would like to know if its possible to still navigate to localhost/{Culture}/folder/page but instead of have to supply the culture get the current users culture.

in my program.cs

builder.Services.Configure<RequestLocalizationOptions>(ops =>
{
    var cultures = new CultureInfo[] { new CultureInfo("en-US"), new CultureInfo("en-AU")
        , new CultureInfo("en-GB")
        , new CultureInfo("es-US")
         , new CultureInfo("en-CA")
          , new CultureInfo("fr-CA")
         , new CultureInfo("en-ZA")

    };
    ops.SupportedCultures = cultures;
    ops.SupportedUICultures = cultures;
    ops.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US");
    ops.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
    ops.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider { Options = ops });
});

have also added manual routes as well

builder.Services.AddRazorPages()
                .AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/{FromIata:length(3)}-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/to-{ToIata:length(3)}");
                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/to-{ToIata:length(3)}-{CityName}");

                    options.Conventions.AddPageRoute("/Flights/Index", "{Culture?}/flights/{FromIata:length(3)?}/{ToIata:length(3)?}");

               ;

on my /page/index.cshtml

@page "/flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
@using Microsoft.AspNetCore.Localization;
@using System.Globalization;

any advice would be greatly appreciated
thanks in advance.


问:
minimum weight vertex cover of a tree by algorist.com
While getting through Algorithm Design Manual (by Skiena) I have faced the minimum weight vertex cover problem. Though I am aware of the DP solution for this problem algorist.com states another one through two coloring technique. It states the following:

We know we will be able to remove at most one every other node, so we
use a two-coloring technique (Red/Black) and perform a post-order
traversal. Let's assume we will remove all the Black node. When we
process a node, we also store with each node the sum over its
immediate children of the respective Red and Black weight for the
subtree. If not all of the children are Red, we need to mark the
current node as Red. But we also have the option to reverse the
coloring of all the Red-children's subtree. So we look at the sum over
the red-children for Red and Black, and compare the difference of
these sum to the current node's weight. If the current node's weight
is above, we swap the coloring for these subtree. The current node
will record the Black and Red sum of its children's subtree, and add
its own weight to its color.

Can anyone, please, rephrase what is written in the solution, since I can't exactly figure out the condition of switching the colors and I have read it quite many times.

Thanks.


问:
How could I use a different port for transmitting data by asio (non-boost version)?
Normally, the port set up for listening is used for accepting connections only, right? When a new connection is built, the sever will use a different port for data transmitting. Here are some parts of the code:

```<code>void WaitForConnection()
        {
            m_asioAcceptor.async_accept(
                [this](std::error_code ec, asio::ip::tcp::socket socket)
            {
                if (!ec)
                {
                    std::shared_ptr<connection<T>> new =
                        std::make_shared<connection<T>>(connection<T>::owner::server,
                                                        m_asioContext, std::move(socket),
                                                        m_qMessagesIn);

                    ...

                }
                else
                {
                    std::cout << "[SERVER] New Connection Error: " << ec.message() << "\n";
                }

                WaitForConnection();
            });
        }
</code>```

Then I found the server use the same port for both listening and data transmitting with all clients. How could I instruct asio to use a unique port for each connection?

Thank you for your help!

Body:
Normally, the port set up for listening is used for accepting connections only, right? When a new connection is built, the sever will use a different port for data transmitting. Here are some parts of the code:

void WaitForConnection()
        {
            m_asioAcceptor.async_accept(
                [this](std::error_code ec, asio::ip::tcp::socket socket)
            {
                if (!ec)
                {
                    std::shared_ptr<connection<T>> new =
                        std::make_shared<connection<T>>(connection<T>::owner::server,
                                                        m_asioContext, std::move(socket),
                                                        m_qMessagesIn);

                    ...

                }
                else
                {
                    std::cout << "[SERVER] New Connection Error: " << ec.message() << "\n";
                }

                WaitForConnection();
            });
        }

Then I found the server use the same port for both listening and data transmitting with all clients. How could I instruct asio to use a unique port for each connection?

Thank you for your help!


问:
Trying to understand why I'm getting "Rendered more hooks than previous render"
I'm working on adding a select box for my React Native component, but I keep getting the mentioned error message and I'm not sure why.  Any help is appreciated.

Error message: Rendered more hooks than previous render

9: useState useState

10: useState useState

11: useState useState

12: undefined useEffect

```<code>import { useState, useEffect } from 'react';
import { gql, useQuery } from '@apollo/client';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Select, { SelectChangeEvent } from '@mui/material/Select';

const GET_CIGARS = gql`
  query getCigars {
    cigars {
      brand,
      name
    }
  }
`;

function AddFaveCigar() {
  const { loading, error, data } = useQuery(GET_CIGARS);
  const [brand, setBrand] = useState("");
  const [brandArr, setBrandArr] = useState([]);
  const [cigarNameArr, setCigarNameArr] = useState([]);

  if (loading) return <Text>Loading...</Text>;
  if (error) return <Text>Error: {error.message}</Text>;

  function addFavorite(e) {

  }

  useEffect(() => {
    const filterByBrand = data.cigars.filter((objArr, index, arr) => index === arr.findIndex(obj => (obj.brand === objArr.brand)));
    let brandsArr = [];
    filterByBrand.forEach((cigar, index) => {
      brandsArr.push({ label: cigar.brand, value: cigar.brand, key: index })
    });
    setBrandArr(brandsArr);
  }, []);

  function fillCigarName(brand) {
    const filterCigarByBrand = data.cigars.filter(objArr => (brand === objArr.brand));
    let cigarArr = [];
    filterCigarByBrand.forEach((cigar, index) => {
      cigarArr.push({ label: cigar.name, value: cigar.name, key: index })
    });
    setCigarNameArr(cigarArr);
  }

  return (
    <>
      {!loading && !error && (
        <View style={styles.faveContainer}>
          <Text style={styles.faveTitle}>New Favorite</Text>
          <Text style={styles.inputName}>Cigar Brand</Text>
          <View style={styles.inputBox}>
            <InputLabel id="select-brand" >Select brand</InputLabel>
            <Select
              labelId="select-brand"
              id="select-brand"
              value={brand}
              label="Select brand"
              onChange={fillCigarName}
            >
              {brandArr.map(brand => (
                <MenuItem value={brand.brand}>{brand.brand}</MenuItem>
              ))}
            </Select>
            {/* <RNPickerSelect
              placeholder={{ label: "Select brand", value: null }}
              items={brandArr}
              onValueChange={
                (value) => {
                  fillCigarName(value)
                  setBrand(value)
                }
              }
            /> */}
          </View>
          <Text style={styles.inputName}>Cigar Name</Text>
          <View style={styles.inputBox}>
            {/* <RNPickerSelect
              placeholder={{ label: "Select name", value: null }}
              items={cigarNameArr}
              onValueChange={(value) => setCigarNameArr(value)}
            /> */}
          </View>
          <Text style={styles.inputName}>Size</Text>
          <TextInput style={styles.inputBox} placeholder="size" />
          {/* <Pressable style={[styles.btnContainer, styles.boxShadow]} onPress={(e) => addFavorite(e)}>
            <View style={styles.btnIconContainer}>
              Add Favorite
            </View>
          </Pressable> */}
        </View>
      )}
    </>
  )
}

export default AddFaveCigar;

const styles = StyleSheet.create({
  faveContainer: {
    backgroundColor: 'rgba(255,255,255,1)',
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: 'red',
    position: 'absolute',
    top: '5%',
    left: 10,
    width: '95%',
    borderRadius: 10,
    paddingVertical: 10,
    paddingHorizontal: 16,
  },
  faveTitle: {
    fontSize: 25,
    textAlign: 'center',
    paddingBottom: 15
  },
  inputName: {
    paddingBottom: 5
  },
  inputBox: {
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderColor: 'grey',
    borderWidth: 1,
    borderRadius: 10,
    position: 'relative'
  },
  pickerStyle: {
    border: 0,
  },
  pickerItem: {
    width: '100%',
    backgroundColor: '#fff',
  }
});
</code>```

Body:
I'm working on adding a select box for my React Native component, but I keep getting the mentioned error message and I'm not sure why.  Any help is appreciated.

Error message: Rendered more hooks than previous render

9: useState useState

10: useState useState

11: useState useState

12: undefined useEffect

import { useState, useEffect } from 'react';
import { gql, useQuery } from '@apollo/client';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Select, { SelectChangeEvent } from '@mui/material/Select';

const GET_CIGARS = gql`
  query getCigars {
    cigars {
      brand,
      name
    }
  }
`;

function AddFaveCigar() {
  const { loading, error, data } = useQuery(GET_CIGARS);
  const [brand, setBrand] = useState("");
  const [brandArr, setBrandArr] = useState([]);
  const [cigarNameArr, setCigarNameArr] = useState([]);

  if (loading) return <Text>Loading...</Text>;
  if (error) return <Text>Error: {error.message}</Text>;

  function addFavorite(e) {

  }

  useEffect(() => {
    const filterByBrand = data.cigars.filter((objArr, index, arr) => index === arr.findIndex(obj => (obj.brand === objArr.brand)));
    let brandsArr = [];
    filterByBrand.forEach((cigar, index) => {
      brandsArr.push({ label: cigar.brand, value: cigar.brand, key: index })
    });
    setBrandArr(brandsArr);
  }, []);

  function fillCigarName(brand) {
    const filterCigarByBrand = data.cigars.filter(objArr => (brand === objArr.brand));
    let cigarArr = [];
    filterCigarByBrand.forEach((cigar, index) => {
      cigarArr.push({ label: cigar.name, value: cigar.name, key: index })
    });
    setCigarNameArr(cigarArr);
  }

  return (
    <>
      {!loading && !error && (
        <View style={styles.faveContainer}>
          <Text style={styles.faveTitle}>New Favorite</Text>
          <Text style={styles.inputName}>Cigar Brand</Text>
          <View style={styles.inputBox}>
            <InputLabel id="select-brand" >Select brand</InputLabel>
            <Select
              labelId="select-brand"
              id="select-brand"
              value={brand}
              label="Select brand"
              onChange={fillCigarName}
            >
              {brandArr.map(brand => (
                <MenuItem value={brand.brand}>{brand.brand}</MenuItem>
              ))}
            </Select>
            {/* <RNPickerSelect
              placeholder={{ label: "Select brand", value: null }}
              items={brandArr}
              onValueChange={
                (value) => {
                  fillCigarName(value)
                  setBrand(value)
                }
              }
            /> */}
          </View>
          <Text style={styles.inputName}>Cigar Name</Text>
          <View style={styles.inputBox}>
            {/* <RNPickerSelect
              placeholder={{ label: "Select name", value: null }}
              items={cigarNameArr}
              onValueChange={(value) => setCigarNameArr(value)}
            /> */}
          </View>
          <Text style={styles.inputName}>Size</Text>
          <TextInput style={styles.inputBox} placeholder="size" />
          {/* <Pressable style={[styles.btnContainer, styles.boxShadow]} onPress={(e) => addFavorite(e)}>
            <View style={styles.btnIconContainer}>
              Add Favorite
            </View>
          </Pressable> */}
        </View>
      )}
    </>
  )
}

export default AddFaveCigar;

const styles = StyleSheet.create({
  faveContainer: {
    backgroundColor: 'rgba(255,255,255,1)',
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: 'red',
    position: 'absolute',
    top: '5%',
    left: 10,
    width: '95%',
    borderRadius: 10,
    paddingVertical: 10,
    paddingHorizontal: 16,
  },
  faveTitle: {
    fontSize: 25,
    textAlign: 'center',
    paddingBottom: 15
  },
  inputName: {
    paddingBottom: 5
  },
  inputBox: {
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderColor: 'grey',
    borderWidth: 1,
    borderRadius: 10,
    position: 'relative'
  },
  pickerStyle: {
    border: 0,
  },
  pickerItem: {
    width: '100%',
    backgroundColor: '#fff',
  }
});


问:
How to open links in vscode without mouse and click?
By default to open link in vscode (for example it might be functions) used Left Click + command

How i can bind this for hotkey without mouse?

i tried editor.action.openLink hotkey, but i still need to point my mouse in link.


问:
How can a shape be removed from a < Group /> and moved and nested into another Group after a Drag and Drop?
Considering this (buggy until other questions are answered) demo from here:
https://codesandbox.io/s/kanbanboard-lackofcarddnd-doce75?file=/src/index.js
where the red < Text /> emulates a button that inserts a < CustomCardContainer /> based on the 2nd  that I wish it could be editable and readable as an < input >,

AND Considering that every big colored < Rect /> (that pretend to contain many < CardItem /> components) is a < Group />, I would ask:

how can a < CardItem /> targeted by a mouseDrag be extracted from a < Group />  for nesting it into another < Group /> ?
Or basically dragging and dropping a card from a Group to another...

Assuming we have well-functioning < CustomCardContainer /> of differenet sizes instead of the hard-coded values in line 86 with let inputValue = "10x2";,
I would like to achieve this result from here:
sectioned custom kanban board


问:
TypeError: 'in <string>' requires string as left operand, not list
I would be glad for your advice.
I've got this function from a dict and it should print list of no vowels keys. But it says "TypeError: 'in ' requires string as left operand, not list" and I don't know that it means. Please help me.</p>
```<code>def ngrams_without_vowels(ngram_dict: Dict[str, int]) -> None:

    nonvowels = []
    vowel = ["a", "e", "i", "o", "u", "i", "y"]
    for key, value in ngram_dict.items():
        for v in key:
            if vowel in key:
                nonvowels.append(key)

    print(nonvowels)
</code>```

Body:
I would be glad for your advice.
I've got this function from a dict and it should print list of no vowels keys. But it says "TypeError: 'in ' requires string as left operand, not list" and I don't know that it means. Please help me.

def ngrams_without_vowels(ngram_dict: Dict[str, int]) -> None:

    nonvowels = []
    vowel = ["a", "e", "i", "o", "u", "i", "y"]
    for key, value in ngram_dict.items():
        for v in key:
            if vowel in key:
                nonvowels.append(key)

    print(nonvowels)