问:
How to enable signing of SAML2 AuthNRequest
We have a spring boot application with Saml2 configured for authentication.

We are having hard time configuring signing of Saml2 AuthNRequest, which gets rejected for that reason at IDP (which is ADFS, don't really know the version for it). We tried to disable the requirement for signing, and our application works nicely. However, this disabling was done only to test that we have everything in place.

All that is missing is now the signing of AuthNRequest. This link seems to have the same problem: Spring Security SAML: Getting <Signature> block to appear in <AuthnRequest>. The solution for it seem to be creating WebSSOProfileOptions and setting the binding to SAMLConstants.SAML2_POST_BINDING_URI.

But there seem to be some sort of version mismatch or something. We cannot find this WebSSPProfileOptions class from our classpath at all. I'm new to all this, including gradle, but our gradle has it as a dependency like this:

```<code>+--- org.springframework.security:spring-security-saml2-service-provider -> 5.4.7
|    +--- org.opensaml:opensaml-core:3.4.6
</code>```

I really hope there is a way to say in the configuration, that the signing is done on the AuthNRequest messages.

```<code>spring:
  security:
    saml2:
      relyingparty:
        registration:
          my-sp:
            decryption.credentials:
              - private-key-location: "classpath:credentials/my_private_key"
                certificate-location: "classpath:credentials/my_cert"
            signing.credentials:
              - private-key-location: "classpath:credentials/my_private_key"
                certificate-location: "classpath:credentials/my_cert"
            identityprovider:
              entity-id: http://idp.....
              verification.credentials:
                  - certificate-location: "classpath:credentials/idp......crt"
              singlesignon:
                sign-request: true
                url: https://idp......
              metadata-uri: https://.....
</code>```

If the signing of AuthnRequest cannot be enforced through configuration, what would be the correct way of doing it.

It feels a bit harsh to downgrade to get this WebSSPProfileOptions into classpath.
spring-security-saml2-core-1.0.10.RELEASE.jar seems to have it. Web page https://spring.io/projects/spring-security-saml says that it is being superseded by https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#saml2.

In short, how do we enforce signing of AuthnRequest with spring-security-saml2-service-provider version 5.4.7

答:
I will answer my own question, as I think we figured it out. There might also be a way to enforce signing on spring, which was really what my original question was all about.

The problem was, that spring implementation seems to be looking for WantAuthnRequestsSigned="true", and it was missing in our IDP metadata.

```<code>  <EntityDescriptor xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        entityID="http://idp......">
    <IDPSSODescriptor xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"
        WantAuthnRequestsSigned="true">
</code>```

We managed to solve this, by downloading the IDP metadata, adding the mentioned attribute and storing the fixed metadata in a place accessible to spring. Not a perfect solution, but that's the best we can do at the moment.

Based on this finding, I believe there is a bug in either IDP or spring code. If the default value is "true", the bug is spring. If it is "false", the bug is in IDP. If the default behaviour is unspecified, then it is bad luck for everyone.

If I found out more on this subject, I will update it in here.

Body:
We have a spring boot application with Saml2 configured for authentication.

We are having hard time configuring signing of Saml2 AuthNRequest, which gets rejected for that reason at IDP (which is ADFS, don't really know the version for it). We tried to disable the requirement for signing, and our application works nicely. However, this disabling was done only to test that we have everything in place.

All that is missing is now the signing of AuthNRequest. This link seems to have the same problem: Spring Security SAML: Getting <Signature> block to appear in <AuthnRequest>. The solution for it seem to be creating WebSSOProfileOptions and setting the binding to SAMLConstants.SAML2_POST_BINDING_URI.

But there seem to be some sort of version mismatch or something. We cannot find this WebSSPProfileOptions class from our classpath at all. I'm new to all this, including gradle, but our gradle has it as a dependency like this:

+--- org.springframework.security:spring-security-saml2-service-provider -> 5.4.7
|    +--- org.opensaml:opensaml-core:3.4.6

I really hope there is a way to say in the configuration, that the signing is done on the AuthNRequest messages.

spring:
  security:
    saml2:
      relyingparty:
        registration:
          my-sp:
            decryption.credentials:
              - private-key-location: "classpath:credentials/my_private_key"
                certificate-location: "classpath:credentials/my_cert"
            signing.credentials:
              - private-key-location: "classpath:credentials/my_private_key"
                certificate-location: "classpath:credentials/my_cert"
            identityprovider:
              entity-id: http://idp.....
              verification.credentials:
                  - certificate-location: "classpath:credentials/idp......crt"
              singlesignon:
                sign-request: true
                url: https://idp......
              metadata-uri: https://.....

If the signing of AuthnRequest cannot be enforced through configuration, what would be the correct way of doing it.

It feels a bit harsh to downgrade to get this WebSSPProfileOptions into classpath.
spring-security-saml2-core-1.0.10.RELEASE.jar seems to have it. Web page https://spring.io/projects/spring-security-saml says that it is being superseded by https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#saml2.

In short, how do we enforce signing of AuthnRequest with spring-security-saml2-service-provider version 5.4.7

Body:
I will answer my own question, as I think we figured it out. There might also be a way to enforce signing on spring, which was really what my original question was all about.

The problem was, that spring implementation seems to be looking for WantAuthnRequestsSigned="true", and it was missing in our IDP metadata.

  <EntityDescriptor xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        entityID="http://idp......">
    <IDPSSODescriptor xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"
        WantAuthnRequestsSigned="true">

We managed to solve this, by downloading the IDP metadata, adding the mentioned attribute and storing the fixed metadata in a place accessible to spring. Not a perfect solution, but that's the best we can do at the moment.

Based on this finding, I believe there is a bug in either IDP or spring code. If the default value is "true", the bug is spring. If it is "false", the bug is in IDP. If the default behaviour is unspecified, then it is bad luck for everyone.

If I found out more on this subject, I will update it in here.


来源: stackexchange

问:
AWS Inspector - Teraform deployment
I am working over AWS trying some security features like securityhub, and I was deployed it trough terraform. Now I am interested in apply from terraform AWS inspector after try it from aws console; but I don't find a way to configure this implementation applying an account delegation and full freatured deployment, I was only found the way to apply the old classic inspector over aws. There is a way to implement aws inspector v2 with terraform?

Thanks

答:
I just saw thath Inspector v2 is a new feature (released one month ago) and at the moment is is not supported by Terraform.

Terraform GitHub Issue

ContentLicense: CC BY-SA 4.0

Title: AWS Inspector - Teraform deployment


问:
Create-React-App creates this  that prevents me from clicking or editing directly the app unless I delete it in the elements browswer editor
I recently did a global install of create-react-app and am having an issue where sometimes, when I'm working on a project, instead of editing directly what I have rendered in , it creates this  container around the entire app.

Upon further inspection it looks like it is an  which is rendered in the browswer as this:

```

I have screenshotted below what this ends up looking like in my app (the iframe is the orange text on the right), but it's super annoying and I've deleted the css props and cannot imagine what is causing this container around my app.

Has anyone else come across this? I have to delete this iframe to edit the elements directly from the browser but can't think why this is rendering each time I load the app in the browser.

答:
I haven't tried it, but the accepted answer looks like it will just disable fast refresh all together which is not ideal so..

Take a look at this github issue response

https://github.com/facebook/create-react-app/issues/11880#issuecomment-1005409614

Specifically I only needed

```<code>// package.json

"resolutions": { "react-error-overlay": "6.0.9" },
</code>```

Make sure to run yarn or npm install after updating

Title: Create-React-App creates this <iframe> that prevents me from clicking or editing directly the app unless I delete it in the elements browswer editor

Body:
I recently did a global install of create-react-app and am having an issue where sometimes, when I'm working on a project, instead of editing directly what I have rendered in , it creates this  container around the entire app.

Upon further inspection it looks like it is an  which is rendered in the browswer as this:

I have screenshotted below what this ends up looking like in my app (the iframe is the orange text on the right), but it's super annoying and I've deleted the css props and cannot imagine what is causing this container around my app.

Has anyone else come across this? I have to delete this iframe to edit the elements directly from the browser but can't think why this is rendering each time I load the app in the browser.

Body:
I haven't tried it, but the accepted answer looks like it will just disable fast refresh all together which is not ideal so..

Take a look at this github issue response

https://github.com/facebook/create-react-app/issues/11880#issuecomment-1005409614

Specifically I only needed

// package.json

"resolutions": { "react-error-overlay": "6.0.9" },

Make sure to run yarn or npm install after updating


问:
Plotly: Scatter plot with dropdown menu and color by group
I'm trying to make a scatter plot with 2 dropdown menus that select a data column (from a pandas data frame) to be plotted for x and y-axis, but I'm also wanting the points to be colored by a third categorical variable that is fixed (no dropdown needed for this one).

So far, I've been able to create the scatterplot correctly with functional dropdown menus thanks to another post, but I don't know how to colorize it by a third variable. Here's the code so far:

```<code>import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

df = px.data.tips().select_dtypes(['number']) # drop non numeric columns

fig = go.Figure(
go.Scatter(
    x=df['total_bill'],
    y=df['tip'],
    hovertemplate='x: %{x} <br>y: %{y}',
    mode="markers"))
fig.update_layout(
updatemenus=[
    {
        "buttons": [
            {
                "label": f"x - {x}",
                "method": "update",
                "args": [
                    {"x": [df[x]]},
                    {"xaxis": {"title": x}},
                ],
            }
            for x in cols
        ]
    },
    {
        "buttons": [
            {
                "label": f"y - {x}",
                "method": "update",
                "args": [
                    {"y": [df[x]]},
                    {"yaxis": {"title": x}}
                ],
            }
            for x in cols
        ],
        "y": 0.9,
    },
],
margin={"l": 0, "r": 0, "t": 25, "b": 0},
height=700)
fig.show()
</code>```

Ultimately, I want the same scatterplot, but for points to be colorized by "Category". I can do this using plotly express, but without dropdown menus very easily:

```<code>df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", trendline="ols")
fig.show()
</code>```

Anyone has an idea of how I could achieve this?

答:
As mentioned below, I was able to find a solution for this by creating a new column with hexadecimal color codes corresponding to categorical levels in another column:

```<code>dfx = px.data.tips()
# create list of columns to iterate over for buttons
cols = dfx.columns.values.tolist()
# make list of default plotly colors in hex
plotly_colors=[
                '#1f77b4',  # muted blue
                '#ff7f0e',  # safety orange
                '#2ca02c',  # cooked asparagus green
                '#d62728',  # brick red
                '#9467bd',  # muted purple
                '#8c564b',  # chestnut brown
                '#e377c2',  # raspberry yogurt pink
                '#7f7f7f',  # middle gray
                '#bcbd22',  # curry yellow-green
                '#17becf'   # blue-teal
              ]
# create dictionary to associate colors with unique categories
color_dict = dict(zip(dfx['smoker'].unique(),plotly_colors))
# map new column with hex colors to pass to go.Scatter()
dfx['hex']= dfx['smoker'].map(color_dict)
#initialize scatter plot
fig = go.Figure(
    go.Scatter(
        x=dfx['total_bill'],
        y=dfx['tip'],
        text=dfx['smoker'],
        marker=dict(color=dfx['hex']),
        mode="markers"
    )
)
# initialize dropdown menus
fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": f"x - {x}",
                    "method": "update",
                    "args": [
                        {"x": [dfx[x]]},
                        {"xaxis": {"title": x}},
                    ],
                }
                for x in cols
            ]
        },
        {
            "buttons": [
                {
                    "label": f"y - {x}",
                    "method": "update",
                    "args": [
                        {"y": [dfx[x]]},
                        {"yaxis": {"title": x}}
                    ],
                }
                for x in cols
            ],
            "y": 0.9,
        },
    ],
    margin={"l": 0, "r": 0, "t": 25, "b": 0},
    height=700
)
fig.show()
</code>```

Body:
I'm trying to make a scatter plot with 2 dropdown menus that select a data column (from a pandas data frame) to be plotted for x and y-axis, but I'm also wanting the points to be colored by a third categorical variable that is fixed (no dropdown needed for this one).

So far, I've been able to create the scatterplot correctly with functional dropdown menus thanks to another post, but I don't know how to colorize it by a third variable. Here's the code so far:

import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px

df = px.data.tips().select_dtypes(['number']) # drop non numeric columns

fig = go.Figure(
go.Scatter(
    x=df['total_bill'],
    y=df['tip'],
    hovertemplate='x: %{x}
y: %{y}',
    mode="markers"))
fig.update_layout(
updatemenus=[
    {
        "buttons": [
            {
                "label": f"x - {x}",
                "method": "update",
                "args": [
                    {"x": [df[x]]},
                    {"xaxis": {"title": x}},
                ],
            }
            for x in cols
        ]
    },
    {
        "buttons": [
            {
                "label": f"y - {x}",
                "method": "update",
                "args": [
                    {"y": [df[x]]},
                    {"yaxis": {"title": x}}
                ],
            }
            for x in cols
        ],
        "y": 0.9,
    },
],
margin={"l": 0, "r": 0, "t": 25, "b": 0},
height=700)
fig.show()

Ultimately, I want the same scatterplot, but for points to be colorized by "Category". I can do this using plotly express, but without dropdown menus very easily:

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", trendline="ols")
fig.show()

Anyone has an idea of how I could achieve this?

Body:
As mentioned below, I was able to find a solution for this by creating a new column with hexadecimal color codes corresponding to categorical levels in another column:

dfx = px.data.tips()
# create list of columns to iterate over for buttons
cols = dfx.columns.values.tolist()
# make list of default plotly colors in hex
plotly_colors=[
                '#1f77b4',  # muted blue
                '#ff7f0e',  # safety orange
                '#2ca02c',  # cooked asparagus green
                '#d62728',  # brick red
                '#9467bd',  # muted purple
                '#8c564b',  # chestnut brown
                '#e377c2',  # raspberry yogurt pink
                '#7f7f7f',  # middle gray
                '#bcbd22',  # curry yellow-green
                '#17becf'   # blue-teal
              ]
# create dictionary to associate colors with unique categories
color_dict = dict(zip(dfx['smoker'].unique(),plotly_colors))
# map new column with hex colors to pass to go.Scatter()
dfx['hex']= dfx['smoker'].map(color_dict)
#initialize scatter plot
fig = go.Figure(
    go.Scatter(
        x=dfx['total_bill'],
        y=dfx['tip'],
        text=dfx['smoker'],
        marker=dict(color=dfx['hex']),
        mode="markers"
    )
)
# initialize dropdown menus
fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": f"x - {x}",
                    "method": "update",
                    "args": [
                        {"x": [dfx[x]]},
                        {"xaxis": {"title": x}},
                    ],
                }
                for x in cols
            ]
        },
        {
            "buttons": [
                {
                    "label": f"y - {x}",
                    "method": "update",
                    "args": [
                        {"y": [dfx[x]]},
                        {"yaxis": {"title": x}}
                    ],
                }
                for x in cols
            ],
            "y": 0.9,
        },
    ],
    margin={"l": 0, "r": 0, "t": 25, "b": 0},
    height=700
)
fig.show()


问:
How to generate SSL only for subdomain without add domain?
I am pretty new with the domain configuration part. I want to know that can I generate SSL only for my subdomain I didn't want to add the root domain with CLOUDFLARE because my root domain already has SSL certificate. Is it possible to do that? I have purchased my domain from the GODADDY. I will add the generated SSL certificate to IIS.

Please help me out !!

Edit: I don't want to add my root domain to CLOUDFLARE because if I will do it I have to change my NAMESERVER for the same and my root domain already has SSL.

答: I believe what you're looking for is the CNAME setup on Cloudflare. This is the alternative method of Name Server setup. However, this setup requires a Business plan. With CNAME setup, you can have just a certain subdomains to be used with Cloudflare. With proxy turned on the subdomain, you'd get the usual Universal SSL certification from Cloudflare.


问:
How to filter object entries to keep only those whose keys start with a string, using ramda?
Having the following array:

const vegsAndFruits = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "veg_tomato": 3,
        "fruit_watermelon": 11
    },
    {
        "veg_carrot": 3,
        "veg_garlic": 11,
        "veg_potato": 0,
        "fruit_apricot": 22
    },
    {
        "veg_eggplant": 2,
        "veg_cabbage": 1,
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]
```
<p>I want to filter it to return the same array <strong>but</strong> to keep only the properties that start with <code>"fruit"</code>.</p>
<p><em>Expected output</em></p>
<pre class="lang-js prettyprint-override"><code>const expectedOutput = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "fruit_watermelon": 11
    },
    {
        "fruit_apricot": 22
    },
    {
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]
</code>```

My attempt

I thought the solution should come from mixing ramda's R.startsWith() and R.pickBy(). But the following doesn't work as I expected:

const R = require("ramda")

R.map(R.pickBy(R.startsWith(["fruit"])),vegsAndFruits)
```
<p>which returns</p>
<pre class="lang-js prettyprint-override"><code>// [ {}, {}, {} ]
</code>```

What am I missing here?

答:
The R.pickBy predicate is called with the value (1st) and key (2nd) parameters. Since you need the key, use R.nthArg to create a function that returns the 2nd param:

const { map, pickBy, pipe, nthArg, startsWith } = R

const fn = map(pickBy(pipe(
  nthArg(1),
  startsWith('fruit')
)))

const vegsAndFruits = [{"fruit_banana":10,"fruit_apple":1,"veg_tomato":3,"fruit_watermelon":11},{"veg_carrot":3,"veg_garlic":11,"veg_potato":0,"fruit_apricot":22},{"veg_eggplant":2,"veg_cabbage":1,"fruit_strawberry":100,"fruit_orange":30}]

const result = fn(vegsAndFruits)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

Body:
Having the following array:

const vegsAndFruits = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "veg_tomato": 3,
        "fruit_watermelon": 11
    },
    {
        "veg_carrot": 3,
        "veg_garlic": 11,
        "veg_potato": 0,
        "fruit_apricot": 22
    },
    {
        "veg_eggplant": 2,
        "veg_cabbage": 1,
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]

I want to filter it to return the same array but to keep only the properties that start with "fruit".

Expected output

const expectedOutput = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "fruit_watermelon": 11
    },
    {
        "fruit_apricot": 22
    },
    {
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]

My attempt

I thought the solution should come from mixing ramda's R.startsWith() and R.pickBy(). But the following doesn't work as I expected:

const R = require("ramda")

R.map(R.pickBy(R.startsWith(["fruit"])),vegsAndFruits)

which returns

// [ {}, {}, {} ]

What am I missing here?

Body:
The R.pickBy predicate is called with the value (1st) and key (2nd) parameters. Since you need the key, use R.nthArg to create a function that returns the 2nd param:

const { map, pickBy, pipe, nthArg, startsWith } = R

const fn = map(pickBy(pipe(
  nthArg(1),
  startsWith('fruit')
)))

const vegsAndFruits = [{"fruit_banana":10,"fruit_apple":1,"veg_tomato":3,"fruit_watermelon":11},{"veg_carrot":3,"veg_garlic":11,"veg_potato":0,"fruit_apricot":22},{"veg_eggplant":2,"veg_cabbage":1,"fruit_strawberry":100,"fruit_orange":30}]

const result = fn(vegsAndFruits)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


问:
How to get the length of a string field in Mongoose?
I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

```<code>const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

</code>```

Let's say I added the following two documents:

```<code>{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}
</code>```

Which query can I use to find all documents where the "title" length is greater than 3?

I tried the following query but it only works with numbers:

```<code>Article.find({title:{$gt:3}}, (err,foundItems)=>{});
</code>```

Many thanks in advance for your help here.

答:
You can also use aggregation query to achieve the result.</p>
```<code>Article.aggregate(
[
  {
    '$project': {
      'titleLength': { '$strLenCP': '$name' }
    }
  }, {
    '$match': {
      'titleLength': {
        '$gt': 2
      }
    }
  }
])
</code>```

Body:
I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

Let's say I added the following two documents:

{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}

Which query can I use to find all documents where the "title" length is greater than 3?

I tried the following query but it only works with numbers:

Article.find({title:{$gt:3}}, (err,foundItems)=>{});

Many thanks in advance for your help here.

Body:
You can also use aggregation query to achieve the result.

Article.aggregate(
[
  {
    '$project': {
      'titleLength': { '$strLenCP': '$name' }
    }
  }, {
    '$match': {
      'titleLength': {
        '$gt': 2
      }
    }
  }
])


问:
Sort values of Observable array of objects
My service get data from Api :

async getCommunes(){
    return await this._http.get<any[]>(this.api)
      .pipe()
      .toPromise()
      .then((response: any) => {
        this._communes$.next(response);
      })
      .catch(err => console.log(err))
  }
```
<p>I call service in a component :</p>
<pre class="lang-js prettyprint-override"><code>
public communes$: Observable<any>;
constructor(private apiService: ApiService) { }

ngOnInit(): void {
   this.loadCommunes();
}

get communesFromService$(){
   return this.apiService.communes$;
}

async loadCommunes(){
  await this.apiService.getCommunes();
  this.communes$ =  this.apiService.communes$;
}
</code>```

I display data in Html by calling communesFrom Service$ (get method) :

{{record?.fields?.name}}

```
<p>My data are formated like below :</p>
<pre class="lang-json prettyprint-override"><code>
{
    "nhits": 38,
    "parameters": {
        "dataset": "communes-de-la-province-de-namur",
        "rows": 3,
        "start": 0,
        "format": "json",
        "timezone": "UTC"
    },
    "records": [
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "5f50799324d15038c9708e48c6a32c907922d00a",
            "fields": {
                "nsi": "93088",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.516510705656462,
                                50.31531488802985
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.26709679846407,
                    4.433557385138468
                ],
                "name": "Walcourt"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.433557385138468,
                    50.26709679846407
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "11fc2dbd6852c06f095e71adee7e0c1d334ccf24",
            "fields": {
                "nsi": "91054",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.971517147861946,
                                50.02965137853804
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    49.98493619689069,
                    4.901523112944346
                ],
                "name": "Gedinne"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.901523112944346,
                    49.98493619689069
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "82a588f6f7d3250b78564fd7a1f16c0a02d0e30a",
            "fields": {
                "nsi": "92045",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.827793680052161,
                                50.41154443216362
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.435523543496686,
                    4.754395027090274
                ],
                "name": "Floreffe"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.754395027090274,
                    50.435523543496686
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        }
    ]
}

</code>```

I only need 'name' field but order by ascending ('records' array).

I have tried this but it doesn't work. I also tried other solution but without success.:

get communesFromService$(){
    return this.apiService.communes$.pipe(
      map((response => response.sort((a,b) => a.name - b.name)))
    );
  }

```

How can I do that?

any suggestions is helpfull.

Thanks

答:
JavaScript arrays have a sort( ) method that sorts the array items into alphabetical order.

You can only get the name property out of all the values and sort it and then return it from service. Like below:-

Service Method:-

```<code>getNames(): Observable<string[]> {
    return this.http.get(`API url`).pipe(
      map((x:any) => x.records.map((item) => item.fields.name).sort())
    );
}
</code>```

Component: Just assign the method to an observable:-

```<code>export class AppComponent {
  name$ = this.dataService.getNames();
  constructor(private dataService: DataService) {}
}
</code>```

In Component, template use the async pipe:-

```<code><div *ngIf="(name$ | async) as result">
  <ul>
    <li *ngFor="let item of result">{{item}}</li>
  </ul>
</div>
</code>```

Demo with sample data:-
https://codesandbox.io/s/optimistic-tdd-dm898?file=/src/app/app.component.html

Update :-
if you have non-English alphabets in your string consider the below method for sorting.

```<code> getNames(): Observable<string[]> {
    return of(APIReponse).pipe(
      map((x) => x.records.map((item) => item.fields.name).sort((a, b) => {
        return a.localeCompare(b, 'en', { sensitivity: 'base' });
      }))
    );
  }
</code>```

Body:
My service get data from Api :

async getCommunes(){
    return await this._http.get<any[]>(this.api)
      .pipe()
      .toPromise()
      .then((response: any) => {
        this._communes$.next(response);
      })
      .catch(err => console.log(err))
  }

I call service in a component :

public communes$: Observable<any>;
constructor(private apiService: ApiService) { }

ngOnInit(): void {
   this.loadCommunes();
}

get communesFromService$(){
   return this.apiService.communes$;
}

async loadCommunes(){
  await this.apiService.getCommunes();
  this.communes$ =  this.apiService.communes$;
}

I display data in Html by calling communesFrom Service$ (get method) :

{{record?.fields?.name}}

My data are formated like below :

{
    "nhits": 38,
    "parameters": {
        "dataset": "communes-de-la-province-de-namur",
        "rows": 3,
        "start": 0,
        "format": "json",
        "timezone": "UTC"
    },
    "records": [
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "5f50799324d15038c9708e48c6a32c907922d00a",
            "fields": {
                "nsi": "93088",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.516510705656462,
                                50.31531488802985
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.26709679846407,
                    4.433557385138468
                ],
                "name": "Walcourt"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.433557385138468,
                    50.26709679846407
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "11fc2dbd6852c06f095e71adee7e0c1d334ccf24",
            "fields": {
                "nsi": "91054",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.971517147861946,
                                50.02965137853804
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    49.98493619689069,
                    4.901523112944346
                ],
                "name": "Gedinne"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.901523112944346,
                    49.98493619689069
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        },
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "82a588f6f7d3250b78564fd7a1f16c0a02d0e30a",
            "fields": {
                "nsi": "92045",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.827793680052161,
                                50.41154443216362
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.435523543496686,
                    4.754395027090274
                ],
                "name": "Floreffe"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.754395027090274,
                    50.435523543496686
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        }
    ]
}

I only need 'name' field but order by ascending ('records' array).

I have tried this but it doesn't work. I also tried other solution but without success.:

get communesFromService$(){
    return this.apiService.communes$.pipe(
      map((response => response.sort((a,b) => a.name - b.name)))
    );
  }

How can I do that?

any suggestions is helpfull.

Thanks

Body:
JavaScript arrays have a sort( ) method that sorts the array items into alphabetical order.

You can only get the name property out of all the values and sort it and then return it from service. Like below:-

Service Method:-

getNames(): Observable<string[]> {
    return this.http.get(`API url`).pipe(
      map((x:any) => x.records.map((item) => item.fields.name).sort())
    );
}

Component: Just assign the method to an observable:-

export class AppComponent {
  name$ = this.dataService.getNames();
  constructor(private dataService: DataService) {}
}

In Component, template use the async pipe:-

<div *ngIf="(name$ | async) as result">
  <ul>
    <li *ngFor="let item of result">{{item}}</li>
  </ul>
</div>

Demo with sample data:-
https://codesandbox.io/s/optimistic-tdd-dm898?file=/src/app/app.component.html

Update :-
if you have non-English alphabets in your string consider the below method for sorting.

 getNames(): Observable<string[]> {
    return of(APIReponse).pipe(
      map((x) => x.records.map((item) => item.fields.name).sort((a, b) => {
        return a.localeCompare(b, 'en', { sensitivity: 'base' });
      }))
    );
  }


问:
SQL : Inner Joins with Different Date Formats
I have the two following tables:

table_1 and table_2

table_1 has a date variable "Date_1" that has a variable type "character_varrying(255)"

table_2 has two date variables "Date_2" and "Date_3" that have variable types "DATE"

All 3 dates have the same form : 2010-12-31

I am trying to run the following SQL command:

```<code>CREATE TABLE final_table AS SELECT * FROM table_1 a
INNER JOIN table_2 b
ON (( a.date_1 BETWEEN b.date_2 AND b.date_3) AND a.id = b.id)
 OR (a.id1 = b.id1)
</code>```

Problem: But this gives me the following error:

```<code>HY000 Error: Bad External Date Representation
</code>```

What I tried so far: I am trying to figure out how to make all DATE variables compatible so that the INNER JOIN works. I thought that maybe this can be done using the ALTER TABLE command:

```<code>#create new date variable
ALTER TABLE table_1
ADD COLUMN new_date DATE;

#set new date variable
UPDATE table_1;
set new_date = date_1;

#repeat inner join with new date variable
CREATE TABLE final_table AS SELECT * FROM table_1 a
INNER JOIN table_2 b
ON (( a.new_date BETWEEN b.date_2 AND b.date_3) AND a.id = b.id)
 OR (a.id1 = b.id1)
</code>```

But the same error is still persisting.

Can someone please show me how to fix this?

答:
This problem is specific to the data in your (varchar) table. The database is attempting to ‘implicitly’ convert from VARCHAR to DATE. You should try to find the values that are ‘wrong’

For a ‘quickfix’ to this particular problem you could try to explicitly convert the other way around: from DATE to VARCHAR:

CREATE TABLE final_table AS SELECT * FROM table_1 a
INNER JOIN table_2 b
ON (( a.date_1 BETWEEN VARCHAR(b.date_2,’YYYY-MM-DD’) AND VARCHAR(b.date_3,’YYYY-MM-DD’)) AND a.id = b.id)
OR (a.id1 = b.id1)

Body:
I have the two following tables:

table_1 and table_2

table_1 has a date variable "Date_1" that has a variable type "character_varrying(255)"

table_2 has two date variables "Date_2" and "Date_3" that have variable types "DATE"

All 3 dates have the same form : 2010-12-31

I am trying to run the following SQL command:

CREATE TABLE final_table AS SELECT * FROM table_1 a
INNER JOIN table_2 b
ON (( a.date_1 BETWEEN b.date_2 AND b.date_3) AND a.id = b.id)
 OR (a.id1 = b.id1)

Problem: But this gives me the following error:

HY000 Error: Bad External Date Representation

What I tried so far: I am trying to figure out how to make all DATE variables compatible so that the INNER JOIN works. I thought that maybe this can be done using the ALTER TABLE command:

#create new date variable
ALTER TABLE table_1
ADD COLUMN new_date DATE;

#set new date variable
UPDATE table_1;
set new_date = date_1;

#repeat inner join with new date variable
CREATE TABLE final_table AS SELECT * FROM table_1 a
INNER JOIN table_2 b
ON (( a.new_date BETWEEN b.date_2 AND b.date_3) AND a.id = b.id)
 OR (a.id1 = b.id1)

But the same error is still persisting.

Can someone please show me how to fix this?


问:
Is .NET Timer more reliable than VB6 Timer
In the good old days of VB6 you could not rely on the timer control to fire at exactly the specified interval. If your program was doing some intense processing the Timer_Tick event is pushed onto the stack and only when it gets to the instruction is it processed, which may be some seconds(?) later.

So my question is - has the .NET timer control been improved such that this can be relied upon to fire at exactly the time interval specified? I guess the above still applies doesn't it? But is it any better than the VB6 version?

Are there any alternatives to using the timer control that ensure that an event fires after a specified interval?

答:
System.Windows.Forms.Timer runs on the UI thread and relies on a message pump; it works essentially in the same way as a VB6 timer.

But .NET has other timers - System.Threading.Timer, System.Timers.Timer that use worker threads in a multi-threaded environment.

Which is "better" depends on your requirement - using a multithreaded timer may fire more nearly at the requested interval, but this comes at the cost of the added complexity inherent in using threading.

ContentLicense: CC BY-SA 3.0


问:
How do find broken document links in SharePoint libraries
We are trying to find all broken document links in a SharePoint document library.  These links are stored in libraries as .url files.  The file itself contains the link we want to test.  Using powershell, we submit the link to invoke-webrequest.  But we always get a 200 (page found) result, even for known broken links.  When we look at the response package, we see that SharePoint is returning the "Login page", which means we most likely do not have permission to access the link via invoke-webrequest.  We are connecting using
-WebLogin, not -Interactive.

```<code>    $text = Get-PnPFile -Url $Item.FileRef -AsString # get content of the .url file
    # parse file to get target link as $link_url
    $result = (invoke-webrequest $link_url - DisableKeepAlive -UseBasicParsing)
</code>```

always returns

StatusCode :200

StatusDescription:OK

Content: ...

Always returns sign-in page.

答:
This solution works for me. Note that you will have to go to your browser to complete the login:</p>
```<code>   Connect-PnPOnline  -Url $site_url -Interactive

   #Get all the items in this library
   $Items = (Get-PnPListItem -List $list_name  -PageSize 2500).FieldValues

   foreach($Item in $Items)
   {
      if (($Item.FileRef).Contains(".url")){
        # this is a document link... do something with it.
      }
      else{
        # this is a document, so do document things with it.,
      }
   } # for-each item in the library
</code>```

Body:
We are trying to find all broken document links in a SharePoint document library.  These links are stored in libraries as .url files.  The file itself contains the link we want to test.  Using powershell, we submit the link to invoke-webrequest.  But we always get a 200 (page found) result, even for known broken links.  When we look at the response package, we see that SharePoint is returning the "Login page", which means we most likely do not have permission to access the link via invoke-webrequest.  We are connecting using
-WebLogin, not -Interactive.

    $text = Get-PnPFile -Url $Item.FileRef -AsString # get content of the .url file
    # parse file to get target link as $link_url
    $result = (invoke-webrequest $link_url - DisableKeepAlive -UseBasicParsing)

always returns

StatusCode :200

StatusDescription:OK

Content: ...

Always returns sign-in page.

Body:
This solution works for me. Note that you will have to go to your browser to complete the login:

   Connect-PnPOnline  -Url $site_url -Interactive

   #Get all the items in this library
   $Items = (Get-PnPListItem -List $list_name  -PageSize 2500).FieldValues

   foreach($Item in $Items)
   {
      if (($Item.FileRef).Contains(".url")){
        # this is a document link... do something with it.
      }
      else{
        # this is a document, so do document things with it.,
      }
   } # for-each item in the library


问:
serving Django static files with Docker, nginx and gunicorn
I am setting us a Django 2.0 application with Docker, nginx and gunicorn.

It's running the server but static files are not working.

Here is the settings.py content

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_my_project')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root')
</code>```

While developing, I put my static files inside static_my_project, which on running collectstatic copies to static_cdn/static_root

The directory structure is like

```<code>app
 |- myapp
    |- settings.py
 |- static_my_project
 |- static_cdn
    |- static_root
 |- config
    |- nginx
       |- nginx.conf
 |- manage.py
 |- Docker
 |- docker-compose.yml
</code>```

on running

```<code>docker-compose up --build
</code>```

on running collectstatic, it gives path where static files will be copied

koober-dev | --: Running collectstatic

  koober-dev |

  koober-dev | You have requested to collect static files at the destination

  myapp-dev | location as specified in your settings:

  myapp-dev |

  myapp-dev |     /app/static_cdn/static_root

  myapp-dev |

  myapp-dev | This will overwrite existing files!

  myapp-dev | Are you sure you want to do this?

  myapp-dev |

  myapp-dev | Type 'yes' to continue, or 'no' to cancel:

  myapp-dev | 0 static files copied to '/app/static_cdn/static_root', 210 unmodified.

the config/nginx/nginx.conf file contains following settings

```<code>upstream web {
    ip_hash;
    server web:9010;
}

server {
    location /static {
        autoindex on;
        alias /static/;
    }

    location / {
        proxy_pass http://web;
    }
    listen 10080;
    server_name localhost;
}
</code>```

docker-compose.yml

```<code>version: '3'

services:
  nginx:
    image: nginx:latest
    container_name: "koober-nginx"
    ports:
      - "10080:80"
      - "10443:43"
    volumes:
      - .:/app
      - ./config/nginx:/etc/nginx/conf.d
      - ./static_cdn/static_root/:/static
    depends_on:
      - web
  web:
    build: .
    container_name: "koober-dev"
    command: ./start.sh
    volumes:
      - .:/app
      - ./static_cdn/static_root/:/app/static_cdn/static_root
    ports:
      - "9010:9010"
    depends_on:
      - db
  db:
    image: postgres
    container_name: "koober-postgres-db"
</code>```

Dockerfile

```<code>FROM ubuntu:18.04

# -- Install Pipenv:
FROM python:3
ENV PYTHONUNBUFFERED 1

ENV LC_ALL C.UTF-8
ENV LANG C.UTF-8

# -- Install Application into container:
RUN set -ex && mkdir /app

WORKDIR /app
ADD requirements.txt /app/

RUN pip install -r requirements.txt

# -- Adding dependencies:
ADD . /app/
</code>```

But it is not loading static files.

答:
Nginx Dockerfile:

```<code>FROM nginx:stable-alpine

COPY default.conf /etc/nginx
COPY default.conf /etc/nginx/conf.d

EXPOSE 80
</code>```

default.conf referred to in the above Dockerfile:

```<code>server {

    listen 80 default_server;
    server_name _;

    location / {
        proxy_pass http://web:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /app/static/;
    }

    location /media/ {
        alias /app/static/;
    }

}

</code>```

Note: The default.conf and Dockerfile mentioned above is under the same folder, build that image and use it as the Nginx image in the below docker-compose file.

The docker-compose file would look like this:

```<code>version: '3.8'

services:
  web:
    image: <django-image-name>
    command: gunicorn --bind 0.0.0.0:8000 licensing_platform.wsgi --workers=4
    volumes:
      - static_volume:/app/static
      - media_volume:/app/media
    expose:
      - "8000"
    networks:
      - django-network

  nginx:
    image: <nginx-image-name>
    restart: always
    volumes:
      - static_volume:/app/static
      - media_volume:/app/media
    ports:
      - "80:80"
    depends_on:
      - web
    networks:
      - django-network

networks:
  django-network:
    name: django-network

volumes:
  media_volume:
  static_volume:
</code>```

The app/ path referenced depends on the working directory:
The django application Dockerfile would start with:

```<code>FROM ubuntu:20.04
ADD . /app
WORKDIR /app
EXPOSE 8000
</code>```

Code reference: https://github.com/addu390/licensing-as-a-platform

The code reference mentioned above is an open-source project I'm working on with no commercial benefits.

Body:
I am setting us a Django 2.0 application with Docker, nginx and gunicorn.

It's running the server but static files are not working.

Here is the settings.py content

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_my_project')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root')

While developing, I put my static files inside static_my_project, which on running collectstatic copies to static_cdn/static_root

The directory structure is like

app
 |- myapp
    |- settings.py
 |- static_my_project
 |- static_cdn
    |- static_root
 |- config
    |- nginx
       |- nginx.conf
 |- manage.py
 |- Docker
 |- docker-compose.yml

on running

docker-compose up --build

on running collectstatic, it gives path where static files will be copied

koober-dev | --: Running collectstatic

  koober-dev |

  koober-dev | You have requested to collect static files at the destination

  myapp-dev | location as specified in your settings:

  myapp-dev |

  myapp-dev |     /app/static_cdn/static_root

  myapp-dev |

  myapp-dev | This will overwrite existing files!

  myapp-dev | Are you sure you want to do this?

  myapp-dev |

  myapp-dev | Type 'yes' to continue, or 'no' to cancel:

  myapp-dev | 0 static files copied to '/app/static_cdn/static_root', 210 unmodified.

the config/nginx/nginx.conf file contains following settings

upstream web {
    ip_hash;
    server web:9010;
}

server {
    location /static {
        autoindex on;
        alias /static/;
    }

    location / {
        proxy_pass http://web;
    }
    listen 10080;
    server_name localhost;
}

docker-compose.yml

version: '3'

services:
  nginx:
    image: nginx:latest
    container_name: "koober-nginx"
    ports:
      - "10080:80"
      - "10443:43"
    volumes:
      - .:/app
      - ./config/nginx:/etc/nginx/conf.d
      - ./static_cdn/static_root/:/static
    depends_on:
      - web
  web:
    build: .
    container_name: "koober-dev"
    command: ./start.sh
    volumes:
      - .:/app
      - ./static_cdn/static_root/:/app/static_cdn/static_root
    ports:
      - "9010:9010"
    depends_on:
      - db
  db:
    image: postgres
    container_name: "koober-postgres-db"

Dockerfile

FROM ubuntu:18.04

# -- Install Pipenv:
FROM python:3
ENV PYTHONUNBUFFERED 1

ENV LC_ALL C.UTF-8
ENV LANG C.UTF-8

# -- Install Application into container:
RUN set -ex && mkdir /app

WORKDIR /app
ADD requirements.txt /app/

RUN pip install -r requirements.txt

# -- Adding dependencies:
ADD . /app/

But it is not loading static files.

Body:
Nginx Dockerfile:

FROM nginx:stable-alpine

COPY default.conf /etc/nginx
COPY default.conf /etc/nginx/conf.d

EXPOSE 80

default.conf referred to in the above Dockerfile:

server {

    listen 80 default_server;
    server_name _;

    location / {
        proxy_pass http://web:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /app/static/;
    }

    location /media/ {
        alias /app/static/;
    }

}

Note: The default.conf and Dockerfile mentioned above is under the same folder, build that image and use it as the Nginx image in the below docker-compose file.

The docker-compose file would look like this:

version: '3.8'

services:
  web:
    image: <django-image-name>
    command: gunicorn --bind 0.0.0.0:8000 licensing_platform.wsgi --workers=4
    volumes:
      - static_volume:/app/static
      - media_volume:/app/media
    expose:
      - "8000"
    networks:
      - django-network

  nginx:
    image: <nginx-image-name>
    restart: always
    volumes:
      - static_volume:/app/static
      - media_volume:/app/media
    ports:
      - "80:80"
    depends_on:
      - web
    networks:
      - django-network

networks:
  django-network:
    name: django-network

volumes:
  media_volume:
  static_volume:

The app/ path referenced depends on the working directory:
The django application Dockerfile would start with:

FROM ubuntu:20.04
ADD . /app
WORKDIR /app
EXPOSE 8000

Code reference: https://github.com/addu390/licensing-as-a-platform

The code reference mentioned above is an open-source project I'm working on with no commercial benefits.


问:
VBA Macro doesn't save Worksheet with date AND time
I have the made the code below that basically saves one sheet of the workbook. First it creates the current year, then the current month, then gives the file todays date and a string that is in Range A1. If the year exists but the month folder doesnt, it then creates only the month folder and saves the sheet. If the file already exists, the sub exits. The sheet works as a daily production review and I want it to work forever (i mean to always save it at the correct folder. The codes works PERFECTLY but now I have a specific problem. There are occasions of 2 reviews during the day, with the same name in the range A1 but are actually 2 different productions so I thought of adding the time also in the filename.

```<code>Sub savesheet()

Application.ScreenUpdating = False
Dim fixedSavePath, yrName, mthName, sheetFileName, mstryr, yearpath, mstrmth, allto As String

fixedSavePath = "C:\Users\jerka\Desktop\Arxeia kapsoulas\"
yrName = Format(Date, "yyyy")
mthName = Format(Date, "mmmm")
sheetFileName = Format(Date, "dd.mm.yyyy") & " " & Worksheets("Sheet1").Range("A1").Value

mstryr = fixedSavePath & yrName
yearpath = fixedSavePath & yrName & "\"
mstrmth = yearpath & mthName
allto = yearpath & mthName & "\"

fol = Dir(yearpath, vbDirectory)
fal = Dir(allto, vbDirectory)

On Error Resume Next
If fol = "" And fall = "" Then
MkDir mstryr
MkDir mstrmth
ElseIf fol <> "" And fall = "" Then
MkDir mstrmth
End If

strFileName = mstrmth & "\" & sheetFileName & ".xlsx"
strFileExists = Dir(strFileName)

If strFileExists <> "" Then
MsgBox "The selected file exists"
Exit Sub
End If

Worksheets("Sheet1").Copy
With ActiveWorkbook
.SaveAs Filename:=mstrmth & "\" & sheetFileName & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
.Close
End With

Application.ScreenUpdating = True

End Sub
</code>```

For some reason that I can't understand, If i write the filename as
VBA Code:

sheetFileName = Format(Date, "dd.mm.yyyy hh:mm") & " " & Worksheets("Sheet1").Range("A1").Value

or in any other way that contains the time, either the "file exists" triggers (even if I delete everything), either it opens a new workbook with the name Book1.xlsx and doesn't save it. Any help will be greatly appreciated cause I really can't wrap my head around this problem

P.S. I have tried the DateTime.Now, putting only the time etc, NOTHING works. Also Format(Datetest, "Long Date") works but "Long Time" doesn't

答:
One thing that stands out immediately is that file names cannot contain a colon.
You could try the 24-hour time format HHmm.</p>

Body:
I have the made the code below that basically saves one sheet of the workbook. First it creates the current year, then the current month, then gives the file todays date and a string that is in Range A1. If the year exists but the month folder doesnt, it then creates only the month folder and saves the sheet. If the file already exists, the sub exits. The sheet works as a daily production review and I want it to work forever (i mean to always save it at the correct folder. The codes works PERFECTLY but now I have a specific problem. There are occasions of 2 reviews during the day, with the same name in the range A1 but are actually 2 different productions so I thought of adding the time also in the filename.

Sub savesheet()

Application.ScreenUpdating = False
Dim fixedSavePath, yrName, mthName, sheetFileName, mstryr, yearpath, mstrmth, allto As String

fixedSavePath = "C:\Users\jerka\Desktop\Arxeia kapsoulas\"
yrName = Format(Date, "yyyy")
mthName = Format(Date, "mmmm")
sheetFileName = Format(Date, "dd.mm.yyyy") & " " & Worksheets("Sheet1").Range("A1").Value

mstryr = fixedSavePath & yrName
yearpath = fixedSavePath & yrName & "\"
mstrmth = yearpath & mthName
allto = yearpath & mthName & "\"

fol = Dir(yearpath, vbDirectory)
fal = Dir(allto, vbDirectory)

On Error Resume Next
If fol = "" And fall = "" Then
MkDir mstryr
MkDir mstrmth
ElseIf fol <> "" And fall = "" Then
MkDir mstrmth
End If

strFileName = mstrmth & "\" & sheetFileName & ".xlsx"
strFileExists = Dir(strFileName)

If strFileExists <> "" Then
MsgBox "The selected file exists"
Exit Sub
End If

Worksheets("Sheet1").Copy
With ActiveWorkbook
.SaveAs Filename:=mstrmth & "\" & sheetFileName & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
.Close
End With

Application.ScreenUpdating = True

End Sub

For some reason that I can't understand, If i write the filename as
VBA Code:

sheetFileName = Format(Date, "dd.mm.yyyy hh:mm") & " " & Worksheets("Sheet1").Range("A1").Value

or in any other way that contains the time, either the "file exists" triggers (even if I delete everything), either it opens a new workbook with the name Book1.xlsx and doesn't save it. Any help will be greatly appreciated cause I really can't wrap my head around this problem

P.S. I have tried the DateTime.Now, putting only the time etc, NOTHING works. Also Format(Datetest, "Long Date") works but "Long Time" doesn't


问:
How to get and set Azure app service configuration settings from C# code?
I have an Azure app service. And I have C# application. I want to get and set configuration settings (appsettings) for my Azure app service from my C# application.

I can do it from PowerShell using az webapp config appsettings list and az webapp config appsettings set. I want to achieve the same from C#.

My current solution is to launch PowerShell from C# (using new Process()) and use az webapp. That is ugly, errors are hard to catch, and it is awkward to get to run on both Windows and Linux.

I have looked at the NuGet package Microsoft.Azure.Management.Fluent. It has a method IWebAppBase.GetSettings which lets me read the settings. But I can find no way to change the settings. The NuGet package says that it is being phased out, but I cannot find a replacement package for managing app services.

Is there a nice NuGet I should use?

答:
You will have to use the SDK to do this.

libs:

Microsoft.Azure.Management.AppService.Fluent

Microsoft.Azure.Common

Microsoft.Azure.Management.Fluent

you will have to do something like this

```<code>    var credentials = SdkContext.AzureCredentialsFactory
    .FromServicePrincipal("",
        "",
        "",
        AzureEnvironment.AzureGlobalCloud);

    RestClient restClient = RestClient
           .Configure()
           .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
           .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
           .WithCredentials(credentials)
           .Build();

    var _websiteClient = new WebSiteManagementClient(restClient);

     // get
    var configs = await _websiteClient.WebApps.ListApplicationSettingsAsync("RG", "WEBAPP");

    // add config
    configs.Properties.Add("newkey", "newValue");

    // update
    var result = await _websiteClient.WebApps.UpdateApplicationSettingsAsync("RG", "WEBAPP", configs);
</code>```

Body:
You will have to use the SDK to do this.

libs:

Microsoft.Azure.Management.AppService.Fluent

Microsoft.Azure.Common

Microsoft.Azure.Management.Fluent

you will have to do something like this

    var credentials = SdkContext.AzureCredentialsFactory
    .FromServicePrincipal("",
        "",
        "",
        AzureEnvironment.AzureGlobalCloud);

    RestClient restClient = RestClient
           .Configure()
           .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
           .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
           .WithCredentials(credentials)
           .Build();

    var _websiteClient = new WebSiteManagementClient(restClient);

     // get
    var configs = await _websiteClient.WebApps.ListApplicationSettingsAsync("RG", "WEBAPP");

    // add config
    configs.Properties.Add("newkey", "newValue");

    // update
    var result = await _websiteClient.WebApps.UpdateApplicationSettingsAsync("RG", "WEBAPP", configs);


问:
Retrieve only a particular number of child records
If I write

```<code>db.Topics.Include("ChildTopics")
</code>```

then it gives all the child comments for that. But what I want is only the top two child topics ordered by "childtopic created date".

答:
This is not possible to include only the first two via Include method.
In your case, you can do this :</p>

```<code>var firstTwo = from topic in datacontext.Topics
    select new { Topic= topic, ChildTopic= topic.ChildTopics.OrderBy(c => c.childtopic_created_date).Take(2) };
</code>```

Body:
If I write

db.Topics.Include("ChildTopics")

then it gives all the child comments for that. But what I want is only the top two child topics ordered by "childtopic created date".

Body:
This is not possible to include only the first two via Include method.
In your case, you can do this :

var firstTwo = from topic in datacontext.Topics
    select new { Topic= topic, ChildTopic= topic.ChildTopics.OrderBy(c => c.childtopic_created_date).Take(2) };


问:
Why is my Python code skipping over the trigging of a nested function?
This code does run but it's not triggering the inner function playerAction() when the
main_game_loop() is triggered.

-I've used the IntelliJ debugger and it shows the condition, while myPlayer.game_over is False:, as being False. (pic added)
img link showing debugger stating the while condition as False

-I've also tried to run it in VS Code and got the same result of the inner function being skipped over.

Question: If the while condition is met, why is the Python code jumping past the inner function call?

```<code>import cmd
import textwrap
import sys
import os
import time
import random

screen_width = 100

########################### PLAYER SET UP ############################
class player:
    def __init__(self):
        self.name = ''
        self.job = ''
        self.hp = 0
        self.mp = 0
        self.status_effects = []
        self.location = 'b2'
        self.game_over = 'False'

myPlayer = player()  # set up the function call in a variable

############################ TITLE SCREEN ############################

def title_screen_selections():
    option = input("> ")
    if option.lower() == "play":
        setup_game()  # placeholder until written
    elif option.lower() == "help":
        help_menu()
    elif option.lower() == "quit":
        sys.exit()
    while option.lower() not in ['play', 'help', 'quit']:
        print("please enter a valid command.")
        option = input("> ")
        if option.lower() == "play":
            setup_game()
        elif option.lower() == "help":
            help_menu()
        elif option.lower() == "quit":
            sys.exit()

def title_screen():
    os.system("cls")
    print("############################")
    print("# Welcome to the Text RPG! #")
    print("############################")
    print("#         - Play -         #")
    print("#         - Help -         #")
    print("#         - Quit -         #")
    print("# Copyright 2022 myoung.me #")
    title_screen_selections()

def help_menu():
    print("############################")
    print("# Welcome to the Help Menu! #")
    print("############################")
    print("# Use up, down, left, right to move #")
    print("# Type your commands to do them #")
    print("# Use 'look' to inspect something #")
    print("# Good luck and have fun! #")
    title_screen_selections()

############################ MAP ############################
''' VISUALIZE THE MAP
a1 a2... # PLAYER STARTS AT b2
-------------
|  |  |  |  |  a4
-------------
|  |  |  |  |  b4 ...
-------------
|  |  |  |  |
-------------
|  |  |  |  |
-------------
'''
ZONENAME = ''
DESCRIPTION = 'description'
EXAMINATION = 'examine'
SOLVED = False
UP = 'up', 'north'
DOWN = 'down', 'south'
LEFT = 'left', 'west'
RIGHT = 'right', 'east'

solved_places = {'a1': False, 'a2': False, 'a3': False, 'a4': False,
                 'b1': False, 'b2': False, 'b3': False, 'b4': False,
                 'c1': False, 'c2': False, 'c3': False, 'c4': False,
                 'd1': False, 'd2': False, 'd3': False, 'd4': False,
                 }

zonemap = {
    'a1': {
        ZONENAME: 'Town Market',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b1',
        LEFT: '',
        RIGHT: 'a2',
    },
    'a2': {
        ZONENAME: 'Town Entrance',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b2',
        LEFT: 'a1',
        RIGHT: 'a3',
    },
    'a3': {
        ZONENAME: 'Town Square',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b3',
        LEFT: 'a2',
        RIGHT: 'a4',
    },
    'a4': {
        ZONENAME: 'Town Hall',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b4',
        LEFT: 'a3',
        RIGHT: '',
    },
    'b1': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a1',
        DOWN: 'c1',
        LEFT: '',
        RIGHT: 'b2',
    },
    'b2': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a2',
        DOWN: 'c2',
        LEFT: 'b1',
        RIGHT: 'b3',
    },
    'b3': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a3',
        DOWN: 'c3',
        LEFT: 'b2',
        RIGHT: 'b4',
    },
    'b4': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a4',
        DOWN: 'c4',
        LEFT: 'b3',
        RIGHT: '',
    },
    'c1': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b1',
        DOWN: 'd1',
        LEFT: '',
        RIGHT: 'c2',
    },
    'c2': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b2',
        DOWN: 'd2',
        LEFT: 'c1',
        RIGHT: 'c3',
    },
    'c3': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b3',
        DOWN: 'd3',
        LEFT: 'b2',
        RIGHT: 'c4',
    },
    'c4': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b4',
        DOWN: 'd4',
        LEFT: 'c3',
        RIGHT: '',
    },
    'd1': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c1',
        DOWN: '',
        LEFT: '',
        RIGHT: 'd2',
    },
    'd2': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c2',
        DOWN: '',
        LEFT: 'd1',
        RIGHT: 'd3',
    },
    'd3': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c3',
        DOWN: '',
        LEFT: 'd2',
        RIGHT: 'd4',
    },
    'd4': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c4',
        DOWN: '',
        LEFT: 'd3',
        RIGHT: '',
    },
}

############################ GAME INTERACTIVITY ############################
def print_location():  # creating a fx to display location of the player
    print('\n' + ('#' * (4 + len(myPlayer.location))))  # creating a buffer of hashtags
    print('#' + myPlayer.location.upper() + '#')
    print('# ' + zonemap[myPlayer.position][DESCRIPTION] + ' #')
    print('\n' + ('#' * (4 + len(myPlayer.location))))

def playerAction():
    print('\n' + '==============================')
    print('what would you like to do?')
    action = input("> ")
    acceptable_actions = ['move', 'go', 'travel', 'walk', 'quit', 'examine', 'inspect', 'interact', 'look']
    while action.lower() not in acceptable_actions:
        print('unknown action, try again. \n')
        action = input("> ")
        if action.lower() == 'quit':
            sys.exit()
        elif action.lower() in ['move', 'go', 'travel', 'walk']:
            player_move(action.lower())
        elif action.lower() in ['examine', 'inspect', 'interact', 'look']:
            player_examine(action.lower())

def player_move(myaction):
    ask = 'where would you like to move to? \n'
    dest = input(ask)
    if dest in ['up', 'north']:
        destination = zonemap[myPlayer.location][UP]
        movement_handler(destination)
    elif dest in ['left', 'west']:
        destination = zonemap[myPlayer.location][LEFT]
        movement_handler(destination)
    elif dest in ['right', 'east']:
        destination = zonemap[myPlayer.location][RIGHT]
        movement_handler(destination)
    elif dest in ['down', 'south']:
        destination = zonemap[myPlayer.location][DOWN]
        movement_handler(destination)

def movement_handler(destination):
    print("\n" + "you have moved to the " + destination + ".")
    myPlayer.location = destination
    print_location()

def player_examine(action):
    if zonemap[myPlayer.location][SOLVED]:
        print("you have already exhausted this zone.")
    else:
        print("you can trigger a puzzle here")

############################ GAME FUNCTIONALITY ############################

def main_game_loop():
    while myPlayer.game_over is False:
        playerAction()

def setup_game(self=None):
    os.system('cls')

    # can duplicate these 'question' codeBlocks
    question1 = "Hello, what's your name? \n"
    for character in question1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    player_name = input("> ")
    myPlayer.name = player_name

    question2 = "Hello, " + player_name + ". What role do you want to play? \n"  # getting player info from user for class/job
    question2added = "You can play as a warrior, priest, or mage)\n"
    for character in question2:  # display each of the question characters at a slow pace
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    for character in question2added:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.01)
    player_job = input("> ")
    valid_jobs = ['warrior', 'mage', 'priest']
    if player_job.lower() in valid_jobs:
        myPlayer.job = player_job
        print("You are now a " + player_job + "!\n")
    while player_job.lower() not in valid_jobs:
        player_job = input("> ")
        if player_job.lower() in valid_jobs:
            myPlayer.job = player_job
            print("You are now a " + player_job + "!\n")

    if myPlayer.job is 'warrior':
        self.hp = 120
        self.mp = 20
    elif myPlayer.job is 'mage':
        self.hp = 40
        self.mp = 120
    elif myPlayer.job is 'priest':
        self.hp = 60
        self.mp = 60

    statement1 = "Welcome, " + player_name + " the " + player_job + "!\n"  # statement made with player info from user for name and role
    for character in statement1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)

    speech1 = "welcome to this fantasy world!\n"
    speech2 = "I hope it greets you well!\n"
    speech3 = "Just make sure you don't get too lost...\n"
    speech4 = "Hehehehe\n"
    for character in speech1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.03)
    for character in speech2:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.03)
    for character in speech3:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    for character in speech4:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)

    os.system('cls')
    print("######################")
    print("#  Let's start now!  #")
    print("######################")
    main_game_loop()

####################### KICK OFF THE METHOD SEQUENCE #####################

title_screen()
</code>```

答:
Thank you for the responses...and thank you Divakar Patil.

I had made the value of the  game_over property in the Player class into a string of 'False' when it should have been a boolean of False.

I will also further research giving a 'minimal reproducible answer' here.

Thank you for the point in the right direction.

Body:
This code does run but it's not triggering the inner function playerAction() when the
main_game_loop() is triggered.

-I've used the IntelliJ debugger and it shows the condition, while myPlayer.game_over is False:, as being False. (pic added)
img link showing debugger stating the while condition as False

-I've also tried to run it in VS Code and got the same result of the inner function being skipped over.

Question: If the while condition is met, why is the Python code jumping past the inner function call?

import cmd
import textwrap
import sys
import os
import time
import random

screen_width = 100

########################### PLAYER SET UP ############################
class player:
    def __init__(self):
        self.name = ''
        self.job = ''
        self.hp = 0
        self.mp = 0
        self.status_effects = []
        self.location = 'b2'
        self.game_over = 'False'

myPlayer = player()  # set up the function call in a variable

############################ TITLE SCREEN ############################

def title_screen_selections():
    option = input("> ")
    if option.lower() == "play":
        setup_game()  # placeholder until written
    elif option.lower() == "help":
        help_menu()
    elif option.lower() == "quit":
        sys.exit()
    while option.lower() not in ['play', 'help', 'quit']:
        print("please enter a valid command.")
        option = input("> ")
        if option.lower() == "play":
            setup_game()
        elif option.lower() == "help":
            help_menu()
        elif option.lower() == "quit":
            sys.exit()

def title_screen():
    os.system("cls")
    print("############################")
    print("# Welcome to the Text RPG! #")
    print("############################")
    print("#         - Play -         #")
    print("#         - Help -         #")
    print("#         - Quit -         #")
    print("# Copyright 2022 myoung.me #")
    title_screen_selections()

def help_menu():
    print("############################")
    print("# Welcome to the Help Menu! #")
    print("############################")
    print("# Use up, down, left, right to move #")
    print("# Type your commands to do them #")
    print("# Use 'look' to inspect something #")
    print("# Good luck and have fun! #")
    title_screen_selections()

############################ MAP ############################
''' VISUALIZE THE MAP
a1 a2... # PLAYER STARTS AT b2
-------------
|  |  |  |  |  a4
-------------
|  |  |  |  |  b4 ...
-------------
|  |  |  |  |
-------------
|  |  |  |  |
-------------
'''
ZONENAME = ''
DESCRIPTION = 'description'
EXAMINATION = 'examine'
SOLVED = False
UP = 'up', 'north'
DOWN = 'down', 'south'
LEFT = 'left', 'west'
RIGHT = 'right', 'east'

solved_places = {'a1': False, 'a2': False, 'a3': False, 'a4': False,
                 'b1': False, 'b2': False, 'b3': False, 'b4': False,
                 'c1': False, 'c2': False, 'c3': False, 'c4': False,
                 'd1': False, 'd2': False, 'd3': False, 'd4': False,
                 }

zonemap = {
    'a1': {
        ZONENAME: 'Town Market',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b1',
        LEFT: '',
        RIGHT: 'a2',
    },
    'a2': {
        ZONENAME: 'Town Entrance',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b2',
        LEFT: 'a1',
        RIGHT: 'a3',
    },
    'a3': {
        ZONENAME: 'Town Square',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b3',
        LEFT: 'a2',
        RIGHT: 'a4',
    },
    'a4': {
        ZONENAME: 'Town Hall',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: '',
        DOWN: 'b4',
        LEFT: 'a3',
        RIGHT: '',
    },
    'b1': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a1',
        DOWN: 'c1',
        LEFT: '',
        RIGHT: 'b2',
    },
    'b2': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a2',
        DOWN: 'c2',
        LEFT: 'b1',
        RIGHT: 'b3',
    },
    'b3': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a3',
        DOWN: 'c3',
        LEFT: 'b2',
        RIGHT: 'b4',
    },
    'b4': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'a4',
        DOWN: 'c4',
        LEFT: 'b3',
        RIGHT: '',
    },
    'c1': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b1',
        DOWN: 'd1',
        LEFT: '',
        RIGHT: 'c2',
    },
    'c2': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b2',
        DOWN: 'd2',
        LEFT: 'c1',
        RIGHT: 'c3',
    },
    'c3': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b3',
        DOWN: 'd3',
        LEFT: 'b2',
        RIGHT: 'c4',
    },
    'c4': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'b4',
        DOWN: 'd4',
        LEFT: 'c3',
        RIGHT: '',
    },
    'd1': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c1',
        DOWN: '',
        LEFT: '',
        RIGHT: 'd2',
    },
    'd2': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c2',
        DOWN: '',
        LEFT: 'd1',
        RIGHT: 'd3',
    },
    'd3': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c3',
        DOWN: '',
        LEFT: 'd2',
        RIGHT: 'd4',
    },
    'd4': {
        ZONENAME: 'Home',
        DESCRIPTION: 'description',
        EXAMINATION: 'examine',
        SOLVED: False,
        UP: 'c4',
        DOWN: '',
        LEFT: 'd3',
        RIGHT: '',
    },
}

############################ GAME INTERACTIVITY ############################
def print_location():  # creating a fx to display location of the player
    print('\n' + ('#' * (4 + len(myPlayer.location))))  # creating a buffer of hashtags
    print('#' + myPlayer.location.upper() + '#')
    print('# ' + zonemap[myPlayer.position][DESCRIPTION] + ' #')
    print('\n' + ('#' * (4 + len(myPlayer.location))))

def playerAction():
    print('\n' + '==============================')
    print('what would you like to do?')
    action = input("> ")
    acceptable_actions = ['move', 'go', 'travel', 'walk', 'quit', 'examine', 'inspect', 'interact', 'look']
    while action.lower() not in acceptable_actions:
        print('unknown action, try again. \n')
        action = input("> ")
        if action.lower() == 'quit':
            sys.exit()
        elif action.lower() in ['move', 'go', 'travel', 'walk']:
            player_move(action.lower())
        elif action.lower() in ['examine', 'inspect', 'interact', 'look']:
            player_examine(action.lower())

def player_move(myaction):
    ask = 'where would you like to move to? \n'
    dest = input(ask)
    if dest in ['up', 'north']:
        destination = zonemap[myPlayer.location][UP]
        movement_handler(destination)
    elif dest in ['left', 'west']:
        destination = zonemap[myPlayer.location][LEFT]
        movement_handler(destination)
    elif dest in ['right', 'east']:
        destination = zonemap[myPlayer.location][RIGHT]
        movement_handler(destination)
    elif dest in ['down', 'south']:
        destination = zonemap[myPlayer.location][DOWN]
        movement_handler(destination)

def movement_handler(destination):
    print("\n" + "you have moved to the " + destination + ".")
    myPlayer.location = destination
    print_location()

def player_examine(action):
    if zonemap[myPlayer.location][SOLVED]:
        print("you have already exhausted this zone.")
    else:
        print("you can trigger a puzzle here")

############################ GAME FUNCTIONALITY ############################

def main_game_loop():
    while myPlayer.game_over is False:
        playerAction()

def setup_game(self=None):
    os.system('cls')

    # can duplicate these 'question' codeBlocks
    question1 = "Hello, what's your name? \n"
    for character in question1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    player_name = input("> ")
    myPlayer.name = player_name

    question2 = "Hello, " + player_name + ". What role do you want to play? \n"  # getting player info from user for class/job
    question2added = "You can play as a warrior, priest, or mage)\n"
    for character in question2:  # display each of the question characters at a slow pace
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    for character in question2added:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.01)
    player_job = input("> ")
    valid_jobs = ['warrior', 'mage', 'priest']
    if player_job.lower() in valid_jobs:
        myPlayer.job = player_job
        print("You are now a " + player_job + "!\n")
    while player_job.lower() not in valid_jobs:
        player_job = input("> ")
        if player_job.lower() in valid_jobs:
            myPlayer.job = player_job
            print("You are now a " + player_job + "!\n")

    if myPlayer.job is 'warrior':
        self.hp = 120
        self.mp = 20
    elif myPlayer.job is 'mage':
        self.hp = 40
        self.mp = 120
    elif myPlayer.job is 'priest':
        self.hp = 60
        self.mp = 60

    statement1 = "Welcome, " + player_name + " the " + player_job + "!\n"  # statement made with player info from user for name and role
    for character in statement1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)

    speech1 = "welcome to this fantasy world!\n"
    speech2 = "I hope it greets you well!\n"
    speech3 = "Just make sure you don't get too lost...\n"
    speech4 = "Hehehehe\n"
    for character in speech1:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.03)
    for character in speech2:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.03)
    for character in speech3:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)
    for character in speech4:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.05)

    os.system('cls')
    print("######################")
    print("#  Let's start now!  #")
    print("######################")
    main_game_loop()

####################### KICK OFF THE METHOD SEQUENCE #####################

title_screen()


问:
Which version of FFMPEG supports HLS v4
Wanted to know which version of FFMPEG library supports Http Live Streaming (HLS) V4.

Specification for this protocol is at:
https://datatracker.ietf.org/doc/html/draft-pantos-http-live-streaming-08

Please clarify.

答:
The latest version (v4.3.3) of FFMpeg supports HLS version 7, check out hls_segment_type option in the documentation.

hls_segment_type flags

Possible values:

‘mpegts’

Output segment files in MPEG-2 Transport Stream format. This is compatible with all HLS versions.

‘fmp4’

Output segment files in fragmented MP4 format, similar to MPEG-DASH. fmp4 files may be used in HLS version 7 and above.

You can also try generating HLS files then read EXT-X-VERSION in the generated plyalist (.m3u8) , which should be 7, means the protocol version.

Title: Which version of FFMPEG supports HLS v4


问:
Remove string from one column if present in string of another column pandas
I feel like I'm close but I am looking for something like this where the new column writes the company name without the city in it:

```<code>                           company  postal_code  name state         city  \
2000-01-01          abc gresham co        97080  john    mi      gresham
2000-01-01             startup llc        97080  jeff    hi     portland
2001-01-01  beaverton business biz        99999   sam    ca    beaverton
2002-01-01                 andy co        92222  joey    or  los angeles

                 new_col
2000-01-01        abc co
2000-01-01   startup llc
2001-01-01  business biz
2002-01-01       andy co
</code>```

This is what I have so far but it's throwing a TypeError: unhashable type: 'Series':

```<code>for idx in df1.index:
    if df1["city"].loc[idx] in df1['company'].loc[idx]:
        print("figure out how to print to new column the company name without the city included")
    else:
        print(df1['company'].loc[idx])
</code>```

Thanks!

答:
Here's a solution:

```<code>df = (
    df.reset_index()
    .assign(new_col=df.reset_index()
        .pipe(lambda x: x.assign(x=x['company'].str.split(' ')))
        .explode('x')
        .loc[lambda x: x['x'] != x['city'], 'x']
        .groupby(level=0)
        .agg(list)
        .str.join(' ')
    )
    .set_index('index')
)
</code>```

Output:

```<code>>>> df
                           company  postal_code  name state         city       new_col
index
2000-01-01          abc gresham co        97080  john    mi      gresham        abc co
2000-01-01             startup llc        97080  jeff    hi     portland   startup llc
2001-01-01  beaverton business biz        99999   sam    ca    beaverton  business biz
2002-01-01                 andy co        92222  joey    or  los angeles       andy co
</code>```

One-liner:

```<code>df = df.reset_index().assign(new_col=df.reset_index().pipe(lambda x: x.assign(x=x['company'].str.split(' '))).explode('x').loc[lambda x: x['x'] != x['city'], 'x'].groupby(level=0).agg(list).str.join(' ')).set_index('index')
</code>```

Body:
I feel like I'm close but I am looking for something like this where the new column writes the company name without the city in it:

                           company  postal_code  name state         city  \
2000-01-01          abc gresham co        97080  john    mi      gresham
2000-01-01             startup llc        97080  jeff    hi     portland
2001-01-01  beaverton business biz        99999   sam    ca    beaverton
2002-01-01                 andy co        92222  joey    or  los angeles

                 new_col
2000-01-01        abc co
2000-01-01   startup llc
2001-01-01  business biz
2002-01-01       andy co

This is what I have so far but it's throwing a TypeError: unhashable type: 'Series':

for idx in df1.index:
    if df1["city"].loc[idx] in df1['company'].loc[idx]:
        print("figure out how to print to new column the company name without the city included")
    else:
        print(df1['company'].loc[idx])

Thanks!

Body:
Here's a solution:

df = (
    df.reset_index()
    .assign(new_col=df.reset_index()
        .pipe(lambda x: x.assign(x=x['company'].str.split(' ')))
        .explode('x')
        .loc[lambda x: x['x'] != x['city'], 'x']
        .groupby(level=0)
        .agg(list)
        .str.join(' ')
    )
    .set_index('index')
)

Output:

>>> df
                           company  postal_code  name state         city       new_col
index
2000-01-01          abc gresham co        97080  john    mi      gresham        abc co
2000-01-01             startup llc        97080  jeff    hi     portland   startup llc
2001-01-01  beaverton business biz        99999   sam    ca    beaverton  business biz
2002-01-01                 andy co        92222  joey    or  los angeles       andy co

One-liner:

df = df.reset_index().assign(new_col=df.reset_index().pipe(lambda x: x.assign(x=x['company'].str.split(' '))).explode('x').loc[lambda x: x['x'] != x['city'], 'x'].groupby(level=0).agg(list).str.join(' ')).set_index('index')


问:
How might I introduce an expression in a struct definition in C?
I defined a struct:

```<code>struct Low {
     double high;
     double low;
     double fraction;   // = (Low.high - Low.low) / Low.high;
     double percentage; // = Low.fraction * 100;
} low2015, low2018, low2021, low2022;

</code>```

The comments hint at what I am getting at.
I would like to introduce an expression in the definition block of the struct Low so that I do not have to manually do the assignment of my_struct.fraction and my_struct.percentage

```<code>low2021.high = 64854;
low2021.low = 28805;
low2021.fraction = (low2021.high - low2021.low) / low2021.high;
low2021.percentage = low2021.fraction * 100;
</code>```

for all the four variables, i.e. low2015, low2018, low2021, low2022.
How might I accomplish this?

答:
The structure is small enough to be returned by value. Consider adding a function MakeLow().

```<code>struct Low {
     double high;
     double low;
     double fraction;
     double percentage;
};

static inline struct Low MakeLow(double high, double low) {
    return (struct Low) {
      .high = high,
      .low = low,
      .fraction = (high - low) / high,
      .percentage = (high - low) / high * 100,
    };
}
</code>```

Usage:

```<code>struct Low low2021 = MakeLow(64854, 28805);
</code>```

Body:
I defined a struct:

struct Low {
     double high;
     double low;
     double fraction;   // = (Low.high - Low.low) / Low.high;
     double percentage; // = Low.fraction * 100;
} low2015, low2018, low2021, low2022;

The comments hint at what I am getting at.
I would like to introduce an expression in the definition block of the struct Low so that I do not have to manually do the assignment of my_struct.fraction and my_struct.percentage

low2021.high = 64854;
low2021.low = 28805;
low2021.fraction = (low2021.high - low2021.low) / low2021.high;
low2021.percentage = low2021.fraction * 100;

for all the four variables, i.e. low2015, low2018, low2021, low2022.
How might I accomplish this?

Body:
The structure is small enough to be returned by value. Consider adding a function MakeLow().

struct Low {
     double high;
     double low;
     double fraction;
     double percentage;
};

static inline struct Low MakeLow(double high, double low) {
    return (struct Low) {
      .high = high,
      .low = low,
      .fraction = (high - low) / high,
      .percentage = (high - low) / high * 100,
    };
}

Usage:

struct Low low2021 = MakeLow(64854, 28805);


问:
Handling untracked attachments between backend and S3
I wanted to ask if you have any proven ways to deal with removing non-tracked attachments from S3?

Architecture diagram

I am using the S3 in project to hold files in a way that the Frontend fetching a pre-signed URL from Backend (1). Then Frontend adds an attachment to S3 (2), and then adds a URL to some resource (3).

The challenge is that there may be a difference between attachments on the server and URLs in the resource - eg Frontend getting the URL from Backend, sends file to S3, and does not add it to the Backend resource.

Does any of you have a way to deal with such a problem?

Fetching all the resources from database once in a day and comparing their attachments with those on the server sounds unsatisfactory. :/

答:
Distributed consistency is hard sometimes...  Orphaned records in non-transactional systems are hard and expensive to track down.

You have to decide what your tolerance for data-consistency-drift is.  If you need it to be absolute, then you need to put in place things like rollbacks when transactions fail (e.g. when the writ to the backend fails, rollback the write to S3 when the backend write fails).  Alternatively you can tag files in S3 with a tag that says something like "backend:pending" when creating the files and update it to "backend:done" so that you can easily identify s3 objects that need cleanup.

A more scalable option would be to use something like SQS to manage your workflow, ensuring that both changes are handled, and creating hospital queues for when things go sideways.


问:
How to return values only within a specific date range?
I have a program that scrapes through an API and gets the required values from the fields. There is a field called published_date one act json object. I want to publish only the values for the last 2 months from current date.

```<code>try:
    price = str(price).replace(',', '')
    price = Decimal(price)

    if date < end:

        if not math.isnan(price):
            report_item = PriceItem(
            source=SOURCE,
            source_url=crawled_url,
            original_index_id=original_index_id,
            index_specification=index_specification,
            published_date=date,
            price=price.quantize(Decimal('1.00'))
        )

            yield report_item
except DecimalException as ex:
    self.logger.error(f"Non decimal price of {price} "
                      f"found in {original_index_id}", exc_info=ex)

</code>```

The published date is extracted:

```<code>                     for report_date in REPORT_DATE_TYPES:
                        if report_date in result:
                            date = result[report_date].split(' ')[0]
                            date = datetime.strptime(date, '%m/%d/%Y')
</code>```
```<code>MAX_REPORT_MONTHS = 3
current_date = datetime.now()
current_date_str = current_date.strftime('%m/%d/%Y')
start = datetime.strptime(current_date_str, '%m/%d/%Y')

last_date = current_date - relativedelta(months=MAX_REPORT_MONTHS)
last_date_str = last_date.strftime('%m/%d/%Y')
end = datetime.strptime(last_date_str, '%m/%d/%Y')
</code>```

The above I say last date string and current date string.

Extract of the api:

答:
After having gathered the data into a dataframe you can convert the column containing the dates to datetime and then through comparison operators mantain just the desidered data.

For example, assuming this is your data:

```<code>data = {'date': ['02/02/2022 10:23:23', '09/23/2021 10:23:23', '02/01/2021 10:23:23', '12/15/2021 10:23:23'], 'random': [324, 231, 213, 123]}
df = pd.DataFrame(data)

# convert date column to datetime
df['date'] = pd.to_datetime(df['date'], format="%m/%d/%Y %H:%M:%S")

# select "threshold" date, two months before current one
current_date = datetime.now()
last_date = current_date - relativedelta(months=2)

# select data published after last_date
df[df['date'] > last_date]
</code>```

If we consider the date of today we will have this result.

Before:

```<code>                   date  random
0   02/02/2022 10:23:23     324
1   09/23/2021 10:23:23     231
2   02/01/2021 10:23:23     213
3   12/15/2021 10:23:23     123
</code>```

After:

```<code>                   date  random
0   2022-02-02 10:23:23     324
3   2021-12-15 10:23:23     123
</code>```

Body:
I have a program that scrapes through an API and gets the required values from the fields. There is a field called published_date one act json object. I want to publish only the values for the last 2 months from current date.

try:
    price = str(price).replace(',', '')
    price = Decimal(price)

    if date < end:

        if not math.isnan(price):
            report_item = PriceItem(
            source=SOURCE,
            source_url=crawled_url,
            original_index_id=original_index_id,
            index_specification=index_specification,
            published_date=date,
            price=price.quantize(Decimal('1.00'))
        )

            yield report_item
except DecimalException as ex:
    self.logger.error(f"Non decimal price of {price} "
                      f"found in {original_index_id}", exc_info=ex)

The published date is extracted:

                     for report_date in REPORT_DATE_TYPES:
                        if report_date in result:
                            date = result[report_date].split(' ')[0]
                            date = datetime.strptime(date, '%m/%d/%Y')

MAX_REPORT_MONTHS = 3
current_date = datetime.now()
current_date_str = current_date.strftime('%m/%d/%Y')
start = datetime.strptime(current_date_str, '%m/%d/%Y')

last_date = current_date - relativedelta(months=MAX_REPORT_MONTHS)
last_date_str = last_date.strftime('%m/%d/%Y')
end = datetime.strptime(last_date_str, '%m/%d/%Y')

The above I say last date string and current date string.

Extract of the api:

Body:
After having gathered the data into a dataframe you can convert the column containing the dates to datetime and then through comparison operators mantain just the desidered data.

For example, assuming this is your data:

data = {'date': ['02/02/2022 10:23:23', '09/23/2021 10:23:23', '02/01/2021 10:23:23', '12/15/2021 10:23:23'], 'random': [324, 231, 213, 123]}
df = pd.DataFrame(data)

# convert date column to datetime
df['date'] = pd.to_datetime(df['date'], format="%m/%d/%Y %H:%M:%S")

# select "threshold" date, two months before current one
current_date = datetime.now()
last_date = current_date - relativedelta(months=2)

# select data published after last_date
df[df['date'] > last_date]

If we consider the date of today we will have this result.

Before:

                   date  random
0   02/02/2022 10:23:23     324
1   09/23/2021 10:23:23     231
2   02/01/2021 10:23:23     213
3   12/15/2021 10:23:23     123

After:

                   date  random
0   2022-02-02 10:23:23     324
3   2021-12-15 10:23:23     123