问:
Change multiple and codependent tkinter Entry value
So I'm trying to create something like the goole unit conversion tool
So far I have this:

```<code>import tkinter

rate = 3.281

def command_P():
    print("button pressed")

def callback1(arg):
    try:
        float(amount1.get())
        amount2.delete(0,"end")
        amount2.insert(0,float(amount1.get())*rate)
    except Exception as e:
        print(e)

def callback2(arg):
    try:
        float(amount2.get())
        amount1.delete(0,"end")
        amount1.insert(0,float(amount2.get())/rate)
    except Exception as e:
        print(e)

trade_w = tkinter.Tk()
trade_w.title("Unit Converter")

label_mont1 = tkinter.Label(trade_w,
                    text = "Metre:")
label_mont1.grid(column=0, row=1)

sv = tkinter.StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback1(sv))

amount1 = tkinter.Entry(trade_w,textvariable=sv)
amount1.grid(column=1, row=1)

label_mont2 = tkinter.Label(trade_w,
                    text = "Foot:")
label_mont2.grid(column=2, row=1)

vs = tkinter.StringVar()
vs.trace("w", lambda name, index, mode, vs=vs: callback2(vs))

amount2 = tkinter.Entry(trade_w, textvariable=vs)
amount2.grid(column=3, row=1)

trade_w.mainloop()
</code>```

Everything seem to work fine but when I write something on either box it moves the text cursor to the end of the Entry box, thats becouse when I do the .get() for amount1 or amount2 it does the callback function and recalculate the value.

Any idea of how to bypass or solve this?

Thanks!

答:
Since you know (or can determine) which widget has focus, just have the callback do nothing unless the focus is in a particular window.

Example:

```<code>def callback1(arg):
    if trade_w.focus_get() == amount1:
        try:
            float(amount1.get())
            amount2.delete(0,"end")
            amount2.insert(0,float(amount1.get())*rate)
        except Exception as e:
            print(e)

def callback2(arg):
    if trade_w.focus_get() == amount2:
        try:
            float(amount2.get())
            amount1.delete(0,"end")
            amount1.insert(0,float(amount2.get())/rate)
        except Exception as e:
            print(e)
</code>```

There are more efficient ways to do that, but this illustrates the point that you can determine which widget has the focus so that you only update the other widget.

Body:
So I'm trying to create something like the goole unit conversion tool
So far I have this:

import tkinter

rate = 3.281

def command_P():
    print("button pressed")

def callback1(arg):
    try:
        float(amount1.get())
        amount2.delete(0,"end")
        amount2.insert(0,float(amount1.get())*rate)
    except Exception as e:
        print(e)

def callback2(arg):
    try:
        float(amount2.get())
        amount1.delete(0,"end")
        amount1.insert(0,float(amount2.get())/rate)
    except Exception as e:
        print(e)

trade_w = tkinter.Tk()
trade_w.title("Unit Converter")

label_mont1 = tkinter.Label(trade_w,
                    text = "Metre:")
label_mont1.grid(column=0, row=1)

sv = tkinter.StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback1(sv))

amount1 = tkinter.Entry(trade_w,textvariable=sv)
amount1.grid(column=1, row=1)

label_mont2 = tkinter.Label(trade_w,
                    text = "Foot:")
label_mont2.grid(column=2, row=1)

vs = tkinter.StringVar()
vs.trace("w", lambda name, index, mode, vs=vs: callback2(vs))

amount2 = tkinter.Entry(trade_w, textvariable=vs)
amount2.grid(column=3, row=1)

trade_w.mainloop()

Everything seem to work fine but when I write something on either box it moves the text cursor to the end of the Entry box, thats becouse when I do the .get() for amount1 or amount2 it does the callback function and recalculate the value.

Any idea of how to bypass or solve this?

Thanks!

Body:
Since you know (or can determine) which widget has focus, just have the callback do nothing unless the focus is in a particular window.

Example:

def callback1(arg):
    if trade_w.focus_get() == amount1:
        try:
            float(amount1.get())
            amount2.delete(0,"end")
            amount2.insert(0,float(amount1.get())*rate)
        except Exception as e:
            print(e)

def callback2(arg):
    if trade_w.focus_get() == amount2:
        try:
            float(amount2.get())
            amount1.delete(0,"end")
            amount1.insert(0,float(amount2.get())/rate)
        except Exception as e:
            print(e)

There are more efficient ways to do that, but this illustrates the point that you can determine which widget has the focus so that you only update the other widget.


来源: stackexchange

问:
MYSQL remove duplicates from table with two columns
Have table contents_tags

```<code>+------------+--------+
| content_id | tag_id |
+------------+--------+
|          1 |      1 |
|          1 |      2 |
|          1 |      2 |
|          2 |      3 |
|          2 |      4 |
|          2 |      4 |
</code>```

I want create unique index with two columns

```<code>alter table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);
</code>```

But I already have duplicate entries and get error:

ERROR 1062 (23000): Duplicate entry '1-2' for key 'contents_tags'

```<code>alter IGNORE table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);
</code>```

IGNORE - don't work in Mysql 8

How can I remove duplicates?

答:
You have to delete all but unique values first. One of the options is using of intermediate table.

CREATE TABLE tmp
AS SELECT DISTINCT content_id, tag_id FROM contents_tags;

TRUNCATE contents_tags;

INSERT INTO contents_tags SELECT * FROM tmp;

DROP TABLE tmp;
```

https://www.db-fiddle.com/f/j6T6PXHvGF8V9HbFfiompk/0

ContentLicense: CC BY-SA 4.0

Body:
Have table contents_tags

+------------+--------+
| content_id | tag_id |
+------------+--------+
|          1 |      1 |
|          1 |      2 |
|          1 |      2 |
|          2 |      3 |
|          2 |      4 |
|          2 |      4 |

I want create unique index with two columns

alter table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);

But I already have duplicate entries and get error:

ERROR 1062 (23000): Duplicate entry '1-2' for key 'contents_tags'

alter IGNORE table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);

IGNORE - don't work in Mysql 8

How can I remove duplicates?

Body:
You have to delete all but unique values first. One of the options is using of intermediate table.

CREATE TABLE tmp
AS SELECT DISTINCT content_id, tag_id FROM contents_tags;

TRUNCATE contents_tags;

INSERT INTO contents_tags SELECT * FROM tmp;

DROP TABLE tmp;

https://www.db-fiddle.com/f/j6T6PXHvGF8V9HbFfiompk/0


问:
migrating flask web application currently using uWSGI web server to ASGI web server(uvicorn)
I currently have a flask web application using uWSGI web server that implements the WSGI standard and need to migrate this app to uvicorn web server that implements the ASGI standard.

If I choose to use uvicorn web server from the many available options say, Hypercorn, Daphne, then which web microframework(instead of flask) should I opt for from the available options say, Starlette, Quart, Django/Channels to get this migration done smoothly?

The hierarchy is like:

```<code>  Uvicorn: an ASGI server

        Starlette: (uses Uvicorn) a web microframework

             FastAPI: (uses Starlette) an API microframework with several
                      additional features for building APIs, with data validation, etc.
</code>```

As what I have read so far,

Quart is a Python web microframework based on Asyncio. It is intended
to provide the easiest way to use asyncio in a web context, especially
with existing Flask apps.

and

FastAPI has shown to be a Python web framework with one of the best
performances, as measured by third-party benchmarks, thanks to being
based on and powered by Starlette. https://fastapi.tiangolo.com/benchmarks/

Please suggest with the best approach

答:
So here I would like to add something that I have concluded so far,

FastAPI learned from Flask (and several of its plug-ins) several
  things, including its simplicity. For example, the way you declare
  routes is very similar. That makes it easy to migrate from Flask to
  FastAPI (which I see a lot of people doing).

Flask is a framework based on the current/old standard for Python web frameworks: WSGI.

FastAPI is based on Starlette, which uses the newer standard for asynchronous web frameworks: ASGI.

Starlette would be more comparable to Flask, in being a pure “micro-framework”. Almost everything that you can do with Flask, you can do with Starlette (and so with FastAPI).
Nevertheless, Starlette has some features not available in Flask (nor in many other WSGI frameworks, like Django, at least by default), like WebSockets, background tasks and others.

As FastAPI is based on Starlette, it inherits all its features. Including WebSockets, GraphQL support, templates, etc. So, at the minimum, with FastAPI you can do virtually everything you can with Flask.

FastAPI is also a micro-framework (maybe mini-framework, as it includes some extra features for APIs). So, you can structure the project however you want, in many cases, you can even use most of the same files from a Flask project (I’ve done that).

This has been explained in this amazing post: https://www.quora.com/What-are-the-advantages-of-using-FastAPI-over-flask

Also, Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.7 and 3.6 with performance auto-tuning can be used for minimal implementation. https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker

Body:
I currently have a flask web application using uWSGI web server that implements the WSGI standard and need to migrate this app to uvicorn web server that implements the ASGI standard.

If I choose to use uvicorn web server from the many available options say, Hypercorn, Daphne, then which web microframework(instead of flask) should I opt for from the available options say, Starlette, Quart, Django/Channels to get this migration done smoothly?

The hierarchy is like:

  Uvicorn: an ASGI server

        Starlette: (uses Uvicorn) a web microframework

             FastAPI: (uses Starlette) an API microframework with several
                      additional features for building APIs, with data validation, etc.

As what I have read so far,

Quart is a Python web microframework based on Asyncio. It is intended
to provide the easiest way to use asyncio in a web context, especially
with existing Flask apps.

and

FastAPI has shown to be a Python web framework with one of the best
performances, as measured by third-party benchmarks, thanks to being
based on and powered by Starlette. https://fastapi.tiangolo.com/benchmarks/

Please suggest with the best approach


问:
CMakeLists cannot find opencv library, although i defined it
I try using ROS with opencv, but when I 'catkin-make', it gives me this:

```<code>  CMake Error at /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:83 (find_package):
  Could not find a package configuration file provided by "OpenCV" with any
  of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake

  Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
  "OpenCV_DIR" to a directory containing one of the above files.  If "OpenCV"
  provides a separate development package or SDK, be sure it has been
  installed.
Call Stack (most recent call first):
  fls_package/CMakeLists.txt:10 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/vered/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/vered/catkin_ws/build/CMakeFiles/CMakeError.log".
Makefile:318: recipe for target 'cmake_check_build_system' failed
make: *** [cmake_check_build_system] Error 1
</code>```

with cmake-gui, I defined:
1. CMAKE_PREFIX_PATH = /home/vered/opencv/build (where OpenCVConfig.cmake is)
2. OpenCV_DIR = /usr/local/include/opencv4/opencv2 (where opencv.hpp is)

configured, generated and then sudo make install,

and still when catkin-make, i've got the same problem.
any ideas?

答:
It seems that i tried all the solutions in the site, except this one:
ROS "catkin_make" cannot find OpenCVConfig.cmake
and that's what worked for me...</p>

Body:
I try using ROS with opencv, but when I 'catkin-make', it gives me this:

  CMake Error at /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:83 (find_package):
  Could not find a package configuration file provided by "OpenCV" with any
  of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake

  Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
  "OpenCV_DIR" to a directory containing one of the above files.  If "OpenCV"
  provides a separate development package or SDK, be sure it has been
  installed.
Call Stack (most recent call first):
  fls_package/CMakeLists.txt:10 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/vered/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/vered/catkin_ws/build/CMakeFiles/CMakeError.log".
Makefile:318: recipe for target 'cmake_check_build_system' failed
make: *** [cmake_check_build_system] Error 1

with cmake-gui, I defined:
1. CMAKE_PREFIX_PATH = /home/vered/opencv/build (where OpenCVConfig.cmake is)
2. OpenCV_DIR = /usr/local/include/opencv4/opencv2 (where opencv.hpp is)

configured, generated and then sudo make install,

and still when catkin-make, i've got the same problem.
any ideas?


问:
Evaluate string expression and convert to bool?
I want to evaluate the string expression and convert the result to bool.

For example

string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;

the above expression has to evaluate and return true.

Can anyone suggest how to evaluate the expression and return bool value?

答:
I dont believe there is any built in expression solver that can be leveraged for this kind of expression evaluation. I would recommend Microsoft.CodeAnalysis.CSharp.Scripting to do the evaluation.

```<code>string expression = "!((71 > 70) && (80 > 71)) || 72 < 71";
bool output = CSharpScript.EvaluateAsync<bool>(expression).Result;
// -> false
</code>```

Issues with your question

The expression will not evaluate to true. I dont know why you assume that and require that it does. After the execution of the above script, the resultant bool will be false.

!((71 > 70) && (80 > 71)) || 72 < 71

!((true)    && (true))    || false

!(true & true)

false

you cannot declare a string without quotes; string express = "within quotes";. Statement above in post (string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;) is not a valid C# statement.

Test snippet here at #dotnetfiddle

Body:
I dont believe there is any built in expression solver that can be leveraged for this kind of expression evaluation. I would recommend Microsoft.CodeAnalysis.CSharp.Scripting to do the evaluation.

string expression = "!((71 > 70) && (80 > 71)) || 72 < 71";
bool output = CSharpScript.EvaluateAsync<bool>(expression).Result;
// -> false

Issues with your question

The expression will not evaluate to true. I dont know why you assume that and require that it does. After the execution of the above script, the resultant bool will be false.

!((71 > 70) && (80 > 71)) || 72 < 71

!((true)    && (true))    || false

!(true & true)

false

you cannot declare a string without quotes; string express = "within quotes";. Statement above in post (string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;) is not a valid C# statement.

Test snippet here at #dotnetfiddle


问:
Is there a way to calculate the stacking context of all DOM elements in order to compare any two elements for above position using JavaScript?
I am attempting to compare any two elements in the DOM to see if they were to be painted(rendered on screen) in the same area (coordinates overlapping) which one would be above the other. This question is not about overlapping calculation, rather it is about comparing any two elements from any part of the DOM tree for above position (calculating stacking context and z-index and HTML hierarchy...).

Although I am new to this area, my approach would traverse and assign a numerical value to each HTML element taking into consideration rules and standards. Another problem is getting them correctly. I was not able to find a JS library that already does this.

For css and full code example see...
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

The expected output is the ability to compare any two HTML elements for above or below position (3D). I will share my code if I get an idea from professionals here and be able to implement it. Thanks any help is appreciated.

答:
There is a package on npm called stacking-order that does exactly that.

You can install it with:

$ npm install stacking-order
```

<pre class="lang-js prettyprint-override"><code>import stackingOrder from 'stacking-order';
</code>```

or use https://npmcdn.com/stacking-order in a script tag.

```

<p>Then to find what you are looking for, simply call <code>stackingOrder.compare(element1, element2)</code></p>

<pre class="lang-js prettyprint-override"><code>const element1 = document.querySelector('#element1');
const element2 = document.querySelector('#element2');

const order = stackingOrder.compare(element1, element2);

if (order === 1)
    console.log('element1 is above element2`)
else
    console.log('element1 in under element2')
</code>```

Body:
There is a package on npm called stacking-order that does exactly that.

You can install it with:

$ npm install stacking-order

import stackingOrder from 'stacking-order';

or use https://npmcdn.com/stacking-order in a script tag.

<script src="https://npmcdn.com/stacking-order"></script>

Then to find what you are looking for, simply call stackingOrder.compare(element1, element2)

const element1 = document.querySelector('#element1');
const element2 = document.querySelector('#element2');

const order = stackingOrder.compare(element1, element2);

if (order === 1)
    console.log('element1 is above element2`)
else
    console.log('element1 in under element2')


问:
Add-In for keyboard shortcut to select current block or execute current block in sql server management studio query window?
In TOAD, you have keyboard shortcuts where you can select the current block or execute the current block....so if you are working on a large sql query, when you make a modification, you can just do a CTRL+ENTER (or something like that, can't recall right now) rather than having to manually highlight the block of sql and htting F5.

I'm pretty sure this doesn't exist natively in SSMS, anyone know if functionality like this exists in any Add-ins?

Sorry....some clarification....I'm talking about working in the query window, which may contain:

```<code>select * from SomeTable

select * from SomeTable
WHERE
    column1 = 'abc'
AND column2 = 'def'  <--- LET'S SAY MY CURSOR IS SITTING HERE
AND column3 = 'ghi'

select * from AnotherTable
WHERE
    column1 = 'abc'
AND column2 = 'def'
AND column3 = 'ghi'
</code>```

So, I just want to execute the statement that my cursor is within.

答:
OK, so to clarify what you're looking for... If you had the following T-SQL with text selection cursor as indicated:

```<code>DECLARE @Test Int
SET @Test = 1

IF @Test=1
BEGIN
    SELECT TestColumn1 FROM TestTable
    SELECT AnotherTestColumn FROM AnotherTestTable

    SELECT [A Valid Column]

    FROM [A Valid Table]

    SELECT LastColumn FROM LastTable ][ <- CURSOR HERE
END
</code>```

You would want a certain hotkey (eg Ctrl-F5) to execute SELECT LastColumn FROM LastTable...? Or SELECT LastColumn FROM LastTable END (which is what you would get with the blank row rule you described)? Or something else? How about the statement broken up with a line break in the middle, or the two statements bunched together?

If you really wanted to use blank rows to define "blocks", then that should be pretty easy to do as an Addin (sample/tutorial here); if, on the other hand, you expected a little more "intelligence", this could be a difficult/complex task, with SQL parsing required etc.

ContentLicense: CC BY-SA 3.0

Body:
In TOAD, you have keyboard shortcuts where you can select the current block or execute the current block....so if you are working on a large sql query, when you make a modification, you can just do a CTRL+ENTER (or something like that, can't recall right now) rather than having to manually highlight the block of sql and htting F5.

I'm pretty sure this doesn't exist natively in SSMS, anyone know if functionality like this exists in any Add-ins?

Sorry....some clarification....I'm talking about working in the query window, which may contain:

select * from SomeTable

select * from SomeTable
WHERE
    column1 = 'abc'
AND column2 = 'def'  <--- LET'S SAY MY CURSOR IS SITTING HERE
AND column3 = 'ghi'

select * from AnotherTable
WHERE
    column1 = 'abc'
AND column2 = 'def'
AND column3 = 'ghi'

So, I just want to execute the statement that my cursor is within.

Body:
OK, so to clarify what you're looking for... If you had the following T-SQL with text selection cursor as indicated:

DECLARE @Test Int
SET @Test = 1

IF @Test=1
BEGIN
    SELECT TestColumn1 FROM TestTable
    SELECT AnotherTestColumn FROM AnotherTestTable

    SELECT [A Valid Column]

    FROM [A Valid Table]

    SELECT LastColumn FROM LastTable ][ <- CURSOR HERE
END

You would want a certain hotkey (eg Ctrl-F5) to execute SELECT LastColumn FROM LastTable...? Or SELECT LastColumn FROM LastTable END (which is what you would get with the blank row rule you described)? Or something else? How about the statement broken up with a line break in the middle, or the two statements bunched together?

If you really wanted to use blank rows to define "blocks", then that should be pretty easy to do as an Addin (sample/tutorial here); if, on the other hand, you expected a little more "intelligence", this could be a difficult/complex task, with SQL parsing required etc.


问:
Python requests hangs whereas CURL doesn't (same request)
I'm getting a permanent hang when trying to read a response using requests to access a particular site, most likely due to blocking of some sort. What I'm unsure about is how CURL, which is successfully receiving a response, is different to my Python get request which never receives any response.

Note: the curl command is expected to return an error as i'm not sending required info like cookies
curl:

```<code>curl 'https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'
</code>```

successfully gets response

Python:

```<code>import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})
</code>```

hangs on read forever

答:
It works with python 3.

```<code>import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})
print(r.headers)
</code>```

Response:

```<code>{'Cache-Control': 'max-age=86400, public', 'Content-Encoding': 'gzip', 'Content-Language': 'en-US', 'Content-Type': 'text/html;charset=utf-8', 'Server': 'Apache-Coyote/1.1', 'Vary': 'Accept-Encoding', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '8009', 'Date': 'Wed, 19 Feb 2020 06:04:55 GMT', 'Connection': 'keep-alive'}
</code>```

Body:
I'm getting a permanent hang when trying to read a response using requests to access a particular site, most likely due to blocking of some sort. What I'm unsure about is how CURL, which is successfully receiving a response, is different to my Python get request which never receives any response.

Note: the curl command is expected to return an error as i'm not sending required info like cookies
curl:

curl 'https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'

successfully gets response

Python:

import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})

hangs on read forever

Body:
It works with python 3.

import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})
print(r.headers)

Response:

{'Cache-Control': 'max-age=86400, public', 'Content-Encoding': 'gzip', 'Content-Language': 'en-US', 'Content-Type': 'text/html;charset=utf-8', 'Server': 'Apache-Coyote/1.1', 'Vary': 'Accept-Encoding', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '8009', 'Date': 'Wed, 19 Feb 2020 06:04:55 GMT', 'Connection': 'keep-alive'}


问:
Detect camera condition in AVCaptureSession swift
I am working on a swift application and I want to take a picture during the video when the camera is not moving or when user focuses on something.
i used AVCaptureVideoDataOutputSampleBufferDelegate *captureOutput method which giving me image every time after starting camera. but I want to take only when the camera is not moving or focused.

```<code>func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        print("didOutput")
        guard let hasImage = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            print("no image")
            return
        }
        let ciimage : CIImage = CIImage(cvPixelBuffer: hasImage)
        DispatchQueue.main.async {
            self.liveCamImage = self.convert(cmage: ciimage)
        }
    }
</code>```

is there any solution for this

答:
You can try to use adjusting focus property of your capture device (AVCaptureDevice), when it is false the focus is stable. See detailed documentation below.

```<code>/**
 @property adjustingFocus
 @abstract
    Indicates whether the receiver is currently performing a focus scan to adjust focus.

 @discussion
    The value of this property is a BOOL indicating whether the receiver's camera focus is being automatically adjusted by means of a focus scan, because its focus mode is AVCaptureFocusModeAutoFocus or AVCaptureFocusModeContinuousAutoFocus. Clients can observe the value of this property to determine whether the camera's focus is stable.
 @seealso lensPosition
 @seealso AVCaptureAutoFocusSystem
 */
open var isAdjustingFocus: Bool { get }
</code>```

Body:
I am working on a swift application and I want to take a picture during the video when the camera is not moving or when user focuses on something.
i used AVCaptureVideoDataOutputSampleBufferDelegate *captureOutput method which giving me image every time after starting camera. but I want to take only when the camera is not moving or focused.

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        print("didOutput")
        guard let hasImage = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            print("no image")
            return
        }
        let ciimage : CIImage = CIImage(cvPixelBuffer: hasImage)
        DispatchQueue.main.async {
            self.liveCamImage = self.convert(cmage: ciimage)
        }
    }

is there any solution for this

Body:
You can try to use adjusting focus property of your capture device (AVCaptureDevice), when it is false the focus is stable. See detailed documentation below.

/**
 @property adjustingFocus
 @abstract
    Indicates whether the receiver is currently performing a focus scan to adjust focus.

 @discussion
    The value of this property is a BOOL indicating whether the receiver's camera focus is being automatically adjusted by means of a focus scan, because its focus mode is AVCaptureFocusModeAutoFocus or AVCaptureFocusModeContinuousAutoFocus. Clients can observe the value of this property to determine whether the camera's focus is stable.
 @seealso lensPosition
 @seealso AVCaptureAutoFocusSystem
 */
open var isAdjustingFocus: Bool { get }


问:
Unicode charecters in android stuido
I am designing a calculator in android and I want to make a button for math pow operation. but instead of X^y, I want the button to show "y" as a propper superscript. also, a special sign for division operation rather than "/". is there a way to do this.
it would best if it was possible to write a line in Values/String.xml file. I can write the special symbol for the registered sign with this code "\u00AE" but codes like division doesn't work this way.  </p>

答:
Here, ÷, Copy paste this symbol, or alternatively you can use an image.

And as for the power thing. You've control over the whole UI, don't take it as a WordPad, why don't you use TextView and position it dynamically so that it looks like it is in the superscript? Like scaling it down, and translating a bit up in the y direction.

Title: Unicode charecters in android stuido


问:
How do I get my nav links in the nav bar?
I'm not sure why this is happening. The  tag that is the title "Don't Be Square" is in the nav bar, but not the links. What am I missing here in the CSS or the HTML that will bump it up inside there? enter image description here</p>

答:
This is just an example you may follow it

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

      Don't Be Square

Home

Page 1

Page 2

Page 3

```

View it in full screen if not the navbar will wrap. Good luck

Body:
This is just an example you may follow it

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Don't Be Square</a>
    </div>
    <ul class="nav navbar-nav" style="float: right;">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>

</body>
</html>

View it in full screen if not the navbar will wrap. Good luck


问:
Laravel Eloquent return count of each group with groupBy()
I want to groupBy() task using Laravel Eloquent. I have searched Internet and didn't find anything with eloquent.
some people used groupBy() query with Query Builder like this link

But I want to create query like this style:

```<code>Task::select('id')->groupBy('category_id')->count();
</code>```

This code just return only count of first category_id. But I want count of all the category_id.

答:
Worked for me as

we need to select one column like 'category_id' or 'user_id' and then
  count the selected column on get()

```<code>    Task::select('category_id')
           ->where('user_id',Auth::user()->id)
           ->groupBy(['category_id'])
           ->get()
           ->count();
</code>```

Body:
I want to groupBy() task using Laravel Eloquent. I have searched Internet and didn't find anything with eloquent.
some people used groupBy() query with Query Builder like this link

But I want to create query like this style:

Task::select('id')->groupBy('category_id')->count();

This code just return only count of first category_id. But I want count of all the category_id.

Body:
Worked for me as

we need to select one column like 'category_id' or 'user_id' and then
  count the selected column on get()

    Task::select('category_id')
           ->where('user_id',Auth::user()->id)
           ->groupBy(['category_id'])
           ->get()
           ->count();


问:
How do i set the current logged in user as default in Django view when no url parameters are given
i want the /profile/ route to be accessible without having to pass any url argument

This is my profile View:

```<code>@login_required
def profile(request, username):
    ctx = {"username" : username}
    return render(request, "raynet/profile.html",ctx)
</code>```

This is my url pattern:

```<code>urlpatterns = [
    path('', views.landing),
    path('home/', views.home),
    path('profile/', views.profile),
    path('profile/<username>', views.profile),
    path('apps/', views.apps),
    path('signin/', views.signin),
    path('signup/', views.signup),
    path('testing/', views.testing),
    path('signout/', views.signout),
]
</code>```

It works fine if i specify a username in the url, but it doesnt work if i just go to /profile/
I want to get the current logged in user as default when no url variable is specified.

答:
Try like this:

```<code>@login_required
def profile(request, username=None):
    ctx = {"username" : username if username else request.user.username}
    return render(request, "raynet/profile.html",ctx)
</code>```

Here I am writing username parameter as keyword argument, so that username default value is None. Then using if else logic, I am assigning username value from argument or from request.user.username.

Body:
i want the /profile/ route to be accessible without having to pass any url argument

This is my profile View:

@login_required
def profile(request, username):
    ctx = {"username" : username}
    return render(request, "raynet/profile.html",ctx)

This is my url pattern:

urlpatterns = [
    path('', views.landing),
    path('home/', views.home),
    path('profile/', views.profile),
    path('profile/<username>', views.profile),
    path('apps/', views.apps),
    path('signin/', views.signin),
    path('signup/', views.signup),
    path('testing/', views.testing),
    path('signout/', views.signout),
]

It works fine if i specify a username in the url, but it doesnt work if i just go to /profile/
I want to get the current logged in user as default when no url variable is specified.

Body:
Try like this:

@login_required
def profile(request, username=None):
    ctx = {"username" : username if username else request.user.username}
    return render(request, "raynet/profile.html",ctx)

Here I am writing username parameter as keyword argument, so that username default value is None. Then using if else logic, I am assigning username value from argument or from request.user.username.


问:
Margins outside Grid layout
I have some problems to add a margin to my grid layout.
I can't insert margins to the body or my .container that is taking the whole viewport.
When the page gets scrollable... the vertical scrollbar forces also a horizontal scrollbar.</p>

```<code>.container {
    height:100vh;
    display: grid;
    grid-template-rows: auto 1fr  auto;
    grid-template-columns: 1fr;
    grid-template-areas:
        "header"
        "content"
        "footer"
    ;
}
</code>```

答:
Use "box-sizing: border-box"

```<code>.container {
    box-sizing: border-box;
    height: 100vh;
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 1fr;
    grid-template-areas:
        "header"
        "content"
        "footer"
    ;
}
</code>```

Title: Margins outside Grid layout

Body:
I have some problems to add a margin to my grid layout.
I can't insert margins to the body or my .container that is taking the whole viewport.
When the page gets scrollable... the vertical scrollbar forces also a horizontal scrollbar.

.container {
    height:100vh;
    display: grid;
    grid-template-rows: auto 1fr  auto;
    grid-template-columns: 1fr;
    grid-template-areas:
        "header"
        "content"
        "footer"
    ;
}

Body:
Use "box-sizing: border-box"

.container {
    box-sizing: border-box;
    height: 100vh;
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 1fr;
    grid-template-areas:
        "header"
        "content"
        "footer"
    ;
}


问:
writing multiple lines back to a file, wrong file length
I want to get the a multiline text file's content, and put it back to the file.

However, I have an issue with the file length.
The null terminator (0) that I add is after some strange characters.

Something wrong with my f_length ?

Edit : If I set the line-endings of my file to Unix (LF), I don't have the issue. So it seems that my code is incompatible with Windows line endings. How can I account for Windows text files ?

```<code>int main()
{
    FILE *fp = NULL;
    int f_length;
    char *buffer = NULL;
    size_t size = 0;

    fp = fopen(FILENAME, "r+");
    fseek(fp, 0, SEEK_END);
    f_length = ftell(fp);
    rewind(fp);

    buffer = malloc((f_length + 1) * sizeof(*buffer));
    fread(buffer, f_length, 1, fp);
    buffer[f_length] = 0;
    printf("%s\n", buffer);

    fp = fopen(FILENAME, "w+");
    fputs(buffer, fp);
    fclose(fp);

    return 0;
}
</code>```

答:
regarding:

```<code>buffer[f_length] = 0;
</code>```

This is placing the '0' way too far into the buffer.  this is why you see garbage characters.  Much better to capture the returned value from the call to fread() and set the '0' using:

```<code>buffer[ <returnedValue> ] = '\0';
</code>```

Body:
I want to get the a multiline text file's content, and put it back to the file.

However, I have an issue with the file length.
The null terminator (0) that I add is after some strange characters.

Something wrong with my f_length ?

Edit : If I set the line-endings of my file to Unix (LF), I don't have the issue. So it seems that my code is incompatible with Windows line endings. How can I account for Windows text files ?

int main()
{
    FILE *fp = NULL;
    int f_length;
    char *buffer = NULL;
    size_t size = 0;

    fp = fopen(FILENAME, "r+");
    fseek(fp, 0, SEEK_END);
    f_length = ftell(fp);
    rewind(fp);

    buffer = malloc((f_length + 1) * sizeof(*buffer));
    fread(buffer, f_length, 1, fp);
    buffer[f_length] = 0;
    printf("%s\n", buffer);

    fp = fopen(FILENAME, "w+");
    fputs(buffer, fp);
    fclose(fp);

    return 0;
}

Body:
regarding:

buffer[f_length] = 0;

This is placing the '0' way too far into the buffer.  this is why you see garbage characters.  Much better to capture the returned value from the call to fread() and set the '0' using:

buffer[ <returnedValue> ] = '\0';


问:
How to check a greater than check in reg expression?
How to use a greater than check in robot framework reg expression?

```<code> show_output    name=${item_name}    action=get    output_regexp=<ip>10.10.10.1</ip>, <time> >60 </time>
</code>```

I want to ensure that the value of <time> is more than 60 secs. How to do this?

答:
Regular expressions are for finding patterns, not performing arithmetic. You simply can't do what you want with regular expressions. At least, not without a really complicated expression that matches 61, 62, 63, etc or any number that is a 7 followed by one or more digits, or any group of three or more digits where the third-from-the-last digit is at least 1, and there aren't any decimal points or a leading negative sign, ...

It's easier to pull the number out and do the logical test on a separate line.

Body:
How to use a greater than check in robot framework reg expression?

 show_output    name=${item_name}    action=get    output_regexp=<ip>10.10.10.1</ip>, <time> >60 </time>

I want to ensure that the value of <time> is more than 60 secs. How to do this?


问:
how to solve the java.io.IOException: failed to load image contents for serialization of jcchart in ByteArrayOutputStream
HI to all I am trying below for serializing a JCChart object in ByteArrayOutputStream

```<code>ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
            ObjectOutput out=new ObjectOutputStream(bos);
            out.writeObject(chart2);
            out.flush();
            out.close();
            ObjectInputStream in=new ObjectInputStream(new

ByteArrayInputStream(bos.toByteArray()));
                chart_clone=(MyGraph)in.readObject();
                in.close();
</code>```

but this code gives exceptione that java.io.IOException: failed to load image contents

can any body tell me where is the problem and how to solve this

答:
Perhaps you are encountering the same issue as the one mentioned in this OTN Post.

The resolution there was to mark all Images which were members of the serialized object to be transient - meaning they will not be serialized. If your chart object has members of the type ImageIcon, it can solve your problem (and explain the stacktrace).

Edit: Keep in mind that not serializing the images might not be what you want if their content is dynamic and user defined, in which case you will loose their content when de-serializing. But I assume from the context that they are constants and can be ignored during serialization.

Body:
HI to all I am trying below for serializing a JCChart object in ByteArrayOutputStream

ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
            ObjectOutput out=new ObjectOutputStream(bos);
            out.writeObject(chart2);
            out.flush();
            out.close();
            ObjectInputStream in=new ObjectInputStream(new

ByteArrayInputStream(bos.toByteArray()));
                chart_clone=(MyGraph)in.readObject();
                in.close();

but this code gives exceptione that java.io.IOException: failed to load image contents

can any body tell me where is the problem and how to solve this


问:
How to add list [index] value to another list using method reference..?
This is my list value [a,b,c,d] ,  I tried to add list[1] index value b  to another list.. If am using lambda! am able to achieve this, any methods or ways was there to achieve same thing using method reference?.
Below code i tried

```<code>List<String> list1 = new ArrayList<>();
//list1 values are like [a,b,c,d]
List<String> list2 = new ArrayList<>();
list1.forEach(x-> {
    list2.add(x.get(1));
});
</code>```

How to achieve same thing using ::

```<code>list1.foreach(list1::add);
</code>```

答:
indexOf() will return the index of the first occurrence of the object

```<code>List<Integer> list2 = new ArrayList<>();
list2.add(list1.indexOf("b"));
</code>```

Body:
This is my list value [a,b,c,d] ,  I tried to add list[1] index value b  to another list.. If am using lambda! am able to achieve this, any methods or ways was there to achieve same thing using method reference?.
Below code i tried

List<String> list1 = new ArrayList<>();
//list1 values are like [a,b,c,d]
List<String> list2 = new ArrayList<>();
list1.forEach(x-> {
    list2.add(x.get(1));
});

How to achieve same thing using ::

list1.foreach(list1::add);

Body:
indexOf() will return the index of the first occurrence of the object

List<Integer> list2 = new ArrayList<>();
list2.add(list1.indexOf("b"));


问:
ReactJS: Getting Failed to Compile Error While Starting the Server
I am a beginner in ReactJS. Just after finishing a course on the basics of React and Redux. I have started a new Udemy course entitled "React Data Visualization - Build a Cryptocurrency Dashboard." I am facing a problem in lecture 4 while trying to start the server with yarn start command:

```<code>Failed to compile
./src/index.js
Cannot find file: 'index.js' does not match the corresponding name on disk: '.\src\App\app'.
</code>```

Here are my codes on index.js file under app directory:

```<code>import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render(){
    return (
      <div>
        Hello World
      </div>
    );
  }

}

export default App;
</code>```

Here are my codes on index.js file under src directory:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
</code>```

How can I fix the issue?

You can find the project files here.

https://drive.google.com/open?id=1u-8mCYSWZtXPbIqELKsF33FOiXb3yrkH

Edit 1: I am adding the codes inside package.json file, as suggested by @Wesgur:

```<code>{
  "name": "cryptodash",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

Edit 2: I am adding the image to show the folder structure, as suggested by @Madhavan.V:

答:
import App from './app';
this will import your index.js of app folder.</p>

Body:
I am a beginner in ReactJS. Just after finishing a course on the basics of React and Redux. I have started a new Udemy course entitled "React Data Visualization - Build a Cryptocurrency Dashboard." I am facing a problem in lecture 4 while trying to start the server with yarn start command:

Failed to compile
./src/index.js
Cannot find file: 'index.js' does not match the corresponding name on disk: '.\src\App\app'.

Here are my codes on index.js file under app directory:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render(){
    return (

        Hello World

    );
  }

}

export default App;

Here are my codes on index.js file under src directory:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

How can I fix the issue?

You can find the project files here.

https://drive.google.com/open?id=1u-8mCYSWZtXPbIqELKsF33FOiXb3yrkH

Edit 1: I am adding the codes inside package.json file, as suggested by @Wesgur:

{
  "name": "cryptodash",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Edit 2: I am adding the image to show the folder structure, as suggested by @Madhavan.V:


问:
How to display correct rows per page using Material UI table pagination
I'm trying to use Material UI table pagination to display 5 rows per page, but it shows all items on page and does not change pages. Cant find out where I'm making mistake. I have recreated my problem in sandbox, could you please check it : https://codesandbox.io/s/magical-davinci-t2nq7 </p>

```<code> state = {
    rowsPerPage: 5,
    page: 0
  };

  handleChangePage = (event, page) => {
    this.setState({ page });
  };

  handleChangeRowsPerPage = event => {
    this.setState({ rowsPerPage: event.target.value });
  };

       <TablePagination
        rowsPerPageOptions={[5, 10, 25]}
        component="div"
        count={data.length}
        rowsPerPage={this.state.rowsPerPage}
        page={this.state.page}
        onChangePage={this.handleChangePage}
        onChangeRowsPerPage={this.handleChangeRowsPerPage}
      />
</code>```

答:
it is better to use a back-end for getting pagination data because you can pass Offset , Limit to API and get data from it but for now i just fix your issue like so :

```<code>import React, { Component } from "react";
import data from "./data.js";
import "./styles.css";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import TablePagination from "@material-ui/core/TablePagination";
import Paper from "@material-ui/core/Paper";

class App extends Component {
  state = {
    rowsPerPage: 5,
    page: 0,
    Offset: 0,
    tempData: []
  };

  componentDidMount() {
    this.getData();
  }

  handleChangePage = (event, page) => {
    let { rowsPerPage, page: currentPage } = this.state;
    if (currentPage < page) {
      return this.setState(
        prevState => {
          return {
            Offset: prevState.Offset + rowsPerPage,
            page
          };
        },
        () => this.getData()
      );
    } else {
      return this.setState(
        prevState => {
          return {
            Offset: prevState.Offset - rowsPerPage,
            page
          };
        },
        () => this.getData()
      );
    }
  };

  handleChangeRowsPerPage = event => {
    this.setState({ rowsPerPage: event.target.value } , () => this.getData());
  };

  getData = () => {
    let { Offset, rowsPerPage: Limit } = this.state;
    let tempArr = [];
    for (let i = Offset; i < Offset + Limit; i++) {
      tempArr.push(data[i]);
    }

    return this.setState({ tempData: tempArr });
  };

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <TableContainer component={Paper} elevation={0}>
          <Table aria-label="simple table">
            <TableHead>
              <TableRow>
                <TableCell>Name</TableCell>
                <TableCell>Age</TableCell>
                <TableCell>ID</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {this.state.tempData.map((rows, idx) => {
                return (
                  <TableRow key={idx} hover={true}>
                    <TableCell>{rows.name}</TableCell>
                    <TableCell>{rows.age}</TableCell>
                    <TableCell>{rows.id}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>

          <TablePagination
            rowsPerPageOptions={[5, 10, 25]}
            component="div"
            count={data.length}
            rowsPerPage={this.state.rowsPerPage}
            page={this.state.page}
            onChangePage={this.handleChangePage}
            onChangeRowsPerPage={this.handleChangeRowsPerPage}
          />
        </TableContainer>
      </div>
    );
  }
}

export default App;

</code>```

in this way you pass Offset , Limit to your get data method and it will render filtered data for you

but you can see demo from here : https://codesandbox.io/s/friendly-williams-xxjf7

Body:
I'm trying to use Material UI table pagination to display 5 rows per page, but it shows all items on page and does not change pages. Cant find out where I'm making mistake. I have recreated my problem in sandbox, could you please check it : https://codesandbox.io/s/magical-davinci-t2nq7

 state = {
    rowsPerPage: 5,
    page: 0
  };

  handleChangePage = (event, page) => {
    this.setState({ page });
  };

  handleChangeRowsPerPage = event => {
    this.setState({ rowsPerPage: event.target.value });
  };

       <TablePagination
        rowsPerPageOptions={[5, 10, 25]}
        component="div"
        count={data.length}
        rowsPerPage={this.state.rowsPerPage}
        page={this.state.page}
        onChangePage={this.handleChangePage}
        onChangeRowsPerPage={this.handleChangeRowsPerPage}
      />

Body:
it is better to use a back-end for getting pagination data because you can pass Offset , Limit to API and get data from it but for now i just fix your issue like so :

import React, { Component } from "react";
import data from "./data.js";
import "./styles.css";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import TablePagination from "@material-ui/core/TablePagination";
import Paper from "@material-ui/core/Paper";

class App extends Component {
  state = {
    rowsPerPage: 5,
    page: 0,
    Offset: 0,
    tempData: []
  };

  componentDidMount() {
    this.getData();
  }

  handleChangePage = (event, page) => {
    let { rowsPerPage, page: currentPage } = this.state;
    if (currentPage < page) {
      return this.setState(
        prevState => {
          return {
            Offset: prevState.Offset + rowsPerPage,
            page
          };
        },
        () => this.getData()
      );
    } else {
      return this.setState(
        prevState => {
          return {
            Offset: prevState.Offset - rowsPerPage,
            page
          };
        },
        () => this.getData()
      );
    }
  };

  handleChangeRowsPerPage = event => {
    this.setState({ rowsPerPage: event.target.value } , () => this.getData());
  };

  getData = () => {
    let { Offset, rowsPerPage: Limit } = this.state;
    let tempArr = [];
    for (let i = Offset; i < Offset + Limit; i++) {
      tempArr.push(data[i]);
    }

    return this.setState({ tempData: tempArr });
  };

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <TableContainer component={Paper} elevation={0}>
          <Table aria-label="simple table">
            <TableHead>
              <TableRow>
                <TableCell>Name</TableCell>
                <TableCell>Age</TableCell>
                <TableCell>ID</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {this.state.tempData.map((rows, idx) => {
                return (
                  <TableRow key={idx} hover={true}>
                    <TableCell>{rows.name}</TableCell>
                    <TableCell>{rows.age}</TableCell>
                    <TableCell>{rows.id}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>

          <TablePagination
            rowsPerPageOptions={[5, 10, 25]}
            component="div"
            count={data.length}
            rowsPerPage={this.state.rowsPerPage}
            page={this.state.page}
            onChangePage={this.handleChangePage}
            onChangeRowsPerPage={this.handleChangeRowsPerPage}
          />
        </TableContainer>
      </div>
    );
  }
}

export default App;

in this way you pass Offset , Limit to your get data method and it will render filtered data for you

but you can see demo from here : https://codesandbox.io/s/friendly-williams-xxjf7


问:
Retrofit 2.0 how to get deserialised error response.body
I'm using Retrofit 2.0.0-beta1.

In tests i have an alternate scenario and expect error HTTP 400

I would like to have retrofit.Response<MyError> response
but response.body() == null

MyError is not deserialised - i see it only here

```<code>response.errorBody().string()
</code>```

but it doesn't give me MyError as object

答:
Create a model of the Error response & user Gson to convert the response to it. This will just work fine.

APIError.java

```<code>public class APIError {
    private String message;

    public String getMessage() {
        return message;
    }
}
</code>```

MainActivity.java (inside request onResponse)

```<code>if (response.isSuccessful()) {
    // Do your success stuff...

} else {
    APIError message = new Gson().fromJson(response.errorBody().charStream(), APIError.class);
    Toast.makeText(MainActivity.this, "" + message.getMessage(), Toast.LENGTH_SHORT).show();
}
</code>```

Body:
I'm using Retrofit 2.0.0-beta1.

In tests i have an alternate scenario and expect error HTTP 400

I would like to have retrofit.Response<MyError> response
but response.body() == null

MyError is not deserialised - i see it only here

response.errorBody().string()

but it doesn't give me MyError as object

Body:
Create a model of the Error response & user Gson to convert the response to it. This will just work fine.

APIError.java

public class APIError {
    private String message;

    public String getMessage() {
        return message;
    }
}

MainActivity.java (inside request onResponse)

if (response.isSuccessful()) {
    // Do your success stuff...

} else {
    APIError message = new Gson().fromJson(response.errorBody().charStream(), APIError.class);
    Toast.makeText(MainActivity.this, "" + message.getMessage(), Toast.LENGTH_SHORT).show();
}


答:
list1.forEach( x -> { } ) works like this: the operation between {} is done for every x from your list. This means that x is already an element and the x.get(1) will not provide the expected result.

One solution could be to simply use : list2.add(list1.get(1));

If you really want to use method reference and lambdas, you can use a BiConsumer functional interface. Here is an example:

```<code>    BiConsumer<List<String>, String> addConsumer = List::add;
    List<String> list1 = new ArrayList<>(); //values [a,b,c,d]
    List<String> list2 = new ArrayList<>();
    addConsumer.accept(list2, list1.get(1));
</code>```

Title: How to add list [index] value to another list using method reference..?

Body:
list1.forEach( x -> { } ) works like this: the operation between {} is done for every x from your list. This means that x is already an element and the x.get(1) will not provide the expected result.

One solution could be to simply use : list2.add(list1.get(1));

If you really want to use method reference and lambdas, you can use a BiConsumer functional interface. Here is an example:

    BiConsumer<List<String>, String> addConsumer = List::add;
    List<String> list1 = new ArrayList<>(); //values [a,b,c,d]
    List<String> list2 = new ArrayList<>();
    addConsumer.accept(list2, list1.get(1));


问:
Error converting data type nvarchar to real
I need to subtract two nvarchar values and store the result in another column. I understand that first I need to convert nvarchar to numeric values, but I always get this error

Error converting data type nvarchar to real

Just to mention in varchar values are stored only numeric values but I can't seem to get this conversion right.

答:
You said that...

Just to mention in varchar values are stored only numeric values but I
  can't seem to get this conversion right.

If that is absolutely true, then there's a very high probability that there are 1 or 2 trailing control characters (Tab, Carriage Return, Line Feed, whatever) in the items causing the errors.

Try converting the NVARCHAR values to the MONEY datatype first.  It won't work for leading control characters but it will for trailing control characters.  Obvioussly your original original value doesn't haven more than 4 decimal places, of course.


问:
Unable to add httplibrary in robot-framework
I trying to write test scripts using HttpLibrary (from robot framework) on Eclipse and below are the steps I have performed:

Installed robot framework HttpLibrary using command:

```<code>    pip install --upgrade robotframework-httplibrary
</code>```

From Settings-> Imports, added HttpLibrary to my script:

```<code>*** Settings ***
Library HttpLibrary
</code>```

I am getting the following error:

' init.py library is absolute, RED prefers using
  workspace relative paths which makes your projects more portable
  'httplibrary' library specification file was not generated. try to
  reload it manually in project explorer'.

答:
According to HttpLibrary documentation the correct way to import the library in your test suite is:</p>

```<code>*** Settings ***
Library    HttpLibrary.HTTP
</code>```

Body:
I trying to write test scripts using HttpLibrary (from robot framework) on Eclipse and below are the steps I have performed:

Installed robot framework HttpLibrary using command:

    pip install --upgrade robotframework-httplibrary

From Settings-> Imports, added HttpLibrary to my script:

*** Settings ***
Library HttpLibrary

I am getting the following error:

' init.py library is absolute, RED prefers using
  workspace relative paths which makes your projects more portable
  'httplibrary' library specification file was not generated. try to
  reload it manually in project explorer'.

Body:
According to HttpLibrary documentation the correct way to import the library in your test suite is:

*** Settings ***
Library    HttpLibrary.HTTP


问:
How to infer datatypes of an existing Spark Dataframe?
I have pivoted a long dataframe to wide. This new dataframe has many more new variables coming out of the pivot. These are all stringType in the Spark Dataframe. How could I get pyspark to re-infer the datatypes of those new columns so that decimals will be recognised as float/double instead of strings?

Background: The number of these new columns per table and the number of pivoted tables are too large to hand-build the schemas.

It would be nice if there is something similar to infer_objects() from Pandas, but within PySpark. I cannot use Pandas because the job lives in AWS Glue Spark, which offers no Pandas library.

答:
You can use ResolveChoice Class to handle your problem. You can choose one of the action type that are listed in documentation.

cast:  Allows you to specify a type to cast to (for example, cast:int).

make_cols:  Resolves a potential ambiguity by flattening the data. For example, if columnA could be an int or a string, the resolution is to produce two columns named columnA_int and columnA_string in the resulting DynamicFrame.

make_struct:  Resolves a potential ambiguity by using a struct to represent the data. For example, if data in a column could be an int or a string, using the make_struct action produces a column of structures in the resulting DynamicFrame with each containing both an int and a string.

project:  Resolves a potential ambiguity by retaining only values of a specified type in the resulting DynamicFrame. For example, if data in a ChoiceType column could be an int or a string, specifying a project:string action drops columns from the resulting DynamicFrame which are not type string.

To check all possible type firstly, you can use make_struct action type then you can use cast action or you can use make_cols action type and glue generate all possible type as new columns.

I'm going to share sample code block below.

```<code>resolvechoiceA = ResolveChoice.apply(frame = datasourceA, choice = "make_cols", transformation_ctx = "resolvechoiceA")
</code>```

I hope this answer can solve your problem.

Body:
You can use ResolveChoice Class to handle your problem. You can choose one of the action type that are listed in documentation.

cast:  Allows you to specify a type to cast to (for example, cast:int).

make_cols:  Resolves a potential ambiguity by flattening the data. For example, if columnA could be an int or a string, the resolution is to produce two columns named columnA_int and columnA_string in the resulting DynamicFrame.

make_struct:  Resolves a potential ambiguity by using a struct to represent the data. For example, if data in a column could be an int or a string, using the make_struct action produces a column of structures in the resulting DynamicFrame with each containing both an int and a string.

project:  Resolves a potential ambiguity by retaining only values of a specified type in the resulting DynamicFrame. For example, if data in a ChoiceType column could be an int or a string, specifying a project:string action drops columns from the resulting DynamicFrame which are not type string.

To check all possible type firstly, you can use make_struct action type then you can use cast action or you can use make_cols action type and glue generate all possible type as new columns.

I'm going to share sample code block below.

resolvechoiceA = ResolveChoice.apply(frame = datasourceA, choice = "make_cols", transformation_ctx = "resolvechoiceA")

I hope this answer can solve your problem.


问:
Limit the number of file Upload Wordpress
I want to limit the number of files upload against a role in wordpress. Is there any code or plugin available to do the job.

Any kind of solution will be entertained.

Thanks

答:
I doubt there is a plugin that does that stuff, but you can look at wp-admin/upload.php file to set your role-based limits there.

Yet, you won't be able to control the flash uploader from that file.


问:
How to use array push method with $or and multiple $in in NodeJS and MongoDB
I have implemented a system in which the registered user can have friends and follow those that he/she don't want to be friends with.
From that, I implemented a system to fetch the posts from those users. Now, I would like to fetch the posts by the loggedIn user as well along with the other posts(by friends and users - loggedIn - user follows).

In order to that, I have to add the req.user._id which is the Id of the loggedIn user.

following and friends are arrays of objects containing the id from the users.

As of now the only way to make the fetching of both following and friends posts is by commenting the lines in which I'm trying to do the pushes?

Now the only way to fetch the loggedIn user posts is by fetching them along just one, the following user posts or the friends user posts... I want to fetch them together with both arrays.

Did I explain myself? Thanks in advance.

```<code>  const { following, friends } = req.user;
  // Include currentLoggedIn user posts
  following.push(req.user._id);
  friends.push(req.user._id);

  // Fetch posts by  both users I follow and users I'm friends with
  const posts = await Post.find({
    $or: [{ user: { $in: [following, friends] } }]
  })
    .populate({ path: 'user', select: 'username avatar bio' })
    .sort('-date')
    .skip(startIndex)
    .limit(limit);
</code>```

Hopefully I could explain myself. This is the code it currently throws me:

```<code>{
    "status": "error",
    "error": {
        "stringValue": "\"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\"",
        "kind": "ObjectId",
        "value": [
            "5e0d1b9315a8f23df855e4c3",
            "5e0925629648903308163aeb"
        ],
        "path": "user",
        "reason": {},
        "message": "Cast to ObjectId failed for value \"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\" at path \"user\" for model \"Post\"",
        "name": "CastError",
        "statusCode": 500,
        "status": "error"
    },
    "message": "Cast to ObjectId failed for value \"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\" at path \"user\" for model \"Post\"",
    "stack": "CastError: Cast to ObjectId failed for value \"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\" at path \"user\" for model \"Post\"\n    at new CastError (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\error\\cast.js:39:11)\n    at ObjectId.cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schema\\objectid.js:246:11)\n    at ObjectId.SchemaType.applySetters (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:975:12)\n    at ObjectId.SchemaType._castForQuery (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1389:15)\n    at ObjectId.SchemaType.castForQuery (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1379:15)\n    at C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1328:18\n    at Array.map (<anonymous>)\n    at ObjectId.handle$in (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1324:14)\n    at ObjectId.SchemaType.castForQuery (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1376:20)\n    at ObjectId.SchemaType.castForQueryWrapper (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1353:17)\n    at cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\cast.js:296:39)\n    at cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\cast.js:58:18)\n    at model.Query.Query.cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\query.js:4683:12)\n    at model.Query.Query._castConditions (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\query.js:1861:10)\n    at model.Query.<anonymous> (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\query.js:1888:8)\n    at model.Query._wrappedThunk [as _find] (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\helpers\\query\\wrapThunk.js:16:8)\n    at C:\\xampp\\htdocs\\myporn\\node_modules\\kareem\\index.js:278:20\n    at _next (C:\\xampp\\htdocs\\myporn\\node_modules\\kareem\\index.js:102:16)\n    at process.nextTick (C:\\xampp\\htdocs\\myporn\\node_modules\\kareem\\index.js:507:38)\n    at process._tickCallback (internal/process/next_tick.js:61:11)"
}
</code>```

Which means (for what I know) that req.user._id could not be converted to the MongoDB ObjectId data type but then I tried requiring mongodb in my file to be able to use ObjectId but it keeps throwing me the same error.

Thanks!.

答:
You can try something like this, assuming all inputs in general are strings & needs to be converted to ObjectId() before querying, if your user field is type ObjectId(), your issue seems to be looking for ObjectId() Vs what you're passing is an array of arrays, Also you don't need $or as there is only one condition, if you're mentioning two or more then use $or :

```<code>const ObjectId = require('mongodb').ObjectId;

const { following, friends } = req.user;

// Include currentLoggedIn user posts
let mergedArray = [...following, ...friends];
mergedArray.push(req.user._id)
let usersArray = []
for (const i of mergedArray) {
    usersArray.push(new ObjectId(i))
}

// Fetch posts by  both users I follow and users I'm friends with
const posts = await Post.find({ user: { $in: usersArray } })
    .populate({ path: 'user', select: 'username avatar bio' })
    .sort('-date')
    .skip(startIndex)
    .limit(limit);
</code>```

Body:
I have implemented a system in which the registered user can have friends and follow those that he/she don't want to be friends with.
From that, I implemented a system to fetch the posts from those users. Now, I would like to fetch the posts by the loggedIn user as well along with the other posts(by friends and users - loggedIn - user follows).

In order to that, I have to add the req.user._id which is the Id of the loggedIn user.

following and friends are arrays of objects containing the id from the users.

As of now the only way to make the fetching of both following and friends posts is by commenting the lines in which I'm trying to do the pushes?

Now the only way to fetch the loggedIn user posts is by fetching them along just one, the following user posts or the friends user posts... I want to fetch them together with both arrays.

Did I explain myself? Thanks in advance.

  const { following, friends } = req.user;
  // Include currentLoggedIn user posts
  following.push(req.user._id);
  friends.push(req.user._id);

  // Fetch posts by  both users I follow and users I'm friends with
  const posts = await Post.find({
    $or: [{ user: { $in: [following, friends] } }]
  })
    .populate({ path: 'user', select: 'username avatar bio' })
    .sort('-date')
    .skip(startIndex)
    .limit(limit);

Hopefully I could explain myself. This is the code it currently throws me:

{
    "status": "error",
    "error": {
        "stringValue": "\"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\"",
        "kind": "ObjectId",
        "value": [
            "5e0d1b9315a8f23df855e4c3",
            "5e0925629648903308163aeb"
        ],
        "path": "user",
        "reason": {},
        "message": "Cast to ObjectId failed for value \"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\" at path \"user\" for model \"Post\"",
        "name": "CastError",
        "statusCode": 500,
        "status": "error"
    },
    "message": "Cast to ObjectId failed for value \"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\" at path \"user\" for model \"Post\"",
    "stack": "CastError: Cast to ObjectId failed for value \"[ 5e0d1b9315a8f23df855e4c3, 5e0925629648903308163aeb ]\" at path \"user\" for model \"Post\"\n    at new CastError (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\error\\cast.js:39:11)\n    at ObjectId.cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schema\\objectid.js:246:11)\n    at ObjectId.SchemaType.applySetters (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:975:12)\n    at ObjectId.SchemaType._castForQuery (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1389:15)\n    at ObjectId.SchemaType.castForQuery (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1379:15)\n    at C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1328:18\n    at Array.map (<anonymous>)\n    at ObjectId.handle$in (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1324:14)\n    at ObjectId.SchemaType.castForQuery (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1376:20)\n    at ObjectId.SchemaType.castForQueryWrapper (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\schematype.js:1353:17)\n    at cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\cast.js:296:39)\n    at cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\cast.js:58:18)\n    at model.Query.Query.cast (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\query.js:4683:12)\n    at model.Query.Query._castConditions (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\query.js:1861:10)\n    at model.Query.<anonymous> (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\query.js:1888:8)\n    at model.Query._wrappedThunk [as _find] (C:\\xampp\\htdocs\\myporn\\node_modules\\mongoose\\lib\\helpers\\query\\wrapThunk.js:16:8)\n    at C:\\xampp\\htdocs\\myporn\\node_modules\\kareem\\index.js:278:20\n    at _next (C:\\xampp\\htdocs\\myporn\\node_modules\\kareem\\index.js:102:16)\n    at process.nextTick (C:\\xampp\\htdocs\\myporn\\node_modules\\kareem\\index.js:507:38)\n    at process._tickCallback (internal/process/next_tick.js:61:11)"
}

Which means (for what I know) that req.user._id could not be converted to the MongoDB ObjectId data type but then I tried requiring mongodb in my file to be able to use ObjectId but it keeps throwing me the same error.

Thanks!.

Body:
You can try something like this, assuming all inputs in general are strings & needs to be converted to ObjectId() before querying, if your user field is type ObjectId(), your issue seems to be looking for ObjectId() Vs what you're passing is an array of arrays, Also you don't need $or as there is only one condition, if you're mentioning two or more then use $or :

const ObjectId = require('mongodb').ObjectId;

const { following, friends } = req.user;

// Include currentLoggedIn user posts
let mergedArray = [...following, ...friends];
mergedArray.push(req.user._id)
let usersArray = []
for (const i of mergedArray) {
    usersArray.push(new ObjectId(i))
}

// Fetch posts by  both users I follow and users I'm friends with
const posts = await Post.find({ user: { $in: usersArray } })
    .populate({ path: 'user', select: 'username avatar bio' })
    .sort('-date')
    .skip(startIndex)
    .limit(limit);


问:
IDEA maven dependency package cannot be downloaded
I used unused images to download the files, and having below errors. In general, there were both.

Could not transfer artifact org.springframework:spring-context:pom:5.1.7.RELEASE from/to nexus-aliyun (http://maven.aliyun.com/nexus/content/groups/public): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Return code is: 501 , ReasonPhrase:HTTPS Required

答:
You need to add proxy in your pom.xml as shown in below example

```<code><settings>
  <proxies>
   <proxy>
      <id>example-proxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.example.com</host>
      <port>8080</port>
      <username>proxyuser</username>
      <password>somepassword</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>
</settings>
</code>```

Body:
You need to add proxy in your pom.xml as shown in below example

<settings>
  <proxies>
   <proxy>
      <id>example-proxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.example.com</host>
      <port>8080</port>
      <username>proxyuser</username>
      <password>somepassword</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>
</settings>


问:
How to display label from many-to-many relationship
I have got a main table called Item, which is connected to table Label with many-to-many relationship. I would like to display the label in the view, but it doesnt work. I have tried item.label.name which gives value None and item.label gives core.Label.None. What would be the right way to display the label?

views.py

```<code>def HomeView(request):
  item_list = Item.objects.all()
  item_list = item_list.annotate(
      current_price=Coalesce('discount_price', 'price'))

  category_list = Category.objects.all()
  label_list = Label.objects.all()

  query = request.GET.get('q')

  if query:
      item_list = item_list.filter(title__icontains=query)

  cat = request.GET.get('cat')
  if cat:
      item_list = item_list.filter(category__pk=cat)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  paginator = Paginator(item_list, 10)

  page = request.GET.get('page')

  try:
      items = paginator.page(page)
  except PageNotAnInteger:
      items = paginator.page(1)
  except EmptyPage:
      items = paginator.page(paginator.num_pages)

  context = {
      'items': items,
      'category': category_list,
      'label': label_list
  }
  return render(request, "home.html", context)
</code>```

hmtl template:

```<code>                {% for item in items %}
            <div class="col-lg-3 col-md-6 mb-4">

                <div class="card">

                    <div class="view overlay">
                        <img src="{{ item.image.url }}" class="card-img-top">
                        <a href="{{ item.get_absolute_url }}">
                            <div class="mask rgba-white-slight"></div>
                        </a>
                    </div>

                    <div class="card-body text-center">

                        <h5>
                            <strong>
                                <a href="{{ item.get_absolute_url }}" class="dark-grey-text">{{ item.title }}

                                    <span class="badge badge-pill "></span>
                                    <p>{{ item.label }}</p>
                                </a>

                            </strong>
                        </h5>

                        <h4 class="font-weight-bold blue-text">
                            <strong>
                                {% if item.discount_price %}
                                <strike>£{{ item.price }}</strike> £{{ item.discount_price }}
                                {% else %}
                                £{{ item.price }}
                                {% endif %}
                            </strong>
                        </h4>

                    </div>

                </div>

            </div>
            {% endfor %}
</code>```

models.py

```<code>class Item(models.Model):
  title = models.CharField(max_length=100)
  price = models.FloatField()
  discount_price = models.FloatField(blank=True, null=True)
  category = models.ManyToManyField(Category, blank=True)
  label = models.ManyToManyField(Label, blank=True)
  slug = models.SlugField()
  description = models.TextField()
  image = models.ImageField()

class Label(models.Model):
  name = models.CharField(max_length=20)
</code>```

答:
you need to use below thing in template to get all labels from the item because it is M2M relationship.</p>

```<code>                          <h5>
                            <strong>
                                <a href="{{ item.get_absolute_url }}" class="dark-grey-text">{{ item.title }}

                                    <span class="badge badge-pill "></span>
                                   {% for label_name in item.label.all  %}
                                   <p>{{label_name.name}}</p>
                                   {% endfor %}
                                </a>

                            </strong>
                        </h5>
</code>```

Body:
I have got a main table called Item, which is connected to table Label with many-to-many relationship. I would like to display the label in the view, but it doesnt work. I have tried item.label.name which gives value None and item.label gives core.Label.None. What would be the right way to display the label?

views.py

def HomeView(request):
  item_list = Item.objects.all()
  item_list = item_list.annotate(
      current_price=Coalesce('discount_price', 'price'))

  category_list = Category.objects.all()
  label_list = Label.objects.all()

  query = request.GET.get('q')

  if query:
      item_list = item_list.filter(title__icontains=query)

  cat = request.GET.get('cat')
  if cat:
      item_list = item_list.filter(category__pk=cat)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  paginator = Paginator(item_list, 10)

  page = request.GET.get('page')

  try:
      items = paginator.page(page)
  except PageNotAnInteger:
      items = paginator.page(1)
  except EmptyPage:
      items = paginator.page(paginator.num_pages)

  context = {
      'items': items,
      'category': category_list,
      'label': label_list
  }
  return render(request, "home.html", context)

hmtl template:

                {% for item in items %}

                                {{ item.title }}

{{ item.label }}

                                {% if item.discount_price %}
                                £{{ item.price }} £{{ item.discount_price }}
                                {% else %}
                                £{{ item.price }}
                                {% endif %}

            {% endfor %}

models.py

class Item(models.Model):
  title = models.CharField(max_length=100)
  price = models.FloatField()
  discount_price = models.FloatField(blank=True, null=True)
  category = models.ManyToManyField(Category, blank=True)
  label = models.ManyToManyField(Label, blank=True)
  slug = models.SlugField()
  description = models.TextField()
  image = models.ImageField()

class Label(models.Model):
  name = models.CharField(max_length=20)

Body:
you need to use below thing in template to get all labels from the item because it is M2M relationship.

                          <h5>
                            <strong>
                                <a href="{{ item.get_absolute_url }}" class="dark-grey-text">{{ item.title }}

                                    <span class="badge badge-pill "></span>
                                   {% for label_name in item.label.all  %}
                                   <p>{{label_name.name}}</p>
                                   {% endfor %}
                                </a>

                            </strong>
                        </h5>