问:
Chrome Extension background.js throws Uncaught EvalError as soon as I import anything
I'm trying to make a chrome extension, and everything works fine, but as soon as I try to import any module the service worker becomes inactive and I get the following error:

manifest.json

```<code>{
    "name":"Site Analyzer",
    "description":"Analyze the text content of the site.",
    "version":"0.1.0",
    "manifest_version":3,
    "action":{
        "default_popup":"popup.html"
    },
    "background": {
        "service_worker": "background.js",
        "type": "module"
    }
}
</code>```

webpack.config.js

```<code>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
    entry: {
        popup:"./src/popup.jsx",
        background: "./src/background.js"
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].js",
        clean:true
    },
    module:{
        rules:[{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: {
                loader: "babel-loader"
            }
        }]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:"./src/popup.html",
            filename: "popup.html"
        }),
        new CopyPlugin({
            patterns:[{from:"public"}]
        })
    ]

}
</code>```

package.json

```<code>{
  "private": true,
  "scripts": {
    "build": "webpack --mode production"
  },
  "dependencies": {
    "arquero": "^5.1.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-merge": "^5.8.0"
  }
}
</code>```

background.js

```<code>import * as aq from "arquero";

const table1 = aq.table({a:["whatewer","there"],b:["beep","boop"]});
console.log(table1.objects());
</code>```

The file that gets built even works "node ./dist/background.js"

When I searched regarding the error, most issues were regarding '--mode development' and not present in production mode.
I attempted the different 'devtool' options in webpack config but there wasn't any difference.
When I made an .env file with "INLINE_RUNTIME_CHUNK=false;", there wasn't any change.

ps.: Yes, I rebuilt, cleaned the errors in the extension, and even refreshed it between attempts. :/

Body:
I'm trying to make a chrome extension, and everything works fine, but as soon as I try to import any module the service worker becomes inactive and I get the following error:

manifest.json

{
    "name":"Site Analyzer",
    "description":"Analyze the text content of the site.",
    "version":"0.1.0",
    "manifest_version":3,
    "action":{
        "default_popup":"popup.html"
    },
    "background": {
        "service_worker": "background.js",
        "type": "module"
    }
}

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
    entry: {
        popup:"./src/popup.jsx",
        background: "./src/background.js"
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name].js",
        clean:true
    },
    module:{
        rules:[{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: {
                loader: "babel-loader"
            }
        }]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:"./src/popup.html",
            filename: "popup.html"
        }),
        new CopyPlugin({
            patterns:[{from:"public"}]
        })
    ]

}

package.json

{
  "private": true,
  "scripts": {
    "build": "webpack --mode production"
  },
  "dependencies": {
    "arquero": "^5.1.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-merge": "^5.8.0"
  }
}

background.js

import * as aq from "arquero";

const table1 = aq.table({a:["whatewer","there"],b:["beep","boop"]});
console.log(table1.objects());

The file that gets built even works "node ./dist/background.js"

When I searched regarding the error, most issues were regarding '--mode development' and not present in production mode.
I attempted the different 'devtool' options in webpack config but there wasn't any difference.
When I made an .env file with "INLINE_RUNTIME_CHUNK=false;", there wasn't any change.

ps.: Yes, I rebuilt, cleaned the errors in the extension, and even refreshed it between attempts. :/


来源: stackexchange

问:
Getting access to CoreMotion raw data via Unity
Apple's Core Motion library allows access to the raw data of the sensors in its device: https://developer.apple.com/documentation/coremotion. This is the type of raw data I would like access to: https://developer.apple.com/documentation/coremotion/getting_raw_gyroscope_events.

Using Unity, I can use Input to access some of these, but they don't seem to be able to provide access to all of the raw data captured by the device sensors. Unity has its own documentation, but it doesn't seem like there's an intuitive way to access the device's raw data.

Someone has tried asking about it on the Unity forums ages ago with no response: https://answers.unity.com/questions/979922/how-do-i-access-coremotion-and-the-android-equival.html.

Is there any way to access Core Motion or get access to the raw device data through Unity?

ContentLicense: CC BY-SA 4.0


问:
is it possible to assign a value when Cookie is being refreshed/renewed in identityserver? or is there an alternative to single session?
I am using IdentityServer and I need to modify a value(I need to have only a single user logged in per session but I need to change a value into the user before it removes the claims from the current context. or is there an actual alternative to single session using IdentityServer?</p>


问:
Nextjs requesting dev site Strapi api from local webapp causing CORS issue
On our dev site we have a Strapi integration that is deployed in an isolated state away from our NextJS application.

The Strapi backend is accessed via /api/*, an example is getting a list of articles, so the endpoint is /api/articles.

Locally, we want to hit the dev site URL instead of having to spin strapi up locally. So we want to hit https://dev.our-website.com/api/articles.

However, I get the following error when trying to run the following in the browser console on our local webapp @ http://localhost:3000

Request

```<code>fetch('https://dev.our-website.com/api/articles', {
  method: 'GET',
  headers: {
    Authorization: 'Bearer bearer token is here',
    'Content-Type': 'application/json',
  },
})
</code>```

Response

```<code>Access to fetch at 'https://dev.our-website.com/api/articles' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. If an opaque response serves your needs, set the request's mode
to 'no-cors' to fetch the resource with CORS disabled.
</code>```

Running the following request works fine when it on the browser console on the dev site, just for a reference that the endpoint does work, just that CORS is blocking the request on the dev site from localhost.

Request

```<code>fetch('/api/articles', {
  method: 'GET',
  headers: {
    Authorization: 'Bearer bearer token is here',
    'Content-Type': 'application/json',
  },
})
</code>```

I'm unsure if there is anywhere in our NextJs application that we can allow requests to the dev site from localhost? As the Strapi integration is isolated from the NextJS application, I'm unsure how to go about it?

Any help would be greatly appreciated

Body:
On our dev site we have a Strapi integration that is deployed in an isolated state away from our NextJS application.

The Strapi backend is accessed via /api/*, an example is getting a list of articles, so the endpoint is /api/articles.

Locally, we want to hit the dev site URL instead of having to spin strapi up locally. So we want to hit https://dev.our-website.com/api/articles.

However, I get the following error when trying to run the following in the browser console on our local webapp @ http://localhost:3000

Request

fetch('https://dev.our-website.com/api/articles', {
  method: 'GET',
  headers: {
    Authorization: 'Bearer bearer token is here',
    'Content-Type': 'application/json',
  },
})

Response

Access to fetch at 'https://dev.our-website.com/api/articles' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. If an opaque response serves your needs, set the request's mode
to 'no-cors' to fetch the resource with CORS disabled.

Running the following request works fine when it on the browser console on the dev site, just for a reference that the endpoint does work, just that CORS is blocking the request on the dev site from localhost.

Request

fetch('/api/articles', {
  method: 'GET',
  headers: {
    Authorization: 'Bearer bearer token is here',
    'Content-Type': 'application/json',
  },
})

I'm unsure if there is anywhere in our NextJs application that we can allow requests to the dev site from localhost? As the Strapi integration is isolated from the NextJS application, I'm unsure how to go about it?

Any help would be greatly appreciated


问:
Nginx doesn't serve subdomain
I thought this would be simple, but for some reason I can't get my subdomain to serve. I am just trying to get the basic "Welcome to Nginx" page to show at this point.

I have A records in digital ocean:

```<code>A api.example.com -> my_ip 3600
A www.api.example.com -> my_ip 3600
A example.com -> my_ip 3600
A www.example.com -> my_ip 3600
</code>```

This is my config file for api.example.com. It sits in /etc/nginx/sites-available/api.example.com and is linked to /sites-enabled:

```<code>server {

        root /var/www/api.example.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name api.example.com www.api.example.com;

        location / {
                try_files $uri $uri/ =404;
        }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.api.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = api.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name api.example.com www.api.example.com;
    return 404; # managed by Certbot
}
</code>```

I know the DNS record exists using Dig and because certbot ran successfully, but when I navigate to the page it is unable to resolve. Ping and curl also cannot resolve. This is the exact same configuration I have for the main domain (example.com), which does display the Nginx splash page.

What I have tried: I noticed that default has configs for example.com but not for api.example.com (why is that?), so I tried creating them and restarting nginx, but that didn't change anything. Is it necessary to have the configs in default?

Title: Nginx doesn't serve subdomain

Body:
I thought this would be simple, but for some reason I can't get my subdomain to serve. I am just trying to get the basic "Welcome to Nginx" page to show at this point.

I have A records in digital ocean:

A api.example.com -> my_ip 3600
A www.api.example.com -> my_ip 3600
A example.com -> my_ip 3600
A www.example.com -> my_ip 3600

This is my config file for api.example.com. It sits in /etc/nginx/sites-available/api.example.com and is linked to /sites-enabled:

server {

        root /var/www/api.example.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name api.example.com www.api.example.com;

        location / {
                try_files $uri $uri/ =404;
        }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.api.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = api.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name api.example.com www.api.example.com;
    return 404; # managed by Certbot
}

I know the DNS record exists using Dig and because certbot ran successfully, but when I navigate to the page it is unable to resolve. Ping and curl also cannot resolve. This is the exact same configuration I have for the main domain (example.com), which does display the Nginx splash page.

What I have tried: I noticed that default has configs for example.com but not for api.example.com (why is that?), so I tried creating them and restarting nginx, but that didn't change anything. Is it necessary to have the configs in default?


问:
GenomicRanges remove overlap from consecutive sequences
I have a GenomicRanges objext like so:

```<code>GRanges object with X ranges and 2 metadata columns:
      seqnames            ranges strand |         enh     score
         <Rle>         <IRanges>  <Rle> | <character> <integer>
  [1]     chr1     838740-841250      * |        enh1         0
  [2]     chr1     839752-842210      * |        enh2         0
  [3]     chr1     844484-846678      * |        enh3         0
  [4]     chr1     854763-857157      * |        enh4         0
  [5]     chr1     855538-857757      * |        enh5         0
</code>```

As you can see, some sequences overlap, for example 1 and 2, 4 and 5.

I'd like to "trim" just the overlapping sequence in a pairwise fashion when there is overlap, keeping the start and end of of the first of the 2 elements, trimming the second, but keeping the rows as they are, e.g.:

```<code>      seqnames            ranges strand |         enh     score
         <Rle>         <IRanges>  <Rle> | <character> <integer>
  [1]     chr1     838740-841250      * |        enh1         0
  [2]     chr1     841250-842210      * |        enh2         0
  [3]     chr1     844484-846678      * |        enh3         0
  [4]     chr1     854763-857157      * |        enh4         0
  [5]     chr1     857157-857757      * |        enh5         0
</code>```

Is there a way to do this? I tried the reduce function but it merges the rows.

The other option would be to change the code generating the gr, which is

```<code>gr %>% resize(width=width(.) + 100, fix="start") %>% resize(width=width(.) + 100, fix="end")
</code>```

to mean: extend the end by 100 bp, or up to the next row start, whichever is shorter.

Body:
I have a GenomicRanges objext like so:

GRanges object with X ranges and 2 metadata columns:
      seqnames            ranges strand |         enh     score
         <Rle>         <IRanges>  <Rle> | <character> <integer>
  [1]     chr1     838740-841250      * |        enh1         0
  [2]     chr1     839752-842210      * |        enh2         0
  [3]     chr1     844484-846678      * |        enh3         0
  [4]     chr1     854763-857157      * |        enh4         0
  [5]     chr1     855538-857757      * |        enh5         0

As you can see, some sequences overlap, for example 1 and 2, 4 and 5.

I'd like to "trim" just the overlapping sequence in a pairwise fashion when there is overlap, keeping the start and end of of the first of the 2 elements, trimming the second, but keeping the rows as they are, e.g.:

      seqnames            ranges strand |         enh     score
         <Rle>         <IRanges>  <Rle> | <character> <integer>
  [1]     chr1     838740-841250      * |        enh1         0
  [2]     chr1     841250-842210      * |        enh2         0
  [3]     chr1     844484-846678      * |        enh3         0
  [4]     chr1     854763-857157      * |        enh4         0
  [5]     chr1     857157-857757      * |        enh5         0

Is there a way to do this? I tried the reduce function but it merges the rows.

The other option would be to change the code generating the gr, which is

gr %>% resize(width=width(.) + 100, fix="start") %>% resize(width=width(.) + 100, fix="end")

to mean: extend the end by 100 bp, or up to the next row start, whichever is shorter.


问:
Increase timeout for migration only
For a SQL Server connection, is it possible to increase the requestTimeout only for migrations?

I'd like to keep the default 15000 for regular queries in the application, but have a different number for migrations.

Title: Increase timeout for migration only


问:
422: Unprocessable Entity with FastAPI and MongoDB
I'm trying to achieve a very simple update of data in MongoDB database and I cannot understand why it is not working.

Here's my code:

models.py:

```<code>class Text(BaseModel):
    id: str = Field(default_factory=uuid.uuid4, alias="_id")
    text: str = Field(...)
    gold: bool = Field(...)
    annotations: int = Field(...)

    class Config:
        allow_population_by_field_name = True
        schema_extra = {
            'example': {
                '_id': '066de609-b04a-4b30-b46c-32537c7f1f6e',
                'text': 'The first mission to the moon happend in 1969...',
                'gold': 'False',
                'annotations': '1'
            }
        }

class AnnotationCountUpdate(BaseModel):
    annotations: int = Field(...)

    class Config:
        schema_extra = {
            "example": {
                "annotations": 1
            }
        }

</code>```

routes.py:

```<code>@router.put("/{text_id}", response_description="Update text annotation count", response_model=Text)
def update_count(text_id: str, request: Request, update: AnnotationCountUpdate = Body(...)):
    update = {k: v for k, v in update.dict().items() if v is not None}
    if len(update) >= 1:
        update_result =  request.app.data.update_one(
            {"_id": text_id}, {"set": update}
        )
        if update_result.modified_count == 0:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Text with ID {text_id} not found")

    if (existing_text := request.app.data.find_one({"_id": text_id})) is not None:
        return existing_text

    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Text with ID {text_id} not found")

</code>```

Here's how my database looks:

Here's the full response I get:

I can't figure it out for the life of me...

Thanks.

Body:
I'm trying to achieve a very simple update of data in MongoDB database and I cannot understand why it is not working.

Here's my code:

models.py:

class Text(BaseModel):
    id: str = Field(default_factory=uuid.uuid4, alias="_id")
    text: str = Field(...)
    gold: bool = Field(...)
    annotations: int = Field(...)

    class Config:
        allow_population_by_field_name = True
        schema_extra = {
            'example': {
                '_id': '066de609-b04a-4b30-b46c-32537c7f1f6e',
                'text': 'The first mission to the moon happend in 1969...',
                'gold': 'False',
                'annotations': '1'
            }
        }

class AnnotationCountUpdate(BaseModel):
    annotations: int = Field(...)

    class Config:
        schema_extra = {
            "example": {
                "annotations": 1
            }
        }

routes.py:

@router.put("/{text_id}", response_description="Update text annotation count", response_model=Text)
def update_count(text_id: str, request: Request, update: AnnotationCountUpdate = Body(...)):
    update = {k: v for k, v in update.dict().items() if v is not None}
    if len(update) >= 1:
        update_result =  request.app.data.update_one(
            {"_id": text_id}, {"set": update}
        )
        if update_result.modified_count == 0:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Text with ID {text_id} not found")

    if (existing_text := request.app.data.find_one({"_id": text_id})) is not None:
        return existing_text

    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Text with ID {text_id} not found")

Here's how my database looks:

Here's the full response I get:

I can't figure it out for the life of me...

Thanks.


问:
Script for Automation to pull from CSV
hope all is well.

I'm here working a script for automation to pull data from a csv and post to an api.

However how I dump the csv it is stored with [] and I would like to remove them before submitting.

```<code>df = pd.read_csv('test1.csv')
for index, data in df.iterrows():
        payload =json.dumps({"adapters": data ["MAC Addresses"], "typeLabel": "Windows","iconType": "windows","operatingSystem": "Windows", "hostName": data ["Endpoint Name"],"role": "Staff"})
        print (payload)
</code>```

This is my script, where adapters is, that's the data I want to manipulate before posting.

In csv file, the data save as this:

```<code>['08:92:04:0a:ec:00']

whenever the code runs, it shows as this
</code>```

"['08:92:04:0a:ec:00']"

```<code>But I want it to be like this ["08:92:04:0a:ec:00"], the API only accepts this.

</code>```

Is there anyway this can be accomplish, much apperciation.

I tried everything, only solution is to learn from the experts.

Title: Script for Automation to pull from CSV

Body:
hope all is well.

I'm here working a script for automation to pull data from a csv and post to an api.

However how I dump the csv it is stored with [] and I would like to remove them before submitting.

df = pd.read_csv('test1.csv')
for index, data in df.iterrows():
        payload =json.dumps({"adapters": data ["MAC Addresses"], "typeLabel": "Windows","iconType": "windows","operatingSystem": "Windows", "hostName": data ["Endpoint Name"],"role": "Staff"})
        print (payload)

This is my script, where adapters is, that's the data I want to manipulate before posting.

In csv file, the data save as this:

['08:92:04:0a:ec:00']

whenever the code runs, it shows as this

"['08:92:04:0a:ec:00']"

But I want it to be like this ["08:92:04:0a:ec:00"], the API only accepts this.

Is there anyway this can be accomplish, much apperciation.

I tried everything, only solution is to learn from the experts.


问:
how can I sort a list according to wse api from here map
i am showing a list of orders with time in listview.builder from backend api but i need to sort that list on the base of sequence from wse api from here map and want show time from interconnections with mylist here is my model
List<Order> allOrderList;
`

```<code>class Order {
  Order({
    this.id,
    this.fname,
    this.lname,
    this.streetAddress,
   this.city,
    this.state,
    this.zip,
    this.phone,
    this.orderId,
    this.storeId,
    this.statusKey,
    this.isBad,
this.Lat,
this.Lng,
  });

  dynamic id;
  dynamic fname;
  dynamic lname;
  dynamic streetAddress;
dynamic city;
  dynamic state;
  int? zip;
  dynamic phone;
dynamic orderId;
  dynamic storeId;
  dynamic Lat;
  dynamic Lng;
  factory Order.fromJson(Map<String, dynamic> json) => Order(
        id: json["_id"],
        fname: json["fname"],
        lname: json["lname"],
        streetAddress: json["street_address"],
         city: json["city"],
        state: json["state"],
        zip: json["zip"],
        phone: json["phone"],
       orderId: json["order_id"],
        storeId: json["store_id"],
        totalBoxes: json["total_boxes"],
        Lat: json["lat"].toDouble(),
        Lng: json["lng"].toDouble(),

      );

  Map<String, dynamic> toJson() => {
        "_id": id,
        "fname": fname,
        "lname": lname,
        "street_address": streetAddress,
        "city": city,
        "state": state,
        "zip": zip,
        "phone": phone,
        "order_id": orderId,
        "store_id": storeId,
        "lat": Lat,
        "lng": Lng,

      };
}
</code>```

 this is example of wse here map api
`

```<code>{
    "results": [{
        "waypoints": [{
            "id": "WiesbadenCentralStation",
            "lat": 50.0715,
            "lng": 8.2434,
            "sequence": 0,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T09:30:00+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "FranfurtCentralStation",
            "lat": 50.1073,
            "lng": 8.6647,
            "sequence": 1,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T10:01:02+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "HanauCentralStation",
            "lat": 50.1218,
            "lng": 8.9298,
            "sequence": 2,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T10:30:43+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "FrankfurtAirport",
            "lat": 50.0505,
            "lng": 8.5698,
            "sequence": 3,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T10:56:10+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "DarmstadtCentralStation",
            "lat": 49.8728,
            "lng": 8.6326,
            "sequence": 4,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T11:16:55+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "MainzCentralStation",
            "lat": 50.0021,
            "lng": 8.259,
            "sequence": 5,
            "estimatedArrival": null,
            "estimatedDeparture": null,
            "fulfilledConstraints": []
        }],
        "distance": "169262",
        "time": "8362",
        "interconnections": [{
            "fromWaypoint": "WiesbadenCentralStation",
            "toWaypoint": "FranfurtCentralStation",
            "distance": 36461.0,
            "time": 1862.0
        },
        {
            "fromWaypoint": "FranfurtCentralStation",
            "toWaypoint": "HanauCentralStation",
            "distance": 34485.0,
            "time": 1781.0
        },
        {
            "fromWaypoint": "HanauCentralStation",
            "toWaypoint": "FrankfurtAirport",
            "distance": 33489.0,
            "time": 1527.0
        },
        {
            "fromWaypoint": "FrankfurtAirport",
            "toWaypoint": "DarmstadtCentralStation",
            "distance": 26905.0,
            "time": 1245.0
        },
        {
            "fromWaypoint": "DarmstadtCentralStation",
            "toWaypoint": "MainzCentralStation",
            "distance": 37922.0,
            "time": 1947.0
        }],
        "description": "Targeted best time; with improvement for traffic"
    }],
    "8.1.11s": [],
    "processingTimeDesc": "1345ms",
    "responseCode": "200",
    "warnings": null,
    "requestId": null
}

</code>```

`
the id in wse api is my street address which i am sending through the wse url like
https://wps.hereapi.com/2/findsequence.json?app_id=my_app_id&app_code=myapp_code&start=Starting%20Location;37.785834,-122.406417&destination1=Ss%20Br0;37.35507,-82.81066&destination2=Ff%20John%20A%20Santore%20Way1;40.63348,-74.1043&destination3=Gorlitz%20Ct2;41.34471,-74.16784&improveFor=distance&mode=fastest;car;traffic:disabled;

i did try many solutions but nothing worked.

Body:
i am showing a list of orders with time in listview.builder from backend api but i need to sort that list on the base of sequence from wse api from here map and want show time from interconnections with mylist here is my model
List<Order> allOrderList;
`

class Order {
  Order({
    this.id,
    this.fname,
    this.lname,
    this.streetAddress,
   this.city,
    this.state,
    this.zip,
    this.phone,
    this.orderId,
    this.storeId,
    this.statusKey,
    this.isBad,
this.Lat,
this.Lng,
  });

  dynamic id;
  dynamic fname;
  dynamic lname;
  dynamic streetAddress;
dynamic city;
  dynamic state;
  int? zip;
  dynamic phone;
dynamic orderId;
  dynamic storeId;
  dynamic Lat;
  dynamic Lng;
  factory Order.fromJson(Map<String, dynamic> json) => Order(
        id: json["_id"],
        fname: json["fname"],
        lname: json["lname"],
        streetAddress: json["street_address"],
         city: json["city"],
        state: json["state"],
        zip: json["zip"],
        phone: json["phone"],
       orderId: json["order_id"],
        storeId: json["store_id"],
        totalBoxes: json["total_boxes"],
        Lat: json["lat"].toDouble(),
        Lng: json["lng"].toDouble(),

      );

  Map<String, dynamic> toJson() => {
        "_id": id,
        "fname": fname,
        "lname": lname,
        "street_address": streetAddress,
        "city": city,
        "state": state,
        "zip": zip,
        "phone": phone,
        "order_id": orderId,
        "store_id": storeId,
        "lat": Lat,
        "lng": Lng,

      };
}

 this is example of wse here map api
`

{
    "results": [{
        "waypoints": [{
            "id": "WiesbadenCentralStation",
            "lat": 50.0715,
            "lng": 8.2434,
            "sequence": 0,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T09:30:00+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "FranfurtCentralStation",
            "lat": 50.1073,
            "lng": 8.6647,
            "sequence": 1,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T10:01:02+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "HanauCentralStation",
            "lat": 50.1218,
            "lng": 8.9298,
            "sequence": 2,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T10:30:43+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "FrankfurtAirport",
            "lat": 50.0505,
            "lng": 8.5698,
            "sequence": 3,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T10:56:10+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "DarmstadtCentralStation",
            "lat": 49.8728,
            "lng": 8.6326,
            "sequence": 4,
            "estimatedArrival": null,
            "estimatedDeparture": "2014-12-09T11:16:55+01:00",
            "fulfilledConstraints": []
        },
        {
            "id": "MainzCentralStation",
            "lat": 50.0021,
            "lng": 8.259,
            "sequence": 5,
            "estimatedArrival": null,
            "estimatedDeparture": null,
            "fulfilledConstraints": []
        }],
        "distance": "169262",
        "time": "8362",
        "interconnections": [{
            "fromWaypoint": "WiesbadenCentralStation",
            "toWaypoint": "FranfurtCentralStation",
            "distance": 36461.0,
            "time": 1862.0
        },
        {
            "fromWaypoint": "FranfurtCentralStation",
            "toWaypoint": "HanauCentralStation",
            "distance": 34485.0,
            "time": 1781.0
        },
        {
            "fromWaypoint": "HanauCentralStation",
            "toWaypoint": "FrankfurtAirport",
            "distance": 33489.0,
            "time": 1527.0
        },
        {
            "fromWaypoint": "FrankfurtAirport",
            "toWaypoint": "DarmstadtCentralStation",
            "distance": 26905.0,
            "time": 1245.0
        },
        {
            "fromWaypoint": "DarmstadtCentralStation",
            "toWaypoint": "MainzCentralStation",
            "distance": 37922.0,
            "time": 1947.0
        }],
        "description": "Targeted best time; with improvement for traffic"
    }],
    "8.1.11s": [],
    "processingTimeDesc": "1345ms",
    "responseCode": "200",
    "warnings": null,
    "requestId": null
}

`
the id in wse api is my street address which i am sending through the wse url like
https://wps.hereapi.com/2/findsequence.json?app_id=my_app_id&app_code=myapp_code&start=Starting%20Location;37.785834,-122.406417&destination1=Ss%20Br0;37.35507,-82.81066&destination2=Ff%20John%20A%20Santore%20Way1;40.63348,-74.1043&destination3=Gorlitz%20Ct2;41.34471,-74.16784&improveFor=distance&mode=fastest;car;traffic:disabled;

i did try many solutions but nothing worked.


问:
Java Springboot Unit-Testing
Building a UnitTest into a CRUD Application

I tried adding a hardcoded business item as variables to the Application.Unit TestComponent class Controller Classoutput

Title: Java Springboot Unit-Testing


问:
SHow from to and no change percent in sankey diagram in R
I created a Sankey diagram of land cover change (raster image in tif format)using the following code in r. Is there a way to show what percentage remains unchanged between dates and changed from to between classes on those dates? Preferably show the percentage as a Y label so that percent looks less cluttered in the graph. Following are my code and image that I have. I would appreciate the help.

```<code>install.packages(c('raster', 'networkD3', 'dplyr'))
library(raster)
library(networkD3)
library(dplyr)
library(rgdal)

###############################################

# define file info
fileInfo <- data.frame(nodeCol=1, rasterFile="C:/Users/Sankey/land90.tif", rasterBand=1) %>%
  rbind(data.frame(nodeCol=2, rasterFile="C:/Users/Sankey/land01.tif", rasterBand=1)) %>%
  rbind(data.frame(nodeCol=3, rasterFile="C:/Users/Sankey/land10.tif",rasterBand=1)) %>%
  rbind(data.frame(nodeCol=4, rasterFile="C:/Users/Sankey/land19.tif",rasterBand=1))

# define node info
nodeInfo <- data.frame(nodeName="1990 AG", nodeID=0,  mapClass=1, nodeCol=1, nodeGroup='a') %>%
  rbind(data.frame(nodeName="1990 DF",     nodeID=1,  mapClass=2, nodeCol=1, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="1990 Dev",    nodeID=2,  mapClass=3, nodeCol=1, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="1990 EF",     nodeID=3,  mapClass=4, nodeCol=1, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="1990 H/G/P",  nodeID=4,  mapClass=5, nodeCol=1, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="1990 MF",     nodeID=5,  mapClass=6, nodeCol=1, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="1990 WR",     nodeID=6,  mapClass=7, nodeCol=1, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="1990 SB",     nodeID=7,  mapClass=8, nodeCol=1, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="1990 WT",     nodeID=8,  mapClass=9, nodeCol=1, nodeGroup='i')) %>%

  rbind(data.frame(nodeName="2000 AG",     nodeID=9,   mapClass=1, nodeCol=2, nodeGroup='a')) %>%
  rbind(data.frame(nodeName="2000 DF",     nodeID=10,  mapClass=2, nodeCol=2, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="2000 Dev",    nodeID=11,  mapClass=3, nodeCol=2, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="2000 EF",     nodeID=12,  mapClass=4, nodeCol=2, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="2000 H/G/P",  nodeID=13,  mapClass=5, nodeCol=2, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="2000 MF",     nodeID=14,  mapClass=6, nodeCol=2, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="2000 WR",     nodeID=15,  mapClass=7, nodeCol=2, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="2000 SB",     nodeID=16,  mapClass=8, nodeCol=2, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="2000 WT",     nodeID=17,  mapClass=9, nodeCol=2, nodeGroup='i')) %>%

  rbind(data.frame(nodeName="2010 AG",     nodeID=18,  mapClass=1, nodeCol=3, nodeGroup='a')) %>%
  rbind(data.frame(nodeName="2010 DF",     nodeID=19,  mapClass=2, nodeCol=3, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="2010 Dev",    nodeID=20,  mapClass=3, nodeCol=3, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="2010 EF",     nodeID=21,  mapClass=4, nodeCol=3, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="2010 H/G/P",  nodeID=22,  mapClass=5, nodeCol=3, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="2010 MF",     nodeID=23,  mapClass=6, nodeCol=3, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="2010 WR",     nodeID=24,  mapClass=7, nodeCol=3, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="2010 SB",     nodeID=25,  mapClass=8, nodeCol=3, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="2010 WT",     nodeID=26,  mapClass=9, nodeCol=3, nodeGroup='i')) %>%

  rbind(data.frame(nodeName="2019 AG",     nodeID=27,  mapClass=1, nodeCol=4, nodeGroup='a')) %>%
  rbind(data.frame(nodeName="2019 DF",     nodeID=28,  mapClass=2, nodeCol=4, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="2019 Dev",    nodeID=29,  mapClass=3, nodeCol=4, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="2019 EF",     nodeID=30,  mapClass=4, nodeCol=4, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="2019 H/G/P",  nodeID=31,  mapClass=5, nodeCol=4, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="2019 MF",     nodeID=32,  mapClass=6, nodeCol=4, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="2019 WR",     nodeID=33,  mapClass=7, nodeCol=4, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="2019 SB",     nodeID=34,  mapClass=8, nodeCol=4, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="2019 WT",     nodeID=35,  mapClass=9, nodeCol=4, nodeGroup='i'))

# define group color - note that the colors correspond to the nodeGroups, one for each unique group, we have used (a, b, c, d, e, f) - color is applied in order
groupColor <- c("#FF8C00","#006400", "#FF0000", "#00FF00", "#FFFF00", "#808000","#0000FF","#00FF7F","#00FFFF")

# define plot features
fontSize <- 13
fontFamily <- "sans-serif"
nodeWidth <- 30
###############################################

# collapse groupColor to a string
groupColor <- paste0('"',paste(groupColor, collapse = '", "'),'"')

# join fileInfo to nodeInfo
nodeInfo <- dplyr::left_join(nodeInfo, fileInfo, by='nodeCol')

# convert factors to characters
nodeInfo$nodeName <- as.character(nodeInfo$nodeName)
nodeInfo$rasterFile <- as.character(nodeInfo$rasterFile)

# define the the links
NodeCols <- sort(unique(nodeInfo$nodeCol))
linkInfo <- data.frame()
for(i in 1:(length(NodeCols)-1)){
  fromCol <- dplyr::filter(nodeInfo, nodeCol==NodeCols[i])
  toCol <- dplyr::filter(nodeInfo, nodeCol==NodeCols[i+1])
  fromR <- values(raster(fromCol$rasterFile[1], fromCol$rasterBand[1]))
  toR <- values(raster(toCol$rasterFile[1], toCol$rasterBand[1]))
  for(f in 1:nrow(fromCol)){
    for(t in 1:nrow(toCol)){
      nFromTo <- length(which(fromR == fromCol$mapClass[f] & toR == toCol$mapClass[t]))
      linkInfo <- rbind(linkInfo, data.frame(source=fromCol$nodeID[f], target=toCol$nodeID[t], value=nFromTo))
    }
  }
}

# make the sankey plot
sankeyNetwork(Links = linkInfo, Nodes = nodeInfo,
              Source = "source",
              Target = "target",
              Value = "value",
              NodeID = "nodeName",
              NodeGroup = "nodeGroup",
              fontSize = fontSize,
              fontFamily = fontFamily,
              nodeWidth = nodeWidth,
              colourScale = paste0('d3.scaleOrdinal().range([',groupColor,'])'))
</code>```

Body:
I created a Sankey diagram of land cover change (raster image in tif format)using the following code in r. Is there a way to show what percentage remains unchanged between dates and changed from to between classes on those dates? Preferably show the percentage as a Y label so that percent looks less cluttered in the graph. Following are my code and image that I have. I would appreciate the help.

install.packages(c('raster', 'networkD3', 'dplyr'))
library(raster)
library(networkD3)
library(dplyr)
library(rgdal)

###############################################

# define file info
fileInfo <- data.frame(nodeCol=1, rasterFile="C:/Users/Sankey/land90.tif", rasterBand=1) %>%
  rbind(data.frame(nodeCol=2, rasterFile="C:/Users/Sankey/land01.tif", rasterBand=1)) %>%
  rbind(data.frame(nodeCol=3, rasterFile="C:/Users/Sankey/land10.tif",rasterBand=1)) %>%
  rbind(data.frame(nodeCol=4, rasterFile="C:/Users/Sankey/land19.tif",rasterBand=1))

# define node info
nodeInfo <- data.frame(nodeName="1990 AG", nodeID=0,  mapClass=1, nodeCol=1, nodeGroup='a') %>%
  rbind(data.frame(nodeName="1990 DF",     nodeID=1,  mapClass=2, nodeCol=1, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="1990 Dev",    nodeID=2,  mapClass=3, nodeCol=1, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="1990 EF",     nodeID=3,  mapClass=4, nodeCol=1, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="1990 H/G/P",  nodeID=4,  mapClass=5, nodeCol=1, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="1990 MF",     nodeID=5,  mapClass=6, nodeCol=1, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="1990 WR",     nodeID=6,  mapClass=7, nodeCol=1, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="1990 SB",     nodeID=7,  mapClass=8, nodeCol=1, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="1990 WT",     nodeID=8,  mapClass=9, nodeCol=1, nodeGroup='i')) %>%

  rbind(data.frame(nodeName="2000 AG",     nodeID=9,   mapClass=1, nodeCol=2, nodeGroup='a')) %>%
  rbind(data.frame(nodeName="2000 DF",     nodeID=10,  mapClass=2, nodeCol=2, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="2000 Dev",    nodeID=11,  mapClass=3, nodeCol=2, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="2000 EF",     nodeID=12,  mapClass=4, nodeCol=2, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="2000 H/G/P",  nodeID=13,  mapClass=5, nodeCol=2, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="2000 MF",     nodeID=14,  mapClass=6, nodeCol=2, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="2000 WR",     nodeID=15,  mapClass=7, nodeCol=2, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="2000 SB",     nodeID=16,  mapClass=8, nodeCol=2, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="2000 WT",     nodeID=17,  mapClass=9, nodeCol=2, nodeGroup='i')) %>%

  rbind(data.frame(nodeName="2010 AG",     nodeID=18,  mapClass=1, nodeCol=3, nodeGroup='a')) %>%
  rbind(data.frame(nodeName="2010 DF",     nodeID=19,  mapClass=2, nodeCol=3, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="2010 Dev",    nodeID=20,  mapClass=3, nodeCol=3, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="2010 EF",     nodeID=21,  mapClass=4, nodeCol=3, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="2010 H/G/P",  nodeID=22,  mapClass=5, nodeCol=3, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="2010 MF",     nodeID=23,  mapClass=6, nodeCol=3, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="2010 WR",     nodeID=24,  mapClass=7, nodeCol=3, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="2010 SB",     nodeID=25,  mapClass=8, nodeCol=3, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="2010 WT",     nodeID=26,  mapClass=9, nodeCol=3, nodeGroup='i')) %>%

  rbind(data.frame(nodeName="2019 AG",     nodeID=27,  mapClass=1, nodeCol=4, nodeGroup='a')) %>%
  rbind(data.frame(nodeName="2019 DF",     nodeID=28,  mapClass=2, nodeCol=4, nodeGroup='b')) %>%
  rbind(data.frame(nodeName="2019 Dev",    nodeID=29,  mapClass=3, nodeCol=4, nodeGroup='c')) %>%
  rbind(data.frame(nodeName="2019 EF",     nodeID=30,  mapClass=4, nodeCol=4, nodeGroup='d')) %>%
  rbind(data.frame(nodeName="2019 H/G/P",  nodeID=31,  mapClass=5, nodeCol=4, nodeGroup='e')) %>%
  rbind(data.frame(nodeName="2019 MF",     nodeID=32,  mapClass=6, nodeCol=4, nodeGroup='f')) %>%
  rbind(data.frame(nodeName="2019 WR",     nodeID=33,  mapClass=7, nodeCol=4, nodeGroup='g')) %>%
  rbind(data.frame(nodeName="2019 SB",     nodeID=34,  mapClass=8, nodeCol=4, nodeGroup='h')) %>%
  rbind(data.frame(nodeName="2019 WT",     nodeID=35,  mapClass=9, nodeCol=4, nodeGroup='i'))

# define group color - note that the colors correspond to the nodeGroups, one for each unique group, we have used (a, b, c, d, e, f) - color is applied in order
groupColor <- c("#FF8C00","#006400", "#FF0000", "#00FF00", "#FFFF00", "#808000","#0000FF","#00FF7F","#00FFFF")

# define plot features
fontSize <- 13
fontFamily <- "sans-serif"
nodeWidth <- 30
###############################################

# collapse groupColor to a string
groupColor <- paste0('"',paste(groupColor, collapse = '", "'),'"')

# join fileInfo to nodeInfo
nodeInfo <- dplyr::left_join(nodeInfo, fileInfo, by='nodeCol')

# convert factors to characters
nodeInfo$nodeName <- as.character(nodeInfo$nodeName)
nodeInfo$rasterFile <- as.character(nodeInfo$rasterFile)

# define the the links
NodeCols <- sort(unique(nodeInfo$nodeCol))
linkInfo <- data.frame()
for(i in 1:(length(NodeCols)-1)){
  fromCol <- dplyr::filter(nodeInfo, nodeCol==NodeCols[i])
  toCol <- dplyr::filter(nodeInfo, nodeCol==NodeCols[i+1])
  fromR <- values(raster(fromCol$rasterFile[1], fromCol$rasterBand[1]))
  toR <- values(raster(toCol$rasterFile[1], toCol$rasterBand[1]))
  for(f in 1:nrow(fromCol)){
    for(t in 1:nrow(toCol)){
      nFromTo <- length(which(fromR == fromCol$mapClass[f] & toR == toCol$mapClass[t]))
      linkInfo <- rbind(linkInfo, data.frame(source=fromCol$nodeID[f], target=toCol$nodeID[t], value=nFromTo))
    }
  }
}

# make the sankey plot
sankeyNetwork(Links = linkInfo, Nodes = nodeInfo,
              Source = "source",
              Target = "target",
              Value = "value",
              NodeID = "nodeName",
              NodeGroup = "nodeGroup",
              fontSize = fontSize,
              fontFamily = fontFamily,
              nodeWidth = nodeWidth,
              colourScale = paste0('d3.scaleOrdinal().range([',groupColor,'])'))


问:
Comparison parameter "-as" in Powershell
Just stumbled on this Powershell code:

```<code>if (!($email -as [Net.Mail.MailAddress])) {
    Write-Output "ERROR: invalid email: $($email)"
    exit -1
}
</code>```

I searched the Microsoft documentation on Powershell comparison operators, but I could not find what "-as" means.
My guess it compares if the string is a valid object of Net.Mail.MailAddress but I am not sure what it does exactly.

Body:
Just stumbled on this Powershell code:

if (!($email -as [Net.Mail.MailAddress])) {
    Write-Output "ERROR: invalid email: $($email)"
    exit -1
}

I searched the Microsoft documentation on Powershell comparison operators, but I could not find what "-as" means.
My guess it compares if the string is a valid object of Net.Mail.MailAddress but I am not sure what it does exactly.


问:
VBA How to get notified with a message box once a web query complete
My worksheet has a web query connection. I use the following code to refresh the connection each time:

```<code>Sub Pull_data_from_JSE_Website()

'Pull data from JSE Website
    Sheets("Raw Data").Select
    ActiveWorkbook.RefreshAll
    Application.Wait (now + TimeValue("0:01:00"))
    MsgBox ("Web Query is Complete!")
End Sub`
</code>```

I would like to be notified when the query is complete instead of using a timer. How can I do this?

Body:
My worksheet has a web query connection. I use the following code to refresh the connection each time:

Sub Pull_data_from_JSE_Website()

'Pull data from JSE Website
    Sheets("Raw Data").Select
    ActiveWorkbook.RefreshAll
    Application.Wait (now + TimeValue("0:01:00"))
    MsgBox ("Web Query is Complete!")
End Sub`

I would like to be notified when the query is complete instead of using a timer. How can I do this?


问:
Min Makespan Algorithm
I have pseudocode for the algorithm I am trying to implement provided below...

```<code>greedy_min_make_span(T, m):
  # T is an array of n numbers, m >= 2
  A = [Nil, ... , Nil] # Initialize the assignments to nil (array size n)
  M = [ 0, 0, ...., 0] # initialize the current load of each processor to 0 (array size m)
  for i = 1 to n
    find processor j for which M[j] is the least.
    A[i] = j
    M[j] = M[j] + T[i]
 # Assignment achieves a makespan of max(M[1], .. M[m])
 return A
</code>```

The code I currently have for this is...

```<code>def greedy_makespan_min(times, m):
    # times is a list of n jobs.
    n = len(times)
    # please do not reorder the jobs in times or else tests will fail.
    # Return a tuple of two things:
    #    - Assignment list of n numbers from 0 to m-1
    #    - The makespan of your assignment
    assignment = [0]*n
    makespan = [0]*m

    i = 1
    for i in range(i, n):
        j = makespan.index(min(makespan))
        assignment[i] = j
        makespan[j] = makespan[j] + times[i]
    return (assignment, makespan)
</code>```

However, this code is failing my test cases. The assignment that I am returning is not correct, and doesn't match what the reported makespan is supposed to be.

```<code>def do_test(times, m, expected):
    (a, makespan) = greedy_makespan_min(times,m )
    print('\t Assignment returned: ', a)
    print('\t Claimed makespan: ', makespan)
    assert compute_makespan(times, m, a) == makespan, 'Assignment returned is not consistent with the reported makespan'
    assert makespan == expected, f'Expected makespan should be {expected}, your core returned {makespan}'
    print('Passed')
print('Test 1:')
times = [2, 2, 2, 2, 2, 2, 2, 2, 3]
m = 3
expected = 7
do_test(times, m, expected)

print('Test 2:')
times = [1]*20 + [5]
m = 5
expected =9
do_test(times, m, expected)

print('Test 3:')
times = [1]*40 + [2]
m = 20
expected = 4
do_test(times, m, expected)
print("PASS")
## END TESTS
</code>```

Here is the compute_makespan function being used in testing...

```<code>def compute_makespan(times, m, assign):
    # times is an array of job times of size n
    # m is the number of processors
    # assign is an array of size n whose entries are between 0 to m-1
    # indicating the processor number for
    # the corresponding job.
    # Return: makespan of the assignment
    times_2 = m*[0]

    for i in range(len(times)):
        proc = assign[i]
        time = times[i]
        times_2[proc] = times_2[proc] + time
    return max(times_2)
</code>```

Title: Min Makespan Algorithm

Body:
I have pseudocode for the algorithm I am trying to implement provided below...

greedy_min_make_span(T, m):
  # T is an array of n numbers, m >= 2
  A = [Nil, ... , Nil] # Initialize the assignments to nil (array size n)
  M = [ 0, 0, ...., 0] # initialize the current load of each processor to 0 (array size m)
  for i = 1 to n
    find processor j for which M[j] is the least.
    A[i] = j
    M[j] = M[j] + T[i]
 # Assignment achieves a makespan of max(M[1], .. M[m])
 return A

The code I currently have for this is...

def greedy_makespan_min(times, m):
    # times is a list of n jobs.
    n = len(times)
    # please do not reorder the jobs in times or else tests will fail.
    # Return a tuple of two things:
    #    - Assignment list of n numbers from 0 to m-1
    #    - The makespan of your assignment
    assignment = [0]*n
    makespan = [0]*m

    i = 1
    for i in range(i, n):
        j = makespan.index(min(makespan))
        assignment[i] = j
        makespan[j] = makespan[j] + times[i]
    return (assignment, makespan)

However, this code is failing my test cases. The assignment that I am returning is not correct, and doesn't match what the reported makespan is supposed to be.

def do_test(times, m, expected):
    (a, makespan) = greedy_makespan_min(times,m )
    print('\t Assignment returned: ', a)
    print('\t Claimed makespan: ', makespan)
    assert compute_makespan(times, m, a) == makespan, 'Assignment returned is not consistent with the reported makespan'
    assert makespan == expected, f'Expected makespan should be {expected}, your core returned {makespan}'
    print('Passed')
print('Test 1:')
times = [2, 2, 2, 2, 2, 2, 2, 2, 3]
m = 3
expected = 7
do_test(times, m, expected)

print('Test 2:')
times = [1]*20 + [5]
m = 5
expected =9
do_test(times, m, expected)

print('Test 3:')
times = [1]*40 + [2]
m = 20
expected = 4
do_test(times, m, expected)
print("PASS")
## END TESTS

Here is the compute_makespan function being used in testing...

def compute_makespan(times, m, assign):
    # times is an array of job times of size n
    # m is the number of processors
    # assign is an array of size n whose entries are between 0 to m-1
    # indicating the processor number for
    # the corresponding job.
    # Return: makespan of the assignment
    times_2 = m*[0]

    for i in range(len(times)):
        proc = assign[i]
        time = times[i]
        times_2[proc] = times_2[proc] + time
    return max(times_2)


问:
apollo kotlin multiple schema sharing fragments
The service i want to work with exposes 2 graphql api's that have overlapping types.

By which way it is possible to share as much fragments as possible?

After getting the schema.graphqls files via introspect and saving it to their source Folder i tried generating the files (query, mutation, fragments) resulting only value types getting generated.

```<code>apollo {
    fun Service.configure() {
        includes.add("com/example/shared")
    }

    service("api1") {
        configure()

        packageName.set("com.example")
        sourceFolder.set("com/example/api1")
    }
    service("api2") {
        configure()

        packageName.set("com.example.api2")
        sourceFolder.set("com/example/api2")
    }
}
</code>```

Body:
The service i want to work with exposes 2 graphql api's that have overlapping types.

By which way it is possible to share as much fragments as possible?

After getting the schema.graphqls files via introspect and saving it to their source Folder i tried generating the files (query, mutation, fragments) resulting only value types getting generated.

apollo {
    fun Service.configure() {
        includes.add("com/example/shared")
    }

    service("api1") {
        configure()

        packageName.set("com.example")
        sourceFolder.set("com/example/api1")
    }
    service("api2") {
        configure()

        packageName.set("com.example.api2")
        sourceFolder.set("com/example/api2")
    }
}


问:
Are `return await ...` and `return ...` the same?
Consider these functions:

function waitASecA() {
  const promise = new Promise(resolve => setTimeout(resolve, 1000));

  return promise; // <--- don't await, just return
}

async function waitASecB() {
  const promise = new Promise(resolve => setTimeout(resolve, 1000));

  return await promise; // <--- first await, then return
}
```

As I understand they should be EXACTLY the same. Are there any scenarios when they'd differ in behavior?

Body:
Consider these functions:

function waitASecA() {
  const promise = new Promise(resolve => setTimeout(resolve, 1000));

  return promise; // <--- don't await, just return
}

async function waitASecB() {
  const promise = new Promise(resolve => setTimeout(resolve, 1000));

  return await promise; // <--- first await, then return
}

As I understand they should be EXACTLY the same. Are there any scenarios when they'd differ in behavior?


问:
Results only show when select option is changed
Having an issue where when the page loads, and I type in the text area, and press the button, the results don't show up. But when I change the select option, it works as intended. Can I make it so that a() works on page load?</p>
```<code>const [text, setText] = useState("")
const [getFunction, setGetFunction]= useState();
const [results, setResults] = useState("");

function handleText(e){
  setText(e.target.value)
}

function a() {
  // some logic involving text state variable
  return {result of some logic};
}

function b() {
  // some logic involving text state variable
  return {result of some logic};
}

handleChange(e) {
  if (e.target.value == "a") {
    setGetFunction(a())
  }
  else if (e.target.value == "b") {
    setGetFunction(b())
  }
}

handleClick(e){
  e.preventDefault();
    setResults(getFunction)
}

return (
  <div>
    <form>
      <select onChange={handleChange}>
        <option value="a">a</option>
        <option value="b">b</option>
      </select>
      <textarea
          type="text"
          id="message"
          onChange={handleText}
          value={message}
        ></textarea>
      <button onClick={handleClick}></button>
    </form>
    <h2>{results}</h2>
  </div>
)
</code>```

Body:
Having an issue where when the page loads, and I type in the text area, and press the button, the results don't show up. But when I change the select option, it works as intended. Can I make it so that a() works on page load?

const [text, setText] = useState("")
const [getFunction, setGetFunction]= useState();
const [results, setResults] = useState("");

function handleText(e){
  setText(e.target.value)
}

function a() {
  // some logic involving text state variable
  return {result of some logic};
}

function b() {
  // some logic involving text state variable
  return {result of some logic};
}

handleChange(e) {
  if (e.target.value == "a") {
    setGetFunction(a())
  }
  else if (e.target.value == "b") {
    setGetFunction(b())
  }
}

handleClick(e){
  e.preventDefault();
    setResults(getFunction)
}

return (

    <form>
      <select onChange={handleChange}>
        <option value="a">a</option>
        <option value="b">b</option>
      </select>
      <textarea
          type="text"
          id="message"
          onChange={handleText}
          value={message}
        ></textarea>
      <button onClick={handleClick}></button>
    </form>

{results}

)


问:
Unable to make .vcf file download able
I am stuck in a problem while building a digital business Card on wordpress, Please help me out with this problem.

Problem
I want to add an option of save the card means save the cotact details directly by just clicking/hiting that button in my digital business card, For that i also created one dedicated folder in my Database for vcf file with the name of Uploads and in this folder i also paste a php file for vcard after guidning by the chat support of hostinger but that only works for that particular vcf file whose name is mentioned in the php but also it is only downloadable not importable (means when we hit the downloaded vcf file then an message apperas Contact couldn't import) and i want to add lots of vcf file so it means i need to add php files as well.

Solution Which I know of that problem

So to achieve this we need to add that vcf file in that upload folder, which i am doing, then we can create a link which is should be like that https://domainname/uploade/vcffilename.vcf. But unfortunatelly it is not happing through this link the coded vcf file available.

Can you please guide me what the thing i am missing here so that my vcf link works properly and i can also provide the save option.

Regards
Vaibhav Narang

Title: Unable to make .vcf file download able


问:
Getting an error even after callling suspend function from coroutine scope
I have an async process in my android app and I am using a co-routine scope to call a suspend function. But I am getting this error.

Suspend function 'getByTimeType' should be called only from a
coroutine or another suspend function

This is the code giving me error:
class WidgetProvider : HomeWidgetProvider() {

```<code>private var job: Job = Job()
private val scope = CoroutineScope(job + Dispatchers.Main)

override fun onUpdate(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetIds: IntArray,
    widgetData: SharedPreferences
) {

    Log.d("debugging", "widget loaded")
    appWidgetIds.forEach { widgetId ->
        val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {
            val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()

            scope.launch {
                val db = Room.databaseBuilder(
                    context,
                    AppDatabase::class.java, "db"
                ).build()
                val todosDAO = db.TodoDAO()
                val todos: List<Todo> = todosDAO.getByTimeType("day")
            }

            Log.d("debugging", "update is triggered");

            setRemoteAdapter(
                R.id.todos_list,
                todosRemoteView
                    .build()
            )

        }

        appWidgetManager.updateAppWidget(widgetId, views)
    }

}
}
</code>```

Body:
I have an async process in my android app and I am using a co-routine scope to call a suspend function. But I am getting this error.

Suspend function 'getByTimeType' should be called only from a
coroutine or another suspend function

This is the code giving me error:
class WidgetProvider : HomeWidgetProvider() {

private var job: Job = Job()
private val scope = CoroutineScope(job + Dispatchers.Main)

override fun onUpdate(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetIds: IntArray,
    widgetData: SharedPreferences
) {

    Log.d("debugging", "widget loaded")
    appWidgetIds.forEach { widgetId ->
        val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {
            val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()

            scope.launch {
                val db = Room.databaseBuilder(
                    context,
                    AppDatabase::class.java, "db"
                ).build()
                val todosDAO = db.TodoDAO()
                val todos: List<Todo> = todosDAO.getByTimeType("day")
            }

            Log.d("debugging", "update is triggered");

            setRemoteAdapter(
                R.id.todos_list,
                todosRemoteView
                    .build()
            )

        }

        appWidgetManager.updateAppWidget(widgetId, views)
    }

}
}


问:
/bin/sh: eval: line 126: –: not found when trying to build a packer image with Gitlab CI
I'm trying to set up a Gitlab pipeline for my packer builds and I'm getting this error when trying to build the packer image

/bin/sh: eval: line 126: –: not found

Here's my .gitlab-ci.yml file as well:

```<code>stages:
  - build
  - deploy

image: alpine

get_packer:
  stage: build
  artifacts:
    paths:
    - packer
  script:
    - echo "Fetching packer"
    - wget https://releases.hashicorp.com/packer/1.5.5/packer_1.5.5_linux_amd64.zip
    - unzip packer_1.5.5_linux_amd64.zip
    - chmod +x packer

deploy_packer:
  stage: deploy
  script:
    – echo "Deploying Packer Build"
    – cd aws
    – ./packer build -only="*rhel*" .
</code>```

The build stage passes, I just get that error during the deploy stage.

Here's the last few lines from my pipeline leading up to the error. I've seen other examples just like this, what could be causing it?

```<code>Downloading artifacts for get_packer (3446587702)...
Downloading artifacts from coordinator... ok        id=3446587702 responseStatus=200 OK token=-s1LvCfZ
Executing "step_script" stage of the job script
00:01
Using docker image sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da for alpine with digest alpine@sha256:8914eb54f968791faf6a8638949e480fef81e697984fba772b3976835194c6d4 ...
/bin/sh: eval: line 126: –: not found
$ – echo "Deploying Packer Build" – cd aws – ./packer build -only="*rhel*" .
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit code 127
</code>```

Body:
I'm trying to set up a Gitlab pipeline for my packer builds and I'm getting this error when trying to build the packer image

/bin/sh: eval: line 126: –: not found

Here's my .gitlab-ci.yml file as well:

stages:
  - build
  - deploy

image: alpine

get_packer:
  stage: build
  artifacts:
    paths:
    - packer
  script:
    - echo "Fetching packer"
    - wget https://releases.hashicorp.com/packer/1.5.5/packer_1.5.5_linux_amd64.zip
    - unzip packer_1.5.5_linux_amd64.zip
    - chmod +x packer

deploy_packer:
  stage: deploy
  script:
    – echo "Deploying Packer Build"
    – cd aws
    – ./packer build -only="*rhel*" .

The build stage passes, I just get that error during the deploy stage.

Here's the last few lines from my pipeline leading up to the error. I've seen other examples just like this, what could be causing it?

Downloading artifacts for get_packer (3446587702)...
Downloading artifacts from coordinator... ok        id=3446587702 responseStatus=200 OK token=-s1LvCfZ
Executing "step_script" stage of the job script
00:01
Using docker image sha256:49176f190c7e9cdb51ac85ab6c6d5e4512352218190cd69b08e6fd803ffbf3da for alpine with digest alpine@sha256:8914eb54f968791faf6a8638949e480fef81e697984fba772b3976835194c6d4 ...
/bin/sh: eval: line 126: –: not found
$ – echo "Deploying Packer Build" – cd aws – ./packer build -only="*rhel*" .
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit code 127


问:
How to mock a templated class in Flutter?
I am currently developing an application that uses MVVM architecture, but I don't think this is relevant to my problem. When I was adding tests to my View Model I ran into a problem, when I was trying to mock my View Model, since it was being passed to the Screen State class only the type of the View Model via template, I couldn't find a way to mock it.

Something like this:

```<code>class MenuScreen extends Screen {
  const MenuScreen({Key? key}) : super(key: key);

  @override
  _MenuScreenState createState() => _MenuScreenState();
}

_MenuScreenState class extends ScreenState<MenuScreen,
    MenuViewModel, MenuData> {
...
}
</code>```
```<code>abstract class ScreenState<T extends Screen, T2 extends ViewModel<T3>,
    T3 extends StateData> extends State<T> {
  ScreenState();

  late final T2 viewModel;

  Widget buildScreen(BuildContext context);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ValueListenableProvider<T3>.value(value: viewModel),
      ],
      builder: (context, _) => buildScreen(context),
    );
  }

  @override
  @mustCallSuper
  void initState() {
    super.initState();
    viewModel = context.read<ViewModelFactory>().create<T2>();
  }

  @override
  @mustCallSuper
  void dispose() {
    viewModel.dispose();
    super.dispose();
  }
}
</code>```

ViewModelFactory is responsible for create an instance of MenuViewModel, that for my unit tests scenario should be something like MockMenuViewModel.

Is there any way I can mock up MenuViewModel within this ScreenState class or somehow inject the mock view model instance i want in the screen state instance?

Body:
I am currently developing an application that uses MVVM architecture, but I don't think this is relevant to my problem. When I was adding tests to my View Model I ran into a problem, when I was trying to mock my View Model, since it was being passed to the Screen State class only the type of the View Model via template, I couldn't find a way to mock it.

Something like this:

class MenuScreen extends Screen {
  const MenuScreen({Key? key}) : super(key: key);

  @override
  _MenuScreenState createState() => _MenuScreenState();
}

_MenuScreenState class extends ScreenState<MenuScreen,
    MenuViewModel, MenuData> {
...
}

abstract class ScreenState<T extends Screen, T2 extends ViewModel<T3>,
    T3 extends StateData> extends State<T> {
  ScreenState();

  late final T2 viewModel;

  Widget buildScreen(BuildContext context);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ValueListenableProvider<T3>.value(value: viewModel),
      ],
      builder: (context, _) => buildScreen(context),
    );
  }

  @override
  @mustCallSuper
  void initState() {
    super.initState();
    viewModel = context.read<ViewModelFactory>().create<T2>();
  }

  @override
  @mustCallSuper
  void dispose() {
    viewModel.dispose();
    super.dispose();
  }
}

ViewModelFactory is responsible for create an instance of MenuViewModel, that for my unit tests scenario should be something like MockMenuViewModel.

Is there any way I can mock up MenuViewModel within this ScreenState class or somehow inject the mock view model instance i want in the screen state instance?


问:
How can I parse an Ethereum block-level logsBloom?
I have been download blocks from EVM-based blockchains via the JSON-RPC API via eth_getBlockByNumber.  In the block there is a logsBloom element which, if I understand this correctly, is an aggregate of the logs of every transaction in that block.

There are certain topics I want to search for, such as 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef (token transfer).  If I can search the block-level logsBloom filter for my topics in my software, then I can decide whether to go back to the blockchain to get any of the transaction-level logs and/or receipts.

I have limited API calls to my blockchain data provider, so I don't want to call eth_getLogs or eth_getTransactionReceipt for every single transaction on a blockchain since 99.9% of them are irrelevant to me and I simply can't send a million requests per day.  I need this data historically back to genesis, so subscribing to real-time, filtered events is insufficient.

Is this possible?  Can I parse and search the 256 byte block-level logsBloom data for "any transaction in the block which emitted a specific topic/event that I am asking for"?


问:
vscode ignoring jsconfig.json file
I have just added the jsconfig.json file to my node and react project. It is at the top level of the project.

here is what is in it:

```<code>{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}
</code>```

It is having no effect. I have reload the vscode window. I have restarted my app.

I even tried to add errors to the file like so :

```<code>{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}s;ldfkjs;al
</code>```

It has no effect. So VScode is simply ignoring the file.

EDITED:
The project is a node module that is imported by my React APP

Title: vscode ignoring jsconfig.json file

Body:
I have just added the jsconfig.json file to my node and react project. It is at the top level of the project.

here is what is in it:

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

It is having no effect. I have reload the vscode window. I have restarted my app.

I even tried to add errors to the file like so :

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}s;ldfkjs;al

It has no effect. So VScode is simply ignoring the file.

EDITED:
The project is a node module that is imported by my React APP


问:
Is it possible to capture an object in Visual Studio on a breakpoint with all values, so it can be used to create moq objects for a Unit Test?
In Visual Studio, if I use Copy Value, it's only the value in the Locals window, like the name of the object.  Is there a way to copy the whole object, values, lists, other objects underneath it?  I want to use it for a unit test, changing the values for my test.  I thought it would be quicker to copy and paste than having to go back and look at the object(s) and create it all by hand.

I had thought I could serialization of the object as JSON and use that to create the object in the test, but I wanted to if there are better ways.

I'm using xUnit if that matters, but it doesn't have to stay xUnit if it matters.  I'm in .NET 4.6, not Core, and it's MVC.  I do not know if any of that has a bearing.

Example:

```<code>public ActionResult GetEmployees(SomeObject someObject)
{
    // I want to get the someObject values from the Visual Studio IDE.
    // someObject may be composed of other objects and lists.

}```
```

Body:
In Visual Studio, if I use Copy Value, it's only the value in the Locals window, like the name of the object.  Is there a way to copy the whole object, values, lists, other objects underneath it?  I want to use it for a unit test, changing the values for my test.  I thought it would be quicker to copy and paste than having to go back and look at the object(s) and create it all by hand.

I had thought I could serialization of the object as JSON and use that to create the object in the test, but I wanted to if there are better ways.

I'm using xUnit if that matters, but it doesn't have to stay xUnit if it matters.  I'm in .NET 4.6, not Core, and it's MVC.  I do not know if any of that has a bearing.

Example:

public ActionResult GetEmployees(SomeObject someObject)
{
    // I want to get the someObject values from the Visual Studio IDE.
    // someObject may be composed of other objects and lists.

}```


问:
Why does NuGet package reference incorrect .NET framework/standard?
tl;dr:

I have a .NET Framework 4.7.2 project consuming a NuGet package which supports .NET Standard 2.0. That package, in turn, requires another package which supports .NET Standard 2.0.  However, when run, the latter package uses net461 binaries rather than netstandard2.0.

How do I force a NuGet package & its dependencies to use .NET Standard 2.0?

Are there special steps required to consume a .NET Standard package from a .NET Framework 4.7.2 project?

Specifics:

I am trying to get the NuGet package for SparkplugNet (which uses the MQTTNet package) working in a .NET Framework 4.7.2 project - just the basic "How to use" SparkplugB example.  Both projects support .NET Standard 2.0.  After some debugging (details below), it appears MQTTNet is trying to use code paths specific to .NET Framework 4.6.1, rather than .NET Standard 2.0, and crashing with no feedback whatsoever.

To troubleshoot, I built SparkplugNet and MQTTNet from source.  As far as I can tell, the crash comes from hitting .NET 4.5/4.6.1-specific code in CrossPlatformSocket.ConnectAsync(), specifically this line (in context):

await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, host, port, null).ConfigureAwait(false)

When I debug, _socket is a System.Net.Sockets.Socket which doesn't appears to have a BeginConnect() method, at least in the source file my debugger pulled.  I am not sure why it branches to that code when .NET Standard 2.0 would be a better fit.

Back to a 4.7.2 project consuming SparkplugNet & MQTTNet via NuGet package....  If I look at the reference paths, SparkplugNet is properly pointed at the netstandard2.0 folder, but MQTTNet points to packages\MQTTnet.4.1.3.436\lib\net461\MQTTnet.dll.  If I change the hint path manually in the project file, MSBuild appears to pull from the netstandard2.0 folder, but it still crashes.  I assume it is the same cause, though I'm having trouble debugging using NuGet packages.  Also, I'm hoping for a better solution than hacking hint paths.


问:
nestjs throw error while using mongoose ref in two related model
I have simple schema in nestjs like bellow for user

```<code>@Schema()
export class User {
 @Prop()
 firstName: string

 @prop()
 lastName: string

 @Prop({ type: [{ type: Types.ObjectId, ref: Post.name }] })
 bookmarks?: Post[]
}
</code>```

and another schema for post like below

```<code>@Schema()
export class Post {
 @Prop()
 title: string

 @Prop()
 body: string

 @Prop({ type: Types.ObjectId, ref: User.name })
 auther: User
}
</code>```

when In User schema comment the bookmarks section the project is compiled, but when uncomment the bookmark throw an error and said

```<code>ref: User.name,
              ^
TypeError: Cannot read properties of undefined (reading 'name')
</code>```

How should resolve this error?

Body:
I have simple schema in nestjs like bellow for user

@Schema()
export class User {
 @Prop()
 firstName: string

 @prop()
 lastName: string

 @Prop({ type: [{ type: Types.ObjectId, ref: Post.name }] })
 bookmarks?: Post[]
}

and another schema for post like below

@Schema()
export class Post {
 @Prop()
 title: string

 @Prop()
 body: string

 @Prop({ type: Types.ObjectId, ref: User.name })
 auther: User
}

when In User schema comment the bookmarks section the project is compiled, but when uncomment the bookmark throw an error and said

ref: User.name,
              ^
TypeError: Cannot read properties of undefined (reading 'name')

How should resolve this error?


问:
Matrix Multiplication in a 3D engine
I am struggling to grasp the idea of how Matrices are used to create the rotation in a 3D wireframe engine. Can someone please give me a brief overview of how they are used.</p>

Title: Matrix Multiplication in a 3D engine


问:
How do I trigger a non-web script in Kubernetes?
I have a Kubernetes cluster (GKE) hosting two applications, each running on a different node pool (thanks to node selectors):

A web application that runs on node-pool-1

A large and computation-intensive python program that runs on node-pool-2

I want: The large python script on node-pool-2 gets triggered by the web application from node-pool-1, and only that way.

The problem:

The python script container gets started when the pod is first deployed, and gets restarted over and over (it is no web application in itself, so when the scripts ends kubernetes considers it as failed and tries to rerun it). I do not want it started at all if not by the web application.

I do not know how to trigger the python script from the web application (programmatically speaking, I guess).


问:
How to prohibit to archive trello card anyone but card creator?
I would like to omit the situation when some manager created a task in Trello card, and someone (not the card creator) could archive it. So, in this case, the manager can miss that he gave a task to someone, and important tasks could be missed.

I would like only the card creator could archive the task and decide whether the task is completed or not.

Is it possible to achieve this in Trello?

Thank you


问:
How to recover the secret keys of environments safely using OpenSSL?
I don't understand much about openSSL and I saw this code in yaml by google:

But the person did not explain in detail how to use it, so the following questions remained:

```<code># Assumption:
# You've created the following GitHub secrets in your repository:
# MY_CLIENT_SECRET - encrypt/decrypt with openssl - useful for public and public repositories
# MY_OPENSSL_PASSWORD - used to protect secrets
# MY_OPENSSL_ITER - Use a number of iterations on the password to derive the encryption key.
#                   High values increase the time required to brute-force the resulting file.
#                   This option enables the use of PBKDF2 algorithm to derive the key.

name: Recovering Secret Keys
on:
  push:
  workflow_dispatch:

jobs:
  openssl:
    name: Recover With OpenSSL
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v3
      - env:
          MY_CLIENT_SECRET: ${{ secrets.MY_CLIENT_SECRET }}
          MY_OPENSSL_PASSWORD: ${{ secrets.MY_OPENSSL_PASSWORD }}
          MY_OPENSSL_ITER: ${{ secrets.MY_OPENSSL_ITER }}
        run: |
          echo "MY_CLIENT_SECRET (***)     = ${MY_CLIENT_SECRET}"
          echo "MY_CLIENT_SECRET (openssl) = $(echo "${MY_CLIENT_SECRET}" | openssl enc -e -aes-256-cbc -a -pbkdf2 -iter ${MY_OPENSSL_ITER} -k "${MY_OPENSSL_PASSWORD}")"
          echo "Copy the above value, and then execute locally:"
          echo "echo PASTE_HERE | openssl base64 -d | openssl enc -d -pbkdf2 -iter \$MY_OPENSSL_ITER -aes-256-cbc -k \$MY_OPENSSL_PASSWORD"
</code>```

I have a personal project where the code will be public, I need to get the secret envs and create a file with them, but only certain people can do it, to be able to use it in the project.

How do I block this so that certain people can view and generate the .envs files with the secret keys?

How do I decrypt and create secret env files?

What is it and how to get the MY_CLIENT_SECRET, MY_OPENSSL_PASSWORD, MY_OPENSSL_ITER?

Body:
I don't understand much about openSSL and I saw this code in yaml by google:

But the person did not explain in detail how to use it, so the following questions remained:

# Assumption:
# You've created the following GitHub secrets in your repository:
# MY_CLIENT_SECRET - encrypt/decrypt with openssl - useful for public and public repositories
# MY_OPENSSL_PASSWORD - used to protect secrets
# MY_OPENSSL_ITER - Use a number of iterations on the password to derive the encryption key.
#                   High values increase the time required to brute-force the resulting file.
#                   This option enables the use of PBKDF2 algorithm to derive the key.

name: Recovering Secret Keys
on:
  push:
  workflow_dispatch:

jobs:
  openssl:
    name: Recover With OpenSSL
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v3
      - env:
          MY_CLIENT_SECRET: ${{ secrets.MY_CLIENT_SECRET }}
          MY_OPENSSL_PASSWORD: ${{ secrets.MY_OPENSSL_PASSWORD }}
          MY_OPENSSL_ITER: ${{ secrets.MY_OPENSSL_ITER }}
        run: |
          echo "MY_CLIENT_SECRET (***)     = ${MY_CLIENT_SECRET}"
          echo "MY_CLIENT_SECRET (openssl) = $(echo "${MY_CLIENT_SECRET}" | openssl enc -e -aes-256-cbc -a -pbkdf2 -iter ${MY_OPENSSL_ITER} -k "${MY_OPENSSL_PASSWORD}")"
          echo "Copy the above value, and then execute locally:"
          echo "echo PASTE_HERE | openssl base64 -d | openssl enc -d -pbkdf2 -iter \$MY_OPENSSL_ITER -aes-256-cbc -k \$MY_OPENSSL_PASSWORD"

I have a personal project where the code will be public, I need to get the secret envs and create a file with them, but only certain people can do it, to be able to use it in the project.

How do I block this so that certain people can view and generate the .envs files with the secret keys?

How do I decrypt and create secret env files?

What is it and how to get the MY_CLIENT_SECRET, MY_OPENSSL_PASSWORD, MY_OPENSSL_ITER?


问:
How to save edits to a data bound table or query (ultra basic)
It's been many years since I've done much programming, and now I'm trying to do a pro bono project for a local library. Relearning everything!

I can't get edits to save.

I have a DataGridView and a BindingNavigator bound to a table, Titles. I also have controls bound to individual fields of this table. I have a save button on the navigator and call
"this.titlesTableAdapter.Update(this.libraryDataSet.Titles)" on click.
The program thumbs its nose at me ;-(

I got this code from https://learn.microsoft.com/en-us/visualstudio/data-tools/update-data-by-using-a-tableadapter?source=recommendations&view=vs-2022&tabs=csharp

I've also visited multiple websites, youtube, and a Udemy course. It seems to be automatic for everyone else. Why, oh why, do the programming gods hate me?

My program is Windows Forms running against an Access back end. I am using VS Community 2022.

Also, my recollection is that best practices call for binding to a query rather than a table, particularly since I am joining several tables (only fields -- including foreign keys -- in the Titles table need to be updated). False memory? If a query is the right approach, does this change my Update code?


问:
How to fix the error with popper js and webpack 5 - popper_js__WEBPACK_IMPORTED_MODULE_5__.default is not a constructor
Problem description -
I need to use react-recurrence in the project, but when hovering over the days of division the following error appears, I have encountered it before but could not solve, the problem was with the tooltip from the old material UI, is there any way to ignore old versions of material UI or maybe not the problem, if someone knows something about this kind of errors and how to solve them would be very grateful for feedback

Error

webpack.config.js

```<code>const { merge } = require('webpack-merge');
const Dotenv = require('dotenv-webpack');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
const singleSpaDefaults = require('webpack-config-single-spa-react-ts');

module.exports = (webpackConfigEnv, argv) => {
  const defaultConfig = singleSpaDefaults({
    orgName: 'app',
    projectName: 'comm',
    webpackConfigEnv,
    argv,
  });

  return merge(defaultConfig, {
    externals: ['@app/styleguide'],
    resolve: {
      extensions: ['.ts', '.d.ts', '.tsx', '.js', '.jsx'],
      preferRelative: true,
      fallback: {
        fs: false,
        tls: false,
        net: false,
        path: false,
        zlib: false,
        http: false,
        https: false,
        stream: false,
        crypto: false,
        'crypto-browserify': require.resolve('crypto-browserify'),
      },
      alias: {
        helpers: path.resolve(__dirname, 'src/helpers/'),
        stores: path.resolve(__dirname, 'src/stores/'),
        hooks: path.resolve(__dirname, 'src/hooks/'),
        components: path.resolve(__dirname, 'src/components/'),
        layouts: path.resolve(__dirname, 'src/layouts/'),
      },
      plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.json' })],
    },
    devServer: {
      port: 8500,
    },
    plugins: [
      new Dotenv({
        path: './.env.development',
      }),
      new FilterWarningsPlugin({
        exclude:
          /There are multiple modules with names that only differ in casing/,
      }),
      new CleanWebpackPlugin(),
    ],
    output: {
      path: path.resolve(__dirname, 'build'),
    },
  });
};
</code>```

Body:
Problem description -
I need to use react-recurrence in the project, but when hovering over the days of division the following error appears, I have encountered it before but could not solve, the problem was with the tooltip from the old material UI, is there any way to ignore old versions of material UI or maybe not the problem, if someone knows something about this kind of errors and how to solve them would be very grateful for feedback

Error

webpack.config.js

const { merge } = require('webpack-merge');
const Dotenv = require('dotenv-webpack');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
const singleSpaDefaults = require('webpack-config-single-spa-react-ts');

module.exports = (webpackConfigEnv, argv) => {
  const defaultConfig = singleSpaDefaults({
    orgName: 'app',
    projectName: 'comm',
    webpackConfigEnv,
    argv,
  });

  return merge(defaultConfig, {
    externals: ['@app/styleguide'],
    resolve: {
      extensions: ['.ts', '.d.ts', '.tsx', '.js', '.jsx'],
      preferRelative: true,
      fallback: {
        fs: false,
        tls: false,
        net: false,
        path: false,
        zlib: false,
        http: false,
        https: false,
        stream: false,
        crypto: false,
        'crypto-browserify': require.resolve('crypto-browserify'),
      },
      alias: {
        helpers: path.resolve(__dirname, 'src/helpers/'),
        stores: path.resolve(__dirname, 'src/stores/'),
        hooks: path.resolve(__dirname, 'src/hooks/'),
        components: path.resolve(__dirname, 'src/components/'),
        layouts: path.resolve(__dirname, 'src/layouts/'),
      },
      plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.json' })],
    },
    devServer: {
      port: 8500,
    },
    plugins: [
      new Dotenv({
        path: './.env.development',
      }),
      new FilterWarningsPlugin({
        exclude:
          /There are multiple modules with names that only differ in casing/,
      }),
      new CleanWebpackPlugin(),
    ],
    output: {
      path: path.resolve(__dirname, 'build'),
    },
  });
};


问:
How to generate IACA analysis report for a c program?
I would like to analyze the effect, if any,  #pragma GCC unroll n has on a simple for-loop summation program in C. From my research, I learned of the IACA tool and have downloaded it but I am having a hard time getting an analysis report as it is shown here.

Issue number 1: Configuring IACA. I noticed IACA is an app and not a collection of libraries but the app doesn't open, (should I be able to interact with it?). I extracted IACA files into its own folder in OS and No squiggly lines appeared under

```<code>#include <iacaMarks.h>
</code>```

So I assumed it was on the right path but when I run the program I get the following error:

```<code>a.c:2:23: fatal error: iacaMarks.h: No such file or directory
#include <iacaMarks.h>
                      ^
compilation terminated.
</code>```

Issue number 2: Which command prompt will produce the analysis report? From the IACA guide. I gathered the command prompt iaca -trace filename.c which I used in the terminal but  received an error:

```<code>iaca : The term 'iaca' is not recognized as the name of a cmdlet..... most likely because it has not been integrated properly.
</code>```

I am getting a bit overwhelmed and could use some help.

What am I doing wrong here?

Is there an easier or another way to analyze performance changes due to loop unrolling? I have a limited capability of reading assembly code, but should I be able to gather any information regarding latency and throughput from it?

I am using a Windows machine with 64-bit operating system and x64-based processor. I have a GCC compiler and am using vs-code for c code and VS for assembly code.
I don't think there is anything wrong with the C code but clearly, I am no expert so here it is:

#include <stdio.h>
#include <iacaMarks.h>

int main(){
int arr[50]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49};
int result=0;
#pragma GCC unroll 2
for(int i=0; i< 50; i++){
    IACA_VC64_START
result+=arr[i];

}
IACA_VC64_END

return 0;

}
```
<p>To try get IACA on the right path did this: I created an IACA folder in OS and extracted the files there. There are 2 items in the folder, the first is the IACA app, and the 2nd is iacaMarks.c. Then I added</p>
```"C:\\iaca\\iaca-win64"
```

under Include path in c_cpp_preperties.json file.

Body:
I would like to analyze the effect, if any,  #pragma GCC unroll n has on a simple for-loop summation program in C. From my research, I learned of the IACA tool and have downloaded it but I am having a hard time getting an analysis report as it is shown here.

Issue number 1: Configuring IACA. I noticed IACA is an app and not a collection of libraries but the app doesn't open, (should I be able to interact with it?). I extracted IACA files into its own folder in OS and No squiggly lines appeared under

#include <iacaMarks.h>

So I assumed it was on the right path but when I run the program I get the following error:

a.c:2:23: fatal error: iacaMarks.h: No such file or directory
#include <iacaMarks.h>
                      ^
compilation terminated.

Issue number 2: Which command prompt will produce the analysis report? From the IACA guide. I gathered the command prompt iaca -trace filename.c which I used in the terminal but  received an error:

iaca : The term 'iaca' is not recognized as the name of a cmdlet..... most likely because it has not been integrated properly.

I am getting a bit overwhelmed and could use some help.

What am I doing wrong here?

Is there an easier or another way to analyze performance changes due to loop unrolling? I have a limited capability of reading assembly code, but should I be able to gather any information regarding latency and throughput from it?

I am using a Windows machine with 64-bit operating system and x64-based processor. I have a GCC compiler and am using vs-code for c code and VS for assembly code.
I don't think there is anything wrong with the C code but clearly, I am no expert so here it is:

#include <stdio.h>
#include <iacaMarks.h>

int main(){
int arr[50]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49};
int result=0;
#pragma GCC unroll 2
for(int i=0; i< 50; i++){
    IACA_VC64_START
result+=arr[i];

}
IACA_VC64_END

return 0;

}

To try get IACA on the right path did this: I created an IACA folder in OS and extracted the files there. There are 2 items in the folder, the first is the IACA app, and the 2nd is iacaMarks.c. Then I added

"C:\\iaca\\iaca-win64"

under Include path in c_cpp_preperties.json file.


问:
avro schema parser ignoring logical type for byte type
I am trying to parse avro schema string to Schema object using avro lib..when parsing the parser seems ignoring the logical type provided in the avro schema and causing the deserilization of json data not to work properly.

Sample avro schema (json representation)

```<code>{
  "type": "record",
  "name": "calculation",
  "fields": [
    {
      "name": "AccountId",
      "type": "string"
    },
    {
      "name": "AccountValue",
      "type": [
        "null",
        {
          "type": "string"
        }
      ],
      "default": null
    },
    {
      "name": "AccountValueAgg",
      "type": [
        "null",
        {
          "type": "bytes",
          "logicalType": "decimal"
        }
      ],
      "default": null
    }
  ]
}
</code>```

I am using the following schema parser from avro (1.11.1 version)

```<code>import org.apache.avro.Schema;
String schemaStr = "json from above";
Schema.Parser schemaParser = new Schema.Parser();
Schema schema = schemaParser.parse(schemaStr);
return schema;
</code>```

the returned schema object doesn't contain the logical type provided for the AccountValueAgg.

this causing issue with apache beam row conversion to avro generic record using https://github.com/apache/beam/blob/release-2.43.0/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/AvroUtils.java#L1006 (where value is defined as decimal) but due to avro schema object returning null for logical type causing the issue

Body:
I am trying to parse avro schema string to Schema object using avro lib..when parsing the parser seems ignoring the logical type provided in the avro schema and causing the deserilization of json data not to work properly.

Sample avro schema (json representation)

{
  "type": "record",
  "name": "calculation",
  "fields": [
    {
      "name": "AccountId",
      "type": "string"
    },
    {
      "name": "AccountValue",
      "type": [
        "null",
        {
          "type": "string"
        }
      ],
      "default": null
    },
    {
      "name": "AccountValueAgg",
      "type": [
        "null",
        {
          "type": "bytes",
          "logicalType": "decimal"
        }
      ],
      "default": null
    }
  ]
}

I am using the following schema parser from avro (1.11.1 version)

import org.apache.avro.Schema;
String schemaStr = "json from above";
Schema.Parser schemaParser = new Schema.Parser();
Schema schema = schemaParser.parse(schemaStr);
return schema;

the returned schema object doesn't contain the logical type provided for the AccountValueAgg.

this causing issue with apache beam row conversion to avro generic record using https://github.com/apache/beam/blob/release-2.43.0/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/utils/AvroUtils.java#L1006 (where value is defined as decimal) but due to avro schema object returning null for logical type causing the issue


问:
Static IP for google cloud functions (ingress)
I have two different projects. The first one have a API Gateway instance (KONG), which i want to connect with the 2nd one, which have a cloud function with an api (serverless). According the infrastructure team, I need to have a IP and port in my function to do that.

It was made a peering between both and now I want to set a static ip to my function. That is because the infrastructure guy has said me that it is necessary.

The questions are:

Is it necessary? Do I configure a static IP for my function?

How can I set a static IP to my function (ingress)?