问:
Why does a custom hook that uses another hooks value via useContext only shows its initial value?
I'm trying to reuse a bunch of custom hooks without re-invoking them and without maintaining an order through which I'll have to pass cascading parameters from one hook to the other.

A working example: https://codesandbox.io/s/laughing-firefly-mlhdw?file=/src/App.js:0-1158

Given the following code:

import React, { useContext, useEffect, useState } from "react";

const globalContext = React.createContext({
  user: null,
  pet: null
});

const usePet = () => {
  const [pet, setPet] = useState(null);

  useEffect(() => {
    setTimeout(() => {
      setPet("Dog");
    }, 3000);
  }, []);

  return pet;
};

const useUser = () => {
  const [user, setUser] = useState(null);
  // I want to proxy pet via the context so that I won't have to re-invoke its side-effects again
  const { pet } = useContext(globalContext);

  useEffect(() => {
    setTimeout(() => {
      setUser("john");
    }, 500);
  }, []);

  // This is only called once with the default value (null)
  useEffect(() => {
    console.log("Called from user!", { pet });
  }, [pet]);

  return user;
};

export const StateProvider = ({ children }) => {
  const user = useUser();
  const pet = usePet();

  useEffect(() => {
    console.log("StateProvider", { user, pet });
  }, [user, pet]);

  return (
    <globalContext.Provider value={{ user, pet }}>
      {children}
    </globalContext.Provider>
  );
};

export default function App() {
  const { user, pet } = useContext(globalContext);
  return (

Hello CodeSandbox

        {pet} {user}

  );
}

// imagine an index.js that's wrapping the App component like this:
const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <StateProvider>
      <App />
    </StateProvider>
  </StrictMode>,
  rootElement
);

```
<p>What I'm expecting to see in the console output is the following</p>
```
Called from user! {pet: null}
StateProvider {user: null, pet: null}
StateProvider {user: "john", pet: null}
StateProvider {user: "john", pet: "Dog"}
Called from user! {pet: "Dog"}
```
<p>But I'm not getting any updates inside <code>useUser</code> other than the initial state:</p>
```Called from user! {pet: null}
StateProvider {user: null, pet: null}
StateProvider {user: "john", pet: null}
StateProvider {user: "john", pet: "Dog"}

```
<p>My questions are:</p>
<ol>
<li>Is it possible to achieve that? if it is, what am I missing here?</li>
<li>If it's not possible, is there a more elegant way of passing data between custom hooks without re-invoking them (creating a new state context for each invocation) and without passing parameters from one another, which will force me to also maintain order between everything?</li>
</ol>
<p>Just to clarify - the UI is working as expected and all the values are rendered correctly inside the component.</p>
<p>Also, when passing the parameters directly to the hook, things are also in order</p>
<pre class="lang-js prettyprint-override"><code>const pet = usePet();
const user = useUser(pet); //this will work as it doesn't go through the context

</code>```

答:
To understand why your expectations are being violated, you must first understand how the context API works, including the useContext hook.

I'll include an especially relevant snippet here:

useContext

const value = useContext(MyContext);
```
<p>Accepts a context object (the value returned from <code>React.createContext</code>) and returns the current context value for that context. The current context value is determined by the <code>value</code> prop of the nearest <code><MyContext.Provider></code> above the calling component in the tree.</p>
</blockquote>
<p>When you use the context hook, your component which invokes the hook only receives updates when the context is updated. <strong>If you invoke the hook outside the root of a context provider tree, there will never be an update.</strong> This is what's happening in your example code.</p>
<p>An easy solution to this is to simply move the invocation of the hooks which depend on the context into a separate component below the context provider root. However, because of the way that your custom hooks are co-dependent (and neither actually update the context itself), this still leaves you in a stalemate of circular dependency.</p>
<p>To address this, you must give yourself the ability to update the context: by including a state setter that you can invoke with values to update the state.</p>
<p>In the following refactor of your code, I've made both of these changes:</p>
<blockquote>
<p>This is a very common pattern, and the most common iteration of it is using the <code>useReducer</code> hook in combination with the context API. You can find lots of examples by querying for <code>react state context</code>.</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.17.2/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

const {
  createContext,
  useContext,
  useEffect,
  useState,
} = React;

const initialContextState = {pet: null, user: null};

// You don't need to supply a default value here because you're no longer
// using it outside the provider root:
// const defaultContextValue = [initialContextState, () => {}];
// const appContext = createContext(defaultContextValue);

const appContext = createContext();

const usePet = () => {
  const [{pet}, setState] = useContext(appContext);
  useEffect(() => setTimeout(() => setState(state => ({...state, pet: 'Dog'})), 3000), [setState]);
  return pet;
};

const useUser = () => {
  const [{pet, user}, setState] = useContext(appContext);
  useEffect(() => setTimeout(() => setState(state => ({...state, user: 'John'})), 500), [setState]);
  useEffect(() => console.log('Called from user!', {pet}), [pet]);
  return user;
};

// This must be rendered within the context provider root
const ContextDependentHooksInvoker = () => {
  const pet = usePet();
  const user = useUser();

  useEffect(
    () => console.log('ContextDependentHooksInvoker', {pet, user}),
    [user, pet],
  );

  return null;
};

const StateProvider = ({children}) => {
  const stateWithSetter = useState(initialContextState);
  return (
    <appContext.Provider value={stateWithSetter}>
      <ContextDependentHooksInvoker />
      {children}
    </appContext.Provider>
  );
};

function App () {
  const [{pet, user}] = useContext(appContext);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{pet} {user}</h2>
    </div>
  );
}

function Example () {
  return (
    <React.StrictMode>
      <StateProvider>
        <App />
      </StateProvider>
    </React.StrictMode>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script></code>```

Body:
I'm trying to reuse a bunch of custom hooks without re-invoking them and without maintaining an order through which I'll have to pass cascading parameters from one hook to the other.

A working example: https://codesandbox.io/s/laughing-firefly-mlhdw?file=/src/App.js:0-1158

Given the following code:

import React, { useContext, useEffect, useState } from "react";

const globalContext = React.createContext({
  user: null,
  pet: null
});

const usePet = () => {
  const [pet, setPet] = useState(null);

  useEffect(() => {
    setTimeout(() => {
      setPet("Dog");
    }, 3000);
  }, []);

  return pet;
};

const useUser = () => {
  const [user, setUser] = useState(null);
  // I want to proxy pet via the context so that I won't have to re-invoke its side-effects again
  const { pet } = useContext(globalContext);

  useEffect(() => {
    setTimeout(() => {
      setUser("john");
    }, 500);
  }, []);

  // This is only called once with the default value (null)
  useEffect(() => {
    console.log("Called from user!", { pet });
  }, [pet]);

  return user;
};

export const StateProvider = ({ children }) => {
  const user = useUser();
  const pet = usePet();

  useEffect(() => {
    console.log("StateProvider", { user, pet });
  }, [user, pet]);

  return (
    <globalContext.Provider value={{ user, pet }}>
      {children}
    </globalContext.Provider>
  );
};

export default function App() {
  const { user, pet } = useContext(globalContext);
  return (

Hello CodeSandbox

        {pet} {user}

  );
}

// imagine an index.js that's wrapping the App component like this:
const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <StateProvider>
      <App />
    </StateProvider>
  </StrictMode>,
  rootElement
);

What I'm expecting to see in the console output is the following

Called from user! {pet: null}
StateProvider {user: null, pet: null}
StateProvider {user: "john", pet: null}
StateProvider {user: "john", pet: "Dog"}
Called from user! {pet: "Dog"}

But I'm not getting any updates inside useUser other than the initial state:

Called from user! {pet: null}
StateProvider {user: null, pet: null}
StateProvider {user: "john", pet: null}
StateProvider {user: "john", pet: "Dog"}

My questions are:

Is it possible to achieve that? if it is, what am I missing here?

If it's not possible, is there a more elegant way of passing data between custom hooks without re-invoking them (creating a new state context for each invocation) and without passing parameters from one another, which will force me to also maintain order between everything?

Just to clarify - the UI is working as expected and all the values are rendered correctly inside the component.

Also, when passing the parameters directly to the hook, things are also in order

const pet = usePet();
const user = useUser(pet); //this will work as it doesn't go through the context

Body:
To understand why your expectations are being violated, you must first understand how the context API works, including the useContext hook.

I'll include an especially relevant snippet here:

useContext

const value = useContext(MyContext);

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

When you use the context hook, your component which invokes the hook only receives updates when the context is updated. If you invoke the hook outside the root of a context provider tree, there will never be an update. This is what's happening in your example code.

An easy solution to this is to simply move the invocation of the hooks which depend on the context into a separate component below the context provider root. However, because of the way that your custom hooks are co-dependent (and neither actually update the context itself), this still leaves you in a stalemate of circular dependency.

To address this, you must give yourself the ability to update the context: by including a state setter that you can invoke with values to update the state.

In the following refactor of your code, I've made both of these changes:

This is a very common pattern, and the most common iteration of it is using the useReducer hook in combination with the context API. You can find lots of examples by querying for react state context.

<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.17.2/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

const {
  createContext,
  useContext,
  useEffect,
  useState,
} = React;

const initialContextState = {pet: null, user: null};

// You don't need to supply a default value here because you're no longer
// using it outside the provider root:
// const defaultContextValue = [initialContextState, () => {}];
// const appContext = createContext(defaultContextValue);

const appContext = createContext();

const usePet = () => {
  const [{pet}, setState] = useContext(appContext);
  useEffect(() => setTimeout(() => setState(state => ({...state, pet: 'Dog'})), 3000), [setState]);
  return pet;
};

const useUser = () => {
  const [{pet, user}, setState] = useContext(appContext);
  useEffect(() => setTimeout(() => setState(state => ({...state, user: 'John'})), 500), [setState]);
  useEffect(() => console.log('Called from user!', {pet}), [pet]);
  return user;
};

// This must be rendered within the context provider root
const ContextDependentHooksInvoker = () => {
  const pet = usePet();
  const user = useUser();

  useEffect(
    () => console.log('ContextDependentHooksInvoker', {pet, user}),
    [user, pet],
  );

  return null;
};

const StateProvider = ({children}) => {
  const stateWithSetter = useState(initialContextState);
  return (
    <appContext.Provider value={stateWithSetter}>
      <ContextDependentHooksInvoker />
      {children}
    </appContext.Provider>
  );
};

function App () {
  const [{pet, user}] = useContext(appContext);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{pet} {user}</h2>
    </div>
  );
}

function Example () {
  return (
    <React.StrictMode>
      <StateProvider>
        <App />
      </StateProvider>
    </React.StrictMode>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>


来源: stackexchange

问:
"this is null" when change in v-select [NuxtJs]
this is my first post! Hope you can help.
So I'm on some new project to migrate to nuxtJs.

I have some trouble with my v-select and v-model, here's the code:

_id.vue:

<template>
  <v-container fluid white>
    <v-card>
      <v-card-title class="headline">
          TEST:
      </v-card-title>
      <v-card-text>

info :

{{this.host.typeS}}

        <v-select
          v-model="this.host.typeS"
          :items="this.fields.typeS"
          item-value="value"
          item-text="value"
          dense outlined>
        </v-select>
      </v-card-text>
    </v-card>
  </v-container>
</template>
```
<p><strong>script</strong></p>
<pre class="lang-js prettyprint-override"><code>export default {
  name: 'EditPage',
  data() {
    return {
      tab: null,
      fields: [],
      host: {},
      tabHeaders: ["tab1", "tab2", "tab3", "tab4", "tab5", "tab6"]
    }
  },
  async fetch() {
    this.fields = await fetch("APIfields")
      .then(res => res.json());
    if (this.$nuxt._route.params.id) {
      this.host = await fetch("APIhost" + this.$nuxt._route.params.id).then(res => res.json());
    } else {
      this.host = {};
    }
  }
}
</code>```

responses

APIfields:

{"typeS": [{"value": "p","order": 100}, {"value":"v","order": 100}],
      "otherThings": [{"value":"se", "order": 100},{"value":"sa", "order": 100}]}
```
<p>APIhost/id:</p>
<pre class="lang-json prettyprint-override"><code>{"typeS": "p",
  "otherThings": "se"}
</code>```

When everything run, My select is initiated with the value "p" and when clicked I see all the values this field can have.
When I try selecting "v" in the v-select, I'm redirected to my error layout, and the console say "Type error: this is null".

Without the v-model, I don't have any error, but the v-select have no selected value.

The goal is to initialise a form based on an existing host, change the data inside the form and then submit it to the database. The form should also be used to create new hosts (empty form)

The same error appear in my textfields and checkboxes.

Do you have any idea or track I can follow?

答:
you don't need this when working on vue templates

<template>
  <v-container fluid white>
    <v-card>
      <v-card-title class="headline">
          TEST:
      </v-card-title>
      <v-card-text>

info :

{{host.typeS}}

        <v-select
          v-model="host.typeS"
          :items="fields.typeS"
          item-value="value"
          item-text="value"
          dense outlined>
        </v-select>
      </v-card-text>
    </v-card>
  </v-container>
</template>
```
<p>note that <code>:items</code> takes an array but you are using <code>fields.typeS</code> so it's better to set field in data as</p>
<pre class="lang-js prettyprint-override"><code>fields: {}
</code>```

since it's an object

ContentLicense: CC BY-SA 4.0

Body:
this is my first post! Hope you can help.
So I'm on some new project to migrate to nuxtJs.

I have some trouble with my v-select and v-model, here's the code:

_id.vue:

<template>
  <v-container fluid white>
    <v-card>
      <v-card-title class="headline">
          TEST:
      </v-card-title>
      <v-card-text>

info :

{{this.host.typeS}}

        <v-select
          v-model="this.host.typeS"
          :items="this.fields.typeS"
          item-value="value"
          item-text="value"
          dense outlined>
        </v-select>
      </v-card-text>
    </v-card>
  </v-container>
</template>

script

export default {
  name: 'EditPage',
  data() {
    return {
      tab: null,
      fields: [],
      host: {},
      tabHeaders: ["tab1", "tab2", "tab3", "tab4", "tab5", "tab6"]
    }
  },
  async fetch() {
    this.fields = await fetch("APIfields")
      .then(res => res.json());
    if (this.$nuxt._route.params.id) {
      this.host = await fetch("APIhost" + this.$nuxt._route.params.id).then(res => res.json());
    } else {
      this.host = {};
    }
  }
}

responses

APIfields:

{"typeS": [{"value": "p","order": 100}, {"value":"v","order": 100}],
      "otherThings": [{"value":"se", "order": 100},{"value":"sa", "order": 100}]}

APIhost/id:

{"typeS": "p",
  "otherThings": "se"}

When everything run, My select is initiated with the value "p" and when clicked I see all the values this field can have.
When I try selecting "v" in the v-select, I'm redirected to my error layout, and the console say "Type error: this is null".

Without the v-model, I don't have any error, but the v-select have no selected value.

The goal is to initialise a form based on an existing host, change the data inside the form and then submit it to the database. The form should also be used to create new hosts (empty form)

The same error appear in my textfields and checkboxes.

Do you have any idea or track I can follow?

Body:
you don't need this when working on vue templates

<template>
  <v-container fluid white>
    <v-card>
      <v-card-title class="headline">
          TEST:
      </v-card-title>
      <v-card-text>
        <p>info :</p>
        <p>{{host.typeS}}</p>
        <v-select
          v-model="host.typeS"
          :items="fields.typeS"
          item-value="value"
          item-text="value"
          dense outlined>
        </v-select>
      </v-card-text>
    </v-card>
  </v-container>
</template>

note that :items takes an array but you are using fields.typeS so it's better to set field in data as

fields: {}

since it's an object


问:
Elasticsearch complex aggregation on match results
I'm trying to get the top 5 teams based on win rate (matches won / all matches) having the match result documents in the index (see below).

The fields I need to get in the bucket:

apiId

name

winrate (won/total)

I guess this would require complex aggregation calculation witch is far beyond my current elasticsearch skills.

Elasticsearch version: 7.15.2

Could anyone help me with such elasticsearch query?

Thanks a lot in advance!

{
  "lastModified": "2022-01-14T09:33:48.232Z",
  "uuid": "01234567",
  "started": "2022-01-14T09:31:27.651Z",
  "editing": false,
  "approved": true,
  "statistics": {
    "teams": [
      {
        "name": "Team1",
        "score": 0,
        "winner": false,
        "apiId": "1"
      },
      {
        "name": "Team2",
        "score": 2,
        "winner": true,
        "apiId": "2"
      }
    ]
  }
}
```
<p>and the mapping:</p>
<pre class="lang-json prettyprint-override"><code>{
    "mappings": {
        "properties": {
            "_class": {
                "type": "keyword",
                "index": false,
                "doc_values": false
            },
            "approved": {
                "type": "boolean"
            },
            "editing": {
                "type": "boolean"
            },
            "ended": {
                "type": "date",
                "format": "date_optional_time||epoch_millis"
            },
            "game": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "lastModified": {
                "type": "date",
                "format": "date_optional_time||epoch_millis"
            },
            "started": {
                "type": "date",
                "format": "date_optional_time||epoch_millis"
            },
            "statistics": {
                "type": "nested",
                "include_in_parent": true,
                "properties": {
                    "_class": {
                        "type": "keyword",
                        "index": false,
                        "doc_values": false
                    },
                    "teams": {
                        "type": "nested",
                        "include_in_parent": true,
                        "properties": {
                            "_class": {
                                "type": "keyword",
                                "index": false,
                                "doc_values": false
                            },
                            "apiId": {
                                "type": "long"
                            },
                            "name": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "score": {
                                "type": "long"
                            },
                            "winner": {
                                "type": "boolean"
                            }
                        }
                    }
                }
            },
            "uuid": {
                "type": "keyword"
            }
        }
    }
}
</code>```

Edit:
Based on @ilvar answer, I constructed the query:

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "approved": true
                    }
                }
            ]
        }
    },
    "size": 0,
    "aggs": {
        "top_teams": {
            "nested": {
                "path": "statistics.teams"
            },
            "aggs": {
                "the_all": {
                    "multi_terms": {
                        "terms": [
                            {
                                "field": "statistics.teams.name.keyword"
                            },
                            {
                                "field": "statistics.teams.apiId"
                            }
                        ]
                    }
                },
                "the_won": {
                    "filter": {
                        "terms": {
                            "statistics.teams.winner": [
                                true
                            ]
                        }
                    },
                    "aggs": {
                        "teams": {
                            "multi_terms": {
                                "terms": [
                                    {
                                        "field": "statistics.teams.name.keyword"
                                    },
                                    {
                                        "field": "statistics.teams.apiId"
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
}
```
<p>Which gives me:</p>
<pre class="lang-json prettyprint-override"><code>{
    "took": 20,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 5,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "top_teams": {
            "doc_count": 10,
            "the_all": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                    {
                        "key": [
                            "Team1",
                            2
                        ],
                        "key_as_string": "Team1|2",
                        "doc_count": 2
                    },
                    {
                        "key": [
                            "Team2",
                            3
                        ],
                        "key_as_string": "Team2|3",
                        "doc_count": 2
                    },
                    {
                        "key": [
                            "Team3",
                            5
                        ],
                        "key_as_string": "Team3|5",
                        "doc_count": 2
                    },
                    {
                        "key": [
                            "Team4",
                            1
                        ],
                        "key_as_string": "Team4|1",
                        "doc_count": 1
                    },
                    {
                        "key": [
                            "Team5",
                            4
                        ],
                        "key_as_string": "Team5|4",
                        "doc_count": 1
                    },
                    {
                        "key": [
                            "Team6",
                            7
                        ],
                        "key_as_string": "Team6|7",
                        "doc_count": 1
                    },
                    {
                        "key": [
                            "Team7",
                            6
                        ],
                        "key_as_string": "Team7|6",
                        "doc_count": 1
                    }
                ]
            },
            "the_won": {
                "doc_count": 4,
                "teams": {
                    "doc_count_error_upper_bound": 0,
                    "sum_other_doc_count": 0,
                    "buckets": [
                        {
                            "key": [
                                "Team2",
                                5
                            ],
                            "key_as_string": "Team2|5",
                            "doc_count": 2
                        },
                        {
                            "key": [
                                "Team4",
                                2
                            ],
                            "key_as_string": "Team4|2",
                            "doc_count": 1
                        },
                        {
                            "key": [
                                "Team7",
                                3
                            ],
                            "key_as_string": "Team7|3",
                            "doc_count": 1
                        }
                    ]
                }
            }
        }
    }
}
</code>```

But I still cannot get the winrate from two siblings, where one sibling might have missing teams that have not won any match.
Should I use some pipeline aggregation?

答: This is very similar to the example docs have for nested aggregation. The only difference would be that you'll have a terms aggregation on the top level instead of filter so you get back all of the teams.

Body:
I'm trying to get the top 5 teams based on win rate (matches won / all matches) having the match result documents in the index (see below).

The fields I need to get in the bucket:

apiId

name

winrate (won/total)

I guess this would require complex aggregation calculation witch is far beyond my current elasticsearch skills.

Elasticsearch version: 7.15.2

Could anyone help me with such elasticsearch query?

Thanks a lot in advance!

{
  "lastModified": "2022-01-14T09:33:48.232Z",
  "uuid": "01234567",
  "started": "2022-01-14T09:31:27.651Z",
  "editing": false,
  "approved": true,
  "statistics": {
    "teams": [
      {
        "name": "Team1",
        "score": 0,
        "winner": false,
        "apiId": "1"
      },
      {
        "name": "Team2",
        "score": 2,
        "winner": true,
        "apiId": "2"
      }
    ]
  }
}

and the mapping:

{
    "mappings": {
        "properties": {
            "_class": {
                "type": "keyword",
                "index": false,
                "doc_values": false
            },
            "approved": {
                "type": "boolean"
            },
            "editing": {
                "type": "boolean"
            },
            "ended": {
                "type": "date",
                "format": "date_optional_time||epoch_millis"
            },
            "game": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "lastModified": {
                "type": "date",
                "format": "date_optional_time||epoch_millis"
            },
            "started": {
                "type": "date",
                "format": "date_optional_time||epoch_millis"
            },
            "statistics": {
                "type": "nested",
                "include_in_parent": true,
                "properties": {
                    "_class": {
                        "type": "keyword",
                        "index": false,
                        "doc_values": false
                    },
                    "teams": {
                        "type": "nested",
                        "include_in_parent": true,
                        "properties": {
                            "_class": {
                                "type": "keyword",
                                "index": false,
                                "doc_values": false
                            },
                            "apiId": {
                                "type": "long"
                            },
                            "name": {
                                "type": "text",
                                "fields": {
                                    "keyword": {
                                        "type": "keyword",
                                        "ignore_above": 256
                                    }
                                }
                            },
                            "score": {
                                "type": "long"
                            },
                            "winner": {
                                "type": "boolean"
                            }
                        }
                    }
                }
            },
            "uuid": {
                "type": "keyword"
            }
        }
    }
}

Edit:
Based on @ilvar answer, I constructed the query:

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "approved": true
                    }
                }
            ]
        }
    },
    "size": 0,
    "aggs": {
        "top_teams": {
            "nested": {
                "path": "statistics.teams"
            },
            "aggs": {
                "the_all": {
                    "multi_terms": {
                        "terms": [
                            {
                                "field": "statistics.teams.name.keyword"
                            },
                            {
                                "field": "statistics.teams.apiId"
                            }
                        ]
                    }
                },
                "the_won": {
                    "filter": {
                        "terms": {
                            "statistics.teams.winner": [
                                true
                            ]
                        }
                    },
                    "aggs": {
                        "teams": {
                            "multi_terms": {
                                "terms": [
                                    {
                                        "field": "statistics.teams.name.keyword"
                                    },
                                    {
                                        "field": "statistics.teams.apiId"
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
}

Which gives me:

{
    "took": 20,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 5,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "top_teams": {
            "doc_count": 10,
            "the_all": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                    {
                        "key": [
                            "Team1",
                            2
                        ],
                        "key_as_string": "Team1|2",
                        "doc_count": 2
                    },
                    {
                        "key": [
                            "Team2",
                            3
                        ],
                        "key_as_string": "Team2|3",
                        "doc_count": 2
                    },
                    {
                        "key": [
                            "Team3",
                            5
                        ],
                        "key_as_string": "Team3|5",
                        "doc_count": 2
                    },
                    {
                        "key": [
                            "Team4",
                            1
                        ],
                        "key_as_string": "Team4|1",
                        "doc_count": 1
                    },
                    {
                        "key": [
                            "Team5",
                            4
                        ],
                        "key_as_string": "Team5|4",
                        "doc_count": 1
                    },
                    {
                        "key": [
                            "Team6",
                            7
                        ],
                        "key_as_string": "Team6|7",
                        "doc_count": 1
                    },
                    {
                        "key": [
                            "Team7",
                            6
                        ],
                        "key_as_string": "Team7|6",
                        "doc_count": 1
                    }
                ]
            },
            "the_won": {
                "doc_count": 4,
                "teams": {
                    "doc_count_error_upper_bound": 0,
                    "sum_other_doc_count": 0,
                    "buckets": [
                        {
                            "key": [
                                "Team2",
                                5
                            ],
                            "key_as_string": "Team2|5",
                            "doc_count": 2
                        },
                        {
                            "key": [
                                "Team4",
                                2
                            ],
                            "key_as_string": "Team4|2",
                            "doc_count": 1
                        },
                        {
                            "key": [
                                "Team7",
                                3
                            ],
                            "key_as_string": "Team7|3",
                            "doc_count": 1
                        }
                    ]
                }
            }
        }
    }
}

But I still cannot get the winrate from two siblings, where one sibling might have missing teams that have not won any match.
Should I use some pipeline aggregation?


问:
How to join adjacent elements in a list with a string in between?
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

and the output needs to be:

```<code>1-2
3-4
5-6
7-8
</code>```

Now I have gotten as far as this, but have no idea what to do next:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))
</code>```

And this only gives me this as result:

```<code>[(1, 2), (3, 4), (5, 6), (7, 8)]
</code>```

I feel like I am close and just missing one tiny step.

答:
A somewhat fun[*] alternative, easily adapts to similar cases just by altering the string of ends:

```<code>from itertools import cycle

a = [1, 2, 3, 4, 5, 6, 7, 8]

for x, end in zip(a, cycle('-\n')):
    print(x, end=end)
</code>```

For example with cycle('+-*\n'), it would instead print this:

```<code>1+2-3*4
5+6-7*8
</code>```

[*] Everything itertools is fun for me :-)

Body:
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

a = [1, 2, 3, 4, 5, 6, 7, 8]

and the output needs to be:

1-2
3-4
5-6
7-8

Now I have gotten as far as this, but have no idea what to do next:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))

And this only gives me this as result:

[(1, 2), (3, 4), (5, 6), (7, 8)]

I feel like I am close and just missing one tiny step.

Body:
A somewhat fun[*] alternative, easily adapts to similar cases just by altering the string of ends:

from itertools import cycle

a = [1, 2, 3, 4, 5, 6, 7, 8]

for x, end in zip(a, cycle('-\n')):
    print(x, end=end)

For example with cycle('+-*\n'), it would instead print this:

1+2-3*4
5+6-7*8

[*] Everything itertools is fun for me :-)


问:
Retrieve the matching TFIDF of each words by sentence from a TFIDF matrix (pandas)
My first dataframe contains sentences I tokenized, the second is a matrix of all the TFIDF of each word in each sentence.

I'm trying to create a new column where only the TFIDF of the words in the sentence are stored. How can i do it ?

Tokenize sentences table

Index
Tokenized_string

1
[word1,word2,word3]

2
[word1,word3,word4]

Tfidf Table

Index
Word1
Word2
...

1
0.03
0.06
...

2
0.5
0.5
...

The table I'm trying to create

Index
Tokenized_string
TFIDF of each word

1
[word1,word2,word3]
[0.03,0.06,0.1]

2
[word1,word3,word4]
[0.5,0.4,0.2]

To create the dataframes in my exemple:

```<code>import pandas as pd
df = pd.DataFrame({ 'Tokenized_string':
                   [['word1','word2','word3'],
                    ['word1','word3','word4']]
                   })

df_2 = pd.DataFrame({ 'Tokenized_string':
                   [['word1','word2','word3'],
                    ['word1','word3','word4']],
                   'TFIDF of each word':
                       [[0.03,0.06,0.1],
                        [0.5,0.4,0.2]]})
</code>```

答:
You can do that with the following.

Using the following tfidf_df as an example.

```<code>tfidf_df = pd.DataFrame({
    'Word1': [0.03, 0.5],
    'Word2': [0.06, 0.5],
    'Word3': [0.04, 0.5]
                   })
</code>```

Note that you may need to change the tfidf_df variable based on your naming scheme

```<code>tfidf_df['TFIDF of each word'] = tfidf_df[sorted(tfidf_df.columns)].values.tolist()
df_2 = pd.concat([df, tfidf_df["TFIDF of each word"]], axis=1)

print(df_2)
        Tokenized_string  TFIDF of each word
0  [word1, word2, word3]  [0.03, 0.06, 0.04]
1  [word1, word3, word4]     [0.5, 0.5, 0.5]
</code>```

Body:
My first dataframe contains sentences I tokenized, the second is a matrix of all the TFIDF of each word in each sentence.

I'm trying to create a new column where only the TFIDF of the words in the sentence are stored. How can i do it ?

Tokenize sentences table

Index
Tokenized_string

1
[word1,word2,word3]

2
[word1,word3,word4]

Tfidf Table

Index
Word1
Word2
...

1
0.03
0.06
...

2
0.5
0.5
...

The table I'm trying to create

Index
Tokenized_string
TFIDF of each word

1
[word1,word2,word3]
[0.03,0.06,0.1]

2
[word1,word3,word4]
[0.5,0.4,0.2]

To create the dataframes in my exemple:

import pandas as pd
df = pd.DataFrame({ 'Tokenized_string':
                   [['word1','word2','word3'],
                    ['word1','word3','word4']]
                   })

df_2 = pd.DataFrame({ 'Tokenized_string':
                   [['word1','word2','word3'],
                    ['word1','word3','word4']],
                   'TFIDF of each word':
                       [[0.03,0.06,0.1],
                        [0.5,0.4,0.2]]})

Body:
You can do that with the following.

Using the following tfidf_df as an example.

tfidf_df = pd.DataFrame({
    'Word1': [0.03, 0.5],
    'Word2': [0.06, 0.5],
    'Word3': [0.04, 0.5]
                   })

Note that you may need to change the tfidf_df variable based on your naming scheme

tfidf_df['TFIDF of each word'] = tfidf_df[sorted(tfidf_df.columns)].values.tolist()
df_2 = pd.concat([df, tfidf_df["TFIDF of each word"]], axis=1)

print(df_2)
        Tokenized_string  TFIDF of each word
0  [word1, word2, word3]  [0.03, 0.06, 0.04]
1  [word1, word3, word4]     [0.5, 0.5, 0.5]


问:
I have multiple forms. Login page then data entry and at the end information about entered data
I have multiple forms. Login page then data entry and at the end information about entered data. When I debug the login form pops up after entering credentials data entry form pops up. I want to close the login screen once the data entry screen is open. How can I do that?</p>

答:
In Project --> XXX Properties, in the Application tab, change the Shutdown mode option to When last form closes.

Now open your data entry form and close the login form:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim frm As New frmDataEntry
    frm.Show()
    Me.Close() ' close the current form (presumably the "login" one)
End Sub
</code>```

Body:
In Project --> XXX Properties, in the Application tab, change the Shutdown mode option to When last form closes.

Now open your data entry form and close the login form:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim frm As New frmDataEntry
    frm.Show()
    Me.Close() ' close the current form (presumably the "login" one)
End Sub


答: You should't use MINUS 1 as a z-index value, but a POSITIVE value for the h1! Or, actually better, z-index: -1 (= negative)  for the SVG background image.

Title: Text is hidden behind SVG

Body:
I added a h1 element after the SVG and it is not showing on the page. I thought that the SVG was maybe layered on top of the h1 element but I used z-index: -1; and the text is still not showing.

Code:

body {
  font-family: Lato, sans-serif;
  background-size: 100%;
}

svg {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

h1 {
  color: #fff;
  z-index: -1 !important;
}

  <svg viewBox="0 0 960 540" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><rect x="0" y="0" width="960" height="540" fill="#1db954"></rect><path d="M0 462L22.8 461.7C45.7 461.3 91.3 460.7 137 457.8C182.7 455 228.3 450 274 444.3C319.7 438.7 365.3 432.3 411.2 439.7C457 447 503 468 548.8 467.7C594.7 467.3 640.3 445.7 686 442.7C731.7 439.7 777.3 455.3 823 458.5C868.7 461.7 914.3 452.3 937.2 447.7L960 443L960 541L937.2 541C914.3 541 868.7 541 823 541C777.3 541 731.7 541 686 541C640.3 541 594.7 541 548.8 541C503 541 457 541 411.2 541C365.3 541 319.7 541 274 541C228.3 541 182.7 541 137 541C91.3 541 45.7 541 22.8 541L0 541Z" fill="#191414" stroke-linecap="round" stroke-linejoin="miter"></path></svg>

a h1 element

What I am seeing:
https://i.imgur.com/ukLCifM.png


问:
Delete all tables in one shot in Ms access
Here is my VBA code, which tries to loop through all the tables which contains PB (PB is the first two letters of all of the tables) in their name and delete them. I get the error msg at DoCmd line

```<code>Option Compare Database
Option Explicit

Public Sub del_all_tables()
   Dim db As DAO.Database
   Dim tdf As DAO.TableDef
   Set db = CurrentDb

   For Each tdf In db.TableDefs
       If Not (tdf.Name Like "PB*") Then
           DoCmd.DeleteObject acTable, tdf.Name
       End If
   Next
End Sub
</code>```

Edit: I would like to not to delete the tables itself but delete the records inside the tables

答:
First the object name in the docmd statement is causing error, because you are not calling a full object name, rather you are trying to use the like operator.

Secondly if you want to delete records and not the table, then you have to use a delete statement.

You can play around with the query design view to have a feel of how the delete statement/query in access is.

Body:
Here is my VBA code, which tries to loop through all the tables which contains PB (PB is the first two letters of all of the tables) in their name and delete them. I get the error msg at DoCmd line

Option Compare Database
Option Explicit

Public Sub del_all_tables()
   Dim db As DAO.Database
   Dim tdf As DAO.TableDef
   Set db = CurrentDb

   For Each tdf In db.TableDefs
       If Not (tdf.Name Like "PB*") Then
           DoCmd.DeleteObject acTable, tdf.Name
       End If
   Next
End Sub

Edit: I would like to not to delete the tables itself but delete the records inside the tables


问:
C# How to instantiate new object with Dependency Injection
I have a class that is using Logger:

```<code>internal class Class1
{
    private readonly ILogger<Class1> _logger;
    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }
    internal void Method1()
    {
        //some code
    }
}
</code>```

When I try using it, the compiler correctly tells me that there is no constructor that matches this signature:

```<code>Class1 cl1 = new Class1();
</code>```

I want to use default constructor.  If I understand this correctly, Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class.  How do I do that??  Thank you for your help.

答:
You state, "I want to use default constructor. ... Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class. How do I do that?"

To do what you are asking,

```<code>internal class Class1
{
    private readonly ILogger<Class1> _logger;

    // This constructor will pass to the constructor with the matching
    // signature and it will pass a new instance of the Logger<Class1> class.
    // But in using this approach you will be bypassing the DI, which may be
    // what you need in some cases, but you should still be aware of what is happening
    internal Class1() : this(new Logger<Class1>())
    {
    }

    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }

    internal void Method1()
    {
        //some code
    }
}
</code>```

Body:
I have a class that is using Logger:

internal class Class1
{
    private readonly ILogger<Class1> _logger;
    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }
    internal void Method1()
    {
        //some code
    }
}

When I try using it, the compiler correctly tells me that there is no constructor that matches this signature:

Class1 cl1 = new Class1();

I want to use default constructor.  If I understand this correctly, Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class.  How do I do that??  Thank you for your help.

Body:
You state, "I want to use default constructor. ... Id need to create default constructor in my Class1, and then call another constructor FROM default constructor to make Logger available inside the class. How do I do that?"

To do what you are asking,

internal class Class1
{
    private readonly ILogger<Class1> _logger;

    // This constructor will pass to the constructor with the matching
    // signature and it will pass a new instance of the Logger<Class1> class.
    // But in using this approach you will be bypassing the DI, which may be
    // what you need in some cases, but you should still be aware of what is happening
    internal Class1() : this(new Logger<Class1>())
    {
    }

    internal Class1(ILogger<Class1> logger)
    {
        _logger = logger;
    }

    internal void Method1()
    {
        //some code
    }
}


问:
How to add RapidXml to a CMake Project?
I want to add RapidXML to my CMake Project, so i can use it.
My Project Structure looks like this:

```<code>Root
|
|_inc (for my own Headers)
|    |_main.h
|    |_CMakeList.txt
|_src (for my own Sources)
|    |_main.cpp
|    |_CMakeList.txt
|_libs (for third party libs)
|     |_rapidxml
|     |_CMakeList.txt
|_CMakeList.txt
</code>```

Can someone help me?
Thanks in advance!

答:
RapidXML is actually a header-only library, so you don't need to add it to CMake - just #include <rapidxml/rapidxml.hpp>. However, you can do it "properly" and in a portable way using CMake's find_package() function. It's not easier though!

Firstly, create a cmake folder in your project directory somewhere - this can be used for other libraries that don't have built-in CMake modules, too. Add it to your module path by putting this line somewhere near the top of your CMakeLists.txt:

```<code>set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")
</code>```

Within that folder, create a file called FindRapidXML.cmake and give it the following contents:

```<code>#
# Search and find the RapidXML library
#

# Search for the include path
find_path(
  RapidXML_INCLUDE_DIR
  NAMES
    rapidxml.hpp
    rapidxml_utils.hpp
    rapidxml_iterators.hpp
    rapidxml_print.hpp
  HINTS "${RapidXML_ROOT_DIR}"
  PATH_SUFFIXES include rapidxml
)

# If we find the library, add it as a target
if (RapidXML_INCLUDE_DIR)
  set(RapidXML_FOUND TRUE)

  # Pull the version number out of the header
  message(DEBUG "Pulling version from ${RapidXML_INCLUDE_DIR}/rapidxml.hpp")
  file(STRINGS "${RapidXML_INCLUDE_DIR}/rapidxml.hpp"
    RapidXML_VERSION REGEX "^//[ ]*Version[ ]+[0-9]+\.[0-9]+[ ]*$")
  string(REGEX REPLACE "^//[ ]*Version[ ]+([0-9]+)\.([0-9]+)[ ]*$" "\\1\.\\2" RapidXML_VERSION "${RapidXML_VERSION}")

  # Print a message that we found it
  if (NOT RapidXML_FIND_QUIETLY)
    message(STATUS "Found RapidXML (found version \"${RapidXML_VERSION}\")")
  endif (NOT RapidXML_FIND_QUIETLY)

  # Create a target for it, if there isn't one already created
  if (NOT TARGET RapidXML::RapidXML)
    add_library(RapidXML::RapidXML INTERFACE IMPORTED)
    set_target_properties(RapidXML::RapidXML PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${RapidXML_INCLUDE_DIR}")
  endif (NOT TARGET RapidXML::RapidXML)
else ()
  # If we don't find the library, fail as appropriate
  if (RapidXML_FIND_REQUIRED)
    message(FATAL_ERROR "RapidXML was NOT found")
  elseif (NOT RapidXML_FIND_QUIETLY)
    message(STATUS "RapidXML was NOT found")
  endif (RapidXML_FIND_REQUIRED)
endif (RapidXML_INCLUDE_DIR)

# Hide the variables that we set
mark_as_advanced(RapidXML_INCLUDE_DIR)

</code>```

Then, you can import RapidXML into your project with one simple line:

```<code>find_package(RapidXML REQUIRED)
</code>```

And you can include it in a target like so:

```<code>target_link_libraries(<target> PRIVATE RapidXML::RapidXML)
</code>```

The beauty of this is that you can use the options from find_package() to have it required or not, so you get an earlier failure if it's not found. The FindRapidXML.cmake file is also reusable in other projects, the loic to find it is kept out of your main cmake file, and if it's installed into non-standard locations you can hint to where it is using HINTS <path> as you would with any other package.

Title: How to add RapidXml to a CMake Project?

Body:
I want to add RapidXML to my CMake Project, so i can use it.
My Project Structure looks like this:

Root
|
|_inc (for my own Headers)
|    |_main.h
|    |_CMakeList.txt
|_src (for my own Sources)
|    |_main.cpp
|    |_CMakeList.txt
|_libs (for third party libs)
|     |_rapidxml
|     |_CMakeList.txt
|_CMakeList.txt

Can someone help me?
Thanks in advance!

Body:
RapidXML is actually a header-only library, so you don't need to add it to CMake - just #include <rapidxml/rapidxml.hpp>. However, you can do it "properly" and in a portable way using CMake's find_package() function. It's not easier though!

Firstly, create a cmake folder in your project directory somewhere - this can be used for other libraries that don't have built-in CMake modules, too. Add it to your module path by putting this line somewhere near the top of your CMakeLists.txt:

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")

Within that folder, create a file called FindRapidXML.cmake and give it the following contents:

#
# Search and find the RapidXML library
#

# Search for the include path
find_path(
  RapidXML_INCLUDE_DIR
  NAMES
    rapidxml.hpp
    rapidxml_utils.hpp
    rapidxml_iterators.hpp
    rapidxml_print.hpp
  HINTS "${RapidXML_ROOT_DIR}"
  PATH_SUFFIXES include rapidxml
)

# If we find the library, add it as a target
if (RapidXML_INCLUDE_DIR)
  set(RapidXML_FOUND TRUE)

  # Pull the version number out of the header
  message(DEBUG "Pulling version from ${RapidXML_INCLUDE_DIR}/rapidxml.hpp")
  file(STRINGS "${RapidXML_INCLUDE_DIR}/rapidxml.hpp"
    RapidXML_VERSION REGEX "^//[ ]*Version[ ]+[0-9]+\.[0-9]+[ ]*$")
  string(REGEX REPLACE "^//[ ]*Version[ ]+([0-9]+)\.([0-9]+)[ ]*$" "\\1\.\\2" RapidXML_VERSION "${RapidXML_VERSION}")

  # Print a message that we found it
  if (NOT RapidXML_FIND_QUIETLY)
    message(STATUS "Found RapidXML (found version \"${RapidXML_VERSION}\")")
  endif (NOT RapidXML_FIND_QUIETLY)

  # Create a target for it, if there isn't one already created
  if (NOT TARGET RapidXML::RapidXML)
    add_library(RapidXML::RapidXML INTERFACE IMPORTED)
    set_target_properties(RapidXML::RapidXML PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${RapidXML_INCLUDE_DIR}")
  endif (NOT TARGET RapidXML::RapidXML)
else ()
  # If we don't find the library, fail as appropriate
  if (RapidXML_FIND_REQUIRED)
    message(FATAL_ERROR "RapidXML was NOT found")
  elseif (NOT RapidXML_FIND_QUIETLY)
    message(STATUS "RapidXML was NOT found")
  endif (RapidXML_FIND_REQUIRED)
endif (RapidXML_INCLUDE_DIR)

# Hide the variables that we set
mark_as_advanced(RapidXML_INCLUDE_DIR)

Then, you can import RapidXML into your project with one simple line:

find_package(RapidXML REQUIRED)

And you can include it in a target like so:

target_link_libraries(<target> PRIVATE RapidXML::RapidXML)

The beauty of this is that you can use the options from find_package() to have it required or not, so you get an earlier failure if it's not found. The FindRapidXML.cmake file is also reusable in other projects, the loic to find it is kept out of your main cmake file, and if it's installed into non-standard locations you can hint to where it is using HINTS <path> as you would with any other package.


问:
Can't start Emacs with Prelude (Windows)
I successfully installed Emacs and Prelude on my Windows 10 machine. I had the following error during the setup that was fixed by adding Emacs to the path:

```<code>Emacs not found. Skipping byte-compilation.
</code>```

While the above issue was resolved (see comments) and Prelude finally found Emacs during installation, when I run emacs or runemacs commands, vanilla Emacs starts. Prelude is ignored.
When I try to start server using emacs --daemon, all I see is the "Starting Emacs daemon." message and no other prelude-related loading messages.

How do I make Emacs start with Prelude?

I have no problems running Emacs with Prelude on Ubuntu or Linux Mint.

答:
curl installed Prelude in .emacs.d folder under my user directory which is also set to be my home directory -  C:\Users\me.

The problem was that there was another instance of .emacs.d configs in C:\Users\me\AppData\Roaming. The latter was the default one. I added it to the PATH, moved Emacs folder (not sure if that was needed at all) to theC:\Users\me\AppData\Roaming as well.

Now I could run emacs command that opened Emacs w/ Prelude, however, this isn't my preferred way. I still couldn't start daemon server because my input to "Continue connection?" question wasn't registered. The fix is described here -https://emacs.stackexchange.com/questions/34781/emacs-daemon-hangs-on-first-run-on-emacs-25-2

Body:
I successfully installed Emacs and Prelude on my Windows 10 machine. I had the following error during the setup that was fixed by adding Emacs to the path:

Emacs not found. Skipping byte-compilation.

While the above issue was resolved (see comments) and Prelude finally found Emacs during installation, when I run emacs or runemacs commands, vanilla Emacs starts. Prelude is ignored.
When I try to start server using emacs --daemon, all I see is the "Starting Emacs daemon." message and no other prelude-related loading messages.

How do I make Emacs start with Prelude?

I have no problems running Emacs with Prelude on Ubuntu or Linux Mint.


问:
Change pandas dataframe first row to become column names
I have the following response from reading a gsheet from google API.

```<code>response =  [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'VICE_DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'VICE_DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file name', 'ADDED']]
</code>```

and created a df from the response:

```<code>df = pd.DataFrame(response)

Index 0       1       2      3             4              5         6
0  Owner  Database   Schema  ...          Column         Comment  Status
1         VICE_DEV  AIRFLOW  ...  _LOAD_DATETIME   Load datetime    None
2         VICE_DEV  AIRFLOW  ...  _LOAD_FILENAME  load file name   ADDED
</code>```

How do I get the 0 row to become the column names instead?

I tried this:

```<code>df.columns = df.iloc[0]
</code>```

and it works in a way, but then I still see the 0 row as the column names (this is not correct)

```<code>Index  Owner  Database   Schema  ...          Column         Comment  Status
0  Owner  Database   Schema  ...          Column         Comment  Status
1         VICE_DEV  AIRFLOW  ...  _LOAD_DATETIME   Load datetime    None
2         VICE_DEV  AIRFLOW  ...  _LOAD_FILENAME  load file name   ADDED
</code>```

答:
You can for example directly set the first row as columns and use the rest as rows:

```<code>response =  [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'VICE_DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'VICE_DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file name', 'ADDED']]

df = pd.DataFrame(response[1:], columns=response[0])
df
</code>```

Output:

```<code>Owner   Database    Schema  Table   Column  Comment Status
0       VICE_DEV    AIRFLOW TASK_INSTANCE   _LOAD_DATETIME  Load datetime   None
1       VICE_DEV    AIRFLOW TEST    _LOAD_FILENAME  load file name  ADDED
</code>```

You can also add one line to the code that you provided and achieve the same result:

```<code>df = pd.DataFrame(response)
df.columns = df.iloc[0]

# Remove first row
df = df[1:]
</code>```

Body:
I have the following response from reading a gsheet from google API.

response =  [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'VICE_DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'VICE_DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file name', 'ADDED']]

and created a df from the response:

df = pd.DataFrame(response)

Index 0       1       2      3             4              5         6
0  Owner  Database   Schema  ...          Column         Comment  Status
1         VICE_DEV  AIRFLOW  ...  _LOAD_DATETIME   Load datetime    None
2         VICE_DEV  AIRFLOW  ...  _LOAD_FILENAME  load file name   ADDED

How do I get the 0 row to become the column names instead?

I tried this:

df.columns = df.iloc[0]

and it works in a way, but then I still see the 0 row as the column names (this is not correct)

Index  Owner  Database   Schema  ...          Column         Comment  Status
0  Owner  Database   Schema  ...          Column         Comment  Status
1         VICE_DEV  AIRFLOW  ...  _LOAD_DATETIME   Load datetime    None
2         VICE_DEV  AIRFLOW  ...  _LOAD_FILENAME  load file name   ADDED

Body:
You can for example directly set the first row as columns and use the rest as rows:

response =  [['Owner', 'Database', 'Schema', 'Table', 'Column', 'Comment', 'Status'], ['', 'VICE_DEV', 'AIRFLOW', 'TASK_INSTANCE', '_LOAD_DATETIME', 'Load datetime'], ['', 'VICE_DEV', 'AIRFLOW', 'TEST', '_LOAD_FILENAME', 'load file name', 'ADDED']]

df = pd.DataFrame(response[1:], columns=response[0])
df

Output:

Owner   Database    Schema  Table   Column  Comment Status
0       VICE_DEV    AIRFLOW TASK_INSTANCE   _LOAD_DATETIME  Load datetime   None
1       VICE_DEV    AIRFLOW TEST    _LOAD_FILENAME  load file name  ADDED

You can also add one line to the code that you provided and achieve the same result:

df = pd.DataFrame(response)
df.columns = df.iloc[0]

# Remove first row
df = df[1:]


答:
Use loc accessor to slice the rows you need. This shouls result into a dataframe. Create a dictionary where old df's column names are the keys and the first row's attributes are values. Use the dict in the column rename method. Code below</p>
```<code>s= df.loc[1:,:].rename(columns=dict(zip(df.columns, df.loc[0,:].to_list())))

Owner  Database   Schema          Table          Column         Comment  \
1        VICE_DEV  AIRFLOW  TASK_INSTANCE  _LOAD_DATETIME   Load datetime
2        VICE_DEV  AIRFLOW           TEST  _LOAD_FILENAME  load file name

  Status
1   None
2  ADDED
</code>```

Title: Change pandas dataframe first row to become column names

Body:
Use loc accessor to slice the rows you need. This shouls result into a dataframe. Create a dictionary where old df's column names are the keys and the first row's attributes are values. Use the dict in the column rename method. Code below

s= df.loc[1:,:].rename(columns=dict(zip(df.columns, df.loc[0,:].to_list())))

Owner  Database   Schema          Table          Column         Comment  \
1        VICE_DEV  AIRFLOW  TASK_INSTANCE  _LOAD_DATETIME   Load datetime
2        VICE_DEV  AIRFLOW           TEST  _LOAD_FILENAME  load file name

  Status
1   None
2  ADDED


答:
Use DELETE action SQL to remove records. Use CurrentDb.Execute and don't have to worry about turning Warnings off and on.

CurrentDb.Execute "DELETE FROM [" & tdf.Name & "]".

If you want to delete records only from tables starting with PB, remove Not from the condition - otherwise you will delete from all other tables (including system tables which is bad).

```<code>Public Sub del_all_records()
   Dim db As DAO.Database
   Dim tdf As DAO.TableDef
   Set db = CurrentDb

   For Each tdf In db.TableDefs
       If tdf.Name Like "PB*" Then
           db.Execute "DELETE FROM [" & tdf.Name & "]"
       End If
   Next
End Sub
</code>```

Title: Delete all tables in one shot in Ms access

Body:
Use DELETE action SQL to remove records. Use CurrentDb.Execute and don't have to worry about turning Warnings off and on.

CurrentDb.Execute "DELETE FROM [" & tdf.Name & "]".

If you want to delete records only from tables starting with PB, remove Not from the condition - otherwise you will delete from all other tables (including system tables which is bad).

Public Sub del_all_records()
   Dim db As DAO.Database
   Dim tdf As DAO.TableDef
   Set db = CurrentDb

   For Each tdf In db.TableDefs
       If tdf.Name Like "PB*" Then
           db.Execute "DELETE FROM [" & tdf.Name & "]"
       End If
   Next
End Sub


问:
Problem with handling path length
I'm creating library which will be used for file manipulations, both on linux and windows. So I need to handle paths, the main requirements is that my functions will recieve strings in UTF8 format. But it causes some problems, one of them is I'm using MAX_PATH on windows and PATH_MAX in linux, to represent static path variables. In the case of ASCII characters there will be no problem, but when path contains unicode characters, the length of path will be twice shorter if unicode char requires 2 bytes per char, 3 times shorter if unicode char requires 3 bytes per char and so on. So is there good solution for this problem?

Thanks in advance!

p.s. sorry for my english.

答:
That totally depends on what you need.

If you want MAX_PATH number of bytes, you simply define a buffer as char name[MAX_PATH]. If you want MAX_PATH number of characters, you define a buffer as char name[MAX_PATH * 4], as UTF-8 encodes each Unicode character as a variable number of 1 to 4 octets.

In a word, as janneb points out, MAX_PATH (or PATH_MAX) specifies the number of underlying bytes instead of characters.

ContentLicense: CC BY-SA 3.0

Title: Problem with handling path length


问:
Unable to get the exceptions in try catch
I have a worker service in .net core 3.1 in my Program.cs i have the below codes

```<code>public static void Main(string[] args)
{
    try
    {
        CreateHostBuilder(args).Build().Run();
    }
    catch(Exception ex)
    {
        Handler(ex);
    }
}
</code>```

And also a worker class as below

```<code>public class Worker : BackgroundService
{
  protected override async Task ExecuteAsync(CancellationToken Token)
  {

    do
    {
     if(condition)
     {
      await _test.GetData();
     }
     await Task.Delay(500,Token);
    }
    while (!Token.IsCancellationRequested);

  }
 }
</code>```

If Task.Delay executes first and then any exception occurs in the GetData() method on the second iteration, it is not being captured by the try catch in my Main method. How can i get these exception to be caught in my main method?

答:
That's the expected behavior.

Your catch block in the Program.cs file will only handle exceptions thrown when building and starting the .NET core generic host. That's all. The catch block is not expected to handle exceptions thrown by the registered hosted services during their execution.

If you check the source code for the BackgroundService base class you will understand why exceptions thrown by a background service are lost.

At this line you see that your implementation of ExecuteAsync is invoked and the
resulting task is stored inside the _executeTask field.

Your override of ExecuteAsync is an async function. When there is an unhandled exception inside of an async funcition, the exception is captured by the runtime and placed on the returned Task. The exception will be thrown (with its original stacktrace preserved) when the Task is awaited, or an api like Task.Wait() is called.

Notice that the _executeTask Task is not awaited and that the executing thread is not trying to synchronously wait for the task completion by calling the Task.Wait() method. So, there is no chance to observe exceptions coming from that Task.

There is only one possibility to observe an exception coming from your implementation of ExecuteAsync. If an exception occurs before the very first await instruction, then the method execution completes synchronously and the returned Task will have the IsCompleted property set to true and its Status will be Faulted. In that case, the _executeTask task will be returned to the calling code (see this line).

The calling code, which is basically the code starting the .NET core generic host, will get back a faulted task and will detect the error occurred while starting the background service by awaiting the task itself. At that point, the exception coming from the ExecuteAsync method will be rethrown and the catch block in your Program.cs will handle the exception.

If any exception occurs inside of ExecuteAsync after the first await instruction, there is no way for the .NET core generic host to observe the exception itself. Those exceptions will result in silent failures. You can find more details on this by reading this great blog post.

As pointed out by a comment to your question, this behavior has been changed in .NET 6, as you can read here. To put it briefly, the default behaviour in .NET 6 is logging any unhandled exception coming from a background service and stopping the Host, so that you are aware of the problem and you have a chance to fix your code and investigate why it is throwing exceptions.

Body:
I have a worker service in .net core 3.1 in my Program.cs i have the below codes

public static void Main(string[] args)
{
    try
    {
        CreateHostBuilder(args).Build().Run();
    }
    catch(Exception ex)
    {
        Handler(ex);
    }
}

And also a worker class as below

public class Worker : BackgroundService
{
  protected override async Task ExecuteAsync(CancellationToken Token)
  {

    do
    {
     if(condition)
     {
      await _test.GetData();
     }
     await Task.Delay(500,Token);
    }
    while (!Token.IsCancellationRequested);

  }
 }

If Task.Delay executes first and then any exception occurs in the GetData() method on the second iteration, it is not being captured by the try catch in my Main method. How can i get these exception to be caught in my main method?


问:
Python: get values from dictionary of dictionaries
I have a dictionary of dictionaries that looks like this:

{'info': {'status': 'OK',
          'data': {'account': [{'currency': 'USD',
                                'name': 'United States Dollar',
                                'amount': '100',
                                'used': '20',
                                'total': '120'},
                               {'currency': 'EUR',
                                'name': 'Euro',
                                'amount': '150',
                                'used': '35',
                                'total': '185'}]}},
 'USD': {'amount': 100, 'used': 20, 'total': 120},
 'EUR': {'amount': 150, 'used': 35, 'total': 185},
 'amount': {'USD': 100, 'EUR': 150},
 'used': {'USD': 20, 'EUR': 35},
 'total': {'USD': 120, 'EUR': 185}}
```
<p>What I want to get from this is a currency list:</p>
```currency_list = ['USD','EUR']
```
<p>and I would like to get a currency name list:</p>
```currency_list = ['United States Dollar','Euro']
```

How can I access the dictionaries?

Thank you

答: You can access a dictionary of dictionaries by calling the dictionary with both keys you need to use. For example currency_list[info][status] would return 'OK'. The way you have your dictionary set up is a bit confusing. I might restructure it in order to access each element in simpler fashion.</p>

Body:
I have a dictionary of dictionaries that looks like this:

{'info': {'status': 'OK',
          'data': {'account': [{'currency': 'USD',
                                'name': 'United States Dollar',
                                'amount': '100',
                                'used': '20',
                                'total': '120'},
                               {'currency': 'EUR',
                                'name': 'Euro',
                                'amount': '150',
                                'used': '35',
                                'total': '185'}]}},
 'USD': {'amount': 100, 'used': 20, 'total': 120},
 'EUR': {'amount': 150, 'used': 35, 'total': 185},
 'amount': {'USD': 100, 'EUR': 150},
 'used': {'USD': 20, 'EUR': 35},
 'total': {'USD': 120, 'EUR': 185}}

What I want to get from this is a currency list:

currency_list = ['USD','EUR']

and I would like to get a currency name list:

currency_list = ['United States Dollar','Euro']

How can I access the dictionaries?

Thank you


问:
Anaconda's autocomplete function Sublime Text not working
I have installed the Anaconda plugin in Sublime Text Build 4126 and it doesn't work its autocomplete function. I don't know why. Anaconda's linting works indeed.

Python version: 3.10

Could you help please to detect and fix the problem?

答:
Note:

Since I wrote this answer, Anaconda has been updated to fix the problem. If you haven't already, simply update your Anaconda installation to v2.3.0 or newer.

The Anaconda plugin comes with several other Python libraries bundled in, including jedi (for autocompletion), autopep8 for code formatting, and several others. These libs are part of the Anaconda plugin itself, and are not installed as Package Control dependencies, so their versions don't change unless the plugin's author, DamnWidget, updates them manually. However, as they explained in a recent comment, they haven't used Python or Sublime Text for a while, and are maintaining the plugin simply because it's popular with the community and no one else has stepped up to maintain it.

One of the included libraries is parso, which parses Python source using a grammar file specific for the version of Python being used. This plugin happens to be where the bugs that are causing your problem lie. The first issue is that the included version of parso, which was last updated in May 2020, does not have grammar files for Python 3.10 (or beyond). (The grammar file for 3.9 is also exactly the same as the one for 3.8, but we'll fix that as well.) The second issue is that even if there were a 3.10 grammar file included, the parso source (and hence Anaconda), wouldn't be able to read it, so you don't get autocomplete.

We'll need to follow several steps to fix both these issues.

Open your Sublime Text Packages folder by clicking on Preferences → Browse Packages…. Depending on your OS and whether or not you installed ST4 fresh or upgraded from ST3, this folder will be in different locations:

Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages

macOS/OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages

Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages

Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages or InstallationFolder\Sublime Text\Data\Packages

Open your Command Prompt, Powershell, or Terminal and navigate to a temporary directory, such as C:\Temp on Windows or /tmp on macOS or Linux.

Type in:

```<code> git clone https://github.com/davidhalter/parso.git
</code>```

Alternatively, if you use a separate source control GUI program, use it to clone that repository someplace like one of the temp directories I mentioned.

Enter the just-created parso directory, then go into the parso/python directory. You'll see that among the files there are the grammarXX[X].txt files, where XX[X] starts at 36 and goes up to 312. Open this folder in your operating system's file explorer app to make copying and pasting easier. Select all of the grammar files and copy them.

Back in the Packages window we opened earlier, navigate to Anaconda/anaconda_lib/parso/python. Paste the copied grammar files here. You'll be overwriting some of them, but that's okay - we want to do that. This will fix the first problem you're having.

Navigate up one level, so that your file explorer location is now Packages/Anaconda/anaconda_lib/parso. Open the file called utils.py in Sublime and navigate down to line 123. It should look like this:

    match = re.match(r'(\d+)(?:\.(\d)(?:\.\d+)?)?$', version)
```
<p>We're going to add exactly one character. Replace the original line with this (make sure it's indented 4 spaces):</p>
<pre class="lang-py prettyprint-override"><code>    match = re.match(r'(\d+)(?:\.(\d+)(?:\.\d+)?)?$', version)
#                                   ^ added this
</code>```

Save the file, and you're done! Restart Sublime Text, and Anaconda autocomplete should now work with versions 3.10 and above!

Please keep in mind that your changes will be overwritten the next time Anaconda is upgraded, but hopefully the next time that happens the new version will fix these bugs.

Body:
Note:

Since I wrote this answer, Anaconda has been updated to fix the problem. If you haven't already, simply update your Anaconda installation to v2.3.0 or newer.

The Anaconda plugin comes with several other Python libraries bundled in, including jedi (for autocompletion), autopep8 for code formatting, and several others. These libs are part of the Anaconda plugin itself, and are not installed as Package Control dependencies, so their versions don't change unless the plugin's author, DamnWidget, updates them manually. However, as they explained in a recent comment, they haven't used Python or Sublime Text for a while, and are maintaining the plugin simply because it's popular with the community and no one else has stepped up to maintain it.

One of the included libraries is parso, which parses Python source using a grammar file specific for the version of Python being used. This plugin happens to be where the bugs that are causing your problem lie. The first issue is that the included version of parso, which was last updated in May 2020, does not have grammar files for Python 3.10 (or beyond). (The grammar file for 3.9 is also exactly the same as the one for 3.8, but we'll fix that as well.) The second issue is that even if there were a 3.10 grammar file included, the parso source (and hence Anaconda), wouldn't be able to read it, so you don't get autocomplete.

We'll need to follow several steps to fix both these issues.

Open your Sublime Text Packages folder by clicking on Preferences → Browse Packages…. Depending on your OS and whether or not you installed ST4 fresh or upgraded from ST3, this folder will be in different locations:

Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages

macOS/OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages

Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages

Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages or InstallationFolder\Sublime Text\Data\Packages

Open your Command Prompt, Powershell, or Terminal and navigate to a temporary directory, such as C:\Temp on Windows or /tmp on macOS or Linux.

Type in:

 git clone https://github.com/davidhalter/parso.git

Alternatively, if you use a separate source control GUI program, use it to clone that repository someplace like one of the temp directories I mentioned.

Enter the just-created parso directory, then go into the parso/python directory. You'll see that among the files there are the grammarXX[X].txt files, where XX[X] starts at 36 and goes up to 312. Open this folder in your operating system's file explorer app to make copying and pasting easier. Select all of the grammar files and copy them.

Back in the Packages window we opened earlier, navigate to Anaconda/anaconda_lib/parso/python. Paste the copied grammar files here. You'll be overwriting some of them, but that's okay - we want to do that. This will fix the first problem you're having.

Navigate up one level, so that your file explorer location is now Packages/Anaconda/anaconda_lib/parso. Open the file called utils.py in Sublime and navigate down to line 123. It should look like this:

    match = re.match(r'(\d+)(?:\.(\d)(?:\.\d+)?)?$', version)

We're going to add exactly one character. Replace the original line with this (make sure it's indented 4 spaces):

    match = re.match(r'(\d+)(?:\.(\d+)(?:\.\d+)?)?$', version)
#                                   ^ added this

Save the file, and you're done! Restart Sublime Text, and Anaconda autocomplete should now work with versions 3.10 and above!

Please keep in mind that your changes will be overwritten the next time Anaconda is upgraded, but hopefully the next time that happens the new version will fix these bugs.


问:
ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. ... Maximum length is 63 characters
I'm writing a GitHub Action to deploy my application to Cloud Run (a GCP service) with action deploy-cloudrun. It successfully create and push my application image to the artifact registry, but it failed to deploy to Cloud Run.

And I don t know what name is too long or how to change it ?

From Github Action console :

```<code>Running: gcloud beta run deploy xxxxxxxxxxxxx --quiet --platform managed --region xxxxxxxxxxxx --tag 1.0.0 --revision-suffix v1.0.0 --project xxxxxxxx --format json
Error: failed to execute gcloud command `gcloud beta run deploy xxxxxxxxxxxxx --quiet --platform managed --region xxxxxxxxxxxx --tag 1.0.0 --revision-suffix v1.0.0 --project xxxxxxxx --format json`: This command is equivalent to running `gcloud builds submit --tag [IMAGE] .` and `gcloud run deploy xxxxxxxxxxxxx --image [IMAGE]`

Building using Dockerfile and deploying container to Cloud Run service [xxxxxxxxxxxxx] in project [xxxxxxxx] region [xxxxxxxxxxx]
Building and deploying...
Uploading sources.........done
Building Container..................................done
failed
Deployment failed
ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. Must begin with a letter and cannot end with a '-'. Maximum length is 63 characters.
</code>```

My workflow :

name: Deploy to production

...

jobs:
  deployment-job:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v2
      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v0
        with:
          ...
      - name: Deploy to Cloud Run
        uses: google-github-actions/deploy-cloudrun@v0
        with:
          service: ${{ env.SERVICE_NAME }}
          image: ${{ env.RUN_REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/cloud-run-source-deploy/${{ env.SERVICE_NAME }}:latest
          project_id: ${{ env.PROJECT_ID }}
          region: ${{ env.RUN_REGION }}
          tag: ${{ env.PACKAGE_VERSION }}
```

答:
According to your error message:

```<code>ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. Must begin with a letter and cannot end with a '-'. Maximum length is 63 characters
</code>```

You can check what contains your env var env.SERVICE_NAME and make it compliance with the requirements of the error.

Resource name must use only lowercase letters, numbers and '-'.

Must begin with a letter and cannot end with a '-'.

Maximum length is 63 characters

The aforementioned is defined in this GCP documentation which points to This K8s reference about RFC 1035 Label Names. This is in similar to the GCP Docs

```<code>..This means the name must:

contain at most 63 characters
contain only lowercase alphanumeric characters or '-'
start with an alphabetic character
end with an alphanumeric character

</code>```

Body:
I'm writing a GitHub Action to deploy my application to Cloud Run (a GCP service) with action deploy-cloudrun. It successfully create and push my application image to the artifact registry, but it failed to deploy to Cloud Run.

And I don t know what name is too long or how to change it ?

From Github Action console :

Running: gcloud beta run deploy xxxxxxxxxxxxx --quiet --platform managed --region xxxxxxxxxxxx --tag 1.0.0 --revision-suffix v1.0.0 --project xxxxxxxx --format json
Error: failed to execute gcloud command `gcloud beta run deploy xxxxxxxxxxxxx --quiet --platform managed --region xxxxxxxxxxxx --tag 1.0.0 --revision-suffix v1.0.0 --project xxxxxxxx --format json`: This command is equivalent to running `gcloud builds submit --tag [IMAGE] .` and `gcloud run deploy xxxxxxxxxxxxx --image [IMAGE]`

Building using Dockerfile and deploying container to Cloud Run service [xxxxxxxxxxxxx] in project [xxxxxxxx] region [xxxxxxxxxxx]
Building and deploying...
Uploading sources.........done
Building Container..................................done
failed
Deployment failed
ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. Must begin with a letter and cannot end with a '-'. Maximum length is 63 characters.

My workflow :

name: Deploy to production

...

jobs:
  deployment-job:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v2
      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v0
        with:
          ...
      - name: Deploy to Cloud Run
        uses: google-github-actions/deploy-cloudrun@v0
        with:
          service: ${{ env.SERVICE_NAME }}
          image: ${{ env.RUN_REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/cloud-run-source-deploy/${{ env.SERVICE_NAME }}:latest
          project_id: ${{ env.PROJECT_ID }}
          region: ${{ env.RUN_REGION }}
          tag: ${{ env.PACKAGE_VERSION }}

Body:
According to your error message:

ERROR: (gcloud.beta.run.deploy) Resource name must use only lowercase letters, numbers and '-'. Must begin with a letter and cannot end with a '-'. Maximum length is 63 characters

You can check what contains your env var env.SERVICE_NAME and make it compliance with the requirements of the error.

Resource name must use only lowercase letters, numbers and '-'.

Must begin with a letter and cannot end with a '-'.

Maximum length is 63 characters

The aforementioned is defined in this GCP documentation which points to This K8s reference about RFC 1035 Label Names. This is in similar to the GCP Docs

..This means the name must:

contain at most 63 characters
contain only lowercase alphanumeric characters or '-'
start with an alphabetic character
end with an alphanumeric character


问:
Force Serial Singleton Function Lock
I'm wanting to run a parallel process using a thread-safe singleton for a portion of that process. I'm using COM Interop in the Singleton and can only have one instance running at a time system-wide.

The Singleton's operations cannot overlap. When a Singleton operation is called, there can't be any other singleton operations currently in-process..

I have a simplified, working example that using lock to ensure the singleton operation stay serialized across the multiple threads.

Would anyone recommend a more optimal solution than what I have currently OR is what I have implemented appropriate? Thank you.

Current working example-

internal class Program
{
    static void Main(string[] args)
    {
        Parallel.ForEach(Enumerable.Range(0, 10), i =>
        {
            if (i % 2 == 0)
                SerializedSingleton.Instance.Serializer(); // Serialized Operation Only
            else
                Thread.Sleep(100); // Concurrent Operations
        });
    }
}

public sealed class SerializedSingleton
{
    private static readonly object SerializerLock = new object();
    // THREAD-SAFE SINGLETON SETUP
    private static readonly Lazy<SerializedSingleton> lazy =
    new Lazy<SerializedSingleton>(() => new SerializedSingleton());
    public static SerializedSingleton Instance { get => lazy.Value; }
    private SerializedSingleton()
    {
    }
    public void Serializer()
    {
        lock (SerializerLock)
        {
            Console.WriteLine("Serializer START");
            Thread.Sleep(2000);
            Console.WriteLine("Serializer STOP");
        }
    }
}
```
<p>Current Output (desired)-</p>
```Serializer START
Serializer STOP
Serializer START
Serializer STOP
Serializer START
Serializer STOP
Serializer START
Serializer STOP
Serializer START
Serializer STOP
```
<p>Need to avoid-</p>
```Serializer START
Serializer START
Serializer START
Serializer START
Serializer START
Serializer STOP
Serializer STOP
Serializer STOP
Serializer STOP
Serializer STOP
```

Thead-safe singleton sourced from: https://csharpindepth.com/Articles/Singleton

答:
Whenever you call lock (SerializerLock) and Thread.Sleep(..), you block the current thread. If there is high contention, you will have a lot of threads waiting for the lock. That has a little impact on your CPU, and reduces the number of threads available in the thread pool. An alternative would be to use SemaphoreSlim, and make the locking asynchronous:

```<code>public sealed class SerializedSingleton
{
    // This doesn't need to be static if the instance is a singleton
    private readonly SemaphoreSlim serializerLock = new SemaphoreSlim(1, 1);

    private static readonly Lazy<SerializedSingleton> lazy =
        new Lazy<SerializedSingleton>(() => new SerializedSingleton());

    public static SerializedSingleton Instance { get => lazy.Value; }

    public async Task SerializerAsync()
    {
        await serializerLock.WaitAsync();

        try
        {
            Console.WriteLine("Serializer START");
            await Task.Delay(2000);
            Console.WriteLine("Serializer STOP");
        }
        finally
        {
            serializerLock.Release();
        }
    }
}
</code>```

Title: Force Serial Singleton Function Lock

Body:
I'm wanting to run a parallel process using a thread-safe singleton for a portion of that process. I'm using COM Interop in the Singleton and can only have one instance running at a time system-wide.

The Singleton's operations cannot overlap. When a Singleton operation is called, there can't be any other singleton operations currently in-process..

I have a simplified, working example that using lock to ensure the singleton operation stay serialized across the multiple threads.

Would anyone recommend a more optimal solution than what I have currently OR is what I have implemented appropriate? Thank you.

Current working example-

internal class Program
{
    static void Main(string[] args)
    {
        Parallel.ForEach(Enumerable.Range(0, 10), i =>
        {
            if (i % 2 == 0)
                SerializedSingleton.Instance.Serializer(); // Serialized Operation Only
            else
                Thread.Sleep(100); // Concurrent Operations
        });
    }
}

public sealed class SerializedSingleton
{
    private static readonly object SerializerLock = new object();
    // THREAD-SAFE SINGLETON SETUP
    private static readonly Lazy<SerializedSingleton> lazy =
    new Lazy<SerializedSingleton>(() => new SerializedSingleton());
    public static SerializedSingleton Instance { get => lazy.Value; }
    private SerializedSingleton()
    {
    }
    public void Serializer()
    {
        lock (SerializerLock)
        {
            Console.WriteLine("Serializer START");
            Thread.Sleep(2000);
            Console.WriteLine("Serializer STOP");
        }
    }
}

Current Output (desired)-

Serializer START
Serializer STOP
Serializer START
Serializer STOP
Serializer START
Serializer STOP
Serializer START
Serializer STOP
Serializer START
Serializer STOP

Need to avoid-

Serializer START
Serializer START
Serializer START
Serializer START
Serializer START
Serializer STOP
Serializer STOP
Serializer STOP
Serializer STOP
Serializer STOP

Thead-safe singleton sourced from: https://csharpindepth.com/Articles/Singleton

Body:
Whenever you call lock (SerializerLock) and Thread.Sleep(..), you block the current thread. If there is high contention, you will have a lot of threads waiting for the lock. That has a little impact on your CPU, and reduces the number of threads available in the thread pool. An alternative would be to use SemaphoreSlim, and make the locking asynchronous:

public sealed class SerializedSingleton
{
    // This doesn't need to be static if the instance is a singleton
    private readonly SemaphoreSlim serializerLock = new SemaphoreSlim(1, 1);

    private static readonly Lazy<SerializedSingleton> lazy =
        new Lazy<SerializedSingleton>(() => new SerializedSingleton());

    public static SerializedSingleton Instance { get => lazy.Value; }

    public async Task SerializerAsync()
    {
        await serializerLock.WaitAsync();

        try
        {
            Console.WriteLine("Serializer START");
            await Task.Delay(2000);
            Console.WriteLine("Serializer STOP");
        }
        finally
        {
            serializerLock.Release();
        }
    }
}


问:
Is there a way to put the image just next to the paragraph using flex properties?
I tried setting justify-content to space-between as but that didn't work either.

The image just seems to come just below the paragraph.
But I want it to look like this.

Home.jsx

```<code>import '../App.css';
import './Home.css';
import pic from './portfolio-image.jpeg';
import React, { Component } from 'react';

function Home(){
    return(
        <div className='safe-area'>
            <div id = 'home-container'>

                <div id = 'home-text-container'>
                    <div id='home-head'>
                        Hi, I'm <Name>.
                    </div>

                    <div id = 'home-body'>
                        I am passionate about software and web development. I like solve interesting and new problems through my expertise in coding.
                        I like to work with React, Firebase, MongoDB, Express, Python and more.
                    </div>
                </div>

                <div id = 'image-social-container'>
                    <img src= {pic} />

                </div>

            </div>
        </div>
    );
}

export default Home;
</code>```

Home.css

```<code>#home-container{
    display: flex;
    flex-flow: row wrap;

    align-content: center;
    justify-content: space-between;

    height: 75vh;
    margin-left: 2cm;
    margin-right: 2cm;

    background-color: black;
}

#home-text-container{
    display: flex;
    flex-direction: column;

    width: 50%;
    line-height: 40px;
}

#home-head{
    font-family: 'Roboto', sans-serif;
    font-size: 210%;
    font-weight: 400;
    color: #b8fff1;
}

#home-body{
    font-family: 'Roboto', sans-serif;
    font-size: 140%;
    font-weight: 300;
    color: #b8fff1;
}

#image-social-container{
    display: flex;
    flex-direction: column;
}

#image-social-container img{
    width: 15%;
    border-radius: 10%;

    align-self: flex-end;
}
</code>```

答:
I'm not sure what exactly your layout goal is, but I'd start with taking out the width: 15%; line from your img styling. See this CodePen example I prepped for you.

A few CSS concerns:

Too many IDs. Consider replacing ids with classes. Actually, you could just rely on basic cascading rules to avoid unnecessary id/class pieces

Mixing different measurement units (e.g. cm, vh, %, and px): I'd suggest you understand what each measurement actually work before mixing and matching them. For instance, % value can mean a few different things depending on what it's used for and what the element's parent is.

Body:
I tried setting justify-content to space-between as but that didn't work either.

The image just seems to come just below the paragraph.
But I want it to look like this.

Home.jsx

import '../App.css';
import './Home.css';
import pic from './portfolio-image.jpeg';
import React, { Component } from 'react';

function Home(){
    return(

                        Hi, I'm <Name>.

                        I am passionate about software and web development. I like solve interesting and new problems through my expertise in coding.
                        I like to work with React, Firebase, MongoDB, Express, Python and more.

    );
}

export default Home;

Home.css

#home-container{
    display: flex;
    flex-flow: row wrap;

    align-content: center;
    justify-content: space-between;

    height: 75vh;
    margin-left: 2cm;
    margin-right: 2cm;

    background-color: black;
}

#home-text-container{
    display: flex;
    flex-direction: column;

    width: 50%;
    line-height: 40px;
}

#home-head{
    font-family: 'Roboto', sans-serif;
    font-size: 210%;
    font-weight: 400;
    color: #b8fff1;
}

#home-body{
    font-family: 'Roboto', sans-serif;
    font-size: 140%;
    font-weight: 300;
    color: #b8fff1;
}

#image-social-container{
    display: flex;
    flex-direction: column;
}

#image-social-container img{
    width: 15%;
    border-radius: 10%;

    align-self: flex-end;
}