问:
JSON schema vs. Open API - Java support
I came across this JSON schema specification here.

http://json-schema.org/understanding-json-schema/

I wonder if it's related in some way to the Open API spec.

https://swagger.io/specification/

To what extent are both specs standard ones? I know Open API is widely used but is it really adopted by the major companies as a de-facto standard?

Which one has better support in Java and is "more" standard?

I mean e.g. from which type of API definition, you can more easily generate client side classes to use in your client code?

Imagine you have an API which you need to consume (via a Java client e.g.). What would you ask for from your API provider, would you ask for a JSON schema API definition, or for an Open API based API definition?

答:
The first link is a documentation site, discussing JSON Schema, whose official site is here and whose specification is here. JSON Schemas are used for describing and validating data structures of all kinds (as long as they can be represented by the JSON document model), but it has wide usage within HTTP applications.

Swagger is now known as OpenAPI (with the move to version 3.x). Its official site is here and the latest specification is here. It uses JSON Schemas internally as part of its data structure. It specifically targets the description (and sometimes validation) of HTTP requests and responses.

Both sites have indexes of implementations in various platforms and languages.

Title: JSON schema vs. Open API - Java support


来源: stackexchange

问:
How to wrap external paths (include, lib) and definitions into a target in cmake
Rather than providing a target, some libraries like LibRaw generate variables that contain information about include paths, library paths and compile definitions. In the case of LibRaw, vcpkg recommends the following usage:

```<code>target_compile_definitions(main PRIVATE ${LibRaw_DEFINITIONS})
target_include_directories(main PRIVATE ${LibRaw_INCLUDE_DIR})
target_link_libraries(main PRIVATE ${LibRaw_LIBRARIES})
</code>```

However, I would much rather stay consistent on linking libraries using

```<code>target_link_libraries(main PRIVATE LibRaw)
</code>```

Is there a way to wrap all of the provided variables into a target.

答:
You should be able to create your own interface library and define the properties that should be applied to the main target with INTERFACE visibility:

```<code>add_library(MyLibRaw INTERFACE)
target_compile_definitions(MyLibRaw INTERFACE ${LibRaw_DEFINITIONS})
target_include_directories(MyLibRaw INTERFACE ${LibRaw_INCLUDE_DIR})
target_link_libraries(MyLibRaw INTERFACE ${LibRaw_LIBRARIES})
</code>```

This way every linking target linking MyLibRaw will inherit those properties.

```<code>target_link_libraries(main PRIVATE MyLibRaw)
</code>```

Note that if you're reusing the target across multiple projects, you may want to create a find script that provides this target, if you do find_package(MyImports COMPONENTS LibRaw) or similar...

ContentLicense: CC BY-SA 4.0

Body:
Rather than providing a target, some libraries like LibRaw generate variables that contain information about include paths, library paths and compile definitions. In the case of LibRaw, vcpkg recommends the following usage:

target_compile_definitions(main PRIVATE ${LibRaw_DEFINITIONS})
target_include_directories(main PRIVATE ${LibRaw_INCLUDE_DIR})
target_link_libraries(main PRIVATE ${LibRaw_LIBRARIES})

However, I would much rather stay consistent on linking libraries using

target_link_libraries(main PRIVATE LibRaw)

Is there a way to wrap all of the provided variables into a target.

Body:
You should be able to create your own interface library and define the properties that should be applied to the main target with INTERFACE visibility:

add_library(MyLibRaw INTERFACE)
target_compile_definitions(MyLibRaw INTERFACE ${LibRaw_DEFINITIONS})
target_include_directories(MyLibRaw INTERFACE ${LibRaw_INCLUDE_DIR})
target_link_libraries(MyLibRaw INTERFACE ${LibRaw_LIBRARIES})

This way every linking target linking MyLibRaw will inherit those properties.

target_link_libraries(main PRIVATE MyLibRaw)

Note that if you're reusing the target across multiple projects, you may want to create a find script that provides this target, if you do find_package(MyImports COMPONENTS LibRaw) or similar...


问:
How can I pass in the login/register data for my django-rest api in the form of a url?
I am following along with a book on the django-rest framework and I am having issues grasping a certain concept. The book uses the built-in Browsable API feature to do basic CRUD and LOGIN/LOGOUT/REGISTRATION functionality. What it fails to mention is how I can achieve such functionality using only the URL, which would be needed for, say connecting the API to the frontend of a REACT app.

Example:
I have an API which displays Posts and this path shows all posts:

```<code>path('api/v1/', include('posts.urls')),
</code>```

I want to use this path for example, to register.

```<code>path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
</code>```

How would the URL look like ?

答:
You can use API documentation tools, such as swagger or redoc.

https://github.com/axnsan12/drf-yasg

Body:
I am following along with a book on the django-rest framework and I am having issues grasping a certain concept. The book uses the built-in Browsable API feature to do basic CRUD and LOGIN/LOGOUT/REGISTRATION functionality. What it fails to mention is how I can achieve such functionality using only the URL, which would be needed for, say connecting the API to the frontend of a REACT app.

Example:
I have an API which displays Posts and this path shows all posts:

path('api/v1/', include('posts.urls')),

I want to use this path for example, to register.

path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),

How would the URL look like ?


问:
Why isn't webpack tree-shaking swiperjs modules?
So, swiperjs, from docs:

"By default Swiper exports only core version without additional modules (like Navigation, Pagination, etc.). So you need to import and configure them too:"

```<code>  // core version + navigation, pagination modules:
  import Swiper, { Navigation, Pagination } from 'swiper';
</code>```

Well, I did. This is my index.js test file:

```<code>import Swiper, { Navigation, Pagination } from 'swiper';
console.log(Swiper);
</code>```

And this is my webpack config:

```<code>const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  //mode: 'development',
  mode: 'production',
  watch: true,
  entry: {
    index: './src/index.js',

  },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  optimization: {
    minimize: true,
    usedExports: true,
  }

  plugins: [
    new BundleAnalyzerPlugin()
  ],

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: { presets: ['@babel/preset-env'] }
        }
      } // babel
    ] // rules
  } // module
};
</code>```

Well, the BundleAnalyzer graph shows that ALL the swiper modules are bundled. Why? How can I avoid that?
I already disabled sideEffect from package.json and activated providedExports in optimizations.

The source code of swiper.esm.js is copied here for reference: https://jsfiddle.net/fw4zj8qk/

答:
I've found out the issue: with swiper (at least), sideEffects option must be used at loader level and not at package level. Or maybe you can use at package level, but explicitly declaring the files. Didn't try though.
Instead, it did worked by setting sideEffects like this:

```<code>  module: {
    rules: [
      // [...] here normally there are babel settings and the like

      { // here doing the swiper loader and declaring no sideEffects
        test: /swiper\.esm\.js/,
        sideEffects: false
      }
    ] // rules
  } // module
</code>```

Now swiper gets tree shaked.

Body:
So, swiperjs, from docs:

"By default Swiper exports only core version without additional modules (like Navigation, Pagination, etc.). So you need to import and configure them too:"

  // core version + navigation, pagination modules:
  import Swiper, { Navigation, Pagination } from 'swiper';

Well, I did. This is my index.js test file:

import Swiper, { Navigation, Pagination } from 'swiper';
console.log(Swiper);

And this is my webpack config:

const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  //mode: 'development',
  mode: 'production',
  watch: true,
  entry: {
    index: './src/index.js',

  },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  optimization: {
    minimize: true,
    usedExports: true,
  }

  plugins: [
    new BundleAnalyzerPlugin()
  ],

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: { presets: ['@babel/preset-env'] }
        }
      } // babel
    ] // rules
  } // module
};

Well, the BundleAnalyzer graph shows that ALL the swiper modules are bundled. Why? How can I avoid that?
I already disabled sideEffect from package.json and activated providedExports in optimizations.

The source code of swiper.esm.js is copied here for reference: https://jsfiddle.net/fw4zj8qk/

Body:
I've found out the issue: with swiper (at least), sideEffects option must be used at loader level and not at package level. Or maybe you can use at package level, but explicitly declaring the files. Didn't try though.
Instead, it did worked by setting sideEffects like this:

  module: {
    rules: [
      // [...] here normally there are babel settings and the like

      { // here doing the swiper loader and declaring no sideEffects
        test: /swiper\.esm\.js/,
        sideEffects: false
      }
    ] // rules
  } // module

Now swiper gets tree shaked.


问:
How to get ONLY Second line with SED
How can I get second line in a file using SED

```<code>@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>
</code>```

With the data that looks like above I want only to get

```<code> GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
</code>```

答:
You always want the second line of a file? No need for SED:</p>

```<code>head -2 file | tail -1
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get ONLY Second line with SED

Body:
How can I get second line in a file using SED

@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>

With the data that looks like above I want only to get

 GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC

Body:
You always want the second line of a file? No need for SED:

head -2 file | tail -1


问:
Find the n largest occurrences of duplicate values in a column
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

```<code>"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"
</code>```

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

```<code>"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times
</code>```

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

```<code>"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times
</code>```

答:
If you don't need to use awk, the command-line tool GoCSV has a number of sub-commands for getting you the top n unique values for a column, sorted and culled by the count of those values.

GoCSV expects a header, so for your input the first step is to add some default column names (which can be stripped away later):

gocsv cap -default-name 'Col' input.csv
```
<p>With a header in place you can pipe that output to a series of commands that will:</p>
<ul>
<li>only keep unique values from the 5th column while adding the count for how many times the values were seen</li>
<li>sort descending by the count (a new 6th column from <code>uniq</code>)</li>
<li>then keeping only 50 rows (the "top 50 counts")</li>
</ul>
<pre class="lang-sh prettyprint-override"><code>... \
| gocsv uniq -c 5 -count \
| gocsv sort -c 6 -reverse
| gocsv head -n 50
</code>```

Running all that I get:

Col 1,Col 2,Col 3,Col 4,Col 5,Count
instance id,src IP,destination ip,63812,389,4
instance id,src IP,destination ip,88,49194,2
instance id,src IP,destination ip,389,65311,1
```

To get rid of the header, just pipe that into gocsv behead.

It's pre-built for a number of platform/OS-es.

Body:
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times

Body:
If you don't need to use awk, the command-line tool GoCSV has a number of sub-commands for getting you the top n unique values for a column, sorted and culled by the count of those values.

GoCSV expects a header, so for your input the first step is to add some default column names (which can be stripped away later):

gocsv cap -default-name 'Col' input.csv

With a header in place you can pipe that output to a series of commands that will:

only keep unique values from the 5th column while adding the count for how many times the values were seen

sort descending by the count (a new 6th column from uniq)

then keeping only 50 rows (the "top 50 counts")

... \
| gocsv uniq -c 5 -count \
| gocsv sort -c 6 -reverse
| gocsv head -n 50

Running all that I get:

Col 1,Col 2,Col 3,Col 4,Col 5,Count
instance id,src IP,destination ip,63812,389,4
instance id,src IP,destination ip,88,49194,2
instance id,src IP,destination ip,389,65311,1

To get rid of the header, just pipe that into gocsv behead.

It's pre-built for a number of platform/OS-es.


问:
Should I store the User Registration Agreement Checkbox in the database
I am using codeigniter and have a registration form that captures basic info such as email, username, and password. I will also have a Terms of use checkbox that will need to be checked in order to complete the registration.

My question is should I be storing this in the database? If so, should it be stored as a bit (1,0)?

答:
Unless the policy will never change, you should track the timestamp of agreement or version of the policy agreed to at the time the user clicks the button.  Then when you update the policy you increment the version (or store the policy itself in the DB and use a created/updated timestamp).  When the user logs into the system again you check the time/version agreed to and the current time/version of the policy and determine if the user has agreed to the latest version.

If you don't do it this way and you ever change the policy, you will have to force every user to agree to it every time they log on to ensure they have agreed to the right version.  Otherwise they can use the argument, "That's not what it said when I agreed to it."


问:
Access Default Value with Today's Date specified time
Real quick question.
I'm trying to set a default value in an Access table that gives me today's date and 8AM as the time.

I attempted to use =Date() & "8:00:00 AM" but I am getting a type mismatch error. I changed the format of the column to General Date to be able to have date and time but still no go.

Any help would be greatly appreciated.

答:
You could build the desired date like that

```<code>dt = Date
dt = DateSerial(Year(dt), Month(dt), Day(dt))
dt = dt + TimeSerial(8, 0, 0)
</code>```

A date is a number, 2020/02/08 is 44600. A time is a fraction, 8am is  0,333333333333333. If you want to build a date like Today 8 am you need to use the build-in functions Dateserial and Timeserial which gives you excatly the date you need.

Body:
You could build the desired date like that

dt = Date
dt = DateSerial(Year(dt), Month(dt), Day(dt))
dt = dt + TimeSerial(8, 0, 0)

A date is a number, 2020/02/08 is 44600. A time is a fraction, 8am is  0,333333333333333. If you want to build a date like Today 8 am you need to use the build-in functions Dateserial and Timeserial which gives you excatly the date you need.


问:
Why does Cython keep making python objects instead of c?
I am trying to learn cython, where I compile with annotate=True.

Says in The basic manual:

If a line is white, it means that the code generated doesn’t interact with Python, so will run as fast as normal C code. The darker the yellow, the more Python interaction there is in that line

Then I wrote this code following (as much as I understood) numpy in cython basic manual instructions:

+14: cdef entropy(counts):
 15:     '''
 16:     INPUT: pandas table with counts as obsN
 17:     OUTPUT: general entropy
 18:     '''
+19:     cdef int l = counts.shape[0]
+20:     cdef np.ndarray probs = np.zeros(l, dtype=np.float)
+21:     cdef int totals = np.sum(counts)
+22:     probs = counts/totals
+23:     cdef np.ndarray plogp = np.zeros(l, dtype=np.float)
+24:     plogp = ( probs.T * (np.log(probs)) ).T
+25:     cdef float d = np.exp(-1 * np.sum(plogp))
+26:     cdef float relative_d = d / probs.shape[0]
 27:
+28:     return {'d':d,
+29:             'relative_d':relative_d
 30:             }
```

Where all the "+" at the beginning of the line are yellow in the cython.debug.output.html file.

What am I doing very wrong? How can I make at least part of this function run at c speed?
The function returns a python dictionary, hence I think that I can't returned any c data type. I might be wrong here to.

Thank you for the help!

答:
First of all, Cython does not rewrite Numpy functions, it just call them like CPython does. This is the case for np.zeros, np.sum or np.log for example. Such calls will not be faster with Cython. If you want a faster code you can use plain loops to reimplement them in you code. However, this may not be faster: on one hand Numpy calls introduce an overhead (due to type checking AFAIK still enabled with Cython, internal function calls, wrappers, etc) certainly significant if you use small arrays and each function generate huge temporary arrays that are often slow to read/write; on the other hand, some Numpy functions makes use of highly-optimized code (like BLAS or low-level SIMD intrinsics). Moreover, the division in Python does not behave the same way than C. This is why Cython provides the flag cython.cdivision which can be set to True (it is False by default). If the Python division is used, Cython generate a slower wrapping code. Finally, np.ndarray is a CPython type and behave as such, you can use memoryviews so not to deal with Numpy objects.

If you want to get a fast code, you certainly need to use memoryviews, loops and and avoid creating temporary arrays as well as using multiple threads. Additionally, you can use np.empty instead of np.zeros in your case. Besides this, the Numpy transposition is not very efficient and Numpy does not solves this problem. You can implement a tiled-transposition to speed it up but this is not trivial to implement it efficiently. Here is a Numba implementation that can certainly be easily transformed to a Cython code. Putting some cdef on a Python Numpy code generally does not make it faster.

Body:
I am trying to learn cython, where I compile with annotate=True.

Says in The basic manual:

If a line is white, it means that the code generated doesn’t interact with Python, so will run as fast as normal C code. The darker the yellow, the more Python interaction there is in that line

Then I wrote this code following (as much as I understood) numpy in cython basic manual instructions:

+14: cdef entropy(counts):
 15:     '''
 16:     INPUT: pandas table with counts as obsN
 17:     OUTPUT: general entropy
 18:     '''
+19:     cdef int l = counts.shape[0]
+20:     cdef np.ndarray probs = np.zeros(l, dtype=np.float)
+21:     cdef int totals = np.sum(counts)
+22:     probs = counts/totals
+23:     cdef np.ndarray plogp = np.zeros(l, dtype=np.float)
+24:     plogp = ( probs.T * (np.log(probs)) ).T
+25:     cdef float d = np.exp(-1 * np.sum(plogp))
+26:     cdef float relative_d = d / probs.shape[0]
 27:
+28:     return {'d':d,
+29:             'relative_d':relative_d
 30:             }

Where all the "+" at the beginning of the line are yellow in the cython.debug.output.html file.

What am I doing very wrong? How can I make at least part of this function run at c speed?
The function returns a python dictionary, hence I think that I can't returned any c data type. I might be wrong here to.

Thank you for the help!


问:
Where do I define px to em mapping?
I heard from w3schools that 1 em = 16px.
http://www.w3schools.com/css/css_font.asp

However, in my Jekyll site

http://madhur.github.com

The standard font in paragraph is 12px even though I have set font-size: 100% in body and font-size: 1em.

Am I missing something?

答:
One em is the width of the letter "M" in your standard font and size. em is completely dependent on what you set your font-size and font as. font-size: 1 em pretty much means font-size: 100%;

Em is only 16px if your font-size already is 16px.

Title: Where do I define px to em mapping?


问:
How to access certain part of a string in python?
I have a string which looks like this:

```<code>0,1,488,332,165;1,1,553,712,206;2,1,803,1248,219;3,1,2222,1285,398
</code>```

The actual string is way more longer than this ...

I need to access the 488, 553, 803 and 2222 but the problem is that these values change.

I don't want to index it because the string is about 1000 characters long.

答:
you could use list comprehension, and string's split method, to wrap this up in:

```<code>result = [x.split(",")[2] for x in string.split(';')]
</code>```

Body:
I have a string which looks like this:

0,1,488,332,165;1,1,553,712,206;2,1,803,1248,219;3,1,2222,1285,398

The actual string is way more longer than this ...

I need to access the 488, 553, 803 and 2222 but the problem is that these values change.

I don't want to index it because the string is about 1000 characters long.

Body:
you could use list comprehension, and string's split method, to wrap this up in:

result = [x.split(",")[2] for x in string.split(';')]


问:
Passing multiple parameters to django url template
I am trying to pass multiple url parameters from a django templated to be used by a view function. Below are my codes :

A snippet from the template from where the parameters will be passed onto :

```<code><a href="{% url 'coordinator_assign_project_recommendations' group_id=row.group client_id=row.client  project_id=row.project_id %}" class="btn btn-primary">Assign</a>
</code>```

The view function :

```<code>def assign_recommended_project(request, group_id, client_id, project_id):
    group = StudentGroup.objects.get(id=group_id)
    group.client = client_id
    group.project = project_id
    group.save()
    project = Project.objects.get(id=project_id)
    project.is_assigned = True
    project.save()
    return redirect("coordinator_view_groups")
</code>```

The  url of the view function :

```<code> path(
        "coordinator/assign_recommended_project/<str:group_id/str:client_id/str:project_id",
        assign_recommended_project,
        name="coordinator_assign_project_recommendations",
    ),
</code>```

This is the error that is shown :

Can someone please help me solve this. Thanks.

答:
You need to open and close the angle brackets (<…>) for each parameter, so:

```<code>path(
    'coordinator/assign_recommended_project/<strong><str:group_id></strong>/<strong><str:client_id></strong>/<strong><str:project_id></strong>/',
    assign_recommended_project,
    name='coordinator_assign_project_recommendations',
),</code>```

Body:
I am trying to pass multiple url parameters from a django templated to be used by a view function. Below are my codes :

A snippet from the template from where the parameters will be passed onto :

Assign

The view function :

def assign_recommended_project(request, group_id, client_id, project_id):
    group = StudentGroup.objects.get(id=group_id)
    group.client = client_id
    group.project = project_id
    group.save()
    project = Project.objects.get(id=project_id)
    project.is_assigned = True
    project.save()
    return redirect("coordinator_view_groups")

The  url of the view function :

 path(
        "coordinator/assign_recommended_project/<str:group_id/str:client_id/str:project_id",
        assign_recommended_project,
        name="coordinator_assign_project_recommendations",
    ),

This is the error that is shown :

Can someone please help me solve this. Thanks.

Body:
You need to open and close the angle brackets (<…>) for each parameter, so:

path(
    'coordinator/assign_recommended_project/<str:group_id>/<str:client_id>/<str:project_id>/',
    assign_recommended_project,
    name='coordinator_assign_project_recommendations',
),


问:
How to set ASAN_OPTIONS to CMake managed projects in CLion
I'm trying to use Google sanitizers https://www.jetbrains.com/help/clion/google-sanitizers.html on my CMake project using CLion. I need to pass ASAN_OPTIONS=detect_container_overflow=0 environment variable so that Google sanitizers can pass on the container overflow error. I put "ASAN_OPTIONS=detect_container_overflow=0" in the Run/Debug configuration, but it didn't work, the sanitizer still halt at container_overflow errors and won't proceed.

So I added a new env variable
TESTENV=testenv put the following lines in my program to check if it works:

```<code>  const char* asan = std::getenv("ASAN_OPTIONS");
  LOG(INFO) << fmt::format("ASAN_OPTIONS {}", asan);

  const char* testEnv = std::getenv("TESTENV");
  LOG(INFO) << fmt::format("TESTENV {}", testEnv);
</code>```

The output does include TESTENV, but the output of ASAN_OPTIONS doesn't have detect_container_overflow=0:

```<code>I20220102 00:34:57.356257 966499840 test.cpp:148] ASAN_OPTIONS detect_stack_use_after_return=false log_path='/private/var/folders/rk/5dyjln0d4551nr1c6q7vz8mc0000gn/T/clion-sanitizersf4b4f3de-dbaf-4dc8-a2fb-fc5f7f2e6138/00f8647a-83ba-4e45-8f4e-2e0c0a45ef9f' stack_trace_format='pc_%p###func_%f###file_%s###line_%l###obj_%M' print_summary='true'
I20220102 00:34:57.356273 966499840 test.cpp:151] TESTENV testenv
</code>```

I also tried ASAN_OPTIONS=$ASAN_OPTIONS:detect_container_overflow=0 but the output is the same. Can someone help?

答:
I'm trying to figure out which is the right way. I suppose it should works just by setting the option right in the Sanitizers section (Build, Execution & Deployment > Dynamic Analysis Tools > Sanitizers)

But for some reason this does not work for me, so I have to set it too in the CMake environment section (Build, Execution & Deployment > CMake)

Body:
I'm trying to use Google sanitizers https://www.jetbrains.com/help/clion/google-sanitizers.html on my CMake project using CLion. I need to pass ASAN_OPTIONS=detect_container_overflow=0 environment variable so that Google sanitizers can pass on the container overflow error. I put "ASAN_OPTIONS=detect_container_overflow=0" in the Run/Debug configuration, but it didn't work, the sanitizer still halt at container_overflow errors and won't proceed.

So I added a new env variable
TESTENV=testenv put the following lines in my program to check if it works:

  const char* asan = std::getenv("ASAN_OPTIONS");
  LOG(INFO) << fmt::format("ASAN_OPTIONS {}", asan);

  const char* testEnv = std::getenv("TESTENV");
  LOG(INFO) << fmt::format("TESTENV {}", testEnv);

The output does include TESTENV, but the output of ASAN_OPTIONS doesn't have detect_container_overflow=0:

I20220102 00:34:57.356257 966499840 test.cpp:148] ASAN_OPTIONS detect_stack_use_after_return=false log_path='/private/var/folders/rk/5dyjln0d4551nr1c6q7vz8mc0000gn/T/clion-sanitizersf4b4f3de-dbaf-4dc8-a2fb-fc5f7f2e6138/00f8647a-83ba-4e45-8f4e-2e0c0a45ef9f' stack_trace_format='pc_%p###func_%f###file_%s###line_%l###obj_%M' print_summary='true'
I20220102 00:34:57.356273 966499840 test.cpp:151] TESTENV testenv

I also tried ASAN_OPTIONS=$ASAN_OPTIONS:detect_container_overflow=0 but the output is the same. Can someone help?


问:
Unable to scroll RecyclerView with Child items
I have a RecyclerView where in each item i can add X child items, when a parent item is added my RecyclerView scrolls to bottom but the issue is that when lot of child items are added to the last element it's not scrolling to last child (obviously as i'm doing scrollToPosition of last RecyclerView item).

So how should i perform the scrolling in the way that it scrolls to even last child not only the parent item?

Here a gif of how it looks like.

XML

```<code>    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            app:stackFromEnd="true"
            android:paddingBottom="45dp"
            tools:listitem="@layout/comanda_list" />

     <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fabInvia"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:backgroundTint="#00C853"
            app:layout_anchor="@+id/bottomSheet"
            app:borderWidth="0dp"
            app:layout_anchorGravity="top|center"
            app:srcCompat="@drawable/ic_baseline_send"
            android:contentDescription="@string/verifica_gp" />

        <include layout="@layout/bottom_sheet_pterm" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Code where i add a child item in my Adapter

```<code>public void addChild(int position, Varianti variante) {
    comandeList.get(position).setVariant(variante);
    notifyItemChanged(position);
}
</code>```

onBindViewHolder where the child items are rendered

```<code>    @Override
    public void onBindViewHolder(@NonNull final ExampleViewHolder holder, final int position) {
        final Comanda item = comandeList.get(position);
    ...
            List<Varianti> variants = item.getVarianti();
        if (variants != null && variants.size() > 0) {
            for (Varianti v : variants) {
                View vView = mInflater.inflate(R.layout.varianti_layout, holder.variantsContainer, false);
                TextView nameTV = vView.findViewById(R.id.variant_name);
                if (v.getState().equals("K") || v.getState().equals("KK")) {
                    nameTV.setTypeface(null, Typeface.BOLD);
                }
                if (!item.getState().equals("S")) {
                    nameTV.setTextColor(Color.parseColor("#FFFFFF"));
                }
                nameTV.setText(v.getDescrizione());
                nameTV.setBackground(v.getDrawable());
                holder.variantsContainer.addView(vView);

            }
        }
    ...

}
</code>```

In activity after adding new item / child item

```<code>        adapterComanda.addVariante(position, variante);
        recyclerComanda.scrollToPosition(adapterComanda.getItemCount() - 1);
</code>```

BottomSheet

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/bottomSheet"
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_hideable="false"
    android:elevation="5dp"
    app:behavior_peekHeight="60dp"
    android:orientation="vertical">

... (different LinearLayouts)

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        android:gravity="bottom"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerViewTasti"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp"
            android:paddingTop="3dp"
            android:paddingBottom="3dp"
            tools:listitem="@layout/tasto_list"
            app:spanCount="4"
            android:scrollbars="vertical"
            app:layoutManager="androidx.recyclerview.widget.GridLayoutManager" />

</LinearLayout>

</LinearLayout>
</code>```

答:
The issue with your code is it is Scrolling to the bottom, but the recycler view is going below the <include layout="@layout/bottom_sheet_pterm" />

Try setting a layout_anchor

```<code><androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="45dp"
        app:layout_anchor="@+id/fabInvia"
        app:stackFromEnd="true" />
</code>```

Or use a constraintlayout which constraints bottom to top of fabInvia.

Body:
I have a RecyclerView where in each item i can add X child items, when a parent item is added my RecyclerView scrolls to bottom but the issue is that when lot of child items are added to the last element it's not scrolling to last child (obviously as i'm doing scrollToPosition of last RecyclerView item).

So how should i perform the scrolling in the way that it scrolls to even last child not only the parent item?

Here a gif of how it looks like.

XML

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            app:stackFromEnd="true"
            android:paddingBottom="45dp"
            tools:listitem="@layout/comanda_list" />

     <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fabInvia"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:backgroundTint="#00C853"
            app:layout_anchor="@+id/bottomSheet"
            app:borderWidth="0dp"
            app:layout_anchorGravity="top|center"
            app:srcCompat="@drawable/ic_baseline_send"
            android:contentDescription="@string/verifica_gp" />

        <include layout="@layout/bottom_sheet_pterm" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

Code where i add a child item in my Adapter

public void addChild(int position, Varianti variante) {
    comandeList.get(position).setVariant(variante);
    notifyItemChanged(position);
}

onBindViewHolder where the child items are rendered

    @Override
    public void onBindViewHolder(@NonNull final ExampleViewHolder holder, final int position) {
        final Comanda item = comandeList.get(position);
    ...
            List<Varianti> variants = item.getVarianti();
        if (variants != null && variants.size() > 0) {
            for (Varianti v : variants) {
                View vView = mInflater.inflate(R.layout.varianti_layout, holder.variantsContainer, false);
                TextView nameTV = vView.findViewById(R.id.variant_name);
                if (v.getState().equals("K") || v.getState().equals("KK")) {
                    nameTV.setTypeface(null, Typeface.BOLD);
                }
                if (!item.getState().equals("S")) {
                    nameTV.setTextColor(Color.parseColor("#FFFFFF"));
                }
                nameTV.setText(v.getDescrizione());
                nameTV.setBackground(v.getDrawable());
                holder.variantsContainer.addView(vView);

            }
        }
    ...

}

In activity after adding new item / child item

        adapterComanda.addVariante(position, variante);
        recyclerComanda.scrollToPosition(adapterComanda.getItemCount() - 1);

BottomSheet

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/bottomSheet"
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_hideable="false"
    android:elevation="5dp"
    app:behavior_peekHeight="60dp"
    android:orientation="vertical">

... (different LinearLayouts)

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        android:gravity="bottom"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerViewTasti"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp"
            android:paddingTop="3dp"
            android:paddingBottom="3dp"
            tools:listitem="@layout/tasto_list"
            app:spanCount="4"
            android:scrollbars="vertical"
            app:layoutManager="androidx.recyclerview.widget.GridLayoutManager" />

</LinearLayout>

</LinearLayout>

Body:
The issue with your code is it is Scrolling to the bottom, but the recycler view is going below the <include layout="@layout/bottom_sheet_pterm" />

Try setting a layout_anchor

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="45dp"
        app:layout_anchor="@+id/fabInvia"
        app:stackFromEnd="true" />

Or use a constraintlayout which constraints bottom to top of fabInvia.


问:
Restrict the output of posts from a specific date (pandas)
I have a regular dataframe with a time series. How can I infer date fields from a specific value? I tried to apply pd.to_datetime ,but some dates start to display month and day incorrectly (swap them). That is, the following occurs: 07-02-2022 to 2022-07-02, but it should be 2020-02-07.

Here is a snippet of what I have:

```<code>      date          infected_in_day
0     07-02-2022    15442.0
1     06-02-2022    18856.0
2     05-02-2022    22444.0
...
214   02-07-2021    6893.0
229   16-06-2021    5782.0
235   11-12-2020    40.0
236   09-12-2020    42.0
237   08-12-2020    41.0
</code>```

I need to filter data by date 16-06-2021, that is, do not display everything that was before. Like this:

```<code>      date          infected_in_day
0     07-02-2022    15442.0
1     06-02-2022    18856.0
2     05-02-2022    22444.0
...
214   02-07-2021    6893.0
229   16-06-2021    5782.0
</code>```

Is there any way to do this without using pd.to_datetime? Or how to do it right?

答:
it seems that you have a problem with the datecolumn. If my assumtion is right, I would try to parse the data as I would expect to work with it something like this :</p>
```<code>mydateparser = lambda x: pd.datetime.strptime(x, "%Y %m %d %H:%M:%S")
df = pd.read_csv("file.csv", sep='\t', parse_dates=['date'], date_parser=mydateparser)
</code>```

Body:
I have a regular dataframe with a time series. How can I infer date fields from a specific value? I tried to apply pd.to_datetime ,but some dates start to display month and day incorrectly (swap them). That is, the following occurs: 07-02-2022 to 2022-07-02, but it should be 2020-02-07.

Here is a snippet of what I have:

      date          infected_in_day
0     07-02-2022    15442.0
1     06-02-2022    18856.0
2     05-02-2022    22444.0
...
214   02-07-2021    6893.0
229   16-06-2021    5782.0
235   11-12-2020    40.0
236   09-12-2020    42.0
237   08-12-2020    41.0

I need to filter data by date 16-06-2021, that is, do not display everything that was before. Like this:

      date          infected_in_day
0     07-02-2022    15442.0
1     06-02-2022    18856.0
2     05-02-2022    22444.0
...
214   02-07-2021    6893.0
229   16-06-2021    5782.0

Is there any way to do this without using pd.to_datetime? Or how to do it right?

Body:
it seems that you have a problem with the datecolumn. If my assumtion is right, I would try to parse the data as I would expect to work with it something like this :

mydateparser = lambda x: pd.datetime.strptime(x, "%Y %m %d %H:%M:%S")
df = pd.read_csv("file.csv", sep='\t', parse_dates=['date'], date_parser=mydateparser)


问:
How can I import an HTML file within my HTML file?
How can I import an HTML file within my HTML file? I will prepare header.html and footer.html files separately and every file that I want to include them I want to import them into my HTML file.,

EDIT: I see that solution based on SSI technique. I use Ubuntu and Tomcat 7.0.11. How can I enable SSI at tomcat?

答: There are many solutions to this problem. You can write simple JavaScript code to include parts of your page on load, you can enable SSI on your web-server, and finally you can use any server-side language to dynamically include chunks of any page for output. Your choice  depends on how dynamic your web-site is. </p>


问:
Is it possible to see if the connection parameter is a type of Interface Extension?
I am looking to execute something dependent on the type of connection it is.  But have not found a way.

```<code>const onSaveHandler = async (connection: Connection) => {
  if (connection is serial) { // do serial task }

  if (connection is ethernet) { //do ethernet task }
}

</code>```

All connections have ID, NAME, TYPE,....

```<code>export interface Connection {
  [CONNECTION_ID_KEY]: number;
  [CONNECTION_NAME_KEY]: string;
  [CONNECTION_TYPE_ID_KEY]: number;
  [CONNECTION_TYPE_NAME_KEY]?: string;
  [CONNECTION_COMM_INTERVAL_KEY]: number;
}
</code>```

Two classes extend:

```<code>export interface SerialConnection extends Connection {
  [COM_PORT_KEY]: number;
  [BAUD_RATE_KEY]: number;
  [DATA_BITS_KEY]: number;
  [STOP_BITS_KEY]: number;
  [PARITY_KEY]: number;
}

export interface EthernetConnection extends Connection {
  [IP_ADDRESS_KEY]: string;
  [PORT_NUMBER_KEY]: number;
}
</code>```

To see what I am trying to achieve
https://codesandbox.io/s/mbuqb

答:
You can also guess the type without adding anything to your hash, by using type-predicates.

    const isSerialConnection = (subject: SerialConnection | EthernetConnection): subject is SerialConnection => {
      return (subject as SerialConnection).COM_PORT_KEY !== undefined;
    };

    const isEthernetConnection = (subject: SerialConnection | EthernetConnection): subject is EthernetConnection => {
      return (subject as EthernetConnection).IP_ADDRESS_KEY !== undefined;
    };

    const onSaveHandler = async (connection: SerialConnection | EthernetConnection) => {
      if (isSerialConnection(connection)) { // do serial task }

      if (isEthernetConnection(connection)) { //do ethernet task }
    }
```

Body:
I am looking to execute something dependent on the type of connection it is.  But have not found a way.

const onSaveHandler = async (connection: Connection) => {
  if (connection is serial) { // do serial task }

  if (connection is ethernet) { //do ethernet task }
}

All connections have ID, NAME, TYPE,....

export interface Connection {
  [CONNECTION_ID_KEY]: number;
  [CONNECTION_NAME_KEY]: string;
  [CONNECTION_TYPE_ID_KEY]: number;
  [CONNECTION_TYPE_NAME_KEY]?: string;
  [CONNECTION_COMM_INTERVAL_KEY]: number;
}

Two classes extend:

export interface SerialConnection extends Connection {
  [COM_PORT_KEY]: number;
  [BAUD_RATE_KEY]: number;
  [DATA_BITS_KEY]: number;
  [STOP_BITS_KEY]: number;
  [PARITY_KEY]: number;
}

export interface EthernetConnection extends Connection {
  [IP_ADDRESS_KEY]: string;
  [PORT_NUMBER_KEY]: number;
}

To see what I am trying to achieve
https://codesandbox.io/s/mbuqb


问:
TypeError: Cannot convert undefined or null to object in Ionic/Angular
I'm trying to setup a crypto currency live market price. But it's not displaying. I'm only seeing this error in my chrome developer console.

ERROR TypeError: Cannot convert undefined or null to object

mycomponent.ts

```<code>
  ngOnInit() {
    this.refreshData();
  }

  refreshData(reset:boolean = false) {
    // Reset table index to 1
    if (reset) {
      this._data._previousIndex = 1;
    }

    // Set table page index and size to previous resevered data
    if (this._data._previousIndex !== null && this._data._previousPageSize !== null) {
      this._current = this._data._previousIndex;
      this._pageSize = this._data._previousPageSize;
      this._sortMap.name = this._data._previousSortMapName;
      this._sortMap.symbol = this._data._previousSortMapSymbol;
      //console.log("reserve data called");
    }

    this._loading = true;
    // Sort dataset before get
    if (this._sortName !== null || this._sortValue !== null) {
      this._data.sortData(this._sortName, this._sortValue);
      //console.log("sort method called");
    }

    this.cryData = [];
    this.cryptoLastPrices = [];
    this.cryptoPriceCompare = [];
    this.cryptoNames = this._data.getNamesFull();
    this.cryptoImages = this._data.getImagesFull();
    this._placeHolderSafe = this._sanitizer.bypassSecurityTrustUrl(this._placeholderBase64);

    this._data.getPricesFull()
      .subscribe(res => {
        this.receiveData = res.DISPLAY;
        //console.log(this.receiveData);

        let coinKeys: any = Object.keys(this.receiveData);
        let coinValues: any = Object.values(this.receiveData);

        // Price compare first time check
        if (this.cryptoLastPrices.length === 0) {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            let _currentPrice = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
            this.cryptoLastPrices[_i] = _currentPrice;
            this.cryptoPriceCompare[_i] = _currentPrice - this.cryptoLastPrices[_i];
          }
        } else {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            this.cryptoPriceCompare[_i] = (parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, '')) -
              this.cryptoLastPrices[_i]);
          }
        }
        //console.log(this.cryptoLastPrices);

        for (let _i = 0; _i < coinKeys.length; _i++) {
          this.cryData[coinKeys[_i]] = {
            image: this.cryptoImages[_i],
            name: this.cryptoNames[_i],
            symbol: coinKeys[_i],
            price: coinValues[_i].USD.PRICE,
            marketCap: coinValues[_i].USD.MKTCAP,
            change24Num: parseFloat((coinValues[_i].USD.CHANGE24HOUR).substring(2).replace(/,/g, '')),
            priceCompare: this.cryptoPriceCompare[_i]
          }

          this.cryptoLastPrices[_i] = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
          this.cryptos = JSON.parse(JSON.stringify(Object.values(this.cryData)));
        }
        //console.log(Object.values(this.cryData));
        this._loading = false;
        this.setTimer();
      });
  }
</code>```

I think the error is sitting on these lines

```<code>let coinKeys: any = Object.keys(this.receiveData);
let coinValues: any = Object.values(this.receiveData);
</code>```

This is how i defined it in export class code private receiveData: any;, i've tried changing any to any[] and to string, i've tried some few other method to fix it but didn't work out, been battling with this for some days now. Someone should kindly help me out.

答:
Looks like you just need to check you're not getting an undefined / null value here

 this._data.getPricesFull()
      .subscribe(res => {
        if (!res || !res.DISPLAY) return;
        this.receiveData = res.DISPLAY;
      ...
```

Body:
I'm trying to setup a crypto currency live market price. But it's not displaying. I'm only seeing this error in my chrome developer console.

ERROR TypeError: Cannot convert undefined or null to object

mycomponent.ts

  ngOnInit() {
    this.refreshData();
  }

  refreshData(reset:boolean = false) {
    // Reset table index to 1
    if (reset) {
      this._data._previousIndex = 1;
    }

    // Set table page index and size to previous resevered data
    if (this._data._previousIndex !== null && this._data._previousPageSize !== null) {
      this._current = this._data._previousIndex;
      this._pageSize = this._data._previousPageSize;
      this._sortMap.name = this._data._previousSortMapName;
      this._sortMap.symbol = this._data._previousSortMapSymbol;
      //console.log("reserve data called");
    }

    this._loading = true;
    // Sort dataset before get
    if (this._sortName !== null || this._sortValue !== null) {
      this._data.sortData(this._sortName, this._sortValue);
      //console.log("sort method called");
    }

    this.cryData = [];
    this.cryptoLastPrices = [];
    this.cryptoPriceCompare = [];
    this.cryptoNames = this._data.getNamesFull();
    this.cryptoImages = this._data.getImagesFull();
    this._placeHolderSafe = this._sanitizer.bypassSecurityTrustUrl(this._placeholderBase64);

    this._data.getPricesFull()
      .subscribe(res => {
        this.receiveData = res.DISPLAY;
        //console.log(this.receiveData);

        let coinKeys: any = Object.keys(this.receiveData);
        let coinValues: any = Object.values(this.receiveData);

        // Price compare first time check
        if (this.cryptoLastPrices.length === 0) {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            let _currentPrice = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
            this.cryptoLastPrices[_i] = _currentPrice;
            this.cryptoPriceCompare[_i] = _currentPrice - this.cryptoLastPrices[_i];
          }
        } else {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            this.cryptoPriceCompare[_i] = (parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, '')) -
              this.cryptoLastPrices[_i]);
          }
        }
        //console.log(this.cryptoLastPrices);

        for (let _i = 0; _i < coinKeys.length; _i++) {
          this.cryData[coinKeys[_i]] = {
            image: this.cryptoImages[_i],
            name: this.cryptoNames[_i],
            symbol: coinKeys[_i],
            price: coinValues[_i].USD.PRICE,
            marketCap: coinValues[_i].USD.MKTCAP,
            change24Num: parseFloat((coinValues[_i].USD.CHANGE24HOUR).substring(2).replace(/,/g, '')),
            priceCompare: this.cryptoPriceCompare[_i]
          }

          this.cryptoLastPrices[_i] = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
          this.cryptos = JSON.parse(JSON.stringify(Object.values(this.cryData)));
        }
        //console.log(Object.values(this.cryData));
        this._loading = false;
        this.setTimer();
      });
  }

I think the error is sitting on these lines

let coinKeys: any = Object.keys(this.receiveData);
let coinValues: any = Object.values(this.receiveData);

This is how i defined it in export class code private receiveData: any;, i've tried changing any to any[] and to string, i've tried some few other method to fix it but didn't work out, been battling with this for some days now. Someone should kindly help me out.


问:
Form.Close() doesn't close window immediately
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

```<code>public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }
</code>```

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

答:
In general I suggest not to use new keyword to any members of Control and/or Form class. If you need your own method use your own name of it.

In your code you don't really need to use Invoke when closing child forms.

If you need to be sure that all your child Forms are closed before you actually execute logic related to MainForm.Close you may subscribe to MainForm.FormClosing event with handler similar to follwing:

```<code>void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    bool allChildFormsClosed = !closeAllChildForms();

    if(!allChildFormsClosed)
    {
        e.Cancel = true;
        MessageBox.Show("Failed to close one or more child forms.");
        // better add some yes|no dialog to force exit if necessary
    }
}
</code>```

You may implement closeAllChildForms in a similar way as you did above - just: remove the formsList.Reverse(); and the 'Invoke..' - just call Close directly and update: if (this == form || form.IsDisposed) continue;

Body:
I need to be sure that all forms will be closed if I user somehow close the main form. So I decided to hide Close() function and I wrote something like this

public new bool Close()
        {
            List<Form> formsList = new List<Form>(Application.OpenForms.Count);
            foreach (var form in Application.OpenForms)
                formsList.Add((Form)form);
            formsList.Reverse();
            foreach (var form in formsList)
            {
                if (form.IsDisposed) continue;
                Invoke(new GenericEventHandler(() => { form.Close(); }));
            }

            return Application.OpenForms.Count == 0;
        }

So if all forms are closed successfully I return true and thanks to this I know that user can be logged out from application.

However it seems that form.Close() function is not fired immediately. After calling form.Close() formclosed event is not fired immediately as well as collection Application.OpenForms is not modified. The amount of opened forms is noted changed.

What could be a reason?

Body:
In general I suggest not to use new keyword to any members of Control and/or Form class. If you need your own method use your own name of it.

In your code you don't really need to use Invoke when closing child forms.

If you need to be sure that all your child Forms are closed before you actually execute logic related to MainForm.Close you may subscribe to MainForm.FormClosing event with handler similar to follwing:

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    bool allChildFormsClosed = !closeAllChildForms();

    if(!allChildFormsClosed)
    {
        e.Cancel = true;
        MessageBox.Show("Failed to close one or more child forms.");
        // better add some yes|no dialog to force exit if necessary
    }
}

You may implement closeAllChildForms in a similar way as you did above - just: remove the formsList.Reverse(); and the 'Invoke..' - just call Close directly and update: if (this == form || form.IsDisposed) continue;


问:
Selecting first non null value in a model
Let's say I have a model class that looks like this:

```<code>   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }
</code>```

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

```<code>   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code
</code>```

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

```<code>     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison
</code>```

答:
You could probably create a method (or even property) like:

public string Val()
{
    if (val1 != null) return val1;
    if (val2 != null) return val2;
    if (val3 != null) return val3;
    return null;
}
```

There is probably a shorter way to write this code. Also, if two or more of the values are not null, then it will return the first one.

Body:
Let's say I have a model class that looks like this:

   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison

Body:
You could probably create a method (or even property) like:

public string Val()
{
    if (val1 != null) return val1;
    if (val2 != null) return val2;
    if (val3 != null) return val3;
    return null;
}

There is probably a shorter way to write this code. Also, if two or more of the values are not null, then it will return the first one.


问:
Change the shadow color to any other color in THREE?
It this possible? If so, I can't seem to locate any documentation around it.</p>

答:
Yes, alter the color of your shadow plane's material. I needed a slightly blue-ish tint to my shadows so used something like this:</p>
```<code>var material = new THREE.ShadowMaterial({opacity: .7, color: '#003'});
</code>```

Body:
Yes, alter the color of your shadow plane's material. I needed a slightly blue-ish tint to my shadows so used something like this:

var material = new THREE.ShadowMaterial({opacity: .7, color: '#003'});


问:
Upload an image onto Imgur API - C# UWP
I've been trying to get uploading an image anonymously onto Imgur using the Imgur API to work, however I've been facing an issue with unauthorized path access.

I've tried search around other similar articles on Microsoft Docs and posts here on stack overflow but couldn't find a solution. I've even given my application "broadFileSystemAccess" as rescap capability in my Package.appxmanifest which I found from reading the Microsoft UWP documentations.

The error I receive is:

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'

The error occurs at the var filecon = File.ReadAllBytes(imgpath); line.

My File Picker code is:

```<code>public static string imgpath = "";

    public static string finalimg = "";

    private async void FileNameButton_Click(object sender, RoutedEventArgs e)
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".jpeg");
        picker.FileTypeFilter.Add(".png");

        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            imgpath = file.Path;
            var filecon = File.ReadAllBytes(imgpath); #Error drops here <---
            finalimg = Convert.ToBase64String(filecon);

            await ImgurUploadAPI();
            Debug.WriteLine("Picked Image: " + file.Name);
            uploadedimage_text.Text = "Picked Image: " + file.Name;
        }
        else
        {
            Debug.WriteLine("Image uploading has been cancelled.");
        }
    }
</code>```

And the ImgurUpload task code is:

```<code>public static string imgurlink = "";

    public async Task ImgurUploadAPI()
    {
        try
        {
            if (imgpath != null)
            {
                // Construct the HttpClient and Uri
                HttpClient httpClient = new HttpClient();
                Uri uri = new Uri("https://api.imgur.com/3/upload");

                httpClient.DefaultRequestHeaders.Add("Authorization", "Client-ID IMGUR-CLIENTIDHERE");
                //Debug.WriteLine("Request Headers: ");

                // Construct the JSON to post
                HttpStringContent content = new HttpStringContent("image=\"{finalimg}\"");
                Debug.WriteLine("Request Upload: " + content);

                // Post the JSON and wait for a response
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                imgurlink = httpResponseBody;
                Debug.WriteLine("Request Response: " + httpResponseBody);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }
</code>```

I feel like it might be something to do with the way I access and convert the image to be ready for upload. Any tips would be very appreciated as I've been stuck on this for awhile now and it's one of the last things I need to complete for my project. Cheers!

答:
When you use UWP your access to the file system is limited. This means that you can't simply read a file at an arbitrary path like you're trying to do here:

```<code>var filecon = File.ReadAllBytes(imgpath);
</code>```

What you need to do instead is to ask the StorageFile object you received from the FilePicker for a read Stream. Like so:

```<code>var buffer = await FileIO.ReadBufferAsync(file);
var filecon = buffer.ToArray();
finalimg = Convert.ToBase64String(filecon);
</code>```

You can find more information about file access for UWP at Microsoft Docs.

Title: Upload an image onto Imgur API - C# UWP

Body:
I've been trying to get uploading an image anonymously onto Imgur using the Imgur API to work, however I've been facing an issue with unauthorized path access.

I've tried search around other similar articles on Microsoft Docs and posts here on stack overflow but couldn't find a solution. I've even given my application "broadFileSystemAccess" as rescap capability in my Package.appxmanifest which I found from reading the Microsoft UWP documentations.

The error I receive is:

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\lysyr\Pictures\ROG Logo.png' is denied.'

The error occurs at the var filecon = File.ReadAllBytes(imgpath); line.

My File Picker code is:

public static string imgpath = "";

    public static string finalimg = "";

    private async void FileNameButton_Click(object sender, RoutedEventArgs e)
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".jpeg");
        picker.FileTypeFilter.Add(".png");

        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            // Application now has read/write access to the picked file
            imgpath = file.Path;
            var filecon = File.ReadAllBytes(imgpath); #Error drops here <---
            finalimg = Convert.ToBase64String(filecon);

            await ImgurUploadAPI();
            Debug.WriteLine("Picked Image: " + file.Name);
            uploadedimage_text.Text = "Picked Image: " + file.Name;
        }
        else
        {
            Debug.WriteLine("Image uploading has been cancelled.");
        }
    }

And the ImgurUpload task code is:

public static string imgurlink = "";

    public async Task ImgurUploadAPI()
    {
        try
        {
            if (imgpath != null)
            {
                // Construct the HttpClient and Uri
                HttpClient httpClient = new HttpClient();
                Uri uri = new Uri("https://api.imgur.com/3/upload");

                httpClient.DefaultRequestHeaders.Add("Authorization", "Client-ID IMGUR-CLIENTIDHERE");
                //Debug.WriteLine("Request Headers: ");

                // Construct the JSON to post
                HttpStringContent content = new HttpStringContent("image=\"{finalimg}\"");
                Debug.WriteLine("Request Upload: " + content);

                // Post the JSON and wait for a response
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                    uri,
                    content);

                // Make sure the post succeeded, and write out the response
                httpResponseMessage.EnsureSuccessStatusCode();
                var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                imgurlink = httpResponseBody;
                Debug.WriteLine("Request Response: " + httpResponseBody);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }

I feel like it might be something to do with the way I access and convert the image to be ready for upload. Any tips would be very appreciated as I've been stuck on this for awhile now and it's one of the last things I need to complete for my project. Cheers!

Body:
When you use UWP your access to the file system is limited. This means that you can't simply read a file at an arbitrary path like you're trying to do here:

var filecon = File.ReadAllBytes(imgpath);

What you need to do instead is to ask the StorageFile object you received from the FilePicker for a read Stream. Like so:

var buffer = await FileIO.ReadBufferAsync(file);
var filecon = buffer.ToArray();
finalimg = Convert.ToBase64String(filecon);

You can find more information about file access for UWP at Microsoft Docs.


问:
how to set a max-height for a css grid row
I am trying to set a max-height of 40px to the second row of a CSS Grid.

The width of the container is unknown therefore it should be responsive.

Also the content of each box is unknown.

I tried grid-template-rows: auto minmax(0, 40px); but unfortunately it will also set a height of 40px if no second row exists.

Is there any way to use grid-template-rows and prevent the second row from growing to 40px?

Here is an example where you can see that the second row takes space although there are no grid items:

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto minmax(0, 40px);
  grid-auto-rows: 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}

li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}

body {
 width: 650px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Colors</h1>

<ul>
  <li>Android green</li>
  <li>Antique brass</li>
  <li>Antique bronze</li>
  <li>Antique fuchsia</li>
  <li>Antique ruby</li>
  <li>Antique white</li>
</ul></code>```

答:
You can use the grid-auto-rows property to define the height of implicitly created grid rows.

In your case, you'll define your grid as having only one row. Then any additional grid rows created by your content will use the dimensions defined with the grid-auto-rows property. This way the second row won't exist until it's needed.

Edit: To have only one row display by default, but also define a height of 40px for a second row if needed, AND define a height of 15px for third, fourth, fifth rows if needed, you can add multiple values to grid-auto-rows.

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto;
  grid-auto-rows: 40px 15px 15px 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}
li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}
body {
 width: 650px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Colors</h1>

<ul>
  <li>Android green</li>
  <li>Antique brass</li>
  <li>Antique bronze</li>
  <li>Antique fuchsia</li>
  <li>Antique ruby</li>
  <li>Antique white</li>
</ul></code>```

Body:
I am trying to set a max-height of 40px to the second row of a CSS Grid.

The width of the container is unknown therefore it should be responsive.

Also the content of each box is unknown.

I tried grid-template-rows: auto minmax(0, 40px); but unfortunately it will also set a height of 40px if no second row exists.

Is there any way to use grid-template-rows and prevent the second row from growing to 40px?

Here is an example where you can see that the second row takes space although there are no grid items:

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto minmax(0, 40px);
  grid-auto-rows: 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}

li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}

body {
 width: 650px;
}

Colors

Android green

Antique brass

Antique bronze

Antique fuchsia

Antique ruby

Antique white

Body:
You can use the grid-auto-rows property to define the height of implicitly created grid rows.

In your case, you'll define your grid as having only one row. Then any additional grid rows created by your content will use the dimensions defined with the grid-auto-rows property. This way the second row won't exist until it's needed.

Edit: To have only one row display by default, but also define a height of 40px for a second row if needed, AND define a height of 15px for third, fourth, fifth rows if needed, you can add multiple values to grid-auto-rows.

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto;
  grid-auto-rows: 40px 15px 15px 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}
li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}
body {
 width: 650px;
}

<h1><a href="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F">Colors</a></h1>

<ul>
  <li>Android green</li>
  <li>Antique brass</li>
  <li>Antique bronze</li>
  <li>Antique fuchsia</li>
  <li>Antique ruby</li>
  <li>Antique white</li>
</ul>


问:
Query status of imagery resource in Google Earth Entreprise Fusion on command line
I'm using Google Earth Entreprise Fusion to add new imagery resources to my imagery project. When I build the project most images build successfully, but some end up in 'Blocked' state. I'm trying to find a way to query the imagery resource status on the command line to find the 'Blocked' images which I then want to remove using the gedropfromimageryproject command. Is there a gequeryimageryresource command I can use on the command line?</p>

答:
```<code>gequery --status <path_to_image_resource>
</code>```

so for example

```<code>[root@mms USA_CIB05]# gequery --status gem/Resources/Imagery/USA_CIB05_CIB05CDS_111453_0_rpf_n28w109
InProgress
</code>```

I did find this script which does something a little different but may also be of use.

https://tst-lsavoie.github.io/earthenterprise/geedocs/5.3.6/answer/fusionResAndProj/monitorBuildsWithTwitter.html

```<code>#!/bin/bash

twittername="YourServersTwitterAccount"
twitterpass="YourServersTwitterPassword"
assetroot="/gevol/assets/"

find $assetroot.state -iname "*.task" -ls >> /tmp/filelist

taskcount=0
inprogresscount=1
declare -a inprogressarray
declare -a queuedarray

while read line
do
asset=`echo $line | awk '{print $13}'`
status=`/opt/google/bin/gequery --status $asset`
   if [ "$status" = "InProgress" ]; then
      inprogressarray[$[${#inprogressarray[@]}+1]]=$asset
   fi
   if [ "$status" = "Queued" ]; then
      queuedarray[$[${#queuedarray[@]}+1]]=$asset
   fi
let taskcount=taskcount+1
done </tmp/filelist

for inprogress in ${inprogressarray[@]}
do
   logfile=`/opt/google/bin/gequery --logfile $inprogress`
      while read line
      do
      progress=$line
      done <$logfile

   curl --basic --user "$twittername:$twitterpass" --data-ascii
   "status=#GEEFusion Task$inprogresscount:
   $progress&source=Google+Earth+Enterprise"
   "http://twitter.com/statuses/update.json"

   curl --basic --user "$twittername:$twitterpass" --data-ascii
   "status=#GEEFusion Task$inprogresscount:
   $inprogress&source=Google+Earth+Enterprise"
   "http://twitter.com/statuses/update.json"

   let inprogresscount=inprogresscount+1
   done

   curl --basic --user "$twittername:$twitterpass" --data-ascii
   "status=#GEEFusion Working on ${#inprogressarray[@]} task(s),
   ${#queuedarray[@]} queued &source=Google+Earth+Enterprise"
   "http://twitter.com/statuses/update.json"

   rm /tmp/filelist
</code>```

Body:
gequery --status <path_to_image_resource>

so for example

[root@mms USA_CIB05]# gequery --status gem/Resources/Imagery/USA_CIB05_CIB05CDS_111453_0_rpf_n28w109
InProgress

I did find this script which does something a little different but may also be of use.

https://tst-lsavoie.github.io/earthenterprise/geedocs/5.3.6/answer/fusionResAndProj/monitorBuildsWithTwitter.html

#!/bin/bash

twittername="YourServersTwitterAccount"
twitterpass="YourServersTwitterPassword"
assetroot="/gevol/assets/"

find $assetroot.state -iname "*.task" -ls >> /tmp/filelist

taskcount=0
inprogresscount=1
declare -a inprogressarray
declare -a queuedarray

while read line
do
asset=`echo $line | awk '{print $13}'`
status=`/opt/google/bin/gequery --status $asset`
   if [ "$status" = "InProgress" ]; then
      inprogressarray[$[${#inprogressarray[@]}+1]]=$asset
   fi
   if [ "$status" = "Queued" ]; then
      queuedarray[$[${#queuedarray[@]}+1]]=$asset
   fi
let taskcount=taskcount+1
done </tmp/filelist

for inprogress in ${inprogressarray[@]}
do
   logfile=`/opt/google/bin/gequery --logfile $inprogress`
      while read line
      do
      progress=$line
      done <$logfile

   curl --basic --user "$twittername:$twitterpass" --data-ascii
   "status=#GEEFusion Task$inprogresscount:
   $progress&source=Google+Earth+Enterprise"
   "http://twitter.com/statuses/update.json"

   curl --basic --user "$twittername:$twitterpass" --data-ascii
   "status=#GEEFusion Task$inprogresscount:
   $inprogress&source=Google+Earth+Enterprise"
   "http://twitter.com/statuses/update.json"

   let inprogresscount=inprogresscount+1
   done

   curl --basic --user "$twittername:$twitterpass" --data-ascii
   "status=#GEEFusion Working on ${#inprogressarray[@]} task(s),
   ${#queuedarray[@]} queued &source=Google+Earth+Enterprise"
   "http://twitter.com/statuses/update.json"

   rm /tmp/filelist


问:
Why are my images not showing at the index page?
I am trying to create an auction website where the users can input an image url and bid on the entries.

The issue I am currently having is that my images are not reflecting on my index page except I hard code it.

I'm not sure what I am doing wrong as I have tried using different options such as using an imageField and trying to convert the URL to an image(This didn't work) and I have tried tweaking the codes but still having the same issue.

Please assist a newbie

URL.PY

```<code>    path("create/", views.create_listing, name="create_listing"),
</code>```

MODELS.PY

```<code>class Auction(models.Model):
    ABSTRACT = 'AB'
    MODERN = 'MN'
    ILLUSTRATION = 'IN'

    select_category = [
        ('ABSTRACT', 'Abstract'),
        ('MODERN', 'Modern'),
        ('ILLUSTRATION', 'Illustration')
    ]

    title = models.CharField(max_length=25)
    description = models.TextField()
    current_bid = models.IntegerField(null=False, blank=False)
    # image_upload = models.ImageField(upload_to='images/')
    image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True)
    category = models.CharField(
        choices=select_category,
        max_length=12,
        default=MODERN,
    )
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

FORMS.PY

```<code>class AuctionForm(forms.ModelForm):

    class Meta:
        model = Auction
        fields = ['title', 'description', 'current_bid', 'image_url', 'category']
</code>```

VIEWS.PY

```<code>def create_listing(request):
    form = AuctionForm()
    user = request.user

    if request.method == 'POST':
        form = AuctionForm(request.POST, request.FILES)
        images = Auction.objects.get('image_url')
        if form.is_valid:
            context = {
                'user': user,
                'images': images
            }
            form.save()
            return redirect('index', context)
    else:
        form = AuctionForm()
        context = {'form': form}
        return render(request, 'auctions/create-listing.html', context)
</code>```

CREATE LISTING HTML

```<code>    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>
</code>```

INDEX.HTML

```<code>    <h2>Active Listings</h2>

    <a href={% url 'create_listing' %}>Add new</a>
    <main>
        <section>
            {% for listing in listings %}
            <div class="row">
                <div class="col-md-4">
                  <div class="thumbnail my-2">
                    <a href={% url 'detail' detail.id %}>

                      {% if auction.image_url %}
                        <img src={{ auction.image_url }} alt="{{ auction.title }}" style="width:100%">
                      {% else %}
                        <img src="https://demofree.sirv.com/nope-not-here.jpg">
                      {% endif %}

                      <div class="caption">
                        <p>{{ Auction.get_category_display }}</p>
                        <p>Title</p>
                        <p>Amount</p>
                      </div>
                      <div class="button">
                        <a href={% url 'listing_detail' listing_detail.pk %} class="btn btn-outline-dark btn-sm m-1">VIEW</a>
                      </div>
                    </a>
                  </div>
                </div>
            </div>
            {% endfor %}
        </section>
</code>```

答: Did you installed pillow? if not you can installed i with pip install pillow or pipenv install pillow(if you installed django using pipenv) and then you can use image_upload = models.ImageField(upload_to='images/') in your model.</p>

Body:
I am trying to create an auction website where the users can input an image url and bid on the entries.

The issue I am currently having is that my images are not reflecting on my index page except I hard code it.

I'm not sure what I am doing wrong as I have tried using different options such as using an imageField and trying to convert the URL to an image(This didn't work) and I have tried tweaking the codes but still having the same issue.

Please assist a newbie

URL.PY

    path("create/", views.create_listing, name="create_listing"),

MODELS.PY

class Auction(models.Model):
    ABSTRACT = 'AB'
    MODERN = 'MN'
    ILLUSTRATION = 'IN'

    select_category = [
        ('ABSTRACT', 'Abstract'),
        ('MODERN', 'Modern'),
        ('ILLUSTRATION', 'Illustration')
    ]

    title = models.CharField(max_length=25)
    description = models.TextField()
    current_bid = models.IntegerField(null=False, blank=False)
    # image_upload = models.ImageField(upload_to='images/')
    image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True)
    category = models.CharField(
        choices=select_category,
        max_length=12,
        default=MODERN,
    )
    created_at = models.DateTimeField(auto_now_add=True)

FORMS.PY

class AuctionForm(forms.ModelForm):

    class Meta:
        model = Auction
        fields = ['title', 'description', 'current_bid', 'image_url', 'category']

VIEWS.PY

def create_listing(request):
    form = AuctionForm()
    user = request.user

    if request.method == 'POST':
        form = AuctionForm(request.POST, request.FILES)
        images = Auction.objects.get('image_url')
        if form.is_valid:
            context = {
                'user': user,
                'images': images
            }
            form.save()
            return redirect('index', context)
    else:
        form = AuctionForm()
        context = {'form': form}
        return render(request, 'auctions/create-listing.html', context)

CREATE LISTING HTML

    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>

INDEX.HTML

Active Listings

    Add new

            {% for listing in listings %}

                      {% if auction.image_url %}

                      {% else %}

                      {% endif %}

{{ Auction.get_category_display }}

Title

Amount

                        VIEW

            {% endfor %}


问:
How to turn these C# foreach loops into LINQ to Objects and return a bool?
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

```<code>private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }
</code>```

答:
Basically what's easiest to do (for me at least) is trying to spell out what you're trying to do:

```<code>return videoTracks.Any(track => track.Events.Any(event => event.Start == currentEvent.Start));
</code>```

What we want to know is does videoTracks have Any tracks where Any of its Events compare to the current one.

Body:
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }

Body:
Basically what's easiest to do (for me at least) is trying to spell out what you're trying to do:

return videoTracks.Any(track => track.Events.Any(event => event.Start == currentEvent.Start));

What we want to know is does videoTracks have Any tracks where Any of its Events compare to the current one.


问:
Camel case in HTML tag attributes and jquery - doesn't work, why?
Yes, there are similar questions, but they are about jquery adding lowercase attributes like here: Does the attr() in jQuery force lowercase?

But I have a different situation. Here is my HTML5 piece of code:

```<code><tr class='projectRow' data-projectId='34'>
</code>```

Notice that this is camelCase. And now this code does not work:

```<code>//"this" points to a child element
$id = $(this).closest('.projectRow').data('projectId');//undefined
</code>```

But if I make it lowercase:

```<code>$(this).closest('.projectRow').data('projectid');
</code>```

It works.

When I look at the source code, it's clearly "projectId" (camelCase), but when in chrome -> dev tools -> elements then it's "projectid" (lowercase) o_O

No wonder jquery can't get this value, but why is Chrome doing this? I did  something similar hundreds of times before, although was using a - like in "project-id" and now after so many years of making web applications I discover something like this o_O

答:
If you're ok with ordinary Javascript and use HTML5 this should work:</p>
```<code>element.getAttributeNS(null, 'data-projectId')
</code>```

Body:
Yes, there are similar questions, but they are about jquery adding lowercase attributes like here: Does the attr() in jQuery force lowercase?

But I have a different situation. Here is my HTML5 piece of code:

Notice that this is camelCase. And now this code does not work:

//"this" points to a child element
$id = $(this).closest('.projectRow').data('projectId');//undefined

But if I make it lowercase:

$(this).closest('.projectRow').data('projectid');

It works.

When I look at the source code, it's clearly "projectId" (camelCase), but when in chrome -> dev tools -> elements then it's "projectid" (lowercase) o_O

No wonder jquery can't get this value, but why is Chrome doing this? I did  something similar hundreds of times before, although was using a - like in "project-id" and now after so many years of making web applications I discover something like this o_O

Body:
If you're ok with ordinary Javascript and use HTML5 this should work:

element.getAttributeNS(null, 'data-projectId')


问:
Deploy a specific subfolder with cloud-run github action when working with a monorepo
I am working with a mono repo and I would like to deploy my back-end (only) with the Cloud Run service (using the "official" google cloud run action). For this action, I need a Dockerfile at the root of my project for building my image. But my Dockerfile is under ./server.

Is there a way to use something like working-directory for the run steps ? I didn't find anything from the doc.

Or do I have to have a Dockerfile at the root of my project and the Dockerfile points to the ./server?

My project tree :

```<code>./
 .github/
   worflows/
     deploy-back.yml
  client/
    ...
  server/
    ...
    Dockerfile
</code>```

# deploy-back.yml
name: Deploy to production

# ...

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

```

答:
Since you are working on a monorepo and wants to run this particular workflow to deploy only when backend code base gets changed, I would start by limiting the trigger by only changes related to the /server folder.

```<code>on:
  push:
    paths:
    - 'server/**'
</code>```

As for the Dockerfile location, I would keep under /server just because it's a monorepo. Now, to answer your question the Cloud Run GitHub actions you provided is expecting a parameter which points to your Docker image

```<code>source: gcr.io/${{ env.PROJECT_ID }}/${{ env.SERVICE_NAME }}:${{ env.PACKAGE_VERSION }}
</code>```

which means your Docker image has to be already built prior to run the "Deploy to Cloud Run" step. What I would do, add two Docker steps prior to the deployment so github actions can build the image:

```<code>- name: Docker auth
  run: gcloud auth configure-docker

- name: Docker build backend
  run: docker build -t gcr.io/${{ env.PROJECT_ID }}/${{ env.SERVICE_NAME }}:${{ env.PACKAGE_VERSION }} . -f server/Dockerfile

- name: Docker push backend
  run: docker push gcr.io/${{ env.PROJECT_ID }}/${{ env.SERVICE_NAME }}:${{ env.PACKAGE_VERSION }}
</code>```

Note the -f server/Dockerfile in the Docker build step which will point to the server folder and run the build from there or if you want (using bash) you can just change the directory during the build: cd server/ then run the docker build ...

Body:
I am working with a mono repo and I would like to deploy my back-end (only) with the Cloud Run service (using the "official" google cloud run action). For this action, I need a Dockerfile at the root of my project for building my image. But my Dockerfile is under ./server.

Is there a way to use something like working-directory for the run steps ? I didn't find anything from the doc.

Or do I have to have a Dockerfile at the root of my project and the Dockerfile points to the ./server?

My project tree :

./
 .github/
   worflows/
     deploy-back.yml
  client/
    ...
  server/
    ...
    Dockerfile

# deploy-back.yml
name: Deploy to production

# ...

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

Body:
Since you are working on a monorepo and wants to run this particular workflow to deploy only when backend code base gets changed, I would start by limiting the trigger by only changes related to the /server folder.

on:
  push:
    paths:
    - 'server/**'

As for the Dockerfile location, I would keep under /server just because it's a monorepo. Now, to answer your question the Cloud Run GitHub actions you provided is expecting a parameter which points to your Docker image

source: gcr.io/${{ env.PROJECT_ID }}/${{ env.SERVICE_NAME }}:${{ env.PACKAGE_VERSION }}

which means your Docker image has to be already built prior to run the "Deploy to Cloud Run" step. What I would do, add two Docker steps prior to the deployment so github actions can build the image:

- name: Docker auth
  run: gcloud auth configure-docker

- name: Docker build backend
  run: docker build -t gcr.io/${{ env.PROJECT_ID }}/${{ env.SERVICE_NAME }}:${{ env.PACKAGE_VERSION }} . -f server/Dockerfile

- name: Docker push backend
  run: docker push gcr.io/${{ env.PROJECT_ID }}/${{ env.SERVICE_NAME }}:${{ env.PACKAGE_VERSION }}

Note the -f server/Dockerfile in the Docker build step which will point to the server folder and run the build from there or if you want (using bash) you can just change the directory during the build: cd server/ then run the docker build ...


问:
How can we use constraint in every individual element in an array in cplex?
Why is my forall loop not working to apply an constraint to all the individual values stored in my variable. For eg: if there are 100 values stored under a variable k, how  can I apply the constraint where each value is less than a certain constant.</p>

答:
```<code> range r=1..100;

 int value[i in r]=2*i;

 dvar int k[r];

 maximize sum(i in r) k[i];
 subject to
 {
   forall(i in r) k[i]<=value[i];
 }

 assert forall(i in r) k[i]==2*i;
</code>```

works fine

Body:
 range r=1..100;

 int value[i in r]=2*i;

 dvar int k[r];

 maximize sum(i in r) k[i];
 subject to
 {
   forall(i in r) k[i]<=value[i];
 }

 assert forall(i in r) k[i]==2*i;

works fine


答:
You could add a property to your ModelTest class that provides the first non-null value (if any) in your object:

```<code>public class ModelTest
{
    public string val1 { get; set; }
    public string val2 { get; set; }
    public string val3 { get; set; }

    public string val => val1 ?? val2 ?? val3;
}
</code>```

and then check against that:

```<code>if (model.val == testCompare) { }
</code>```

Title: Selecting first non null value in a model

Body:
You could add a property to your ModelTest class that provides the first non-null value (if any) in your object:

public class ModelTest
{
    public string val1 { get; set; }
    public string val2 { get; set; }
    public string val3 { get; set; }

    public string val => val1 ?? val2 ?? val3;
}

and then check against that:

if (model.val == testCompare) { }