问:
Why do two svg elements move with the same `transition` property behave differently?
In svg, I add transition: all 3s linear to both <rect> and <path>, and then click a button to make the <rect>
and <path> repeatedly and simultaneously move the same distance between two positions, but during the movement, why doesn't the relative distance between <rect> and <path> stay the same?

Browser: Chrome

Demo running with Chrome:

const svg = document.querySelector("#svg");
const path = svg.querySelector("path");
const rect = svg.querySelector("g");
const btn = document.querySelector("#btn");

const paths = [
  'M 29 12.6 h 30',
  'M 29 32.6 h 30',
]
const hs = [2, 22];
let i = 0;
btn.onclick = () => {
  path.setAttribute("d", paths[i]);
  rect.setAttribute("transform", `translate(0,${hs[i]})`);
  i ^= 1;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg * {
  transition: all 3s linear;
}</code>```

<svg id="svg" width="200" height="200" viewbox="0 -10 50 50">
  <path fill="none" stroke="#ff6699" d="M 29 12.6 h 30"></path>
  <g transform="translate(0,2)">
  <rect x="29" y="0" width="30" height="10"></rect>
  </g>
</svg>

<button id="btn">Click quickly and repeatedly</button>```

答:
Edit: The following answer only applies to the Firefox behavior, where transform is not animated. Chrome shows a different problem, and it seems that was what you asked about.

transition is a CSS property, but you try to animate presentation attributes. That seems to work for d (amazingly, in my opinion), but not for transform, where there is no transition and the value changes instantaneously.

While the spec tries to give the impression that presentation attributes and CSS properties are freely interchangable, in practice you get some rough edges again and again. I am not going to try to find out if what you tried to do is supposed to work according to spec. In my experience it is just sensible to stay on one side of the fence. So, if you try to animate something with the CSS transition property, that something should also be written as a CSS property.

Instead of transform="translate(0,2)", use style="transform:translate(0,2px)" - take care to add the px unit.

const svg = document.querySelector("#svg");
const path = svg.querySelector("path");
const rect = svg.querySelector("g");
const btn = document.querySelector("#btn");

const paths = [
  'M 29 12.6 h 30',
  'M 29 32.6 h 30',
]
const hs = [2, 22];
let i = 0;
btn.onclick = () => {
  path.setAttribute("d", paths[i]);
  rect.style.transform = `translate(0,${hs[i]}px)`;
  i ^= 1;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg * {
  transition: all 3s linear;
}</code>```

<svg id="svg" width="200" height="200" viewbox="0 -10 50 50">
  <path fill="none" stroke="#ff6699" d="M 29 12.6 h 30"></path>
  <g style="transform:translate(0,2px)">
  <rect x="29" y="0" width="30" height="10"></rect>
  </g>
</svg>

<button id="btn">Click quickly and repeatedly</button>```

Body:
In svg, I add transition: all 3s linear to both <rect> and <path>, and then click a button to make the <rect>
and <path> repeatedly and simultaneously move the same distance between two positions, but during the movement, why doesn't the relative distance between <rect> and <path> stay the same?

Browser: Chrome

Demo running with Chrome:

const svg = document.querySelector("#svg");
const path = svg.querySelector("path");
const rect = svg.querySelector("g");
const btn = document.querySelector("#btn");

const paths = [
  'M 29 12.6 h 30',
  'M 29 32.6 h 30',
]
const hs = [2, 22];
let i = 0;
btn.onclick = () => {
  path.setAttribute("d", paths[i]);
  rect.setAttribute("transform", `translate(0,${hs[i]})`);
  i ^= 1;
}

svg * {
  transition: all 3s linear;
}

<svg id="svg" width="200" height="200" viewbox="0 -10 50 50">
  <path fill="none" stroke="#ff6699" d="M 29 12.6 h 30"></path>
  <g transform="translate(0,2)">
  <rect x="29" y="0" width="30" height="10"></rect>
  </g>
</svg>

<button id="btn">Click quickly and repeatedly</button>

Body:
Edit: The following answer only applies to the Firefox behavior, where transform is not animated. Chrome shows a different problem, and it seems that was what you asked about.

transition is a CSS property, but you try to animate presentation attributes. That seems to work for d (amazingly, in my opinion), but not for transform, where there is no transition and the value changes instantaneously.

While the spec tries to give the impression that presentation attributes and CSS properties are freely interchangable, in practice you get some rough edges again and again. I am not going to try to find out if what you tried to do is supposed to work according to spec. In my experience it is just sensible to stay on one side of the fence. So, if you try to animate something with the CSS transition property, that something should also be written as a CSS property.

Instead of transform="translate(0,2)", use style="transform:translate(0,2px)" - take care to add the px unit.

const svg = document.querySelector("#svg");
const path = svg.querySelector("path");
const rect = svg.querySelector("g");
const btn = document.querySelector("#btn");

const paths = [
  'M 29 12.6 h 30',
  'M 29 32.6 h 30',
]
const hs = [2, 22];
let i = 0;
btn.onclick = () => {
  path.setAttribute("d", paths[i]);
  rect.style.transform = `translate(0,${hs[i]}px)`;
  i ^= 1;
}

svg * {
  transition: all 3s linear;
}

<svg id="svg" width="200" height="200" viewbox="0 -10 50 50">
  <path fill="none" stroke="#ff6699" d="M 29 12.6 h 30"></path>
  <g style="transform:translate(0,2px)">
  <rect x="29" y="0" width="30" height="10"></rect>
  </g>
</svg>
<br>
<button id="btn">Click quickly and repeatedly</button>


来源: stackexchange

问:
How to get key value pairs of the objects from complex JSON using jq and map? (Active Campaign)
I have following JSON. I want to get key-value pair objects based on their role. In this example there are 3 roles(Presenter, Approver, Customer) but there can be more as it is dynamic.

JSON

{
   "Presenter Name": "Roney",
   "Presenter Email": "roney@domain.com",
   "Approver Name": "Tim",
   "Approver Email": "tim@domain.com",
   "Customer Name": "Alex",
   "Customer Email": "alex@domain.com",
   "Invoice": "001",
   "Date": "2022-02-14"
}
```
<p>Expected output using jq, map,</p>
<pre class="lang-json prettyprint-override"><code>{
    "Presenter": {
      "email_address": "roney@domain.com",
      "name": "Roney",
      "role": "Presenter"
    },
    "Approver": {
      "email_address": "tim@domain.com",
      "name": "Tim",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "name": "Alex",
      "role": "Customer"
    }
}
</code>```

I have tried till following but didn't get what to do next. Please advice.

to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add

答:
This splits the keys at the space character while discarding any items that don't have one in it. Then it assigns the three fields to their values accordingly, using reduce to combine the grouping.

```<code>to_entries
| map(.key |= split(" ") | select(.key[1]))
| reduce group_by(.key[0])[] as $g ({};
    .[$g[0].key[0]] = (
      INDEX($g[]; .key[1]) | {
        email_address: .Email.value,
        name: .Name.value,
        role: .Name.key[0]
      }
    )
  )
</code>```

{
  "Approver": {
    "email_address": "tim@domain.com",
    "name": "Tim",
    "role": "Approver"
  },
  "Customer": {
    "email_address": "alex@domain.com",
    "name": "Alex",
    "role": "Customer"
  },
  "Presenter": {
    "email_address": "roney@domain.com",
    "name": "Roney",
    "role": "Presenter"
  }
}
```

Demo

ContentLicense: CC BY-SA 4.0

Body:
I have following JSON. I want to get key-value pair objects based on their role. In this example there are 3 roles(Presenter, Approver, Customer) but there can be more as it is dynamic.

JSON

{
   "Presenter Name": "Roney",
   "Presenter Email": "roney@domain.com",
   "Approver Name": "Tim",
   "Approver Email": "tim@domain.com",
   "Customer Name": "Alex",
   "Customer Email": "alex@domain.com",
   "Invoice": "001",
   "Date": "2022-02-14"
}

Expected output using jq, map,

{
    "Presenter": {
      "email_address": "roney@domain.com",
      "name": "Roney",
      "role": "Presenter"
    },
    "Approver": {
      "email_address": "tim@domain.com",
      "name": "Tim",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "name": "Alex",
      "role": "Customer"
    }
}

I have tried till following but didn't get what to do next. Please advice.

to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add

Body:
This splits the keys at the space character while discarding any items that don't have one in it. Then it assigns the three fields to their values accordingly, using reduce to combine the grouping.

to_entries
| map(.key |= split(" ") | select(.key[1]))
| reduce group_by(.key[0])[] as $g ({};
    .[$g[0].key[0]] = (
      INDEX($g[]; .key[1]) | {
        email_address: .Email.value,
        name: .Name.value,
        role: .Name.key[0]
      }
    )
  )

{
  "Approver": {
    "email_address": "tim@domain.com",
    "name": "Tim",
    "role": "Approver"
  },
  "Customer": {
    "email_address": "alex@domain.com",
    "name": "Alex",
    "role": "Customer"
  },
  "Presenter": {
    "email_address": "roney@domain.com",
    "name": "Roney",
    "role": "Presenter"
  }
}

Demo


问:
how to change confige react-mui-draft-wysiwyg?
I use HTML editor material ui :

```<code>import MUIEditor, { MUIEditorState } from "react-mui-draft-wysiwyg";

 <MUIEditor
    editorState={formElement.editorState}
    onChange={formElement.onChange}
  />
</code>```

I want to remove the font color button in the toolbar. When I go to the MUIEditor file at node-modules and I want to make some changes to that file but it does not seem to change even when I get a console I can not see the result. What should I do?

```<code> .node_modules
        .react-mui-draft-wysiwyg
           .dist
             .index.js
</code>```

答:
It is rarely advisable to edit the contents of /node_modules -- instead react-mui-draft-wysiwyg provides direct a way to customize the toolbar configuration through the config prop, in your own React code.

In your case, to hide the font color button, you simply need to pass in the menu options that you would like to display. (ie. remove/comment out the toolbarControlTypes.fontColor option). For example:

```<code>    import MUIEditor, {
      MUIEditorState,
      toolbarControlTypes // Added toolbarControlTypes
    } from "react-mui-draft-wysiwyg";

...

    <MUIEditor
      editorState={editorState}
      onChange={onChange}
      config={{
        toolbar: {
          controls: [
            toolbarControlTypes.undo,
            toolbarControlTypes.redo,
            toolbarControlTypes.divider,
            toolbarControlTypes.bold,
            toolbarControlTypes.italic,
            toolbarControlTypes.underline,
            toolbarControlTypes.strikethrough,
            // Include all of the default toolbar options except for fontColor
            // toolbarControlTypes.fontColor,
            toolbarControlTypes.fontBackgroundColor,
            toolbarControlTypes.divider,
            toolbarControlTypes.linkAdd,
            toolbarControlTypes.linkRemove,
            toolbarControlTypes.image,
            toolbarControlTypes.divider,
            toolbarControlTypes.blockType,
            toolbarControlTypes.fontSize,
            toolbarControlTypes.fontFamily,
            toolbarControlTypes.textAlign,
            toolbarControlTypes.divider,
            toolbarControlTypes.unorderedList,
            toolbarControlTypes.orderedList
          ]
        }
      }}
    />

</code>```

Documentation: Default Configuration Options

Working CodeSandbox: https://codesandbox.io/s/mui4-draft-wysiwyg-bre8e?file=/demo.js

Body:
I use HTML editor material ui :

import MUIEditor, { MUIEditorState } from "react-mui-draft-wysiwyg";

 <MUIEditor
    editorState={formElement.editorState}
    onChange={formElement.onChange}
  />

I want to remove the font color button in the toolbar. When I go to the MUIEditor file at node-modules and I want to make some changes to that file but it does not seem to change even when I get a console I can not see the result. What should I do?

 .node_modules
        .react-mui-draft-wysiwyg
           .dist
             .index.js

Body:
It is rarely advisable to edit the contents of /node_modules -- instead react-mui-draft-wysiwyg provides direct a way to customize the toolbar configuration through the config prop, in your own React code.

In your case, to hide the font color button, you simply need to pass in the menu options that you would like to display. (ie. remove/comment out the toolbarControlTypes.fontColor option). For example:

    import MUIEditor, {
      MUIEditorState,
      toolbarControlTypes // Added toolbarControlTypes
    } from "react-mui-draft-wysiwyg";

...

    <MUIEditor
      editorState={editorState}
      onChange={onChange}
      config={{
        toolbar: {
          controls: [
            toolbarControlTypes.undo,
            toolbarControlTypes.redo,
            toolbarControlTypes.divider,
            toolbarControlTypes.bold,
            toolbarControlTypes.italic,
            toolbarControlTypes.underline,
            toolbarControlTypes.strikethrough,
            // Include all of the default toolbar options except for fontColor
            // toolbarControlTypes.fontColor,
            toolbarControlTypes.fontBackgroundColor,
            toolbarControlTypes.divider,
            toolbarControlTypes.linkAdd,
            toolbarControlTypes.linkRemove,
            toolbarControlTypes.image,
            toolbarControlTypes.divider,
            toolbarControlTypes.blockType,
            toolbarControlTypes.fontSize,
            toolbarControlTypes.fontFamily,
            toolbarControlTypes.textAlign,
            toolbarControlTypes.divider,
            toolbarControlTypes.unorderedList,
            toolbarControlTypes.orderedList
          ]
        }
      }}
    />

Documentation: Default Configuration Options

Working CodeSandbox: https://codesandbox.io/s/mui4-draft-wysiwyg-bre8e?file=/demo.js


问:
Adding string to a string before some certain characters?
```<code>myString = '(247, 246, 244), (13, 23, 24), (85, 101, 100)'

substring = 'rgb'
</code>```

I want to add this string the substring above, before every '(' character. So that it would be look like this below.

myString = 'rgb(247, 246, 244), rgb(13, 23, 24), rgb(85, 101, 100)'

答:
Just showing full implementation of Jasonharper's, where you change how you define your sub-string and replace the opening parenthesis:</p>
```<code>myString = '(247, 246, 244), (13, 23, 24), (85, 101, 100)'
substring = 'rgb('
myString.replace("(", substring)
</code>```

Body:
myString = '(247, 246, 244), (13, 23, 24), (85, 101, 100)'

substring = 'rgb'

I want to add this string the substring above, before every '(' character. So that it would be look like this below.

myString = 'rgb(247, 246, 244), rgb(13, 23, 24), rgb(85, 101, 100)'

Body:
Just showing full implementation of Jasonharper's, where you change how you define your sub-string and replace the opening parenthesis:

myString = '(247, 246, 244), (13, 23, 24), (85, 101, 100)'
substring = 'rgb('
myString.replace("(", substring)


问:
Using aws chalice to build a single page application?
Has anyone here ever worked with chalice?  Its an aws tool for creating api's.  I want to use it to create a single page application, but Im not sure how to actually serve html from it.  I've seen videos where its explored, but I can't figure out how they actually built the thing.  Anyone have any advice on where to go, how to start this?</p>

答:
Add Response from Chalice and the use it to set the response headers and you're g2g.

```<code>from chalice import Chalice, Response
</code>```
```<code>return Response(template, status_code=200, headers={"Content-Type": "text/html", "Access-Control-Allow-Origin": "*"})
</code>```

I read about it here;

https://medium.com/@tim_33529/creating-a-serverless-blog-with-chalice-bdc39b835f75

ContentLicense: CC BY-SA 3.0

Body:
Add Response from Chalice and the use it to set the response headers and you're g2g.

from chalice import Chalice, Response

return Response(template, status_code=200, headers={"Content-Type": "text/html", "Access-Control-Allow-Origin": "*"})

I read about it here;

https://medium.com/@tim_33529/creating-a-serverless-blog-with-chalice-bdc39b835f75


问:
How to output formated text but with added values - Python
I am new to Python and I can´t find any way to execute this code.

I am using JSON generator and need to print formated code and add some changes to it. I have variables that have some values and I need to insert them into my code. So the final code will have exact formating but with added values.

hp = 50;
cp = 100;
wp = 40;

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "<hp (value of hp here)>",
        "Combat Power": "<cp (value of cp here)>",
        "Working Power": "<wp (value of wp here)>",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }```
</div>
</div>
</p>
<p>Final output (I want to generate 100 of this same code with exact formating but with different hp wp and cp values.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "50",
        "Combat Power": "100",
        "Working Power": "40",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }</code>```

答:
I am not sure if I understand you correctly, but first you need to know what kind of formatting you need, for example how many spaces you want to indent.

Code

json.dumps accept an indent as an argument to format your json output.

import json

hp = 50;
cp = 100;
wp = 40;

data = {
    "721": {
        "<policy_id>": {
            "<asset_name>": {
                "name": "<display_name>",
                "image": "<ipfs_link>",
                "mediaType": "<mime_type>",
                "description": "<description>",
                "Visual": "<rarity>",
                "Health Points": "<hp (value of hp here)>",
                "Combat Power": "<cp (value of cp here)>",
                "Working Power": "<wp (value of wp here)>",
                "files": [
                    {
                    "name": "<display_name>",
                    "mediaType": "<mime_type>",
                    "src": "<ipfs_link>"
                    }
                ]
            }
        }
    }
}

data["721"]["<policy_id>"]["<asset_name>"]["Health Points"] = hp
data["721"]["<policy_id>"]["<asset_name>"]["Combat Power"] = cp
data["721"]["<policy_id>"]["<asset_name>"]["Working Power"] = wp

# Use indent=2 if you prefer less space
print(json.dumps(data, indent=4))
```
<p><strong>Output</strong></p>
<pre class="lang-json prettyprint-override"><code>{
    "721": {
        "<policy_id>": {
            "<asset_name>": {
                "name": "<display_name>",
                "image": "<ipfs_link>",
                "mediaType": "<mime_type>",
                "description": "<description>",
                "Visual": "<rarity>",
                "Health Points": 50,
                "Combat Power": 100,
                "Working Power": 40,
                "files": [
                    {
                        "name": "<display_name>",
                        "mediaType": "<mime_type>",
                        "src": "<ipfs_link>"
                    }
                ]
            }
        }
    }
}
</code>```

If you are loading the JSON from a file or as a string, then you can use the json.load or json.loads methods.

Body:
I am new to Python and I can´t find any way to execute this code.

I am using JSON generator and need to print formated code and add some changes to it. I have variables that have some values and I need to insert them into my code. So the final code will have exact formating but with added values.

hp = 50;
cp = 100;
wp = 40;

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "<hp (value of hp here)>",
        "Combat Power": "<cp (value of cp here)>",
        "Working Power": "<wp (value of wp here)>",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }

Final output (I want to generate 100 of this same code with exact formating but with different hp wp and cp values.

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "50",
        "Combat Power": "100",
        "Working Power": "40",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }

Body:
I am not sure if I understand you correctly, but first you need to know what kind of formatting you need, for example how many spaces you want to indent.

Code

json.dumps accept an indent as an argument to format your json output.

import json

hp = 50;
cp = 100;
wp = 40;

data = {
    "721": {
        "<policy_id>": {
            "<asset_name>": {
                "name": "<display_name>",
                "image": "<ipfs_link>",
                "mediaType": "<mime_type>",
                "description": "<description>",
                "Visual": "<rarity>",
                "Health Points": "<hp (value of hp here)>",
                "Combat Power": "<cp (value of cp here)>",
                "Working Power": "<wp (value of wp here)>",
                "files": [
                    {
                    "name": "<display_name>",
                    "mediaType": "<mime_type>",
                    "src": "<ipfs_link>"
                    }
                ]
            }
        }
    }
}

data["721"]["<policy_id>"]["<asset_name>"]["Health Points"] = hp
data["721"]["<policy_id>"]["<asset_name>"]["Combat Power"] = cp
data["721"]["<policy_id>"]["<asset_name>"]["Working Power"] = wp

# Use indent=2 if you prefer less space
print(json.dumps(data, indent=4))

Output

{
    "721": {
        "<policy_id>": {
            "<asset_name>": {
                "name": "<display_name>",
                "image": "<ipfs_link>",
                "mediaType": "<mime_type>",
                "description": "<description>",
                "Visual": "<rarity>",
                "Health Points": 50,
                "Combat Power": 100,
                "Working Power": 40,
                "files": [
                    {
                        "name": "<display_name>",
                        "mediaType": "<mime_type>",
                        "src": "<ipfs_link>"
                    }
                ]
            }
        }
    }
}

If you are loading the JSON from a file or as a string, then you can use the json.load or json.loads methods.


问:
How can I get the user's IP-Address in my Cloud-Run Flask app?
I have a Flask app running via Google Cloud Run and I need to know the user's IP-Address.
I am using gunicorn as my Server.
I have tried the following code:

```<code>request.remote_addr
request.environ['REMOTE_ADDR']
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
</code>```

It is returning this IP-Address: 169.254.8.129 which is not mine.
Is this maybe the IP of a Load-Balancer between the app and the user?

And is there a way to get the correct IP-Address without having to use additional Services?

答:
I am running my service in Google App Engine, and did not get any of the above working, but this did work.</p>
```<code>ip = request.headers['X-Appengine-User-Ip']
</code>```

Body:
I have a Flask app running via Google Cloud Run and I need to know the user's IP-Address.
I am using gunicorn as my Server.
I have tried the following code:

request.remote_addr
request.environ['REMOTE_ADDR']
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)

It is returning this IP-Address: 169.254.8.129 which is not mine.
Is this maybe the IP of a Load-Balancer between the app and the user?

And is there a way to get the correct IP-Address without having to use additional Services?

Body:
I am running my service in Google App Engine, and did not get any of the above working, but this did work.

ip = request.headers['X-Appengine-User-Ip']


问:
is there any free barcode reader sdk for Windows Phone 7?
I am developing windows mobile application to scan a product barcode by using in built camera. Can you tell me something about barcode reader sdk which are supporting windows mobile 7?</p>

答:
In Windows Phone 7, with the upcoming Mango update, there will be direct access to the camera feed, without having to take a picture of the barcode.  Prior to Mango, there is a library that can be downloaded from Codeplex, called ZXIng (Zebra Crossing).  http://silverlightzxing.codeplex.com/

Are you developing for Windows Phone, or Windows Mobile?  There is no Windows Mobile 7 - with the complete rewrite, the name changed to Windows Phone.


问:
@SQSListener not using concurrency settings
I'm building a Spring Boot application that consumes an AWS SQS queue.  I'm able to consume the queue, however I can't seem to do so with multiple concurrent consumers.

When running from the command line mvn spring-boot:run, it connects to the SQS and will receive the messages one at a time.  The listener method has additional code which causes a several second delay, during which I would expect the second message to be received and processed.

It's as if the configuration isn't being used.

pom.xml:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.SR1</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-aws</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-aws-messaging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.419</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-aws</artifactId>
            <version>2.0.0.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

main class:

```<code>@SpringBootApplication
public class IngestConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(IngestConsumerApplication.class, args);
    }
}
</code>```

Configuration class:

```<code>@Configuration
public class AppConfig {

@Value("${aws.region}")
private String region;

@Bean
@Primary
public AWSCredentialsProvider buildAWSCredentialsProvider() {
    return new ProfileCredentialsProvider();
}

@Bean
@Primary
public AmazonS3 buildS3Client(@Autowired AWSCredentialsProvider credentials) {
    return AmazonS3ClientBuilder
            .standard()
            .withCredentials(credentials)
            .withRegion(region)
            .build();
}

@Bean
@Primary
public AmazonSQSAsync amazonSQSAsync(@Autowired AWSCredentialsProvider credentials) {
    return AmazonSQSAsyncClientBuilder.standard()
            .withCredentials(credentials)
            .withRegion(region)
            .build();
}

@Bean
public QueueMessageHandler queueMessageHandler(@Autowired AmazonSQSAsync sqsClient, @Autowired QueueMessageHandlerFactory queueMessageHandlerFactory) {
    queueMessageHandlerFactory.setAmazonSqs(sqsClient);
    QueueMessageHandler queueMessageHandler = queueMessageHandlerFactory.createQueueMessageHandler();
    return queueMessageHandler;
}

@Bean
public ObjectMapper buildJacksonObjectMapper() {
    return new ObjectMapper();
}

@Bean
public QueueMessageHandlerFactory queueMessageHandlerFactory() {
    QueueMessageHandlerFactory factory = new QueueMessageHandlerFactory();
    MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter();

    //set strict content type match to false
    messageConverter.setStrictContentTypeMatch(false);
    factory.setArgumentResolvers(Collections.<HandlerMethodArgumentResolver>singletonList(new PayloadArgumentResolver(messageConverter)));
    return factory;
}

@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer(@Autowired AmazonSQSAsync amazonSQSAsync,
        @Autowired QueueMessageHandler queueMessageHandler,
        @Autowired ThreadPoolTaskExecutor threadPoolExecutor) {
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
    simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync);
    simpleMessageListenerContainer.setMessageHandler(queueMessageHandler);
    simpleMessageListenerContainer.setMaxNumberOfMessages(2);
    simpleMessageListenerContainer.setTaskExecutor(threadPoolExecutor);

    return simpleMessageListenerContainer;
}

@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setThreadNamePrefix("queueExec");
    executor.initialize();
    return executor;
}

}
</code>```

An finally, the consumer:

```<code>@Async
@SqsListener(deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS, value = "${queue}")
public void listener(S3EventNotification event) {
    ...
}
</code>```

答:
Remove the @Async tag off the @SqsListner tagged method for starters. I do not believe that will give you anything as the second tag is evaluated at runtime by a different process and probably doesn't get the proxy object that facilitates the Async anyways.

Also "simpleMessageListenerContainer.setMaxNumberOfMessages(2);" is how many messages you can pull back in a single poll of SQS. The max is 10. But this isn't concurrency however it DOES give the process more messages to call more listener instances. So that value would better facilitate concurrency but not guarantee it.

Body:
I'm building a Spring Boot application that consumes an AWS SQS queue.  I'm able to consume the queue, however I can't seem to do so with multiple concurrent consumers.

When running from the command line mvn spring-boot:run, it connects to the SQS and will receive the messages one at a time.  The listener method has additional code which causes a several second delay, during which I would expect the second message to be received and processed.

It's as if the configuration isn't being used.

pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.SR1</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-aws</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-aws-messaging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.419</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-aws</artifactId>
            <version>2.0.0.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

main class:

@SpringBootApplication
public class IngestConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(IngestConsumerApplication.class, args);
    }
}

Configuration class:

@Configuration
public class AppConfig {

@Value("${aws.region}")
private String region;

@Bean
@Primary
public AWSCredentialsProvider buildAWSCredentialsProvider() {
    return new ProfileCredentialsProvider();
}

@Bean
@Primary
public AmazonS3 buildS3Client(@Autowired AWSCredentialsProvider credentials) {
    return AmazonS3ClientBuilder
            .standard()
            .withCredentials(credentials)
            .withRegion(region)
            .build();
}

@Bean
@Primary
public AmazonSQSAsync amazonSQSAsync(@Autowired AWSCredentialsProvider credentials) {
    return AmazonSQSAsyncClientBuilder.standard()
            .withCredentials(credentials)
            .withRegion(region)
            .build();
}

@Bean
public QueueMessageHandler queueMessageHandler(@Autowired AmazonSQSAsync sqsClient, @Autowired QueueMessageHandlerFactory queueMessageHandlerFactory) {
    queueMessageHandlerFactory.setAmazonSqs(sqsClient);
    QueueMessageHandler queueMessageHandler = queueMessageHandlerFactory.createQueueMessageHandler();
    return queueMessageHandler;
}

@Bean
public ObjectMapper buildJacksonObjectMapper() {
    return new ObjectMapper();
}

@Bean
public QueueMessageHandlerFactory queueMessageHandlerFactory() {
    QueueMessageHandlerFactory factory = new QueueMessageHandlerFactory();
    MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter();

    //set strict content type match to false
    messageConverter.setStrictContentTypeMatch(false);
    factory.setArgumentResolvers(Collections.<HandlerMethodArgumentResolver>singletonList(new PayloadArgumentResolver(messageConverter)));
    return factory;
}

@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer(@Autowired AmazonSQSAsync amazonSQSAsync,
        @Autowired QueueMessageHandler queueMessageHandler,
        @Autowired ThreadPoolTaskExecutor threadPoolExecutor) {
    SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer();
    simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync);
    simpleMessageListenerContainer.setMessageHandler(queueMessageHandler);
    simpleMessageListenerContainer.setMaxNumberOfMessages(2);
    simpleMessageListenerContainer.setTaskExecutor(threadPoolExecutor);

    return simpleMessageListenerContainer;
}

@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setThreadNamePrefix("queueExec");
    executor.initialize();
    return executor;
}

}

An finally, the consumer:

@Async
@SqsListener(deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS, value = "${queue}")
public void listener(S3EventNotification event) {
    ...
}


问:
understanding the concept of amounts with regex
I am aware that regex does not work with numeric values,  yet, how can we have a regex pattern to differentiate between numbers in a google sheets formula?

for example: >=13 and <13

A
B

desired result

5
5♥

2
2♥

13
13♦♦♦

12
12♥

30
30♦♦♦

17
17♦♦♦

0
0♥

-4
-4♥

-12
-12♥

22
22♦♦♦

-55
-55♥

31
31♦♦♦

-13
-13♥

-31
-31♥

I can solve this in alternative ways like:

```<code>=INDEX(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE("" & A2:A16,
 "\b(^" & JOIN("$|^", SEQUENCE(13, 1, )) & "$)\b", "$1♥"),
 "(^-\d+)", "$1♥"),
 "(\d+$)", "$1♦♦♦"))
</code>```

...but I feel there could be some more "regexy" solution.

rules of combat:

regex pattern

no IF-statements

>=13 add ♦♦♦

<13 add ♥

no IFERROR pivots

no non-regex solutions

Body:
I am aware that regex does not work with numeric values,  yet, how can we have a regex pattern to differentiate between numbers in a google sheets formula?

for example: >=13 and <13

A
B

desired result

5
5♥

2
2♥

13
13♦♦♦

12
12♥

30
30♦♦♦

17
17♦♦♦

0
0♥

-4
-4♥

-12
-12♥

22
22♦♦♦

-55
-55♥

31
31♦♦♦

-13
-13♥

-31
-31♥

I can solve this in alternative ways like:

=INDEX(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE("" & A2:A16,
 "\b(^" & JOIN("$|^", SEQUENCE(13, 1, )) & "$)\b", "$1♥"),
 "(^-\d+)", "$1♥"),
 "(\d+$)", "$1♦♦♦"))

...but I feel there could be some more "regexy" solution.

rules of combat:

regex pattern

no IF-statements

>=13 add ♦♦♦

<13 add ♥

no IFERROR pivots

no non-regex solutions

Body:
Try:

=REGEXREPLACE(REGEXREPLACE(TO_TEXT(A1), "^(-\d+|[0-9]|1[0-2])$", "$1♥"), "^([^♥]+)$", "$1♦♦♦")


问:
React native jest.preset.js file missing error
I use @testing-library/react-native to test my RN app. When I run yarn test, following error occurs.

```<code>@testing-library/react-native should have "jest-preset.js" or "jest-preset.json" file at the root.
</code>```

I use typescript for my app.

my test script is like this.

```<code>test": "jest --config jest.config.json"
</code>```

jest.config.json file is like this.

```<code>{
  "preset": "@testing-library/react-native",
  "collectCoverageFrom": ["src/**/*.{ts,tsx}"],
  "moduleDirectories": ["node_modules", "src"],
  "setupFiles": [
    "<rootDir>/jestSetup/setup.js",
    "./node_modules/react-native-gesture-handler/jestSetup.js"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?(react-native|@?react-navigation|@react-native-community))"
  ],
  "coveragePathIgnorePatterns": ["/node_modules/", "/jestSetup", "/src/config.ts", "/src/app.tsx"]
}
</code>```

Why am I getting this error?

答:
For those seeing this in a fully up to date project, the missing file is [./node_modules/]react-native/jest-preset.js and you need to make sure that react-native itself is installed.

This will happen if you don't have react-native install globally.

yarn add react-native (or do it globally)

so in package.json you should see something like:

```<code>    "react-native": "0.66.3",
</code>```

Body:
I use @testing-library/react-native to test my RN app. When I run yarn test, following error occurs.

@testing-library/react-native should have "jest-preset.js" or "jest-preset.json" file at the root.

I use typescript for my app.

my test script is like this.

test": "jest --config jest.config.json"

jest.config.json file is like this.

{
  "preset": "@testing-library/react-native",
  "collectCoverageFrom": ["src/**/*.{ts,tsx}"],
  "moduleDirectories": ["node_modules", "src"],
  "setupFiles": [
    "<rootDir>/jestSetup/setup.js",
    "./node_modules/react-native-gesture-handler/jestSetup.js"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?(react-native|@?react-navigation|@react-native-community))"
  ],
  "coveragePathIgnorePatterns": ["/node_modules/", "/jestSetup", "/src/config.ts", "/src/app.tsx"]
}

Why am I getting this error?

Body:
For those seeing this in a fully up to date project, the missing file is [./node_modules/]react-native/jest-preset.js and you need to make sure that react-native itself is installed.

This will happen if you don't have react-native install globally.

yarn add react-native (or do it globally)

so in package.json you should see something like:

    "react-native": "0.66.3",


问:
Replace only leading NaN values in Pandas dataframe
I have a dataframe of time series data, in which data reporting starts at different times (columns) for different observation units (rows). Prior to first reported datapoint for each unit, the dataframe contains NaN values, e.g.

```<code>    0   1   2   3   4 ...
A   NaN NaN 4   5   6 ...
B   NaN 7   8   NaN 10...
C   NaN 2   11  24  17...
</code>```

I want to replace the leading (left-side) NaN values with 0, but only the leading ones (i.e. leaving the internal missing ones as NaN. So the result on the example above would be:

```<code>    0   1   2   3   4 ...
A   0   0   4   5   6 ...
B   0   7   8   NaN 10...
C   0   2   11  24  17...
</code>```

(Note the retained NaN for row B col 3)

I could iterate through the dataframe row-by-row, identify the first index of a non-NaN value in each row, and replace everything left of that with 0. But is there a way to do this as a whole-array operation?

答:
Here is another way using cumprod() and apply()

```<code>s = df.isna().cumprod(axis=1).sum(axis=1)
df.apply(lambda x: x.fillna(0,limit = s.loc[x.name]),axis=1)
</code>```

Output:

```<code>     0    1     2     3     4
A  0.0  0.0   4.0   5.0   6.0
B  0.0  7.0   8.0   NaN  10.0
C  0.0  2.0  11.0  24.0  17.0
</code>```

Body:
I have a dataframe of time series data, in which data reporting starts at different times (columns) for different observation units (rows). Prior to first reported datapoint for each unit, the dataframe contains NaN values, e.g.

    0   1   2   3   4 ...
A   NaN NaN 4   5   6 ...
B   NaN 7   8   NaN 10...
C   NaN 2   11  24  17...

I want to replace the leading (left-side) NaN values with 0, but only the leading ones (i.e. leaving the internal missing ones as NaN. So the result on the example above would be:

    0   1   2   3   4 ...
A   0   0   4   5   6 ...
B   0   7   8   NaN 10...
C   0   2   11  24  17...

(Note the retained NaN for row B col 3)

I could iterate through the dataframe row-by-row, identify the first index of a non-NaN value in each row, and replace everything left of that with 0. But is there a way to do this as a whole-array operation?

Body:
Here is another way using cumprod() and apply()

s = df.isna().cumprod(axis=1).sum(axis=1)
df.apply(lambda x: x.fillna(0,limit = s.loc[x.name]),axis=1)

Output:

     0    1     2     3     4
A  0.0  0.0   4.0   5.0   6.0
B  0.0  7.0   8.0   NaN  10.0
C  0.0  2.0  11.0  24.0  17.0


问:
Get IP address of visitors using Flask for Python
I'm making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).

I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this? Surely there is a way to do it with Python?

答:
I did not get any of the above work with Google Cloud App Engine. This worked, however

```<code>ip = request.headers['X-Appengine-User-Ip']
</code>```

The proposed request.remote_addr did only return local host ip every time.

Body:
I did not get any of the above work with Google Cloud App Engine. This worked, however

ip = request.headers['X-Appengine-User-Ip']

The proposed request.remote_addr did only return local host ip every time.


问:
Compile-time ceiling function, for literals, in C?
I have a C program which involves some floating-point literal that's defined by a macro. And - it just so happens that in a performance-critical part of the code, I need the ceiling of that floating-point number, as an integer (say, an int). Now, if it were an actual literal, then I would just manually take the ceiling and be done with it. But since it's a macro, I can't do that.

Naturally, ceilf(MY_DOUBLE_LITERAL) works, but - it's expensive. (int)(MY_DOUBLE_LITERAL) + 1 will also work... except if the literal is itself an integer, in which case it will be wrong.

So, is there some way - preprocessor macros are fine - to obtain the ceiling of MY_DOUBLE_LITERAL, or alternatively to determine whether it is an integer or not?

Notes:

I cannot perform the ceil() before the performance-critical part of the code, due to constraints I won't go into. Naturally if one can move computation outside of the performance-critical part or loop, that's always best, and thanks goes to @SpyrosK for mentioning that.

C99 preferred.

You may assume the literal is a double, i.e. a decimal number like 123.4 or an exponential-notation like 1.23e4.

答:
A solution could be to statically store the rounded float macro literal in a const variable outside the critical part of the code and use the precomputed int const value in the critical part.
This will work as long as the float returned by the macro is always the same value.</p>


问:
"Temporary value dropped while borrowed" when using string.replace()
Can someone explain which exact temporary value is dropped and what the recommended way to do this operation is?</p>
```<code>fn main() {
    let mut a = &mut String::from("Hello Ownership");
    a = &mut a.replace("Ownership", "World");
    println!("a is {}", a);
}
</code>```

答:
Aha, figured it out!

https://doc.rust-lang.org/nightly/error-index.html#E0716 says:

Temporaries are not always dropped at the end of the enclosing statement. In simple cases where the & expression is immediately stored into a variable, the compiler will automatically extend the lifetime of the temporary until the end of the enclosing block. Therefore, an alternative way to fix the original program is to write let tmp = &foo() and not let tmp = foo():

fn foo() -> i32 { 22 }
fn bar(x: &i32) -> &i32 { x }
let value = &foo();
let p = bar(value);
let q = *p;
```
<p>Here, we are still borrowing foo(), but as the borrow is assigned directly into a variable, the temporary will not be dropped until the end of the enclosing block. Similar rules apply when temporaries are stored into aggregate structures like a tuple or struct:</p>
<pre class="lang-rust prettyprint-override"><code>// Here, two temporaries are created, but
// as they are stored directly into `value`,
// they are not dropped until the end of the
// enclosing block.
fn foo() -> i32 { 22 }
let value = (&foo(), &foo());
</code>```

Body:
Can someone explain which exact temporary value is dropped and what the recommended way to do this operation is?

fn main() {
    let mut a = &mut String::from("Hello Ownership");
    a = &mut a.replace("Ownership", "World");
    println!("a is {}", a);
}

Body:
Aha, figured it out!

https://doc.rust-lang.org/nightly/error-index.html#E0716 says:

Temporaries are not always dropped at the end of the enclosing statement. In simple cases where the & expression is immediately stored into a variable, the compiler will automatically extend the lifetime of the temporary until the end of the enclosing block. Therefore, an alternative way to fix the original program is to write let tmp = &foo() and not let tmp = foo():

fn foo() -> i32 { 22 }
fn bar(x: &i32) -> &i32 { x }
let value = &foo();
let p = bar(value);
let q = *p;

Here, we are still borrowing foo(), but as the borrow is assigned directly into a variable, the temporary will not be dropped until the end of the enclosing block. Similar rules apply when temporaries are stored into aggregate structures like a tuple or struct:

// Here, two temporaries are created, but
// as they are stored directly into `value`,
// they are not dropped until the end of the
// enclosing block.
fn foo() -> i32 { 22 }
let value = (&foo(), &foo());


问:
How to include ManyToMany Fields in DjangoRestFramework?
```<code>class EntityServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields =  '__all__'

class EntityCreateSerializer(serializers.ModelSerializer):
    entity_service = EntityServiceSerializerThrough(read_only=True, source='serviceschedule_set', many=True)

        class Meta:
        model = Entity
        fields = '__all__'
</code>```

Model looks like this

```<code>class Entity(models.Model):
    entity_service = models.ManyToManyField(Service, through='ServiceSchedule')

class ServiceSchedule(models.Model):
    service = models.ForeignKey(Service, on_delete=models.CASCADE)
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)

class Service(models.Model):
    service_name = models.CharField(max_length=256, null=True)
    slug = models.SlugField(max_length=128, unique=True, null=False, editable=False)
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    animal = models.ForeignKey(Animal, on_delete=models.CASCADE, default=None)
</code>```

I have these serializers (there are more fields in entity model, but they're irrelevant since the only problem i have is with the Many2Many)
The thing is, when i put in body "entity_service": [1,2] in the response i still get = []. Even though i have in my database Services with pk 1,2,3,4.

Do you know how can i make it work?

答:
Try it without a source as the field name is the same as the model field name</p>
```<code>class EntityCreateSerializer(serializers.ModelSerializer):
    entity_service = EntityServiceSerializerThrough(read_only=True, many=True)

        class Meta:
        model = Entity
        fields = '__all__'
</code>```

Body:
class EntityServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields =  '__all__'

class EntityCreateSerializer(serializers.ModelSerializer):
    entity_service = EntityServiceSerializerThrough(read_only=True, source='serviceschedule_set', many=True)

        class Meta:
        model = Entity
        fields = '__all__'

Model looks like this

class Entity(models.Model):
    entity_service = models.ManyToManyField(Service, through='ServiceSchedule')

class ServiceSchedule(models.Model):
    service = models.ForeignKey(Service, on_delete=models.CASCADE)
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)

class Service(models.Model):
    service_name = models.CharField(max_length=256, null=True)
    slug = models.SlugField(max_length=128, unique=True, null=False, editable=False)
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    animal = models.ForeignKey(Animal, on_delete=models.CASCADE, default=None)

I have these serializers (there are more fields in entity model, but they're irrelevant since the only problem i have is with the Many2Many)
The thing is, when i put in body "entity_service": [1,2] in the response i still get = []. Even though i have in my database Services with pk 1,2,3,4.

Do you know how can i make it work?

Body:
Try it without a source as the field name is the same as the model field name

class EntityCreateSerializer(serializers.ModelSerializer):
    entity_service = EntityServiceSerializerThrough(read_only=True, many=True)

        class Meta:
        model = Entity
        fields = '__all__'


问:
Why connection is not establishing on first time?
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me. </p>

```<code>HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
int respCode = con.getResponseCode();

if (respCode != HttpsURLConnection.HTTP_OK)
{
  throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
 else {
//read the content from server
}
</code>```

答:
Here is how you should send POST requests in Android

```<code>HttpPost httpGet = new HttpPost(server + "/login?email="+username+"&password="+password);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpGet);
</code>```

You can read response using:

```<code>response.getEntity().getContent()
</code>```

Body:
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me.

HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
int respCode = con.getResponseCode();

if (respCode != HttpsURLConnection.HTTP_OK)
{
  throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
 else {
//read the content from server
}

Body:
Here is how you should send POST requests in Android

HttpPost httpGet = new HttpPost(server + "/login?email="+username+"&password="+password);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpGet);

You can read response using:

response.getEntity().getContent()


问:
responsive owl carousel with data attributes
how to responsive owl carousel with data attributes?

some thing like this...

```<code><div class="owl-carousel data-carousel" data-carousel='{"responsive": {0:{"items":1},768:{"items":2},992:{"items":3}}}'>

    <div class="item"><h1>1</h1></div>
    <div class="item"><h1>2</h1></div>
    <div class="item"><h1>3</h1></div>
    <div class="item"><h1>4</h1></div>
    <div class="item"><h1>1</h1></div>
    <div class="item"><h1>2</h1></div>
    <div class="item"><h1>3</h1></div>
    <div class="item"><h1>4</h1></div>

</div>
</code>```

and

```<code>var $carousel = $('.data-carousel[data-carousel]');
if ($carousel.length) {
    $carousel.each(function() {
        $(this).owlCarousel($(this).data('carousel'));
    });
}
</code>```

in owl carousel documentations we have like this ...

```<code>$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    responsiveClass:true,
    responsive:{
        0:{
            items:1,
            nav:true
        },
        600:{
            items:3,
            nav:false
        },
        1000:{
            items:5,
            nav:true,
            loop:false
        }
    }
});
</code>```

but in my way, i want a new way to responsive owl carousel with data attributes. i see some snippets like this ...

```<code><div class="owl-carousel" data-carousel='{"breakpoint":"0:1,992:2"}'></div>
</code>```

答:
We can do this like</p>
```<code><div class="your-custom-class">
    <ul class="tab-list owl-carousel nav-style5" data-nav="true" data-autoplay="true" data-dots="false" data-loop="true"
    data-margin="30" data-responsive='{"0":{"items":1},"600":{"items":2},"1000":{"items":6}}'>
        <li class="custom-class2">
            <div class="custom-class3">
                <div class="custom-class4">
                    <a href="#"><img src="/src/images/img1.png" alt=""></a>
                    <div class="gorup-button">
                        <a href="#" class="wishlist">
                            <i class="fa fa-heart"></i>
                        </a>
                    </div>
                </div>
                <div class="product-info">
                    <h3 class="product-name">
                        <a href="#">Product Name</a>
                    </h3>
                    <span class="price">
                       <ins>₹300</ins>
                       <del>₹400</del>
                    </span>
                    <a href="#" class="button">ADD TO WISHLIST</a>
                </div>
            </div>
        </li>
    </ul>
</div>

</code>```

Body:
how to responsive owl carousel with data attributes?

some thing like this...

1

2

3

4

1

2

3

4

and

var $carousel = $('.data-carousel[data-carousel]');
if ($carousel.length) {
    $carousel.each(function() {
        $(this).owlCarousel($(this).data('carousel'));
    });
}

in owl carousel documentations we have like this ...

$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    responsiveClass:true,
    responsive:{
        0:{
            items:1,
            nav:true
        },
        600:{
            items:3,
            nav:false
        },
        1000:{
            items:5,
            nav:true,
            loop:false
        }
    }
});

but in my way, i want a new way to responsive owl carousel with data attributes. i see some snippets like this ...

Body:
We can do this like

<div class="your-custom-class">
    <ul class="tab-list owl-carousel nav-style5" data-nav="true" data-autoplay="true" data-dots="false" data-loop="true"
    data-margin="30" data-responsive='{"0":{"items":1},"600":{"items":2},"1000":{"items":6}}'>
        <li class="custom-class2">
            <div class="custom-class3">
                <div class="custom-class4">
                    <a href="#"><img src="/src/images/img1.png" alt=""></a>
                    <div class="gorup-button">
                        <a href="#" class="wishlist">
                            <i class="fa fa-heart"></i>
                        </a>
                    </div>
                </div>
                <div class="product-info">
                    <h3 class="product-name">
                        <a href="#">Product Name</a>
                    </h3>
                    <span class="price">
                       <ins>₹300</ins>
                       <del>₹400</del>
                    </span>
                    <a href="#" class="button">ADD TO WISHLIST</a>
                </div>
            </div>
        </li>
    </ul>
</div>


问:
Oracle, find differences in records between two "sets"
Some scripts:

```<code>create table set_1
( id number(12));

create table set_2
( id number(12));

create table map_set
( id_set_1 number(12),
  id_set_2 number(12)
);

  insert into set_1 values(1);
  insert into set_1 values(2);
  insert into set_1 values(3);
  insert into set_1 values(4);

  insert into map_set values(1,5);
  insert into map_set values(2,6);
  insert into map_set values(3,7);
  insert into map_set values(4,8);

  insert into set_2 values(5);
  insert into set_2 values(6);
  insert into set_2 values(7);
  insert into set_2 values(8);

create table attrib_1(
id           number(12),
set_id       number(12),
attrib_id    number(2),
val          number(10,2));

create table attrib_2
(
id number(12),
set_id number(12),
attrib_id number(2),
val       number(10,2)
);

insert into attrib_1 values(1,1,1,10.2);
insert into attrib_1 values(2,1,2,2.5);
insert into attrib_1 values(3,1,3,5.23);

SELECT * FROM attrib_1;

insert into attrib_2 values(1,5,2,4.54);
insert into attrib_2 values(2,5,3,89.5);
</code>```

There is a - let's call them sets. There is also a table which mapping this sets, so in this case f.e. set from set_1 table with id = 1 is a copy of set_2 with id =2. Sets can have attributes, one or more. Then we make some changes in this attrib sets.

What I want is to detect differences between this attributes between "same" sets. I've wrote this:

```<code>   SELECT  *
    FROM    (
              SELECT a1.id       ,
                     a1.attrib_id,
                     a1.val      ,
                     s1.id  AS set_id,
                     mp.id_set_2

              FROM   set_1   s1,
                     map_Set mp,
                     attrib_1 a1
              WHERE  mp.id_set_1 = s1.id
              AND    s1.id = 1
              and    a1.set_id = S1.id
            ) s1
    full    join
            (
              SELECT a2.id       ,
                     a2.attrib_id,
                     a2.val      ,
                     s2.id  AS set_id
              FROM   set_2   s2,
                     attrib_2 a2
              WHERE  s2.id = 5
              and    a2.set_id = S2.id
            ) s2
    ON      s1.id_set_2 = s2.set_id
    AND     s1.attrib_id = s2.attrib_id
</code>```

I want to create for .. loop plsql code where it gets all records and:

if attrib_id's are the same and val is different - update record

if there is attrib in set_2 but missing in set_1 - delete

if there is attrib in set_1 but missing in set_2 - add and here's the problem:

I need an id of set to do INSERT, but there is no id "empty attrib" records.

I want output to look like this:

to have ALL data about sets, and left join attributes.

I tried left joins, this is closest I've got to my goal but now I'm stuck.

Any ideas?
Thanks!

Edit: i prefer to do this in one SQL. Triggers on tables forbides operatioms on few id's in one insert.

答:
You want to perform three operations. They can be done with three separate queries:

1. If attrib_id's are the same and val is diffrent - update record

```<code>update (
  select x.*, u.bval
  from attrib_1 x
  join (
    select
      m.*, a.attrib_id as aid, a.val as aval, b.val as bval
    from map_set m
    join attrib_1 a on a.set_id = m.id_set_1
    full join attrib_2 b on b.set_id = m.id_set_2 and b.attrib_id = a.attrib_id
  ) u on u.aid = x.attrib_id and u.aval <> u.bval
)
set val = bval
</code>```

2. If there is attrib in set_2 but missing in set_1 - delete

```<code>delete from attrib_2
where (set_id, attrib_id) in (
  select b.set_id, b.attrib_id
  from map_set m
  join attrib_1 a on a.set_id = m.id_set_1
  right join attrib_2 b on b.set_id = m.id_set_2 and b.attrib_id = a.attrib_id
  where a.set_id is null
);
</code>```

3. If there is attrib in set_1 but missing in set_2 - add

```<code>insert into attrib_2 (id, set_id, attrib_id, val)
select
  100, -- probably use an identity or sequence
  m.id_set_2, a.attrib_id, a.val
from map_set m
join attrib_1 a on a.set_id = m.id_set_1
left join attrib_2 b on b.set_id = m.id_set_2 and b.attrib_id = a.attrib_id
where b.set_id is null
</code>```

Final Result:

```<code> ID_SET_1  ID_SET_2  AID  AVAL  BVAL
 --------- --------- ---- ----- ----
 1         5         1    10.2  10.2
 1         5         2    4.54  4.54
 1         5         3    89.5  89.5
</code>```

See running example at db<>fiddle. I added one extra row to your example to test case #3 (add).

Body:
Some scripts:

create table set_1
( id number(12));

create table set_2
( id number(12));

create table map_set
( id_set_1 number(12),
  id_set_2 number(12)
);

  insert into set_1 values(1);
  insert into set_1 values(2);
  insert into set_1 values(3);
  insert into set_1 values(4);

  insert into map_set values(1,5);
  insert into map_set values(2,6);
  insert into map_set values(3,7);
  insert into map_set values(4,8);

  insert into set_2 values(5);
  insert into set_2 values(6);
  insert into set_2 values(7);
  insert into set_2 values(8);

create table attrib_1(
id           number(12),
set_id       number(12),
attrib_id    number(2),
val          number(10,2));

create table attrib_2
(
id number(12),
set_id number(12),
attrib_id number(2),
val       number(10,2)
);

insert into attrib_1 values(1,1,1,10.2);
insert into attrib_1 values(2,1,2,2.5);
insert into attrib_1 values(3,1,3,5.23);

SELECT * FROM attrib_1;

insert into attrib_2 values(1,5,2,4.54);
insert into attrib_2 values(2,5,3,89.5);

There is a - let's call them sets. There is also a table which mapping this sets, so in this case f.e. set from set_1 table with id = 1 is a copy of set_2 with id =2. Sets can have attributes, one or more. Then we make some changes in this attrib sets.

What I want is to detect differences between this attributes between "same" sets. I've wrote this:

   SELECT  *
    FROM    (
              SELECT a1.id       ,
                     a1.attrib_id,
                     a1.val      ,
                     s1.id  AS set_id,
                     mp.id_set_2

              FROM   set_1   s1,
                     map_Set mp,
                     attrib_1 a1
              WHERE  mp.id_set_1 = s1.id
              AND    s1.id = 1
              and    a1.set_id = S1.id
            ) s1
    full    join
            (
              SELECT a2.id       ,
                     a2.attrib_id,
                     a2.val      ,
                     s2.id  AS set_id
              FROM   set_2   s2,
                     attrib_2 a2
              WHERE  s2.id = 5
              and    a2.set_id = S2.id
            ) s2
    ON      s1.id_set_2 = s2.set_id
    AND     s1.attrib_id = s2.attrib_id

I want to create for .. loop plsql code where it gets all records and:

if attrib_id's are the same and val is different - update record

if there is attrib in set_2 but missing in set_1 - delete

if there is attrib in set_1 but missing in set_2 - add and here's the problem:

I need an id of set to do INSERT, but there is no id "empty attrib" records.

I want output to look like this:

to have ALL data about sets, and left join attributes.

I tried left joins, this is closest I've got to my goal but now I'm stuck.

Any ideas?
Thanks!

Edit: i prefer to do this in one SQL. Triggers on tables forbides operatioms on few id's in one insert.

Body:
You want to perform three operations. They can be done with three separate queries:

1. If attrib_id's are the same and val is diffrent - update record

update (
  select x.*, u.bval
  from attrib_1 x
  join (
    select
      m.*, a.attrib_id as aid, a.val as aval, b.val as bval
    from map_set m
    join attrib_1 a on a.set_id = m.id_set_1
    full join attrib_2 b on b.set_id = m.id_set_2 and b.attrib_id = a.attrib_id
  ) u on u.aid = x.attrib_id and u.aval <> u.bval
)
set val = bval

2. If there is attrib in set_2 but missing in set_1 - delete

delete from attrib_2
where (set_id, attrib_id) in (
  select b.set_id, b.attrib_id
  from map_set m
  join attrib_1 a on a.set_id = m.id_set_1
  right join attrib_2 b on b.set_id = m.id_set_2 and b.attrib_id = a.attrib_id
  where a.set_id is null
);

3. If there is attrib in set_1 but missing in set_2 - add

insert into attrib_2 (id, set_id, attrib_id, val)
select
  100, -- probably use an identity or sequence
  m.id_set_2, a.attrib_id, a.val
from map_set m
join attrib_1 a on a.set_id = m.id_set_1
left join attrib_2 b on b.set_id = m.id_set_2 and b.attrib_id = a.attrib_id
where b.set_id is null

Final Result:

 ID_SET_1  ID_SET_2  AID  AVAL  BVAL
 --------- --------- ---- ----- ----
 1         5         1    10.2  10.2
 1         5         2    4.54  4.54
 1         5         3    89.5  89.5

See running example at db<>fiddle. I added one extra row to your example to test case #3 (add).


问:
Can't create recursive type `using T = vector<T::iterator>`
I'm trying to create a vector that contains its own iterators as elements, and I find it impossible to fully expand the type declaration.

```<code>using MyVectorType = std::vector<std::vector<...>::iterator>;
// Trying to fill in the ...                 ^^^
</code>```

Another approach that fails is:

```<code>using MyVectorType = std::vector<MyVectorType::iterator>;
</code>```

use of undeclared identifier 'MyVectorType'
Trying to use an intermediate declaration also fails

```<code>template <class T>
using MyVectorType_incomplete = std::vector<T>;
using MyVectorType = MyVectorType_incomplete<MyVectorType_incomplete::iterator>;
</code>```

error: 'MyVectorType_incomplete' is not a class,

namespace, or enumeration

Clearly using a pointer instead solves this issue.

```<code>struct It {
   It *iterator;
};
vector<It>;
</code>```

However this means that you cannot use the iterator interface, and basically have to reimplement the iterator for the given class.

Is there a way to do this in C++?

More generally, is there a way to create recursive types like the above, where you refer to a type before it's created?

答:
using introduces a type alias. An alias is a name of some other thing. You can always replace the alias with that other thing. In fact you must do it in order to figure out properties of types that involve aliases, because aliases don't have properties of their own.

```<code>using MyVectorType = std::vector<MyVectorType::iterator>; // replace the name with the thing named
using MyVectorType = std::vector<std::vector<MyVectorType::iterator>::iterator>; // again
using MyVectorType = std::vector<std::vector<std::vector<std::vector<MyVectorType::iterator>::iterator>; ::iterator>::iterator>; // and again and again
</code>```

So you cannot have a recursive type alias.

You can create a recursive type, but you cannot close the loop with a type alias. You can do it with a pointer or with a template. Something like this should be legal C++:

```<code>struct my_vector : public std::vector<std::vector<my_vector>::iterator> {}
</code>```

but I don't know how useful it is to you.

Body:
I'm trying to create a vector that contains its own iterators as elements, and I find it impossible to fully expand the type declaration.

using MyVectorType = std::vector<std::vector<...>::iterator>;
// Trying to fill in the ...                 ^^^

Another approach that fails is:

using MyVectorType = std::vector<MyVectorType::iterator>;

use of undeclared identifier 'MyVectorType'
Trying to use an intermediate declaration also fails

template <class T>
using MyVectorType_incomplete = std::vector<T>;
using MyVectorType = MyVectorType_incomplete<MyVectorType_incomplete::iterator>;

error: 'MyVectorType_incomplete' is not a class,

namespace, or enumeration

Clearly using a pointer instead solves this issue.

struct It {
   It *iterator;
};
vector<It>;

However this means that you cannot use the iterator interface, and basically have to reimplement the iterator for the given class.

Is there a way to do this in C++?

More generally, is there a way to create recursive types like the above, where you refer to a type before it's created?

Body:
using introduces a type alias. An alias is a name of some other thing. You can always replace the alias with that other thing. In fact you must do it in order to figure out properties of types that involve aliases, because aliases don't have properties of their own.

using MyVectorType = std::vector<MyVectorType::iterator>; // replace the name with the thing named
using MyVectorType = std::vector<std::vector<MyVectorType::iterator>::iterator>; // again
using MyVectorType = std::vector<std::vector<std::vector<std::vector<MyVectorType::iterator>::iterator>; ::iterator>::iterator>; // and again and again

So you cannot have a recursive type alias.

You can create a recursive type, but you cannot close the loop with a type alias. You can do it with a pointer or with a template. Something like this should be legal C++:

struct my_vector : public std::vector<std::vector<my_vector>::iterator> {}

but I don't know how useful it is to you.


问:
import geopandas successfully, but raise issue with fiona(import error)
I am Windows and using python through jupyternotebook.
python 3.9.7, windows 64 bit,
I want to import geopandas, so I used the code  conda install --channel conda-forge geopandas. It seemed work at first because I could successfully import geopandas without error, but when I want to run the following code, an import error appears.

world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

world.columns

ImportError: the 'read_file' function requires the 'fiona' package, but it is not installed or does not import correctly.
Importing fiona resulted in: DLL load failed while importing ogrext

I saw other people asked the same questions, but none of their solutions worked. At first, I saw someone said nstalling geopandas by condas might installed wrong version of fiona and gdal. So I tried to update by conda update conda, and conda update -n base conda-package-handling and conda update --all. However, these code didn't work. Later, I directly installed the .whl file from python library: Fiona-1.8.20-cp39-cp39-win_amd64.whl and GDAL-3.4.1-cp39-cp39-win_amd64.whl, and use pip to install them. But the error still appeared.
I really have no idea how to deal with such issue, is it because the version of fiona and gdal was not consistent? Please give me some suggestions, thanks ahead!

答:
I have solved this problem by creating a new environment followed this article: https://medium.com/analytics-vidhya/fastest-way-to-install-geopandas-in-jupyter-notebook-on-windows-8f734e11fa2b

This is the fast way to solve this problem.


答:
I do not think that it is possible by the standard.

To achieve what you want you must be able to refer to std::vector<T>::iterator while T is incomplete.

Before C++17 T was required to be complete to instantiate std::vector<T> at all, so it cannot work there.

Since C++17 the standard allows instantiating std::vector<T> with incomplete types T, however only as long as the type is complete before any of its members are referenced, see [vector.overview]/4 of the post-C++20 draft.

However, if you want to achieve such a recursion, you need to be able to inherit or have a member of type std::vector<T>::iterator. Not only does this reference the ::iterator type, but it also requires it to be instantiated, which is not guaranteed to work at this point.

Having the class inherit from std::vector<T::iterator> won't work either, since then T needs to be complete. Deferring T::iterator to another inherited class will also not work, since the classes then recursively depend on being completed before one another.

Depending on how the standard library is implementing std::vector<T>::iterator the following may work, although it is technically undefined behavior according to the standard:

```<code>struct MakeMyVectorType : std::vector<MakeMyVectorType>::iterator  {
};

using MyVectorType = std::vector<MakeMyVectorType>;

int main() {
    MyVectorType v1(10);
    MyVectorType v2(v1.begin(), v1.end());
    v2.push_back({v1.begin()+5});
    MyVectorType v3{{v2.begin()}, {v2.end()}};
    std::cout << v1.size() << "\n";  // 10
    std::cout << v2.size() << "\n";  // 11
    std::cout << v3.size() << "\n";  // 2
}
</code>```

I am also not really sure how you would use this type.

Title: Can't create recursive type `using T = vector<T::iterator>`

Body:
I do not think that it is possible by the standard.

To achieve what you want you must be able to refer to std::vector<T>::iterator while T is incomplete.

Before C++17 T was required to be complete to instantiate std::vector<T> at all, so it cannot work there.

Since C++17 the standard allows instantiating std::vector<T> with incomplete types T, however only as long as the type is complete before any of its members are referenced, see [vector.overview]/4 of the post-C++20 draft.

However, if you want to achieve such a recursion, you need to be able to inherit or have a member of type std::vector<T>::iterator. Not only does this reference the ::iterator type, but it also requires it to be instantiated, which is not guaranteed to work at this point.

Having the class inherit from std::vector<T::iterator> won't work either, since then T needs to be complete. Deferring T::iterator to another inherited class will also not work, since the classes then recursively depend on being completed before one another.

Depending on how the standard library is implementing std::vector<T>::iterator the following may work, although it is technically undefined behavior according to the standard:

struct MakeMyVectorType : std::vector<MakeMyVectorType>::iterator  {
};

using MyVectorType = std::vector<MakeMyVectorType>;

int main() {
    MyVectorType v1(10);
    MyVectorType v2(v1.begin(), v1.end());
    v2.push_back({v1.begin()+5});
    MyVectorType v3{{v2.begin()}, {v2.end()}};
    std::cout << v1.size() << "\n";  // 10
    std::cout << v2.size() << "\n";  // 11
    std::cout << v3.size() << "\n";  // 2
}

I am also not really sure how you would use this type.


问:
perl help troubleshooting error msg using perl module
I am testing perl script using this example found on the forum. I took the sample data and put it in a separate file and using an open to try it this way.

I don't understand why I would be getting undef. I am getting the msg:

Use of uninitialized value in join or string at ./h.pl line 15,  line 4.

```<code>#!/usr/local/bin/perl

use warnings;
use strict;
use Data::Dumper;
use Text::CSV_XS;

    open my $fh, '<', 't.out' or die "Unable to open: $!";
    my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
    my @list;
    $csv->column_names ($csv->getline ($fh));
    while ( my $hr = $csv->getline_hr($fh) ) {
        push @list, $hr->{'Ball'};
    }

    print "@list\n";
    print Dumper(\@list);
</code>```

Test file (t.out)

```<code>Camera Make Camera Model    Text    Ball    Swing
a   b   c   d   e
f   g   h   i   j
k   l   m   n   o

$ od -cx t.out
0000000   C   a   m   e   r   a       M   a   k   e  \t   C   a   m   e
        6143 656d 6172 4d20 6b61 0965 6143 656d
0000020   r   a       M   o   d   e   l  \t   T   e   x   t  \t   B   a
        6172 4d20 646f 6c65 5409 7865 0974 6142
0000040   l   l  \t   S   w   i   n   g  \n   a  \t   b  \t   c  \t   d
        6c6c 5309 6977 676e 610a 6209 6309 6409
0000060  \t   e  \n   f  \t   g  \t   h  \t   i  \t   j  \n   k  \t   l
        6509 660a 6709 6809 6909 6a09 6b0a 6c09
0000100  \t   m  \t   n  \t   o  \n  \0
        6d09 6e09 6f09 000a
0000107
</code>```

Results:

```<code>$VAR1 = [
          undef,
          undef,
          undef
        ];
</code>```

答:
As others have mentioned, it is very possible that @list never got a value in it. If $csv->getline_hr($fh) returns an undef the first time through, you'll never push anything into @list.

There are two things you can do:

You can test if @list is uninitialized before printing it

You can loosen the use warnings pragma not to include uninitialized warnings:

Here's how you can do your testing:

```<code>if (@list) {
   print "List = " . @list . "\n";
}
else {
   print "List has no values\n";
}
</code>```

You can use scalar @list as Igor Zinov'yev shows, but that's not really necessary in this case and I think the simple if (@list) is clearer. You can also use if (defined @list) which is very clear, but has been discouraged over the last few years.

If this is a temporary thing (just seeing if your code works or not), you can loosen the use of strict:

```<code>no warnings qw(uninitialized);
print "@list\n";   #Now you won't get a warning if @list has no value
use warnings;      #Turn the warnings back on. It helps you code better
</code>```

A slight Word 'o Warning: In this case, your statement won't print anything and that might confuse you even more. Always put a prompt of some sort to make sure something prints:

```<code>print "\@list = @list\n";
</code>```

I prefer this as a temporary solution when I'm printing out a lot of debugging statements which I'll later remove. In fact, I'll create a special debug subroutine for these types of messages:

```<code>use strict;
use warnings;
use constant DEBUG_LEVEL => 1;  #0 = no debug messages 1 = debug messages

[...]
while (yadda, yadda, yadda) {
   push @list, $hr->{Name};
}
debug (qq(\@list = ") . join "|", @list . qq("));

[...]

sub debug {
   my $message = shift;

   return if (not DEBUG_LEVEL);
   no warnings qw(uninitialized);
   print qq(DEBUG: $message\n);
   use warnings;      #Not really needed since the code block ends
   return $message;
}
</code>```

Body:
I am testing perl script using this example found on the forum. I took the sample data and put it in a separate file and using an open to try it this way.

I don't understand why I would be getting undef. I am getting the msg:

Use of uninitialized value in join or string at ./h.pl line 15,  line 4.

#!/usr/local/bin/perl

use warnings;
use strict;
use Data::Dumper;
use Text::CSV_XS;

    open my $fh, '<', 't.out' or die "Unable to open: $!";
    my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
    my @list;
    $csv->column_names ($csv->getline ($fh));
    while ( my $hr = $csv->getline_hr($fh) ) {
        push @list, $hr->{'Ball'};
    }

    print "@list\n";
    print Dumper(\@list);

Test file (t.out)

Camera Make Camera Model    Text    Ball    Swing
a   b   c   d   e
f   g   h   i   j
k   l   m   n   o

$ od -cx t.out
0000000   C   a   m   e   r   a       M   a   k   e  \t   C   a   m   e
        6143 656d 6172 4d20 6b61 0965 6143 656d
0000020   r   a       M   o   d   e   l  \t   T   e   x   t  \t   B   a
        6172 4d20 646f 6c65 5409 7865 0974 6142
0000040   l   l  \t   S   w   i   n   g  \n   a  \t   b  \t   c  \t   d
        6c6c 5309 6977 676e 610a 6209 6309 6409
0000060  \t   e  \n   f  \t   g  \t   h  \t   i  \t   j  \n   k  \t   l
        6509 660a 6709 6809 6909 6a09 6b0a 6c09
0000100  \t   m  \t   n  \t   o  \n  \0
        6d09 6e09 6f09 000a
0000107

Results:

$VAR1 = [
          undef,
          undef,
          undef
        ];

Body:
As others have mentioned, it is very possible that @list never got a value in it. If $csv->getline_hr($fh) returns an undef the first time through, you'll never push anything into @list.

There are two things you can do:

You can test if @list is uninitialized before printing it

You can loosen the use warnings pragma not to include uninitialized warnings:

Here's how you can do your testing:

if (@list) {
   print "List = " . @list . "\n";
}
else {
   print "List has no values\n";
}

You can use scalar @list as Igor Zinov'yev shows, but that's not really necessary in this case and I think the simple if (@list) is clearer. You can also use if (defined @list) which is very clear, but has been discouraged over the last few years.

If this is a temporary thing (just seeing if your code works or not), you can loosen the use of strict:

no warnings qw(uninitialized);
print "@list\n";   #Now you won't get a warning if @list has no value
use warnings;      #Turn the warnings back on. It helps you code better

A slight Word 'o Warning: In this case, your statement won't print anything and that might confuse you even more. Always put a prompt of some sort to make sure something prints:

print "\@list = @list\n";

I prefer this as a temporary solution when I'm printing out a lot of debugging statements which I'll later remove. In fact, I'll create a special debug subroutine for these types of messages:

use strict;
use warnings;
use constant DEBUG_LEVEL => 1;  #0 = no debug messages 1 = debug messages

[...]
while (yadda, yadda, yadda) {
   push @list, $hr->{Name};
}
debug (qq(\@list = ") . join "|", @list . qq("));

[...]

sub debug {
   my $message = shift;

   return if (not DEBUG_LEVEL);
   no warnings qw(uninitialized);
   print qq(DEBUG: $message\n);
   use warnings;      #Not really needed since the code block ends
   return $message;
}


问:
FileStream Constructors in ASP.NET Core
In ASP.NET, we can achieve this by FileStream.FileStream(string path, FileMode mode, FileAccess access); as below:

```<code>public class LoginController : MMBaseController
{
    [AllowAnonymous]
    public ActionResult Home(string returnUrl){
        var fileStream = new FileStream(Server.MapPath("~/key.crt"), FileMode.Open, FileAccess.Read);
        string text;
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            text = streamReader.ReadToEnd();
        }
        Response response = new Response(text, samlTmp);
    }
}

public class MMBaseController : Controller
{
    //Controller for SignIn, SignOut, OnException, Dispose etc..
}
</code>```

I tried below code:

```<code>[AllowAnonymous]
public ActionResult Home(string returnUrl, [FromService] IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
}
</code>```

But it is showing:

The type or namespace name 'FromService' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'FromServiceAttribute' could not be found (are you missing a using directive or an assembly reference?)

Can we achieve same in .NET Core? I need to pass file path and specify file mode along with the file read/write permission.

I have tried File.Open(). But I get this error even after adding the namespace using System.IO;

The name 'Server' does not exist in the current context

答:
So two things

File is an method on your Controller. You need to use the full name System.IO.File

In .NET Core you should inject IWebHostEnvironment and then call environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath to resolve the relative path to your key file.

All in all, your example could look like this instead

```<code>public IActionResult YourMethod([FromServices]IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
    Response response = new Response(text, samlTmp);
......
</code>```

You should also be able to reduce

```<code>var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
</code>```

to

```<code>var fileStream = environment.ContentRootFileProvider.GetFileInfo("/key.crt").CreateReadStream();
</code>```

Title: FileStream Constructors in ASP.NET Core

Body:
In ASP.NET, we can achieve this by FileStream.FileStream(string path, FileMode mode, FileAccess access); as below:

public class LoginController : MMBaseController
{
    [AllowAnonymous]
    public ActionResult Home(string returnUrl){
        var fileStream = new FileStream(Server.MapPath("~/key.crt"), FileMode.Open, FileAccess.Read);
        string text;
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            text = streamReader.ReadToEnd();
        }
        Response response = new Response(text, samlTmp);
    }
}

public class MMBaseController : Controller
{
    //Controller for SignIn, SignOut, OnException, Dispose etc..
}

I tried below code:

[AllowAnonymous]
public ActionResult Home(string returnUrl, [FromService] IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
}

But it is showing:

The type or namespace name 'FromService' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'FromServiceAttribute' could not be found (are you missing a using directive or an assembly reference?)

Can we achieve same in .NET Core? I need to pass file path and specify file mode along with the file read/write permission.

I have tried File.Open(). But I get this error even after adding the namespace using System.IO;

The name 'Server' does not exist in the current context

Body:
So two things

File is an method on your Controller. You need to use the full name System.IO.File

In .NET Core you should inject IWebHostEnvironment and then call environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath to resolve the relative path to your key file.

All in all, your example could look like this instead

public IActionResult YourMethod([FromServices]IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
    Response response = new Response(text, samlTmp);
......

You should also be able to reduce

var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);

to

var fileStream = environment.ContentRootFileProvider.GetFileInfo("/key.crt").CreateReadStream();


问:
Change values in np array Python
I am trying to change the value in np array if there is a match

For example, a np array a and its shape is (50,4)

```<code>a.shape#(50,4)
</code>```

I need to check if the np array a has this value [0,1,20,4] in the 1st axis, then I need to change that into [-1,-1,-1,-1].

I tried this format -

```<code>a[a==[0,1,20,4]]=[-1,-1,-1,-1]
</code>```

But, this is not working,

How to do this modification?

Title: Change values in np array Python

Body:
I am trying to change the value in np array if there is a match

For example, a np array a and its shape is (50,4)

a.shape#(50,4)

I need to check if the np array a has this value [0,1,20,4] in the 1st axis, then I need to change that into [-1,-1,-1,-1].

I tried this format -

a[a==[0,1,20,4]]=[-1,-1,-1,-1]

But, this is not working,

How to do this modification?

Body:
For example for a random matrix

x = np.random.randint(1,11,size=(10,4))
>> array([[10,  1,  7,  7],
   [ 3,  1,  3,  2],
   [ 8, 10,  2,  9],
   [ 4,  6,  4,  4],
   [ 1,  4,  3,  5],
   [10,  1,  5,  4],
   [ 7, 10,  8,  8],
   [ 5, 10,  8,  3],
   [ 6,  5,  5,  3],
   [ 7,  2,  5,  7]])

Check all rows that are equal to target row

rows_cond = np.all(x == [1,4,3,5], axis=1)

this returns a boolean array that can be used to modify the desired rows

x[rows_cond,:]  = [-1,-1,-1,-1]


问:
enforcing order of calling function in google mock
I am learning about using google mock. I have observed following code as sample to specify the order of function calls. Here we are using InSequence object but not used any where in code. Request to guide me what idea of C++ technique is used internally by TEST_F to use this object  and enforce the oder

```<code>TEST_F(APlaceDescriptionService, MakesHttpRequestToObtainAddress) {
InSequence forceExpectationOrder;
HttpStub httpStub;
string urlStart{
"http://open.mapquestapi.com/nominatim/v1/reverse?format=json&"};
auto expectedURL = urlStart +
"lat=" + APlaceDescriptionService::ValidLatitude + "&" +
"lon=" + APlaceDescriptionService::ValidLongitude;
EXPECT_CALL(httpStub, initialize());
EXPECT_CALL(httpStub, get(expectedURL));
PlaceDescriptionService service{&httpStub};
service.summaryDescription(ValidLatitude, ValidLongitude);
}
</code>```

答:
The idea is simple: if HttpStub::get is called before HttpStub::initialize, then fail the test APlaceDescriptionService.MakesHttpRequestToObtainAddress. In other words, the test insures that HttpStub::get is not called before httpStub is initialized.

If your question is how it works:

InSequence forceExpectationOrder sets new Sequence object to the global g_gmock_implicit_sequence on creation, that uses a chain of expectations in the order of their creations.

```<code>// Points to the implicit sequence introduced by a living InSequence
// object (if any) in the current thread or NULL.
GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
</code>```
```<code>// Creates the implicit sequence if there isn't one.
InSequence::InSequence() {
  if (internal::g_gmock_implicit_sequence.get() == nullptr) {
    internal::g_gmock_implicit_sequence.set(new Sequence);
    sequence_created_ = true;
  }
  // ...
}

// Deletes the implicit sequence if it was created by the constructor
// of this object.
InSequence::~InSequence() {
  if (sequence_created_) {
    delete internal::g_gmock_implicit_sequence.get();
    internal::g_gmock_implicit_sequence.set(nullptr);
  }
}
</code>```
```<code>// Adds and returns an expectation spec for this mock function.
TypedExpectation<F>& AddNewExpectation(const char* file, int line,
                                       const std::string& source_text,
                                       const ArgumentMatcherTuple& m) {
  // ...

  // Adds this expectation into the implicit sequence if there is one.
  Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
  if (implicit_sequence != nullptr) {
    implicit_sequence->AddExpectation(Expectation(untyped_expectation));
  }

  return *expectation;
}
</code>```

Body:
I am learning about using google mock. I have observed following code as sample to specify the order of function calls. Here we are using InSequence object but not used any where in code. Request to guide me what idea of C++ technique is used internally by TEST_F to use this object  and enforce the oder

TEST_F(APlaceDescriptionService, MakesHttpRequestToObtainAddress) {
InSequence forceExpectationOrder;
HttpStub httpStub;
string urlStart{
"http://open.mapquestapi.com/nominatim/v1/reverse?format=json&"};
auto expectedURL = urlStart +
"lat=" + APlaceDescriptionService::ValidLatitude + "&" +
"lon=" + APlaceDescriptionService::ValidLongitude;
EXPECT_CALL(httpStub, initialize());
EXPECT_CALL(httpStub, get(expectedURL));
PlaceDescriptionService service{&httpStub};
service.summaryDescription(ValidLatitude, ValidLongitude);
}

Body:
The idea is simple: if HttpStub::get is called before HttpStub::initialize, then fail the test APlaceDescriptionService.MakesHttpRequestToObtainAddress. In other words, the test insures that HttpStub::get is not called before httpStub is initialized.

If your question is how it works:

InSequence forceExpectationOrder sets new Sequence object to the global g_gmock_implicit_sequence on creation, that uses a chain of expectations in the order of their creations.

// Points to the implicit sequence introduced by a living InSequence
// object (if any) in the current thread or NULL.
GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;

// Creates the implicit sequence if there isn't one.
InSequence::InSequence() {
  if (internal::g_gmock_implicit_sequence.get() == nullptr) {
    internal::g_gmock_implicit_sequence.set(new Sequence);
    sequence_created_ = true;
  }
  // ...
}

// Deletes the implicit sequence if it was created by the constructor
// of this object.
InSequence::~InSequence() {
  if (sequence_created_) {
    delete internal::g_gmock_implicit_sequence.get();
    internal::g_gmock_implicit_sequence.set(nullptr);
  }
}

// Adds and returns an expectation spec for this mock function.
TypedExpectation<F>& AddNewExpectation(const char* file, int line,
                                       const std::string& source_text,
                                       const ArgumentMatcherTuple& m) {
  // ...

  // Adds this expectation into the implicit sequence if there is one.
  Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
  if (implicit_sequence != nullptr) {
    implicit_sequence->AddExpectation(Expectation(untyped_expectation));
  }

  return *expectation;
}