问:
generic line syntax parser in python
THE PROBLEM:
I'm looking for a python library that might already implement a text parser that I have written in another language.

I have lines of text that represent either configuration commands in devices or dynamic output from commands run on devices. For simplicity, let's assume each line is parsed independently.
The bottom line is that a line contains fixed keywords and values/variables/parameters. Some keywords are optional and some are mandatory and in specific order. The number and type of variables/values associated with / following a given keyword can vary from one keyword to another.

SOLUTION IN OTHER LANGUAGE:
I wrote generic code in c++ that would parse any line and convert the input into structured data. The input to the code is
1. the line to be parsed and
2. a model/structure that described what keywords to look for, whether they are optional or not, in what order they might appear and what type of values/variables to expect for each (and also how many values/variables).
In c++ the interface allows the user among other things to supply a set of user-defined callback functions (one for each keyword) to be invoked by the parsing engine to supply the results (the parsed parameters associated with the given keyword). The implementation of the callback is user-defined but the callback signature is pre-defined.

WHAT ABOUT PYTHON?
I'm hoping for a simple library in python (or a completely different direction if this is something done differently/better in python) that provides an interface to specify the grammar/syntax/model of a given line (the details of all keywords, their order, what number and type of parameters each requires) and then does the parsing of input lines based on that syntax.

I'm not sure how much argparse fits what I need but this is not about parsing a command line input thou similar.

AN EXAMPLE:
Here is an example line from the IP networking world but the problem is more generic:
access-list SOMENAME-IN extended permit tcp host 117.21.212.54 host 174.163.16.23 range 5160 7000

In the above line, the keywords and their corresponding parameters are:

```<code>key: extended, no parameters
key: permit, no parameters
key: tcp, no parameters
key: host, par1: 117.21.212.54
key: host, par1: 174.163.16.23
key: range, par1: 5160, par2: 7000
</code>```

This is a form of firewall access control list ACL. In this case the parser would be used to fill a structure that indicates

```<code>- the name of the ACL (SOMENAME-IN in the above example)
- the type of ACL (extended in the above example but there are other valid keywords)
- the protocol (tcp in the above example)
- the src host/IP (117.21.212.54 in the example)
- the src port (optional and not present in the above example)
- the dst host/IP (174.163.16.23 in the example)
- the dst port (a range of ports from 5160 to 7000 in the above example)
</code>```

One can rather easily write a dedicated parser that assume the above example specific syntax and checks for it (perhaps this might also be more efficient and more clear since targeted to a specific syntax) but what I want is to be able to write a general parsing code, where all the keywords and the expected syntax is provided as data / model to the parsing engine which uses it to parse the lines and is also capable of pointing out errors in the parsed line.

I'm not obviously looking for a full solution cause that would be a lot but I hope for thoughts specifically in the context of using python and reusing any features or libraries python may have to do such parsing.

Thanks,
Al.

答:
If I understand your needs correctly (and it is possible that I don't, because it is hard to know what limits you place on the possible grammars), then you should be able to solve this problem fairly simply with a tokeniser and a map of keyword parsers for each command.

If your needs are very simple, you might be able to tokenise using the split string method, but it is possible that you would prefer a tokeniser which at least handles quoted strings and maybe some operator symbols. The standard Python library provides the shlex module for this purpose.

There is no standard library module which does the parsing. There are a large variety of third-party parsing frameworks, but I think that they are likely to be overkill for your needs (although I might be wrong, and you might want to check them out even if you don't need anything that sophisticated). While I don't usually advocate hand-rolling a parser, this particular application is both simple enough to make that possible and sufficiently different from the possibilities of a context-free grammar to make direct coding useful.

(What makes a context-free grammar impractical is the desire to allow different command options to be provided in arbitrary order without allowing repetition of non-repeatable options. But rereading this answer, I realize that it is just an assumption on my part that you need that feature.)

Title: generic line syntax parser in python

Body:
THE PROBLEM:
I'm looking for a python library that might already implement a text parser that I have written in another language.

I have lines of text that represent either configuration commands in devices or dynamic output from commands run on devices. For simplicity, let's assume each line is parsed independently.
The bottom line is that a line contains fixed keywords and values/variables/parameters. Some keywords are optional and some are mandatory and in specific order. The number and type of variables/values associated with / following a given keyword can vary from one keyword to another.

SOLUTION IN OTHER LANGUAGE:
I wrote generic code in c++ that would parse any line and convert the input into structured data. The input to the code is
1. the line to be parsed and
2. a model/structure that described what keywords to look for, whether they are optional or not, in what order they might appear and what type of values/variables to expect for each (and also how many values/variables).
In c++ the interface allows the user among other things to supply a set of user-defined callback functions (one for each keyword) to be invoked by the parsing engine to supply the results (the parsed parameters associated with the given keyword). The implementation of the callback is user-defined but the callback signature is pre-defined.

WHAT ABOUT PYTHON?
I'm hoping for a simple library in python (or a completely different direction if this is something done differently/better in python) that provides an interface to specify the grammar/syntax/model of a given line (the details of all keywords, their order, what number and type of parameters each requires) and then does the parsing of input lines based on that syntax.

I'm not sure how much argparse fits what I need but this is not about parsing a command line input thou similar.

AN EXAMPLE:
Here is an example line from the IP networking world but the problem is more generic:
access-list SOMENAME-IN extended permit tcp host 117.21.212.54 host 174.163.16.23 range 5160 7000

In the above line, the keywords and their corresponding parameters are:

key: extended, no parameters
key: permit, no parameters
key: tcp, no parameters
key: host, par1: 117.21.212.54
key: host, par1: 174.163.16.23
key: range, par1: 5160, par2: 7000

This is a form of firewall access control list ACL. In this case the parser would be used to fill a structure that indicates

- the name of the ACL (SOMENAME-IN in the above example)
- the type of ACL (extended in the above example but there are other valid keywords)
- the protocol (tcp in the above example)
- the src host/IP (117.21.212.54 in the example)
- the src port (optional and not present in the above example)
- the dst host/IP (174.163.16.23 in the example)
- the dst port (a range of ports from 5160 to 7000 in the above example)

One can rather easily write a dedicated parser that assume the above example specific syntax and checks for it (perhaps this might also be more efficient and more clear since targeted to a specific syntax) but what I want is to be able to write a general parsing code, where all the keywords and the expected syntax is provided as data / model to the parsing engine which uses it to parse the lines and is also capable of pointing out errors in the parsed line.

I'm not obviously looking for a full solution cause that would be a lot but I hope for thoughts specifically in the context of using python and reusing any features or libraries python may have to do such parsing.

Thanks,
Al.


来源: stackexchange

问:
How can I use fieldsets in a form with CSS grid?
I want to use <fieldset> for the semantic HTML.
I'm using CSS grid to make my form look nice.

form {
  display: grid;
  grid-template-columns: minmax(100px, max-content) minmax(200px, max-content) minmax(200px, 1fr);
  grid-gap: 10px;
}

.field__label {
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" method="POST">

  <label class="field__label" for="first-names">
             First names
  </label>

  <input class="form__entry" id="first-names" type="text" name="firstName">

  <span class="form__feedback form__instructions">
            Must only use letters, spaces, hyphens and apostrophes
    </span>

</form></code>```

This all works nicely (and in my real form I have the  -> <input> ->  pattern repeated several times).

The problem is - if I wrap a few instances of that pattern in a <fieldset> which I want to do for personal details, bank details etc, because then the <fieldset>s are the direct descendents of the element with display: grid; it places those in the grid, and not the form elements. How can I get round this?

答:
I see two options:

If you strictly want to go with CSS grid layout you need to use this

```fieldset {
  display: contents;
}```

However, this will eliminate the fielset from the view so there is no way to get a border, etc. You can still style the legend.

In case you want to have the fieldset display normally with border, etc. you need to change your layout. Here is an example that may work as a starting point:

```fieldset > label, form > label {
  clear: both;
  float: left;
  width: 18%;
  text-align: right;
  font-weight: bold;
  white-space: nowrap;
}
fieldset>label {
  margin-right: 0.5em;
  padding-top: 0.1em;
}
form>label {
  margin-left: 0.75em;
  margin-right: 0.5em;
  padding-top: 0.1em;
}
fieldset>:not(label):not(legend) {
  min-width: 72%;
  width: 72%;
  margin-bottom: 0.5em;
  display: block;
}
form>:not(label):not(fieldset) {
  min-width: 70%;
  width: 70%;
  margin-bottom: 0.5em;
  display: block;
}```

ContentLicense: CC BY-SA 4.0

Body:
I want to use <fieldset> for the semantic HTML.
I'm using CSS grid to make my form look nice.

form {
  display: grid;
  grid-template-columns: minmax(100px, max-content) minmax(200px, max-content) minmax(200px, 1fr);
  grid-gap: 10px;
}

.field__label {
  text-align: right;
}

<form action="#" method="POST">

             First names

  <input class="form__entry" id="first-names" type="text" name="firstName">

            Must only use letters, spaces, hyphens and apostrophes

</form>

This all works nicely (and in my real form I have the  -> <input> ->  pattern repeated several times).

The problem is - if I wrap a few instances of that pattern in a <fieldset> which I want to do for personal details, bank details etc, because then the <fieldset>s are the direct descendents of the element with display: grid; it places those in the grid, and not the form elements. How can I get round this?

Body:
I see two options:

If you strictly want to go with CSS grid layout you need to use this

fieldset {
  display: contents;
}

However, this will eliminate the fielset from the view so there is no way to get a border, etc. You can still style the legend.

In case you want to have the fieldset display normally with border, etc. you need to change your layout. Here is an example that may work as a starting point:

fieldset > label, form > label {
  clear: both;
  float: left;
  width: 18%;
  text-align: right;
  font-weight: bold;
  white-space: nowrap;
}
fieldset>label {
  margin-right: 0.5em;
  padding-top: 0.1em;
}
form>label {
  margin-left: 0.75em;
  margin-right: 0.5em;
  padding-top: 0.1em;
}
fieldset>:not(label):not(legend) {
  min-width: 72%;
  width: 72%;
  margin-bottom: 0.5em;
  display: block;
}
form>:not(label):not(fieldset) {
  min-width: 70%;
  width: 70%;
  margin-bottom: 0.5em;
  display: block;
}


问:
Refresh cache on App update not working - Vue, webpack, router split code
I apply lazy loading and code splitting in my vue app

But somehow when I update my code and I deploy it to production only some chunks are updated with a new hash.

```<code> File                                      Size             Gzipped

  dist/js/chunk-vendors.8bacd999.js         1379.15 KiB      418.03 KiB
  dist/js/super-user.55f6d84e.js            230.82 KiB       43.40 KiB
  dist/js/user.75857fc3.js                  141.31 KiB       28.63 KiB
  dist/js/worker.3f845d96.js                116.95 KiB       27.14 KiB
  dist/js/super-user~user~worker.89497bd    95.72 KiB        26.28 KiB
  4.js
  dist/js/super-user~worker.de7f3513.js     41.93 KiB        14.24 KiB
  dist/js/app.d05288d8.js                   33.93 KiB        9.72 KiB
  dist/js/landing-page.abe82391.js          28.14 KiB        10.78 KiB
  dist/precache-manifest.9e6d4f8b3b203e5    6.23 KiB         1.84 KiB
  a7409c4e5738c04b0.js
  dist/service-worker.js                    1.04 KiB         0.61 KiB
  dist/css/chunk-vendors.c380a352.css       354.50 KiB       40.53 KiB
  dist/css/super-user~user~worker.b6103c    30.99 KiB        4.90 KiB
  9d.css
  dist/css/user.efb5b1bf.css                24.94 KiB        4.66 KiB
  dist/css/super-user.78d831e9.css          17.71 KiB        3.26 KiB
  dist/css/super-user~worker.3a0fff16.cs    12.84 KiB        1.87 KiB
  s
  dist/css/landing-page.de5bd5da.css        7.32 KiB         1.77 KiB
  dist/css/worker.7dcd23eb.css              5.72 KiB         1.63 KiB
  dist/css/app.3e078b33.css                 3.55 KiB         1.16 KiB
</code>```

VS

```<code>  File                                      Size             Gzipped

  dist/js/chunk-vendors.8bacd999.js         1379.15 KiB      418.03 KiB
  dist/js/super-user.0cf42025.js            233.18 KiB       43.64 KiB
  dist/js/user.75857fc3.js                  141.31 KiB       28.63 KiB
  dist/js/worker.3f845d96.js                116.95 KiB       27.14 KiB
  dist/js/super-user~user~worker.89497bd    95.72 KiB        26.28 KiB
  4.js
  dist/js/super-user~worker.de7f3513.js     41.93 KiB        14.24 KiB
  dist/js/app.68802416.js                   33.93 KiB        9.72 KiB
  dist/js/landing-page.abe82391.js          28.14 KiB        10.78 KiB
  dist/precache-manifest.5d1728ab9e82dbe    6.23 KiB         1.84 KiB
  f01c617532cf35342.js
  dist/service-worker.js                    1.04 KiB         0.61 KiB
  dist/css/chunk-vendors.c380a352.css       354.50 KiB       40.53 KiB
  dist/css/super-user~user~worker.b6103c    30.99 KiB        4.90 KiB
  9d.css
  dist/css/user.efb5b1bf.css                24.94 KiB        4.66 KiB
  dist/css/super-user.822e51f6.css          17.71 KiB        3.26 KiB
  dist/css/super-user~worker.3a0fff16.cs    12.84 KiB        1.87 KiB
  s
  dist/css/landing-page.de5bd5da.css        7.32 KiB         1.77 KiB
  dist/css/worker.7dcd23eb.css              5.72 KiB         1.63 KiB
  dist/css/app.3e078b33.css                 3.55 KiB         1.16 KiB
</code>```

I've updated a view, we will call it Feature.vue, and is defined as

```<code>const Feature = () =>
  import(/* webpackChunkName: "user" */ "./views/Feature.vue");
</code>```

But in the build the hash of the user modules are not updated, this causes to a lot of users see old versions of my app and need to go to the landing page and make a refresh to refresh the app, if they refresh the page on feature they can see changes, but the next time they access to feature the cache will show the old version.

Also to be more specific my changes are some js changes, then at least the js file needs to change the hash there is a way to force change hash of all files every update?.

答:
assuming you have a Vue CLI project. under your src folder open up registerServiceWorker.js and make sure to flush the cache when the service worker detects changes:

import { register } from "register-service-worker";

if (process.env.NODE_ENV === "production") {
  register(`${process.env.BASE_URL}firebase-messaging-sw.js`, {
    registered() {
      console.log("Service worker has been registered.");
    },
    cached() {
      console.log("Content has been cached for offline use.");
    },
    updatefound() {
      // new content clear cache so user gets the new version
      caches.keys().then(cacheNames => {
        cacheNames.forEach(cacheName => {
          caches.delete(cacheName);
        });
      });
      console.log("New content is downloading.");
    },
    updated() {
      console.log("New content is available; please refresh.");
    },
    offline() {
      console.log(
        "No internet connection found. App is running in offline mode."
      );
    },
    error(error) {
      console.error("Error during service worker registration:", error);
    }
  });
}

```

Body:
I apply lazy loading and code splitting in my vue app

But somehow when I update my code and I deploy it to production only some chunks are updated with a new hash.

 File                                      Size             Gzipped

  dist/js/chunk-vendors.8bacd999.js         1379.15 KiB      418.03 KiB
  dist/js/super-user.55f6d84e.js            230.82 KiB       43.40 KiB
  dist/js/user.75857fc3.js                  141.31 KiB       28.63 KiB
  dist/js/worker.3f845d96.js                116.95 KiB       27.14 KiB
  dist/js/super-user~user~worker.89497bd    95.72 KiB        26.28 KiB
  4.js
  dist/js/super-user~worker.de7f3513.js     41.93 KiB        14.24 KiB
  dist/js/app.d05288d8.js                   33.93 KiB        9.72 KiB
  dist/js/landing-page.abe82391.js          28.14 KiB        10.78 KiB
  dist/precache-manifest.9e6d4f8b3b203e5    6.23 KiB         1.84 KiB
  a7409c4e5738c04b0.js
  dist/service-worker.js                    1.04 KiB         0.61 KiB
  dist/css/chunk-vendors.c380a352.css       354.50 KiB       40.53 KiB
  dist/css/super-user~user~worker.b6103c    30.99 KiB        4.90 KiB
  9d.css
  dist/css/user.efb5b1bf.css                24.94 KiB        4.66 KiB
  dist/css/super-user.78d831e9.css          17.71 KiB        3.26 KiB
  dist/css/super-user~worker.3a0fff16.cs    12.84 KiB        1.87 KiB
  s
  dist/css/landing-page.de5bd5da.css        7.32 KiB         1.77 KiB
  dist/css/worker.7dcd23eb.css              5.72 KiB         1.63 KiB
  dist/css/app.3e078b33.css                 3.55 KiB         1.16 KiB

VS

  File                                      Size             Gzipped

  dist/js/chunk-vendors.8bacd999.js         1379.15 KiB      418.03 KiB
  dist/js/super-user.0cf42025.js            233.18 KiB       43.64 KiB
  dist/js/user.75857fc3.js                  141.31 KiB       28.63 KiB
  dist/js/worker.3f845d96.js                116.95 KiB       27.14 KiB
  dist/js/super-user~user~worker.89497bd    95.72 KiB        26.28 KiB
  4.js
  dist/js/super-user~worker.de7f3513.js     41.93 KiB        14.24 KiB
  dist/js/app.68802416.js                   33.93 KiB        9.72 KiB
  dist/js/landing-page.abe82391.js          28.14 KiB        10.78 KiB
  dist/precache-manifest.5d1728ab9e82dbe    6.23 KiB         1.84 KiB
  f01c617532cf35342.js
  dist/service-worker.js                    1.04 KiB         0.61 KiB
  dist/css/chunk-vendors.c380a352.css       354.50 KiB       40.53 KiB
  dist/css/super-user~user~worker.b6103c    30.99 KiB        4.90 KiB
  9d.css
  dist/css/user.efb5b1bf.css                24.94 KiB        4.66 KiB
  dist/css/super-user.822e51f6.css          17.71 KiB        3.26 KiB
  dist/css/super-user~worker.3a0fff16.cs    12.84 KiB        1.87 KiB
  s
  dist/css/landing-page.de5bd5da.css        7.32 KiB         1.77 KiB
  dist/css/worker.7dcd23eb.css              5.72 KiB         1.63 KiB
  dist/css/app.3e078b33.css                 3.55 KiB         1.16 KiB

I've updated a view, we will call it Feature.vue, and is defined as

const Feature = () =>
  import(/* webpackChunkName: "user" */ "./views/Feature.vue");

But in the build the hash of the user modules are not updated, this causes to a lot of users see old versions of my app and need to go to the landing page and make a refresh to refresh the app, if they refresh the page on feature they can see changes, but the next time they access to feature the cache will show the old version.

Also to be more specific my changes are some js changes, then at least the js file needs to change the hash there is a way to force change hash of all files every update?.


问:
Are spatial queries possible using Python and cx_Oracle?
I am trying to execute a spatial query on an Oracle spatial table via python using the cx_Oracle package.

I can make generic queries successfully, but when I try a spatial query it results in errors.

This is what I have tried:

```<code>import cx_Oracle
...

lon = -120.494352
lat = 36.585289

# open a connection to oracle
con = cx_Oracle.connect('myuser/mypass@spatialdb')

# create a cursor
cur = con.cursor()

# Create and populate Oracle objects
typeObj = con.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = con.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = con.gettype("MDSYS.SDO_ORDINATE_ARRAY")
obj = typeObj.newobject()
obj.SDO_GTYPE = 2001
obj.SDO_SRID = 8307
obj.SDO_ELEM_INFO = elementInfoTypeObj.newobject()
obj.SDO_ELEM_INFO.extend([1, 1, 1])
obj.SDO_ORDINATES = ordinateTypeObj.newobject()
obj.SDO_ORDINATES.extend([lon, lat])
print("Created object", obj)

# set up a distance-calculating sql statement
sql = "select id into :id from spatialtbl s where sdo_nn(s.geometry, :obj, 'sdo_num_res=1', 1) = 'TRUE'"

try:
    # execute the distance sql
    cur.execute(sql, id=id, obj=obj)
    print(f'The id is {id.getvalue()}')
except cx_Oracle.Error as error:
    print(error)
</code>```

which results in the error:

```<code>ORA-01036: illegal variable name/number
</code>```

Can anyone tell me what I may be doing wrong code-wise or if spatial queries are even possible using Python and cx_Oracle? The cx_Oracle documentation doesn't specifically address this as far as I can tell/find.

答:
There is a brief mention in the documentation:

Binding Spatial Datatypes

Here are two examples from the cx_Oracle source code repository:

InsertGeometry.py

SpatialToGeoPandas.py

Here's a presentation from the recent Oracle Conference:

Analyzing Location-based Patterns with Python and Oracle Database
The download links are there but may not be obvious pdf and zip.

In your example, you probably need to do at least id = cursor.var(int), see Bind Direction so cx_Oracle knows what to do with the value you are getting from the DB.

Body:
I am trying to execute a spatial query on an Oracle spatial table via python using the cx_Oracle package.

I can make generic queries successfully, but when I try a spatial query it results in errors.

This is what I have tried:

import cx_Oracle
...

lon = -120.494352
lat = 36.585289

# open a connection to oracle
con = cx_Oracle.connect('myuser/mypass@spatialdb')

# create a cursor
cur = con.cursor()

# Create and populate Oracle objects
typeObj = con.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = con.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = con.gettype("MDSYS.SDO_ORDINATE_ARRAY")
obj = typeObj.newobject()
obj.SDO_GTYPE = 2001
obj.SDO_SRID = 8307
obj.SDO_ELEM_INFO = elementInfoTypeObj.newobject()
obj.SDO_ELEM_INFO.extend([1, 1, 1])
obj.SDO_ORDINATES = ordinateTypeObj.newobject()
obj.SDO_ORDINATES.extend([lon, lat])
print("Created object", obj)

# set up a distance-calculating sql statement
sql = "select id into :id from spatialtbl s where sdo_nn(s.geometry, :obj, 'sdo_num_res=1', 1) = 'TRUE'"

try:
    # execute the distance sql
    cur.execute(sql, id=id, obj=obj)
    print(f'The id is {id.getvalue()}')
except cx_Oracle.Error as error:
    print(error)

which results in the error:

ORA-01036: illegal variable name/number

Can anyone tell me what I may be doing wrong code-wise or if spatial queries are even possible using Python and cx_Oracle? The cx_Oracle documentation doesn't specifically address this as far as I can tell/find.


问:
Mixing HTML and Python code - how to refer to a changing filename within the HTML code
I'm trying to automate a process where I take a snapshot everyday but change the filename to that date. For example, I'd like to reference today's file as "20200219 snapshot.png" and change it to "20200220 snapshot.png" tomorrow. The problem is, I can't input the variable name filename after the img src and have to put in the hardcoded exact String.

```<code>date = date.strftime('%Y%m%d')
filename = date + " snapshot.png"

html = """\
<html>
  <head></head>
    <body>
      <img src="Directory/snapshot.png"/>
    </body>
</html>
"""
</code>```

答:
Just make it a string preceded by f and add your variable between {} to the string

import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"

html = f"""\

"""

print(html)
```

<p>Or use simple string concatenation instead</p>

<pre class="lang-py prettyprint-override"><code>import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"

html = f"""\
<html>
  <head></head>
    <body>
      <img src="Directory/"""
html += filename
html += """/>
    </body>
</html>
"""

print(html)
</code>```

Body:
I'm trying to automate a process where I take a snapshot everyday but change the filename to that date. For example, I'd like to reference today's file as "20200219 snapshot.png" and change it to "20200220 snapshot.png" tomorrow. The problem is, I can't input the variable name filename after the img src and have to put in the hardcoded exact String.

date = date.strftime('%Y%m%d')
filename = date + " snapshot.png"

html = """\

"""

Body:
Just make it a string preceded by f and add your variable between {} to the string

import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"

html = f"""\
<html>
  <head></head>
    <body>
      <img src="Directory/{filename}"/>
    </body>
</html>
"""

print(html)

Or use simple string concatenation instead

import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"

html = f"""\
<html>
  <head></head>
    <body>
      <img src="Directory/"""
html += filename
html += """/>
    </body>
</html>
"""

print(html)


问:
How To Set Format Of Multiline Comment in IntelliJ
By default IntelliJ is formatting multiline comment as

```<code>/*
A multi line comment
Line 2
*/
</code>```

I would like it to format the multiline comment as

```<code>   /*
    * A multi line comment
    * Line 2
    *
    */
</code>```

to match the code style standard used by other developers who use Eclipse on my team.

I've combed through the Settings Java Code but cannot find a way to force IntelliJ to automatically put an * at the beginning of each line in the multiline comment.

Thank you for the help.

答:
We can achieve the same with /** + Enter.

Source

Body:
By default IntelliJ is formatting multiline comment as

/*
A multi line comment
Line 2
*/

I would like it to format the multiline comment as

   /*
    * A multi line comment
    * Line 2
    *
    */

to match the code style standard used by other developers who use Eclipse on my team.

I've combed through the Settings Java Code but cannot find a way to force IntelliJ to automatically put an * at the beginning of each line in the multiline comment.

Thank you for the help.


问:
exercise 18-8 python crash course - Can't loop
I'm trying to loop through the toppings but the code doesn't work.

models:

```<code>from django.db import models

class Pizza(models.Model):

name = models.CharField(max_length=200)

def __str__(self):
    return self.name

class Toppings(models.Model):

pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE)
name = models.CharField(max_length=200)

class Meta:
    verbose_name_plural = 'toppings'

def __str__(self):
    return self.name
</code>```

urls.py:

```<code>from django.urls import path
from . import views

app_name = 'pizzas'

urlpatterns = [
    path('', views.index, name='index'),
    path('pizzas/', views.pizzas, name='pizzas'),
    path('pizzas/<int:toppings_id>/', views.toppings, name='toppings')
]
</code>```

views:

```<code>from django.shortcuts import render
from .models import Pizza
from .models import Toppings

def index(request):
return render(request, 'pizzas/index.html')

def pizzas(request):

pizzas = Pizza.objects.all()
context = {'pizzas': pizzas}
return render(request, 'pizzas/pizzas.html', context)

def toppings(request, toppings_id):

toppings = Toppings.objects.get(id=toppings_id)
context = {'toppings': toppings}
return render(request, 'pizzas/toppings.html', context)
</code>```

toppings.html:

```<code>{% extends 'pizzas/base.html' %}

{% block content %}

<p>Pizzas: {{ pizza }}</p>
<p>Toppings:</p>
<ul>
{% for topping in toppings %}
  <li>
      <p>{{ topping }}</p>
  </li>
{% empty %}
  <li>There are no toppings</li>
{% endfor %}
</ul>

{% endblock content %}
</code>```

pizzas.html:

```<code>{% extends 'pizzas/base.html' %}

{% block content %}

<p>Pizzas</p>

<ul>
{% for pizza in pizzas %}
  <li>
    <a href="{% url 'pizzas:toppings' pizza.id %}">{{ pizza }}</a>
  </li>
{% empty %}
  <li>
    No pizzas yet duh
  </li>
{% endfor %}
</ul>

{% endblock content %}
</code>```

The problem is in toppings.html on the for loop, and maybe something wrong with the toppings views too.

答:
Here:

```<code>toppings = Toppings.objects.get(id=toppings_id)
context = {'toppings': toppings}
</code>```

you have single record because of using get. You can't loop over single object. Please, read the docs about methods usage.
If you want to list all toppings, then remove toppings_id from url and view, and use all() instead:

```<code>Toppings.objects.all()
</code>```

You can look forward and check this example of how to create a view that allows to get single record by ID and list all records list.

Body:
I'm trying to loop through the toppings but the code doesn't work.

models:

from django.db import models

class Pizza(models.Model):

name = models.CharField(max_length=200)

def __str__(self):
    return self.name

class Toppings(models.Model):

pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE)
name = models.CharField(max_length=200)

class Meta:
    verbose_name_plural = 'toppings'

def __str__(self):
    return self.name

urls.py:

from django.urls import path
from . import views

app_name = 'pizzas'

urlpatterns = [
    path('', views.index, name='index'),
    path('pizzas/', views.pizzas, name='pizzas'),
    path('pizzas/<int:toppings_id>/', views.toppings, name='toppings')
]

views:

from django.shortcuts import render
from .models import Pizza
from .models import Toppings

def index(request):
return render(request, 'pizzas/index.html')

def pizzas(request):

pizzas = Pizza.objects.all()
context = {'pizzas': pizzas}
return render(request, 'pizzas/pizzas.html', context)

def toppings(request, toppings_id):

toppings = Toppings.objects.get(id=toppings_id)
context = {'toppings': toppings}
return render(request, 'pizzas/toppings.html', context)

toppings.html:

{% extends 'pizzas/base.html' %}

{% block content %}

Pizzas: {{ pizza }}

Toppings:

{% for topping in toppings %}

{{ topping }}

{% empty %}

There are no toppings

{% endfor %}

{% endblock content %}

pizzas.html:

{% extends 'pizzas/base.html' %}

{% block content %}

Pizzas

{% for pizza in pizzas %}

    {{ pizza }}

{% empty %}

    No pizzas yet duh

{% endfor %}

{% endblock content %}

The problem is in toppings.html on the for loop, and maybe something wrong with the toppings views too.

Body:
Here:

toppings = Toppings.objects.get(id=toppings_id)
context = {'toppings': toppings}

you have single record because of using get. You can't loop over single object. Please, read the docs about methods usage.
If you want to list all toppings, then remove toppings_id from url and view, and use all() instead:

Toppings.objects.all()

You can look forward and check this example of how to create a view that allows to get single record by ID and list all records list.


问:
Disabling the linux virtual console completely
I have a raspberry pi, which listens on the network and plays videos on hdmi when told.
This is accomplished with omxplayer, without X11.

I want to make the screen completely back at all times except when omxplayer is showing something. By default there were a getty, linux debug output, a blinking cursor, a raspberry logo etc showing on the hdmi output. I have managed to disable everything with several cmdline.txt options.

However, it feels like a whole bunch of workarounds. I would like to disable the text output to the screen altogether in linux, like disabling the virtual terminal and the console altogether. Just like there is nothing on the 3.5mm sound output by default I don't want anything on the hdmi. Is this possible?

答:
Check out this question for details on how to disable the VT console.

For my specific system (i.MX6), getty was still being initialized on tty1 so I had to disable it on startup:

```<code>systemctl stop getty@tty1.service
systemctl disable getty@tty1.service
</code>```

You can also disable the framebuffer through a bootloader option. I'm not sure which bootloader the RPi uses but you can look into the fbcon parameter.

The default might be fbcon=map:1 in which case you should to map it to a different fbdev device. This should remove the VT console entirely.

ContentLicense: CC BY-SA 3.0

Body:
Check out this question for details on how to disable the VT console.

For my specific system (i.MX6), getty was still being initialized on tty1 so I had to disable it on startup:

systemctl stop getty@tty1.service
systemctl disable getty@tty1.service

You can also disable the framebuffer through a bootloader option. I'm not sure which bootloader the RPi uses but you can look into the fbcon parameter.

The default might be fbcon=map:1 in which case you should to map it to a different fbdev device. This should remove the VT console entirely.


问:
Email only specific values in a for loop
This is my first time using Python to call an API, so please bear with me.

I was able to grab from the list of everything, but I only want to store the users that are disabled in a variable and then send the variable as an email.

The entire list is as follows:

```<code>username, address, etc, ..., enabled
username1, address, etc, ..., disabled
username2, address, etc, ..., enabled
username3, address, etc, ..., disabled
</code>```

Here is the code I have so far:

users = admin_api.get_users()

for user in users:
       #some code that only adds username and status to a variable if status = disabled

#if variable has a value, send email, if not, do not send email.
if variable is None:

me= "from@123.com"
you = "to@123.com"

msg = MIMEMultipart('alternative')
msg['Subject'] = "Users that are disabled"
msg['From'] = me
msg['To'] = you

html = """\

Here are the list of disabled users

     $VARIABLE

"""

part = MIMEText(html, 'html')
msg.attach(part)
s = smtplib.SMTP('smtp@123.com')
s.sendmail(me, you, msg.as_string())
s.quit()
```

Output:
Email shows only users that are disabled:
username1 account is disabled
username3 account is disabled

Thanks

答:
I'm assuming below that users is a list of dictionaries like this:

```<code>{"username": "username1", "address": "address1", ..., "status": "disabled"}
</code>```

Adjust the syntax if it's something else, like class instances.

Then use a list comprehension and then join the results.

```<code>disabled_users = "<br>".join([user['username'] + ' is disabled' for user in users if user['status'] == 'disabled'])
</code>```

And in the HTML you can then substitute the variable

```<code>html = f"""
<html>
  <head></head>
  <body>
    <p>Here are the list of disabled users<br>
     {disabled_users}
    </p>
  </body>
</html>
"""
</code>```

Body:
This is my first time using Python to call an API, so please bear with me.

I was able to grab from the list of everything, but I only want to store the users that are disabled in a variable and then send the variable as an email.

The entire list is as follows:

username, address, etc, ..., enabled
username1, address, etc, ..., disabled
username2, address, etc, ..., enabled
username3, address, etc, ..., disabled

Here is the code I have so far:

users = admin_api.get_users()

for user in users:
       #some code that only adds username and status to a variable if status = disabled

#if variable has a value, send email, if not, do not send email.
if variable is None:

me= "from@123.com"
you = "to@123.com"

msg = MIMEMultipart('alternative')
msg['Subject'] = "Users that are disabled"
msg['From'] = me
msg['To'] = you

html = """\

Here are the list of disabled users

     $VARIABLE

"""

part = MIMEText(html, 'html')
msg.attach(part)
s = smtplib.SMTP('smtp@123.com')
s.sendmail(me, you, msg.as_string())
s.quit()

Output:
Email shows only users that are disabled:
username1 account is disabled
username3 account is disabled

Thanks

Body:
I'm assuming below that users is a list of dictionaries like this:

{"username": "username1", "address": "address1", ..., "status": "disabled"}

Adjust the syntax if it's something else, like class instances.

Then use a list comprehension and then join the results.

disabled_users = "<br>".join([user['username'] + ' is disabled' for user in users if user['status'] == 'disabled'])

And in the HTML you can then substitute the variable

html = f"""
<html>
  <head></head>
  <body>
    <p>Here are the list of disabled users<br>
     {disabled_users}
    </p>
  </body>
</html>
"""


问:
Flutter: Flutter Firebase Crashlytics not showing for iOS
I can't get the crash logs to show for iOS (works for Android).
I have tested the following:

Started the app using "flutter run", detached the debugger, trigger the crash and restarted the application (all this several time)

Also tried to run from XCode and then stopped the application and trigger the crash and restarted the application

Not that the crash doesn't actually make the application crash, but I don't know how to do that from flutter

Startup:

```<code>void main() {
  // Set `enableInDevMode` to true to see reports while in debug mode
  // This is only to be used for confirming that reports are being
  // submitted as expected. It is not intended to be used for everyday
  // development.
  Crashlytics.instance.enableInDevMode = true;

  // Pass all uncaught errors from the framework to Crashlytics.
  FlutterError.onError = Crashlytics.instance.recordFlutterError;
  runApp(MyApp());
}
</code>```

Trigger:

```<code>FlatButton(
  child: const Text('Crash'),
  onPressed: () {
    Crashlytics.instance.crash();
    Crashlytics.instance.log("msg");
    Crashlytics.instance.recordFlutterError(new FlutterErrorDetails());
    Crashlytics.instance.recordError(new Exception("test"), null);
  }),
</code>```

Settings iOS:

Logg:

```<code>2020-02-07 10:47:59.988421+0100 Runner[32021:139387]  - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
2020-02-07 10:48:00.467672+0100 Runner[32021:139200] Configuring the default Firebase app...
2020-02-07 10:48:00.509841+0100 Runner[32021:139388] 6.12.0 - [Firebase/Core][I-COR000004] App with name __FIRAPP_DEFAULT does not exist.
2020-02-07 10:48:00.564015+0100 Runner[32021:139403] 6.12.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60105000 started
2020-02-07 10:48:00.633609+0100 Runner[32021:139403] 6.12.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2020-02-07 10:48:00.686296+0100 Runner[32021:139428] flutter: Observatory listening on http://127.0.0.1:51095/Jl5T2U0QjXU=/
2020-02-07 10:48:00.703093+0100 Runner[32021:139200] [Crashlytics] Version 3.14.0 (144)
2020-02-07 10:48:00.741256+0100 Runner[32021:139200] Configured the default Firebase app __FIRAPP_DEFAULT.
2020-02-07 10:48:00.746360+0100 Runner[32021:139200] [Fabric] [Fabric +with] called multiple times. Only the first call is honored, please pass all kits you wish to initialize
2020-02-07 10:48:00.788062+0100 Runner[32021:139387] 6.12.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO.
to ensure proper integration.
2020-02-07 10:48:00.907902+0100 Runner[32021:139387] [Fabric] failed to download settings Error Domain=FABNetworkError Code=-5 "(null)" UserInfo={status_code=403, type=2, request_id=, content_type=application/json; charset=utf-8}
2020-02-07 10:48:03.072501+0100 Runner[32021:139403] 6.12.0 - [Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: remote notifications are not supported in the simulator
2020-02-07 10:48:03.100106+0100 Runner[32021:139403] 6.12.0 - [Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: remote notifications are not supported in the simulator
2020-02-07 10:49:51.975510+0100 Runner[32021:139410] flutter: Flutter error caught by Crashlytics plugin:
2020-02-07 10:49:52.003794+0100 Runner[32021:139410] flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
2020-02-07 10:49:52.004161+0100 Runner[32021:139410] flutter: The following StateError was thrown while handling a gesture:
2020-02-07 10:49:52.004429+0100 Runner[32021:139410] flutter: Bad state: Error thrown by Crashlytics plugin
2020-02-07 10:49:52.005323+0100 Runner[32021:139410] flutter:
2020-02-07 10:49:52.006106+0100 Runner[32021:139410] flutter: When the exception was thrown, this was the stack:
2020-02-07 10:49:52.006490+0100 Runner[32021:139410] flutter: #0      Crashlytics.crash (package:firebase_crashlytics/src/firebase_crashlytics.dart:54:5)
2020-02-07 10:49:52.007125+0100 Runner[32021:139410] flutter: #1      _InformationPageState.build.<anonymous closure> (package:mainapp/pages/informationpage.dart:71:42)
2020-02-07 10:49:52.007856+0100 Runner[32021:139410] flutter: #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
2020-02-07 10:49:52.008560+0100 Runner[32021:139410] flutter: #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
2020-02-07 10:49:52.008828+0100 Runner[32021:139410] flutter: #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
2020-02-07 10:49:52.009341+0100 Runner[32021:139410] flutter: #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
2020-02-07 10:49:52.009923+0100 Runner[32021:139410] flutter: #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
2020-02-07 10:49:52.010181+0100 Runner[32021:139410] flutter: #7      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
2020-02-07 10:49:52.010389+0100 Runner[32021:139410] flutter: #8      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
2020-02-07 10:49:52.011013+0100 Runner[32021:139410] flutter: #9      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
2020-02-07 10:49:52.011399+0100 Runner[32021:139410] flutter: #10     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
2020-02-07 10:49:52.011511+0100 Runner[32021:139410] flutter: #11     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
2020-02-07 10:49:52.011970+0100 Runner[32021:139410] flutter: #12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
2020-02-07 10:49:52.012203+0100 Runner[32021:139410] flutter: #13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
2020-02-07 10:49:52.012346+0100 Runner[32021:139410] flutter: #17     _invoke1 (dart:ui/hooks.dart:273:10)
2020-02-07 10:49:52.012806+0100 Runner[32021:139410] flutter: #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
2020-02-07 10:49:52.012924+0100 Runner[32021:139410] flutter: (elided 3 frames from package dart:async)
2020-02-07 10:49:52.013019+0100 Runner[32021:139410] flutter:
2020-02-07 10:49:52.013112+0100 Runner[32021:139410] flutter: Handler: "onTap"
2020-02-07 10:49:52.013202+0100 Runner[32021:139410] flutter: Recognizer:
2020-02-07 10:49:52.013695+0100 Runner[32021:139410] flutter:   TapGestureRecognizer#89339
2020-02-07 10:49:52.014395+0100 Runner[32021:139410] flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
2020-02-07 10:49:52.086067+0100 Runner[32021:139410] flutter: firebase_crashlytics: Error reported to Crashlytics.
2020-02-07 10:49:52.739934+0100 Runner[32021:139410] flutter: Flutter error caught by Crashlytics plugin:
2020-02-07 10:49:52.743795+0100 Runner[32021:139410] flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
2020-02-07 10:49:52.743983+0100 Runner[32021:139410] flutter: The following StateError was thrown while handling a gesture:
2020-02-07 10:49:52.744139+0100 Runner[32021:139410] flutter: Bad state: Error thrown by Crashlytics plugin
2020-02-07 10:49:52.744313+0100 Runner[32021:139410] flutter:
2020-02-07 10:49:52.744542+0100 Runner[32021:139410] flutter: When the exception was thrown, this was the stack:
2020-02-07 10:49:52.744708+0100 Runner[32021:139410] flutter: #0      Crashlytics.crash (package:firebase_crashlytics/src/firebase_crashlytics.dart:54:5)
2020-02-07 10:49:52.744848+0100 Runner[32021:139410] flutter: #1      _InformationPageState.build.<anonymous closure> (package:mainapp/pages/informationpage.dart:71:42)
2020-02-07 10:49:52.744946+0100 Runner[32021:139410] flutter: #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
2020-02-07 10:49:52.745148+0100 Runner[32021:139410] flutter: #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
2020-02-07 10:49:52.751009+0100 Runner[32021:139410] flutter: #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
2020-02-07 10:49:52.751514+0100 Runner[32021:139410] flutter: #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
2020-02-07 10:49:52.751758+0100 Runner[32021:139410] flutter: #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
2020-02-07 10:49:52.752005+0100 Runner[32021:139410] flutter: #7      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
2020-02-07 10:49:52.752543+0100 Runner[32021:139410] flutter: #8      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
2020-02-07 10:49:52.753430+0100 Runner[32021:139410] flutter: #9      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
2020-02-07 10:49:52.753672+0100 Runner[32021:139410] flutter: #10     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
2020-02-07 10:49:52.755470+0100 Runner[32021:139410] flutter: #11     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
2020-02-07 10:49:52.755806+0100 Runner[32021:139410] flutter: #12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
2020-02-07 10:49:52.756565+0100 Runner[32021:139410] flutter: #13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
2020-02-07 10:49:52.757056+0100 Runner[32021:139410] flutter: #17     _invoke1 (dart:ui/hooks.dart:273:10)
2020-02-07 10:49:52.757240+0100 Runner[32021:139410] flutter: #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
2020-02-07 10:49:52.757838+0100 Runner[32021:139410] flutter: (elided 3 frames from package dart:async)
2020-02-07 10:49:52.758046+0100 Runner[32021:139410] flutter:
</code>```

Result:

Edit1:
If I look into project.pbxproj, in their example https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_crashlytics/example/ios/Runner.xcodeproj/project.pbxproj it says:

inputPaths = (
"$(SRCROOT)/newInputFile",          );

while mine says:

inputPaths = (
"$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)",          );

which is according to their documentation https://pub.dev/packages/firebase_crashlytics
.Could that be the reason?

答:
Did you add the GoogleService.plist to your project? Since the console output for me looks like Firebase can not find the configurations.

Also keep in mind that crashes have a delay of one day before they are in your Online Dashboard, since you have the spark plan. For the paid versions i don’t know the delay.

Body:
I can't get the crash logs to show for iOS (works for Android).
I have tested the following:

Started the app using "flutter run", detached the debugger, trigger the crash and restarted the application (all this several time)

Also tried to run from XCode and then stopped the application and trigger the crash and restarted the application

Not that the crash doesn't actually make the application crash, but I don't know how to do that from flutter

Startup:

void main() {
  // Set `enableInDevMode` to true to see reports while in debug mode
  // This is only to be used for confirming that reports are being
  // submitted as expected. It is not intended to be used for everyday
  // development.
  Crashlytics.instance.enableInDevMode = true;

  // Pass all uncaught errors from the framework to Crashlytics.
  FlutterError.onError = Crashlytics.instance.recordFlutterError;
  runApp(MyApp());
}

Trigger:

FlatButton(
  child: const Text('Crash'),
  onPressed: () {
    Crashlytics.instance.crash();
    Crashlytics.instance.log("msg");
    Crashlytics.instance.recordFlutterError(new FlutterErrorDetails());
    Crashlytics.instance.recordError(new Exception("test"), null);
  }),

Settings iOS:

Logg:

2020-02-07 10:47:59.988421+0100 Runner[32021:139387]  - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
2020-02-07 10:48:00.467672+0100 Runner[32021:139200] Configuring the default Firebase app...
2020-02-07 10:48:00.509841+0100 Runner[32021:139388] 6.12.0 - [Firebase/Core][I-COR000004] App with name __FIRAPP_DEFAULT does not exist.
2020-02-07 10:48:00.564015+0100 Runner[32021:139403] 6.12.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60105000 started
2020-02-07 10:48:00.633609+0100 Runner[32021:139403] 6.12.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2020-02-07 10:48:00.686296+0100 Runner[32021:139428] flutter: Observatory listening on http://127.0.0.1:51095/Jl5T2U0QjXU=/
2020-02-07 10:48:00.703093+0100 Runner[32021:139200] [Crashlytics] Version 3.14.0 (144)
2020-02-07 10:48:00.741256+0100 Runner[32021:139200] Configured the default Firebase app __FIRAPP_DEFAULT.
2020-02-07 10:48:00.746360+0100 Runner[32021:139200] [Fabric] [Fabric +with] called multiple times. Only the first call is honored, please pass all kits you wish to initialize
2020-02-07 10:48:00.788062+0100 Runner[32021:139387] 6.12.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO.
to ensure proper integration.
2020-02-07 10:48:00.907902+0100 Runner[32021:139387] [Fabric] failed to download settings Error Domain=FABNetworkError Code=-5 "(null)" UserInfo={status_code=403, type=2, request_id=, content_type=application/json; charset=utf-8}
2020-02-07 10:48:03.072501+0100 Runner[32021:139403] 6.12.0 - [Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: remote notifications are not supported in the simulator
2020-02-07 10:48:03.100106+0100 Runner[32021:139403] 6.12.0 - [Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: remote notifications are not supported in the simulator
2020-02-07 10:49:51.975510+0100 Runner[32021:139410] flutter: Flutter error caught by Crashlytics plugin:
2020-02-07 10:49:52.003794+0100 Runner[32021:139410] flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
2020-02-07 10:49:52.004161+0100 Runner[32021:139410] flutter: The following StateError was thrown while handling a gesture:
2020-02-07 10:49:52.004429+0100 Runner[32021:139410] flutter: Bad state: Error thrown by Crashlytics plugin
2020-02-07 10:49:52.005323+0100 Runner[32021:139410] flutter:
2020-02-07 10:49:52.006106+0100 Runner[32021:139410] flutter: When the exception was thrown, this was the stack:
2020-02-07 10:49:52.006490+0100 Runner[32021:139410] flutter: #0      Crashlytics.crash (package:firebase_crashlytics/src/firebase_crashlytics.dart:54:5)
2020-02-07 10:49:52.007125+0100 Runner[32021:139410] flutter: #1      _InformationPageState.build.<anonymous closure> (package:mainapp/pages/informationpage.dart:71:42)
2020-02-07 10:49:52.007856+0100 Runner[32021:139410] flutter: #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
2020-02-07 10:49:52.008560+0100 Runner[32021:139410] flutter: #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
2020-02-07 10:49:52.008828+0100 Runner[32021:139410] flutter: #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
2020-02-07 10:49:52.009341+0100 Runner[32021:139410] flutter: #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
2020-02-07 10:49:52.009923+0100 Runner[32021:139410] flutter: #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
2020-02-07 10:49:52.010181+0100 Runner[32021:139410] flutter: #7      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
2020-02-07 10:49:52.010389+0100 Runner[32021:139410] flutter: #8      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
2020-02-07 10:49:52.011013+0100 Runner[32021:139410] flutter: #9      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
2020-02-07 10:49:52.011399+0100 Runner[32021:139410] flutter: #10     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
2020-02-07 10:49:52.011511+0100 Runner[32021:139410] flutter: #11     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
2020-02-07 10:49:52.011970+0100 Runner[32021:139410] flutter: #12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
2020-02-07 10:49:52.012203+0100 Runner[32021:139410] flutter: #13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
2020-02-07 10:49:52.012346+0100 Runner[32021:139410] flutter: #17     _invoke1 (dart:ui/hooks.dart:273:10)
2020-02-07 10:49:52.012806+0100 Runner[32021:139410] flutter: #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
2020-02-07 10:49:52.012924+0100 Runner[32021:139410] flutter: (elided 3 frames from package dart:async)
2020-02-07 10:49:52.013019+0100 Runner[32021:139410] flutter:
2020-02-07 10:49:52.013112+0100 Runner[32021:139410] flutter: Handler: "onTap"
2020-02-07 10:49:52.013202+0100 Runner[32021:139410] flutter: Recognizer:
2020-02-07 10:49:52.013695+0100 Runner[32021:139410] flutter:   TapGestureRecognizer#89339
2020-02-07 10:49:52.014395+0100 Runner[32021:139410] flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
2020-02-07 10:49:52.086067+0100 Runner[32021:139410] flutter: firebase_crashlytics: Error reported to Crashlytics.
2020-02-07 10:49:52.739934+0100 Runner[32021:139410] flutter: Flutter error caught by Crashlytics plugin:
2020-02-07 10:49:52.743795+0100 Runner[32021:139410] flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
2020-02-07 10:49:52.743983+0100 Runner[32021:139410] flutter: The following StateError was thrown while handling a gesture:
2020-02-07 10:49:52.744139+0100 Runner[32021:139410] flutter: Bad state: Error thrown by Crashlytics plugin
2020-02-07 10:49:52.744313+0100 Runner[32021:139410] flutter:
2020-02-07 10:49:52.744542+0100 Runner[32021:139410] flutter: When the exception was thrown, this was the stack:
2020-02-07 10:49:52.744708+0100 Runner[32021:139410] flutter: #0      Crashlytics.crash (package:firebase_crashlytics/src/firebase_crashlytics.dart:54:5)
2020-02-07 10:49:52.744848+0100 Runner[32021:139410] flutter: #1      _InformationPageState.build.<anonymous closure> (package:mainapp/pages/informationpage.dart:71:42)
2020-02-07 10:49:52.744946+0100 Runner[32021:139410] flutter: #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
2020-02-07 10:49:52.745148+0100 Runner[32021:139410] flutter: #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
2020-02-07 10:49:52.751009+0100 Runner[32021:139410] flutter: #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
2020-02-07 10:49:52.751514+0100 Runner[32021:139410] flutter: #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
2020-02-07 10:49:52.751758+0100 Runner[32021:139410] flutter: #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
2020-02-07 10:49:52.752005+0100 Runner[32021:139410] flutter: #7      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
2020-02-07 10:49:52.752543+0100 Runner[32021:139410] flutter: #8      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
2020-02-07 10:49:52.753430+0100 Runner[32021:139410] flutter: #9      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
2020-02-07 10:49:52.753672+0100 Runner[32021:139410] flutter: #10     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
2020-02-07 10:49:52.755470+0100 Runner[32021:139410] flutter: #11     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
2020-02-07 10:49:52.755806+0100 Runner[32021:139410] flutter: #12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
2020-02-07 10:49:52.756565+0100 Runner[32021:139410] flutter: #13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
2020-02-07 10:49:52.757056+0100 Runner[32021:139410] flutter: #17     _invoke1 (dart:ui/hooks.dart:273:10)
2020-02-07 10:49:52.757240+0100 Runner[32021:139410] flutter: #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
2020-02-07 10:49:52.757838+0100 Runner[32021:139410] flutter: (elided 3 frames from package dart:async)
2020-02-07 10:49:52.758046+0100 Runner[32021:139410] flutter:

Result:

Edit1:
If I look into project.pbxproj, in their example https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_crashlytics/example/ios/Runner.xcodeproj/project.pbxproj it says:

inputPaths = (
"$(SRCROOT)/newInputFile",          );

while mine says:

inputPaths = (
"$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)",          );

which is according to their documentation https://pub.dev/packages/firebase_crashlytics
.Could that be the reason?


问:
Downloading/Exporting sites Search Results by using Export button in Python
So I'm trying to use Python to scrape data from the following website (with sample query): https://par.nsf.gov/**search**/fulltext:NASA%20NOAA%20coral

However instead of scraping the search results, I realized that it would just be easier if I somehow click on the Save Results as "CSV" link in a programmatic way and work with that CSV data instead as it would free me from having to navigate all the pages of the search results.

I inspected the CSV link element and found it called an "exportSearch('csv') function.

By typing the function's name into the console I found that the CSV link is just setting window.location.href to: https://par.nsf.gov/export/format:csv/fulltext:NASA%20NOAA%20coral

If I follow that link in the same browser, the save prompt will open up with a csv to save.

My issue starts when I want to do replicate this process using python. If I try to call the export link directly using the Requests library, the response is empty.

```<code>url = "https://par.nsf.gov/export/format:csv/fulltext:" + urllib.parse.quote("NASA NOAA coral")
print("URL: ", url)
response = requests.get(url)
print("Response: ", len(response.content))
</code>```

Can someone show me what I'm missing? I don't know how to first establish search results on the website's server that I can then access for export using Python.

答:
I believe the link to download the CSV is here:

```<code>https://par.nsf.gov/export/format:csv//term:your_search_term
</code>```

your_search_term is URL encoded

in your case, the link is: https://par.nsf.gov/export/format:csv//filter-results:F/term:NASA%20NOAA%20coral

Body:
So I'm trying to use Python to scrape data from the following website (with sample query): https://par.nsf.gov/**search**/fulltext:NASA%20NOAA%20coral

However instead of scraping the search results, I realized that it would just be easier if I somehow click on the Save Results as "CSV" link in a programmatic way and work with that CSV data instead as it would free me from having to navigate all the pages of the search results.

I inspected the CSV link element and found it called an "exportSearch('csv') function.

By typing the function's name into the console I found that the CSV link is just setting window.location.href to: https://par.nsf.gov/export/format:csv/fulltext:NASA%20NOAA%20coral

If I follow that link in the same browser, the save prompt will open up with a csv to save.

My issue starts when I want to do replicate this process using python. If I try to call the export link directly using the Requests library, the response is empty.

url = "https://par.nsf.gov/export/format:csv/fulltext:" + urllib.parse.quote("NASA NOAA coral")
print("URL: ", url)
response = requests.get(url)
print("Response: ", len(response.content))

Can someone show me what I'm missing? I don't know how to first establish search results on the website's server that I can then access for export using Python.

Body:
I believe the link to download the CSV is here:

https://par.nsf.gov/export/format:csv//term:your_search_term

your_search_term is URL encoded

in your case, the link is: https://par.nsf.gov/export/format:csv//filter-results:F/term:NASA%20NOAA%20coral


问:
How to extract the orderconfirmedoid from from the current url using Selenium and Python
I have created an automation script to place an order, My main objective was to get the order id from the URL. I am storing my whole URL in a string this URL has my order id. Now, how I can only get order id from URL.
This is my URL which I am getting as a string I have also bold out the specific string (order id) which I want:

https://www.fitotouch.com/checkout/orderconfirmedoid=5e4d212fadda911b34f8862c&authCode=NWU0ZDIxMmZhZGRhOTExYjM0Zjg4NjJjOjIwMjAtMDItMTlUMTE6NTE6MDkuNDE2WnqeukQEbFNV8aOXKuJtXpOsH_DpTTGB7zCdbXlrhZOR

Below is my code

```<code>import time
import self as self
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# declare variable to store the URL to be visited
base_url="https://www.fitotouch.com"

driver = webdriver.Chrome('E:/Chrome driver/chromedriver.exe')
driver.maximize_window()
#function of our 'driver' object.
driver.implicitly_wait(10) #10 is in seconds
driver.get(base_url)
driver.implicitly_wait(10)
driver.find_element_by_name('password').send_keys("*****")
driver.implicitly_wait(10)
driver.find_element_by_class_name('arrow-icon').click()

driver.implicitly_wait(10)
            #FITO NAMES
driver.find_element_by_link_text("FiveSeasons").click()
driver.find_element_by_xpath('/html/body/div[1]/main/article/section/div[2]/div/section/div/div[1]/a').click()
driver.find_element_by_xpath('/html/body/div[1]/main/article/section/div[2]/div/section/article/section[1]/section/div/div[4]/div').click()
time.sleep(2.4)

#driver.find_element_by_xpath('/html/body/div[1]/header/div[3]/div/div[2]/div[3]/div[2]/a/span/svg').click()
driver.get("https://www.fitotouch.com/cart")
time.sleep(2.4)
#driver.execute_script("window.scrollTo(300, 0)")
driver.get("https://www.fitotouch.com/checkout")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[1]/div[2]/form/div[1]/div[1]/input').send_keys("test@gmail.com")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[1]/div[2]/form/div[3]/button').click()
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[1]/div[1]/input').send_keys("test")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[1]/div[2]/input').send_keys("Malik")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[1]/div[1]/input').send_keys("port qasim")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[4]/input').send_keys("5426")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[5]/input').send_keys("karachi")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[6]/input').send_keys("sindh")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[3]/input').send_keys("031545454")
time.sleep(2.4)
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[4]').click()
time.sleep(2.4)
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[3]/div[2]/div/form/div[7]').click()
time.sleep(2.4)
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[4]/div[2]/div[4]').click()
time.sleep(2.4)
url = driver.current_url
print(url)
</code>```

答:
You can use the Python built-in module re to extract the orderconfirmedoid using multiple delimiters as follows:

Code:

```<code>#url = driver.current_url
url = "https://www.fitotouch.com/checkout/orderconfirmedoid=5e4d212fadda911b34f8862c&authCode=NWU0ZDIxMmZhZGRhOTExYjM0Zjg4NjJjOjIwMjAtMDItMTlUMTE6NTE6MDkuNDE2WnqeukQEbFNV8aOXKuJtXpOsH_DpTTGB7zCdbXlrhZOR"
my_order_id = re.split('=|&', url)[1]
print(my_order_id)
</code>```

Console Output:

```<code>5e4d212fadda911b34f8862c
</code>```

Body:
I have created an automation script to place an order, My main objective was to get the order id from the URL. I am storing my whole URL in a string this URL has my order id. Now, how I can only get order id from URL.
This is my URL which I am getting as a string I have also bold out the specific string (order id) which I want:

https://www.fitotouch.com/checkout/orderconfirmedoid=5e4d212fadda911b34f8862c&authCode=NWU0ZDIxMmZhZGRhOTExYjM0Zjg4NjJjOjIwMjAtMDItMTlUMTE6NTE6MDkuNDE2WnqeukQEbFNV8aOXKuJtXpOsH_DpTTGB7zCdbXlrhZOR

Below is my code

import time
import self as self
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# declare variable to store the URL to be visited
base_url="https://www.fitotouch.com"

driver = webdriver.Chrome('E:/Chrome driver/chromedriver.exe')
driver.maximize_window()
#function of our 'driver' object.
driver.implicitly_wait(10) #10 is in seconds
driver.get(base_url)
driver.implicitly_wait(10)
driver.find_element_by_name('password').send_keys("*****")
driver.implicitly_wait(10)
driver.find_element_by_class_name('arrow-icon').click()

driver.implicitly_wait(10)
            #FITO NAMES
driver.find_element_by_link_text("FiveSeasons").click()
driver.find_element_by_xpath('/html/body/div[1]/main/article/section/div[2]/div/section/div/div[1]/a').click()
driver.find_element_by_xpath('/html/body/div[1]/main/article/section/div[2]/div/section/article/section[1]/section/div/div[4]/div').click()
time.sleep(2.4)

#driver.find_element_by_xpath('/html/body/div[1]/header/div[3]/div/div[2]/div[3]/div[2]/a/span/svg').click()
driver.get("https://www.fitotouch.com/cart")
time.sleep(2.4)
#driver.execute_script("window.scrollTo(300, 0)")
driver.get("https://www.fitotouch.com/checkout")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[1]/div[2]/form/div[1]/div[1]/input').send_keys("test@gmail.com")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[1]/div[2]/form/div[3]/button').click()
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[1]/div[1]/input').send_keys("test")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[1]/div[2]/input').send_keys("Malik")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[1]/div[1]/input').send_keys("port qasim")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[4]/input').send_keys("5426")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[5]/input').send_keys("karachi")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[2]/div[6]/input').send_keys("sindh")
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[1]/div[3]/input').send_keys("031545454")
time.sleep(2.4)
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[2]/div[2]/form/div[4]').click()
time.sleep(2.4)
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[3]/div[2]/div/form/div[7]').click()
time.sleep(2.4)
driver.find_element_by_xpath('//*[@id="checkout"]/div/div[3]/div/div/div[1]/div[4]/div[2]/div[4]').click()
time.sleep(2.4)
url = driver.current_url
print(url)

Body:
You can use the Python built-in module re to extract the orderconfirmedoid using multiple delimiters as follows:

Code:

#url = driver.current_url
url = "https://www.fitotouch.com/checkout/orderconfirmedoid=5e4d212fadda911b34f8862c&authCode=NWU0ZDIxMmZhZGRhOTExYjM0Zjg4NjJjOjIwMjAtMDItMTlUMTE6NTE6MDkuNDE2WnqeukQEbFNV8aOXKuJtXpOsH_DpTTGB7zCdbXlrhZOR"
my_order_id = re.split('=|&', url)[1]
print(my_order_id)

Console Output:

5e4d212fadda911b34f8862c


问:
Convert int array to std::vector<int*>
I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.

I'm currently implementing this by doing the follow:

```<code>for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}
</code>```

Is it possible to implement this by using std::vector::insert() and std::being/end?

答:
The code below is rather fancy way to do what you want, but it is generic and it doesn't use for loop - it just passes pointers of array's elements to vector constructor:

```<code>template<class T, size_t ... Ints, size_t N>
std::vector<T*> makePtrsHelper(std::array<T,N>& arr, std::index_sequence<Ints...>) {
       return std::vector<T*>{ & std::get<Ints>(arr)... };
       // vector ctor taking pointers to array's elements
}

template<class T, size_t N>
std::vector<T*> makePtrs(std::array<T,N>& array) {
    return makePtrsHelper(array, std::make_index_sequence<N>{});
}

int main(){
    std::array<int,5> ar{1,2,3,4,5};
    std::vector<int*> v = makePtrs(ar);
</code>```

Live demo

Title: Convert int array to std::vector<int*>

Body:
I'm trying to "convert" an integer C style array to std::vector<int*> without using a for loop, or rather insert pointers of all array items in a vector.

I'm currently implementing this by doing the follow:

for (size_t i = 0; i < 5; i++)
{
    vector.push_back(&values[i]);
}

Is it possible to implement this by using std::vector::insert() and std::being/end?

Body:
The code below is rather fancy way to do what you want, but it is generic and it doesn't use for loop - it just passes pointers of array's elements to vector constructor:

template<class T, size_t ... Ints, size_t N>
std::vector<T*> makePtrsHelper(std::array<T,N>& arr, std::index_sequence<Ints...>) {
       return std::vector<T*>{ & std::get<Ints>(arr)... };
       // vector ctor taking pointers to array's elements
}

template<class T, size_t N>
std::vector<T*> makePtrs(std::array<T,N>& array) {
    return makePtrsHelper(array, std::make_index_sequence<N>{});
}

int main(){
    std::array<int,5> ar{1,2,3,4,5};
    std::vector<int*> v = makePtrs(ar);

Live demo


问:
React JS: Create a function that reads props and passes into render
I might have butchered the title/question completely as I'm new to React...

I have multiple objects which I'd like to pass into a component that'll output items in a certain format. The issue is that I'm not certain on how to pass in props into the object or component.

```<code>const ObjectA = {
   name: "objectA",
   data: {
     values: "Adds",
     dateRange: [props.state.startDate, props.state.endDate]
   }
}
</code>```

```<code>const DisplayObject = ({data}) => {
   <div>
      <RenderChart {data=data}/>
   </div>
}
</code>```

```<code>class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: moment("2019-12-01", "YYYY-MM-DD"),
      endDate: moment("2019-12-31", "YYYY-MM-DD"),
      focusedInput: null,
    };
  };
  render() {
    return (
       <DisplayObject {data=ObjectA.data} />
       <DisplayObject {data=ObjectB.data} />
    );
  };
}
</code>```

Currently I have it such that I have the entire code from DisplayObject and ObjectA, etc under render() but this is getting messy and also repetitive with DisplayObject being used multiple times. And in these I'm passing in this.state.startDate, this.state.endDate.

Thanks!

答:
you want to pass it like

```<code><DisplayObject data={ObjectA.data} />
</code>```

you don't need to encompass the jsx attribute in curly brackets

Body:
I might have butchered the title/question completely as I'm new to React...

I have multiple objects which I'd like to pass into a component that'll output items in a certain format. The issue is that I'm not certain on how to pass in props into the object or component.

const ObjectA = {
   name: "objectA",
   data: {
     values: "Adds",
     dateRange: [props.state.startDate, props.state.endDate]
   }
}

const DisplayObject = ({data}) => {

      <RenderChart {data=data}/>

}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: moment("2019-12-01", "YYYY-MM-DD"),
      endDate: moment("2019-12-31", "YYYY-MM-DD"),
      focusedInput: null,
    };
  };
  render() {
    return (
       <DisplayObject {data=ObjectA.data} />
       <DisplayObject {data=ObjectB.data} />
    );
  };
}

Currently I have it such that I have the entire code from DisplayObject and ObjectA, etc under render() but this is getting messy and also repetitive with DisplayObject being used multiple times. And in these I'm passing in this.state.startDate, this.state.endDate.

Thanks!

Body:
you want to pass it like

<DisplayObject data={ObjectA.data} />

you don't need to encompass the jsx attribute in curly brackets


问:
Alternative to fgets()?
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

```<code>void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}
</code>```

答:
You should be using the string.getline function for strings
cppreference

however in your case, you should be using a char[] to read into.

eg

```<code>string s;
char buffer[ 4096 ];
fgets(buffer, sizeof( buffer ), condorData);
s.assign( buffer, strlen( buffer ));
</code>```

or your code:

```<code>void Q_analysis( const char *data )
{
    char buffer[ 4096 ];

    FILE *condorData = _popen ("condor_q", "r");
    while( fgets( buffer, sizeof( buffer ), condorData ) != NULL )
    {
        if( strstr( buffer, data ) == NULL )
        {
                Sleep(2000);
        }
        else
        {
                break;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Alternative to fgets()?

Body:
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}

Body:
You should be using the string.getline function for strings
cppreference

however in your case, you should be using a char[] to read into.

eg

string s;
char buffer[ 4096 ];
fgets(buffer, sizeof( buffer ), condorData);
s.assign( buffer, strlen( buffer ));

or your code:

void Q_analysis( const char *data )
{
    char buffer[ 4096 ];

    FILE *condorData = _popen ("condor_q", "r");
    while( fgets( buffer, sizeof( buffer ), condorData ) != NULL )
    {
        if( strstr( buffer, data ) == NULL )
        {
                Sleep(2000);
        }
        else
        {
                break;
        }
    }
}

OwnerDisplayName: sfossen

LastEditorDisplayName: sfossen


问:
Control access to files based on DB values with PHP/Apache

What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

```<code>//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}
</code>```

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.

答:
You can redirect all requests for certain filetypes (or filenames, anything you can regex) with an '.htaccess' file in your DocumentRoot:

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule \.(gif|jpg|jpeg|png)$ imageHandler.php [NC,L]
</code>```

You can determine the original request from the $_SERVER superglobal, and use the appropriate headers to alert the browser you're returning an image. Then you read the image from disk (with file_get_contents() or similar) and write it to the browser with echo, in the same way you'd output HTML.

Body:
What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.

Body:
You can redirect all requests for certain filetypes (or filenames, anything you can regex) with an '.htaccess' file in your DocumentRoot:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule \.(gif|jpg|jpeg|png)$ imageHandler.php [NC,L]

You can determine the original request from the $_SERVER superglobal, and use the appropriate headers to alert the browser you're returning an image. Then you read the image from disk (with file_get_contents() or similar) and write it to the browser with echo, in the same way you'd output HTML.


问:
some existing users cant be found in TFS2018 workitem 'assigned to' field. even they are added to team project
My customer are using TFS2018 update2 version. and AD is used to manager TFS user.
there are about 1000 users right now. and about 10 to 20 users reported that their user account can't be found in TFS workitem "Assigned to" field. so strange and confused!

1)  we did check the 'AssignedTo' field of the workitem setting, is is of default setting, which allows existing user and valid users.

2) the users are even added to the team project, however, they can't be found when using search in 'assigned to 'field.

3) tried other type of workitems, any projects. same issues.

Generally speaking,  such users can be added to team project successfully.and they can't  be found in 'assigned to' filed of all workitems in all projects.  so we doubt it is some kind of user account sync issues?

and we did do more investigation and debugging.  and we found a para named operationScopes,and its value is 'ims';and if we add value 'ad' to this array. the users can be found!  and we noticed the returned value bdifference between such 'bad users' and 'good users' are of the 'Local directory'and 'localId' field.  the value is null here, for good user, neither local directory nor LocalID is null.
hope this clue works.
http://TFS2018server:8080/tfs/TFSCollection/_apis/IdentityPicker/Identities

and add more clues, we updated the Web Services_static\tfs\Dev16.M122.5_script\TFS\debug\VSS\Identities\Picker\Services.js; by adding queryScopes.push("ims") in the OperationScope.IMS switch, then the users can be found. and I know, it is not a good way to update TFS code, it is just to do debugging. hope it is useful.

答:
I have the same issue in Azure DevOps Server 2019 (Version Dev17.M153.3)
when I tried to add a user to a security group it shows the user but it cannot retrieve the scopeName such that if there is any other user in other domains with the same username it raises the following error

Multiple identities found matching 'theusername'. Use the unique name
  to specify one of the following identities:

fullname1 (unique name: domain1\theusername)

fullname2 (unique name: domain2\theusername)

but the same user in other collection is working.

in C:\Program Files\Azure DevOps Server 2019\Application Tier\Web Services_static\tfs\Dev17.M153.3_scripts\TFS\debug\VSS\Identities\Picker\Services.js queryScopes.push("ims") was already there.

after some investigation i could reduce the problem to the following powershell code

```<code>$url1 = "https://tfsserver/CB/_apis/IdentityPicker/Identities?api-version=5.1-preview.1"
$Body = '{"query":"mydomainname\\myusername","identityTypes":["user","group"],"operationScopes":["ims","ad","wmd"],"properties":["DisplayName","IsMru","ScopeName","SamAccountName","Active","SubjectDescriptor","Department","JobTitle","Mail","MailNickname","PhysicalDeliveryOfficeName","SignInAddress","Surname","Guest","TelephoneNumber","Description"],"filterByAncestorEntityIds":[],"filterByEntityIds":[],"options":{"MinResults":40,"MaxResults":40,"ExtensionId":"F12CA7AD-00EE-424F-B6D7-9123A60F424F","ProjectScopeName":"ateamprojectname","CollectionScopeName":"badcollection","Constraints":[]}}'
$x= Invoke-Webrequest $url1 -Method POST -ContentType application/json -UseDefaultCredentials -Body $Body
$y = $x.Content | ConvertFrom-Json
Write-Host "badcollection->", $y.results.identities.scopeName

$url1 = "https://tfsserver/CB_TestCollection/_apis/IdentityPicker/Identities?api-version=5.1-preview.1"
$Body = '{"query":"mydomainname\\myusername","identityTypes":["user","group"],"operationScopes":["ims","ad","wmd"],"properties":["DisplayName","IsMru","ScopeName","SamAccountName","Active","SubjectDescriptor","Department","JobTitle","Mail","MailNickname","PhysicalDeliveryOfficeName","SignInAddress","Surname","Guest","TelephoneNumber","Description"],"filterByAncestorEntityIds":[],"filterByEntityIds":[],"options":{"MinResults":40,"MaxResults":40,"ExtensionId":"F12CA7AD-00EE-424F-B6D7-9123A60F424F","ProjectScopeName":"ateamprojectname","CollectionScopeName":"goodCollection","Constraints":[]}}'
$x= Invoke-Webrequest $url1 -Method POST -ContentType application/json -UseDefaultCredentials -Body $Body
$y = $x.Content | ConvertFrom-Json
Write-Host "goodcollection->", $y.results.identities.scopeName
</code>```

the output result for the first write-host is "badcollection->"
but the output result for the second write-host is "goodcollection->mydomainname"

the questions are:
Why does it depend on collection?
How can i force tfs to sychronize that user account for the badcollection as well as the good collection.

Body:
I have the same issue in Azure DevOps Server 2019 (Version Dev17.M153.3)
when I tried to add a user to a security group it shows the user but it cannot retrieve the scopeName such that if there is any other user in other domains with the same username it raises the following error

Multiple identities found matching 'theusername'. Use the unique name
  to specify one of the following identities:

fullname1 (unique name: domain1\theusername)

fullname2 (unique name: domain2\theusername)

but the same user in other collection is working.

in C:\Program Files\Azure DevOps Server 2019\Application Tier\Web Services_static\tfs\Dev17.M153.3_scripts\TFS\debug\VSS\Identities\Picker\Services.js queryScopes.push("ims") was already there.

after some investigation i could reduce the problem to the following powershell code

$url1 = "https://tfsserver/CB/_apis/IdentityPicker/Identities?api-version=5.1-preview.1"
$Body = '{"query":"mydomainname\\myusername","identityTypes":["user","group"],"operationScopes":["ims","ad","wmd"],"properties":["DisplayName","IsMru","ScopeName","SamAccountName","Active","SubjectDescriptor","Department","JobTitle","Mail","MailNickname","PhysicalDeliveryOfficeName","SignInAddress","Surname","Guest","TelephoneNumber","Description"],"filterByAncestorEntityIds":[],"filterByEntityIds":[],"options":{"MinResults":40,"MaxResults":40,"ExtensionId":"F12CA7AD-00EE-424F-B6D7-9123A60F424F","ProjectScopeName":"ateamprojectname","CollectionScopeName":"badcollection","Constraints":[]}}'
$x= Invoke-Webrequest $url1 -Method POST -ContentType application/json -UseDefaultCredentials -Body $Body
$y = $x.Content | ConvertFrom-Json
Write-Host "badcollection->", $y.results.identities.scopeName

$url1 = "https://tfsserver/CB_TestCollection/_apis/IdentityPicker/Identities?api-version=5.1-preview.1"
$Body = '{"query":"mydomainname\\myusername","identityTypes":["user","group"],"operationScopes":["ims","ad","wmd"],"properties":["DisplayName","IsMru","ScopeName","SamAccountName","Active","SubjectDescriptor","Department","JobTitle","Mail","MailNickname","PhysicalDeliveryOfficeName","SignInAddress","Surname","Guest","TelephoneNumber","Description"],"filterByAncestorEntityIds":[],"filterByEntityIds":[],"options":{"MinResults":40,"MaxResults":40,"ExtensionId":"F12CA7AD-00EE-424F-B6D7-9123A60F424F","ProjectScopeName":"ateamprojectname","CollectionScopeName":"goodCollection","Constraints":[]}}'
$x= Invoke-Webrequest $url1 -Method POST -ContentType application/json -UseDefaultCredentials -Body $Body
$y = $x.Content | ConvertFrom-Json
Write-Host "goodcollection->", $y.results.identities.scopeName

the output result for the first write-host is "badcollection->"
but the output result for the second write-host is "goodcollection->mydomainname"

the questions are:
Why does it depend on collection?
How can i force tfs to sychronize that user account for the badcollection as well as the good collection.


问:
CSV File: counting how many times the word "life" appears in a column
```<code>with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line[1]:
        continue
    else:
        print(line)
</code>```

What I want to accomplish is to count how many times the word "life" comes up in song titles. The CSV file is as follow: rank, song, artist, year, lyrics, source and it is split by commas (obviously). So we are looking in location [1] with song.

What am I doing wrong? My output gives me a list of songs but none have the word "life" in them.

答:
One very important addition that I thought of after the fact is that many song titles actually have commas in them.  The way you are splitting the data lines (by comma) does not take into account that CSV files have both field delimiters (the comma in this case) and text delimiters (usually " character).  So with your data, if the 2001 Roxette song "My World, My Love, My life" was in your list, the CSV file might look like this:

```<code>rank, song, artist, year, lyrics, source
rank here,"My World, My Love, My Life",Roxette,2001,Lyrics here, Source here
</code>```

Your line line_strip = line.split(",") would split that data line into the following:

```<code>rank here
"My World
 My Love
 My Life"
Roxette
2001
Lyrics here
 Source here
</code>```

Therefore, piece [1] would be "My World, and therefore would not be returned as having the word life in the title, where, in fact, it clearly does.  This is because you are not reading the .CSV file properly.

When properly reading a .CSV file, a routine needs to know it should only split the line on field delimiters (commas) which do not occur inside of a pair of text delimiters ("), as well as knowing it has to strip off the text delimiters.  My sample data line should properly be split like this:

```<code>rank here
My World, My Love, My Life
Roxette
2001
Lyrics here
 Source here
</code>```

The best way to do this is to use a more mature CSV reader, such as the built-in python csv module - see this question/answer

Good luck!

Body:
with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line[1]:
        continue
    else:
        print(line)

What I want to accomplish is to count how many times the word "life" comes up in song titles. The CSV file is as follow: rank, song, artist, year, lyrics, source and it is split by commas (obviously). So we are looking in location [1] with song.

What am I doing wrong? My output gives me a list of songs but none have the word "life" in them.

Body:
One very important addition that I thought of after the fact is that many song titles actually have commas in them.  The way you are splitting the data lines (by comma) does not take into account that CSV files have both field delimiters (the comma in this case) and text delimiters (usually " character).  So with your data, if the 2001 Roxette song "My World, My Love, My life" was in your list, the CSV file might look like this:

rank, song, artist, year, lyrics, source
rank here,"My World, My Love, My Life",Roxette,2001,Lyrics here, Source here

Your line line_strip = line.split(",") would split that data line into the following:

rank here
"My World
 My Love
 My Life"
Roxette
2001
Lyrics here
 Source here

Therefore, piece [1] would be "My World, and therefore would not be returned as having the word life in the title, where, in fact, it clearly does.  This is because you are not reading the .CSV file properly.

When properly reading a .CSV file, a routine needs to know it should only split the line on field delimiters (commas) which do not occur inside of a pair of text delimiters ("), as well as knowing it has to strip off the text delimiters.  My sample data line should properly be split like this:

rank here
My World, My Love, My Life
Roxette
2001
Lyrics here
 Source here

The best way to do this is to use a more mature CSV reader, such as the built-in python csv module - see this question/answer

Good luck!


问:
How to see SSIS packages on SQL Server
My issue pertains specifically to SSIS packages saved to "SQL Server" through the Import and Export Wizard in SQL Server Management Studio. When a package is saved to "SQL Server" instead of "File System", it does not save to the Integration Services Catalog. My question is, how do you access those packages for editing or viewing. </p>

<p>I.E., I want to make a minor adjustment to an SSIS package stored in SQL Server, but I do not recall all the changes and options I made when initially setting it up (so I cannot simply recreate it). Additionally, I'd like to delete old test versions of the package. </p>

答:
As per the Wizard documentation:

The wizard saves the package in the msdb database in the sysssispackages table. This option does not save the package to the SSIS Catalog database (SSISDB).

Removing records from this table will remove the package.

You can open the package to edit it with SQL Server Data Tools. Create a new SSIS project, and then in the Solution Explorer pane, right-click on the SSIS Packages folder icon and choose Add existing package....

In the next dialog, you'd choose "SQL Server" as the package location, put in your server address and login credentials, and then for "Package Path" click on the three dots and it will let you browse to the package. Hit "OK" and your package will then be loaded into SSDT.

Title: How to see SSIS packages on SQL Server

Body:
My issue pertains specifically to SSIS packages saved to "SQL Server" through the Import and Export Wizard in SQL Server Management Studio. When a package is saved to "SQL Server" instead of "File System", it does not save to the Integration Services Catalog. My question is, how do you access those packages for editing or viewing.

I.E., I want to make a minor adjustment to an SSIS package stored in SQL Server, but I do not recall all the changes and options I made when initially setting it up (so I cannot simply recreate it). Additionally, I'd like to delete old test versions of the package.


问:
How to load a STL vector with a constant
If I have a vector<double> that has already been resized to be 1200, what is the best way to load that vector with the same value in each slot? The value is not known at compile time.

Right now I just use a loop through all 1200 slots and set each slot equal to the value. I was wondering if this was the best way to do this.

答:
You can use std::vector constructor

explicit vector (size_type n, const value_type& val = value_type(),
                   const allocator_type& alloc = allocator_type());

next way

```<code>vector<double> myVector;
double value = 1.;
myVector = vector<double>(1200, value);
</code>```

alternative is std::fill, which will avoid memory allocation

```<code>std::fill(begin(myVector), end(myVector), value);
</code>```

Body:
You can use std::vector constructor

explicit vector (size_type n, const value_type& val = value_type(),
                   const allocator_type& alloc = allocator_type());

next way

vector<double> myVector;
double value = 1.;
myVector = vector<double>(1200, value);

alternative is std::fill, which will avoid memory allocation

std::fill(begin(myVector), end(myVector), value);


问:
Generating PDF and Microsoft Word files in Ruby on Rails
I want to build a web app that will allow, based on answering questions from a series of prompts from users, to generate a report in Microsoft Word and/or PDF format. I would like the output of the report to be configured in the actual code, where the end result will not have to be altered by an user. Is that possible using Ruby and the Rails framework?</p>

答:
fabdocx.com is an demo of such a system, built using docx4j (Java) to process real docx input documents according to the OpenDoPE Convention

The front end is done using the XForms standard (implementation is betterform)

docx4j gives you the PDF part for free.

You could implement the web bit in Ruby on Rails, still using docx4j if you wanted.  Several Ruby on Rails guys have declared XForms dead over the years, so you might want to consider their perspective before doing things the way I did.