问:
How to avoid if statements which returns value based on the input in java 8
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

```<code>RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}
</code>```

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

答:
If you're not allowed to touch RoleEnum, and you have tests to prove the order of enums never changes, and another set of tests to prove the id's are in increasing order from 1, then you could possibly do such an abomination:

```<code>RoleEnum fetchProcessForRole(long roleID) {
    RoleEnum[] values = RoleEnum.values();
    if (roleID < 1 || roleID > values.length) {
        throw new IllegalArgumentException("Role id not found");
    }
    return values[(int) roleID - 1];
}
</code>```

But you really should just store it all in an id:enum map.

Body:
I have input as roleID (of Long data type), so I can not use switch case,
I am using if else statements right now.
I have search for the solution but have not came across with the perfect one.

RoleEnum fetchProcessForRole(roleID) {
    if (RoleEnum.USER.equals(roleID) {
        return RoleEnum.USER_VALIDATION; // this is of int type
    } else if (RoleEnum.ADMIN.equals(roleID) {
        return RoleEnum.ADMIN_VALIDATION;
    } else if (RoleEnum.MGR.equals(roleID) {
        return RoleEnum.MGR_VALIDATION;
    }
}

RoleEnum {
    USER(1,"USER","userrpt"),
    ADMIN(2,"ADMIN","adminrpt"),
    MGR(3,"MGR","mgrrpt"),
    USER_VALIDATION(4,"USER_VALIDATION","userrpt"),
    ADMIN_VALIDATION(5,"ADMIN_VALIDATION","adminrpt"),
    MGR_VALIDATION(6,"MGR_VALIDATION","mgrrpt");
    // it have int id, String name and its getters
}

I want to know if there is any other way to achieve same thing, as the input is Long, I do not want to use switch as it will require lot of conversions.

Body:
If you're not allowed to touch RoleEnum, and you have tests to prove the order of enums never changes, and another set of tests to prove the id's are in increasing order from 1, then you could possibly do such an abomination:

RoleEnum fetchProcessForRole(long roleID) {
    RoleEnum[] values = RoleEnum.values();
    if (roleID < 1 || roleID > values.length) {
        throw new IllegalArgumentException("Role id not found");
    }
    return values[(int) roleID - 1];
}

But you really should just store it all in an id:enum map.


来源: stackexchange

问:
hasOne() with select and where condition
I have two tables:

ForumPost, with the structure:

```<code>+---------+---------+
|      id | message |
+---------+---------+
</code>```

ForumPostVote, with the structure:

```<code>+---------+---------+---------+
|      id | post_id | user_id |
+---------+---------+---------+
</code>```

Here are my two model classes for each:

ForumPost.php

```<code>class ForumPost extends Model
{
    protected $with = [
        'userVote'
    ];

    public function votes()
    {
        return $this->hasMany('App\ForumPostVote', 'post_id', 'id');
    }

    public function userVote()
    {
        if (Auth::check())
        {
            return $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id)->select('id');
        }

        return null;
    }
}
</code>```

ForumPostVote.php

```<code>class ForumPostVote extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function post()
    {
        return $this->belongsTo('App\ForumPost', 'id', 'post_id');
    }
}
</code>```

As you can see, in ForumPost.php, I have a function userVote() where I try to to select the id from ForumPostVote where the user ID matches the logged in user.

When I make the request, it returns null. If I remove ->select('id'), it returns the object as normal:

```<code>"user_vote": {
    "id": 1,
    "post_id": 1,
    "user_id": 1
}
</code>```

If I try something like:

```<code>public function userVote()
{
    if (Auth::check())
    {
        $query = $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id);

        return $query->id;
    }

    return null;
}
</code>```

If I do:

```<code>public function userVote()
{
    if (Auth::check())
    {
        return $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id)->select(['id', 'post_id']);
    }

    return null;
}
</code>```

This returns:

```<code>"user_vote": {
    "id": 1,
    "post_id": 1
}
</code>```

But that's not what I want. I only want id.

What am I doing wrong?

答:
if i understand you correctly, you have many to many relation between ForumPost and user ... and the pivot table is ForumPostVote

1- the forumPostVote must inherit From Pivot not from model.

https://laravel.com/docs/7.x/eloquent-relationships#defining-custom-intermediate-table-models

2- if you want to get the id of the pivot table for the current user:

```<code>public function userVote()
{
    if (Auth::check())
    {
$value=$this->votes()->where('user_id',Auth::user()->id)->first();
if($value!=null) return $value->id;
        return value;
    }

    return null;
}
</code>```

please note that if there is no corresponding id in ForumPostVote table the result will be null

ContentLicense: CC BY-SA 4.0

Body:
I have two tables:

ForumPost, with the structure:

+---------+---------+
|      id | message |
+---------+---------+

ForumPostVote, with the structure:

+---------+---------+---------+
|      id | post_id | user_id |
+---------+---------+---------+

Here are my two model classes for each:

ForumPost.php

class ForumPost extends Model
{
    protected $with = [
        'userVote'
    ];

    public function votes()
    {
        return $this->hasMany('App\ForumPostVote', 'post_id', 'id');
    }

    public function userVote()
    {
        if (Auth::check())
        {
            return $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id)->select('id');
        }

        return null;
    }
}

ForumPostVote.php

class ForumPostVote extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function post()
    {
        return $this->belongsTo('App\ForumPost', 'id', 'post_id');
    }
}

As you can see, in ForumPost.php, I have a function userVote() where I try to to select the id from ForumPostVote where the user ID matches the logged in user.

When I make the request, it returns null. If I remove ->select('id'), it returns the object as normal:

"user_vote": {
    "id": 1,
    "post_id": 1,
    "user_id": 1
}

If I try something like:

public function userVote()
{
    if (Auth::check())
    {
        $query = $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id);

        return $query->id;
    }

    return null;
}

If I do:

public function userVote()
{
    if (Auth::check())
    {
        return $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id)->select(['id', 'post_id']);
    }

    return null;
}

This returns:

"user_vote": {
    "id": 1,
    "post_id": 1
}

But that's not what I want. I only want id.

What am I doing wrong?

Body:
if i understand you correctly, you have many to many relation between ForumPost and user ... and the pivot table is ForumPostVote

1- the forumPostVote must inherit From Pivot not from model.

https://laravel.com/docs/7.x/eloquent-relationships#defining-custom-intermediate-table-models

2- if you want to get the id of the pivot table for the current user:

public function userVote()
{
    if (Auth::check())
    {
$value=$this->votes()->where('user_id',Auth::user()->id)->first();
if($value!=null) return $value->id;
        return value;
    }

    return null;
}

please note that if there is no corresponding id in ForumPostVote table the result will be null


问:
Setting same height on columns
I am making a row with 2 columns with Bootstrap 3. I am programming for a webshop there is having around 100.000 products, so it is not converted to BS4 yet. Therefore I am forced to use BS3. The left column is gonna contain a background color and some text, while the right column will be an image.

This is how the row is looking like now:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

Headline

Some text here

            <button type="button" class="btn btn-info">Button</button>

```

This is how my end result should be:

答:
As said in comments your code is working, since you are using bootstrap 3 you may want to use img-responsive class for your image, because it has a large width.

By the way I have changed your col-sm-3 and col-sm-9 classes to xs ones, you may want to consider changing them to md or sm for your case.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
      integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
      crossorigin="anonymous"
    />
    <title>Static Template</title>

      This is a static template, there is no bundler or bundling involved!

Headline

Some text here

          <button type="button" class="btn btn-info">Button</button>

```

-Edit: after taking a deeper look on what you really want to achieve (same height for both columns) I updated my question with the follow:

Adding a class called d-flex to set a display: flex on any container you need, once a container has a display: flex; value its children will stretch by default.

You may also need to update your image to support a height: 100% which I highly recommend not to, cause it will make the image look ugly. Instead take advantage of background-size: cover;.

Some good resources on how to make your image fit in nicely:

https://css-tricks.com/almanac/properties/o/object-fit/

https://css-tricks.com/almanac/properties/b/background-size/

Title: Setting same height on columns

Body:
I am making a row with 2 columns with Bootstrap 3. I am programming for a webshop there is having around 100.000 products, so it is not converted to BS4 yet. Therefore I am forced to use BS3. The left column is gonna contain a background color and some text, while the right column will be an image.

This is how the row is looking like now:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

Headline

Some text here

            <button type="button" class="btn btn-info">Button</button>

This is how my end result should be:

Body:
As said in comments your code is working, since you are using bootstrap 3 you may want to use img-responsive class for your image, because it has a large width.

By the way I have changed your col-sm-3 and col-sm-9 classes to xs ones, you may want to consider changing them to md or sm for your case.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
      integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
      crossorigin="anonymous"
    />
    <title>Static Template</title>
    <style>
      .d-flex {
        display: flex;
      }
      .image-container {
        background-size: cover;
        background-position: center center;
      }
    </style>
  </head>
  <body>
    <h1>
      This is a static template, there is no bundler or bundling involved!
    </h1>
  </body>
  <!-- Latest compiled and minified CSS -->
  <div class="container">
    <div class="wrapper">
      <div class="row d-flex">
        <div class="col-xs-3" style="background-color:pink;">
          <h3>Headline</h3>
          <p>Some text here</p>
          <button type="button" class="btn btn-info">Button</button>
        </div>
        <div
          class="col-xs-9 image-container"
          style="background-image: url(https://picsum.photos/id/287/900/200)"
        ></div>
      </div>
    </div>
  </div>

  <!-- Latest compiled and minified JavaScript -->
</html>

-Edit: after taking a deeper look on what you really want to achieve (same height for both columns) I updated my question with the follow:

Adding a class called d-flex to set a display: flex on any container you need, once a container has a display: flex; value its children will stretch by default.

You may also need to update your image to support a height: 100% which I highly recommend not to, cause it will make the image look ugly. Instead take advantage of background-size: cover;.

Some good resources on how to make your image fit in nicely:

https://css-tricks.com/almanac/properties/o/object-fit/

https://css-tricks.com/almanac/properties/b/background-size/


问:
File Picker for Android
Is there any picker available to pick file from the SDCard or Device memory,like FilePicker available in Blackberry?
If not ,then any alternative for doing this?

Please help me.
Thanks in advance.

答:
Here is the help for implementing File picker.

You can also see the out put here

ContentLicense: CC BY-SA 3.0

Title: File Picker for Android


问:
Substitute bitwise in hexToRgba conversion
I am trying to implement the following function which converts hex into rgba:

```<code>  static hexToRgbA(hex: string): string {
    let c;
    if (hex.charAt(0) === '#') {
      if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
        c = hex.substring(1).split('');
        if (c.length === 3) {
          c = [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c = '0x' + c.join('');
        return (
          'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'
        );
      }
    } else {
      return hex;
    }
  }
</code>```

However at the following line, I get the ESLint error: ESLint: Unexpected use of '>>'.(no-bitwise). How do I fix this

```<code>'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'
</code>```

答:
The linter rule is to avoid accidentally using bitwise operators like & and >> when && and > are intended. You can disable the rule in your eslint configuration, or make it less strict by specifying operators you don't want it to flag (see no-bitwise documentation). But you can also just disable it only for this line:

```<code>// eslint-disable-next-line no-bitwise
return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)';
</code>```

Note that the comment is line based, so if you use multiple lines for the return statement you'll have to do

```<code>return (
  // eslint-disable-next-line no-bitwise
  'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'
);
</code>```

Body:
I am trying to implement the following function which converts hex into rgba:

  static hexToRgbA(hex: string): string {
    let c;
    if (hex.charAt(0) === '#') {
      if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
        c = hex.substring(1).split('');
        if (c.length === 3) {
          c = [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c = '0x' + c.join('');
        return (
          'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'
        );
      }
    } else {
      return hex;
    }
  }

However at the following line, I get the ESLint error: ESLint: Unexpected use of '>>'.(no-bitwise). How do I fix this

'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'

Body:
The linter rule is to avoid accidentally using bitwise operators like & and >> when && and > are intended. You can disable the rule in your eslint configuration, or make it less strict by specifying operators you don't want it to flag (see no-bitwise documentation). But you can also just disable it only for this line:

// eslint-disable-next-line no-bitwise
return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)';

Note that the comment is line based, so if you use multiple lines for the return statement you'll have to do

return (
  // eslint-disable-next-line no-bitwise
  'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'
);


答:
So couple things to note. What does the equals method for enum look like if you have overridden it. Is it a simple check to see if the roleId is equal to the enums id:

```<code>public boolean equals(long roleId) {
   return (int) roleId == id
}
</code>```

But I think the best way to approach this is to use a Map:

```<code>HashMap<int, RoleEnum> validation = new HashMap<int, RoleEnum>();

RoleEnum fetchProcessForRole(long roleId){
   return validation.get((int) roleId);
}
</code>```

Title: How to avoid if statements which returns value based on the input in java 8

Body:
So couple things to note. What does the equals method for enum look like if you have overridden it. Is it a simple check to see if the roleId is equal to the enums id:

public boolean equals(long roleId) {
   return (int) roleId == id
}

But I think the best way to approach this is to use a Map:

HashMap<int, RoleEnum> validation = new HashMap<int, RoleEnum>();

RoleEnum fetchProcessForRole(long roleId){
   return validation.get((int) roleId);
}


问:
merge 2 txt file in linux
file1

```<code>1
2
3
4
</code>```

file2

```<code>5
6
7
8
</code>```

result I want

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

which file1 alternative with file2

not like

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

can I merge file like this?

答: As an alternative to the sed method suggested by @Michael, you can also use the paste command, in this case: paste -d \\n file1 file2

Title: merge 2 txt file in linux

Body:
file1

1
2
3
4

file2

5
6
7
8

result I want

1
5
2
6
3
7
4
8

which file1 alternative with file2

not like

1
2
3
4
5
6
7
8

can I merge file like this?


问:
Calling a C++ function from python, using cython, with cythonize
I'm trying to learn Cython, and I want to call a simple C++ function from python

When building, I either have a uio.obj : error LNK2001: unresolved external symbol _just_a_func, or when I tried different combinations of cython prototypes, my just_a_func() function does not land in my module.

Here is all the code, setup.py, test.py, .pxd, .pyx and .h

```<code>########################
### uio.h
########################
#include <string>
using namespace std;
struct uio{
    int i;
    uio():i(2){}
    float f;
    string s;
    // float fun(int a);
    float fun(int a){return float(a+i);}

};

// int just_a_func(string s);
int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string

cdef extern from "uio.h":
    cdef extern int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++

from uio cimport just_a_func
cdef extern int just_a_func(s):
    return just_a_func(s)

########################
### setup.py
########################
# python .\setup.py build_ext --inplace --compiler=msvc

from setuptools import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("uio.pyx"))

########################
### test2.py
########################
import uio
print(dir(uio))
print("just_a_func", uio.just_a_func("fdsfds"))
</code>```

答:
May be, the explicit definition your function as "clear C" is helping you. In any case, your error message specifies that type of function. Try this:</p>

```<code>extern "C" {
  int just_a_func(string s){return s.length();}
}

</code>```

Body:
I'm trying to learn Cython, and I want to call a simple C++ function from python

When building, I either have a uio.obj : error LNK2001: unresolved external symbol _just_a_func, or when I tried different combinations of cython prototypes, my just_a_func() function does not land in my module.

Here is all the code, setup.py, test.py, .pxd, .pyx and .h

########################
### uio.h
########################
#include <string>
using namespace std;
struct uio{
    int i;
    uio():i(2){}
    float f;
    string s;
    // float fun(int a);
    float fun(int a){return float(a+i);}

};

// int just_a_func(string s);
int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string

cdef extern from "uio.h":
    cdef extern int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++

from uio cimport just_a_func
cdef extern int just_a_func(s):
    return just_a_func(s)

########################
### setup.py
########################
# python .\setup.py build_ext --inplace --compiler=msvc

from setuptools import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("uio.pyx"))

########################
### test2.py
########################
import uio
print(dir(uio))
print("just_a_func", uio.just_a_func("fdsfds"))

Body:
May be, the explicit definition your function as "clear C" is helping you. In any case, your error message specifies that type of function. Try this:

extern "C" {
  int just_a_func(string s){return s.length();}
}


问:
Bootstrap table striped: How do I change the stripe background colour?
With Bootstrap class table-striped, every other row in my table has a background colour equal to #F9F9F9. How can I change this colour?

答:
Easiest way for changing order of striped:

Add empty tr before your table tr tags.


问:
How to use throttle or debounce with React Hook?
I'm trying to use the throttle method from lodash in a functional component, e.g.:

```<code>const App = () => {
  const [value, setValue] = useState(0)
  useEffect(throttle(() => console.log(value), 1000), [value])
  return (
    <button onClick={() => setValue(value + 1)}>{value}</button>
  )
}
</code>```

Since the method inside useEffect is redeclared at each render, the throttling effect does not work.

Does anyone have a simple solution (without moving the throttle implementation outside of the component) ?

答:
Using lodash's debounce function here is what I do:

```<code>import debounce from 'lodash/debounce'

// The function that we want to debounce, for example the function that makes the API calls
const getUsers = (event) => {
// ...
}

// The magic!
const debouncedGetUsers = useCallback(debounce(getUsers, 500), [])
</code>```

In your JSX:

```<code><input value={value} onChange={debouncedGetUsers} />
</code>```

Body:
I'm trying to use the throttle method from lodash in a functional component, e.g.:

const App = () => {
  const [value, setValue] = useState(0)
  useEffect(throttle(() => console.log(value), 1000), [value])
  return (
    <button onClick={() => setValue(value + 1)}>{value}</button>
  )
}

Since the method inside useEffect is redeclared at each render, the throttling effect does not work.

Does anyone have a simple solution (without moving the throttle implementation outside of the component) ?

Body:
Using lodash's debounce function here is what I do:

import debounce from 'lodash/debounce'

// The function that we want to debounce, for example the function that makes the API calls
const getUsers = (event) => {
// ...
}

// The magic!
const debouncedGetUsers = useCallback(debounce(getUsers, 500), [])

In your JSX:

<input value={value} onChange={debouncedGetUsers} />


问:
Python3 eyed3 module, reading comments from mp3 file?
My goal is to use python3 (3.8 preferred) to read and eventually set the comments tag on an MP3 file.

I have installed eyed3 (python3.8 -m pip install eyed3) and the following code will load and can read all the tags, except when it comes to the comments. I've tried reading the documentation from the creator's website (http://eyed3.nicfit.net/) and the GitHub site with no luck and I'm not fully understanding the output from the following code:

```<code>import eyed3

music = "/path/to/valid/music/file.mp3"
audio = eyed3.load(music)

print(audio.tag.comments)
</code>```

this spits out the following:

```<code><eyed3.id3.tag.CommentsAccessor object at 0x7f54ca55d2b0>
</code>```

I've tried doing a dir(audio.tag.comments) and that doesn't provide anything except a bunch of class bits, and the following functions "get", "remove", "set"

Using something like:

```<code>moo = audio.tag.comments.get()
</code>```

throws an error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mrhobbits/.local/lib/python3.8/site-packages/eyed3/utils/__init__.py", line 138, in wrapped_fn
    return fn(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'description'
</code>```

Yet I can't find anything that would show me what 'description' is, or maybe I have to drill deeper to get the comment information?

I should also mention that doing:

```<code>print(audio.tag.artist)
</code>```

works just fine and returns:

```<code>Alestorm
</code>```

I'm a bit lost here. Any help would be great.

答:
Nevermind,

A quick search here revealed that the 'comments' is a list sort of object, and that doing:

```<code>audio.tag.comments[0].text
</code>```

reveals the information I was looking for.

Body:
My goal is to use python3 (3.8 preferred) to read and eventually set the comments tag on an MP3 file.

I have installed eyed3 (python3.8 -m pip install eyed3) and the following code will load and can read all the tags, except when it comes to the comments. I've tried reading the documentation from the creator's website (http://eyed3.nicfit.net/) and the GitHub site with no luck and I'm not fully understanding the output from the following code:

import eyed3

music = "/path/to/valid/music/file.mp3"
audio = eyed3.load(music)

print(audio.tag.comments)

this spits out the following:

<eyed3.id3.tag.CommentsAccessor object at 0x7f54ca55d2b0>

I've tried doing a dir(audio.tag.comments) and that doesn't provide anything except a bunch of class bits, and the following functions "get", "remove", "set"

Using something like:

moo = audio.tag.comments.get()

throws an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mrhobbits/.local/lib/python3.8/site-packages/eyed3/utils/__init__.py", line 138, in wrapped_fn
    return fn(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'description'

Yet I can't find anything that would show me what 'description' is, or maybe I have to drill deeper to get the comment information?

I should also mention that doing:

print(audio.tag.artist)

works just fine and returns:

Alestorm

I'm a bit lost here. Any help would be great.

Body:
Nevermind,

A quick search here revealed that the 'comments' is a list sort of object, and that doing:

audio.tag.comments[0].text

reveals the information I was looking for.


问:
gps not getting user location
I am trying to get the current user location (latitude and longitude ) but onLocationChanged method is not getting called
but other methods like public void onProviderDisabled(String provider). Please help, what can be the problem ?
I have a class:

```<code>package com.javacodegeeks.android.lbs;

import android.app.Activity;
import android.os.Bundle;

 import android.app.Activity;

 import android.content.Context;

 import android.location.Location;

 import android.location.LocationListener;

 import android.location.LocationManager;

 import android.os.Bundle;

 import android.view.View;

 import android.view.View.OnClickListener;

 import android.widget.Button;

 import android.widget.Toast;

 public class LbsGeocodingActivity extends Activity {

     private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters

     private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

     protected LocationManager locationManager;

     protected Button retrieveLocationButton;

     @Override

     public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.main);

     retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

     locationManager.requestLocationUpdates(

             LocationManager.GPS_PROVIDER,

             MINIMUM_TIME_BETWEEN_UPDATES,

             MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,

             new MyLocationListener()

     );

 retrieveLocationButton.setOnClickListener(new OnClickListener() {

         @Override

         public void onClick(View v) {

             showCurrentLocation();

         }

 });

 }

 protected void showCurrentLocation() {

     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

     if (location != null) {

         String message = String.format(

                 "Current Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message,

                 Toast.LENGTH_LONG).show();

     }

 }

 private class MyLocationListener implements LocationListener {

     public void onLocationChanged(Location location) {

         String message = String.format(

                 "New Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();

     }

     public void onStatusChanged(String s, int i, Bundle b) {

         Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderDisabled(String s) {
         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider disabled by the user. GPS turned off",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderEnabled(String s) {

         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider enabled by the user. GPS turned on",

                 Toast.LENGTH_LONG).show();

     }
 }
 }
</code>```

答:
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters

change this to 0 ....

Title: gps not getting user location

Body:
I am trying to get the current user location (latitude and longitude ) but onLocationChanged method is not getting called
but other methods like public void onProviderDisabled(String provider). Please help, what can be the problem ?
I have a class:

package com.javacodegeeks.android.lbs;

import android.app.Activity;
import android.os.Bundle;

 import android.app.Activity;

 import android.content.Context;

 import android.location.Location;

 import android.location.LocationListener;

 import android.location.LocationManager;

 import android.os.Bundle;

 import android.view.View;

 import android.view.View.OnClickListener;

 import android.widget.Button;

 import android.widget.Toast;

 public class LbsGeocodingActivity extends Activity {

     private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters

     private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

     protected LocationManager locationManager;

     protected Button retrieveLocationButton;

     @Override

     public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.main);

     retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

     locationManager.requestLocationUpdates(

             LocationManager.GPS_PROVIDER,

             MINIMUM_TIME_BETWEEN_UPDATES,

             MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,

             new MyLocationListener()

     );

 retrieveLocationButton.setOnClickListener(new OnClickListener() {

         @Override

         public void onClick(View v) {

             showCurrentLocation();

         }

 });

 }

 protected void showCurrentLocation() {

     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

     if (location != null) {

         String message = String.format(

                 "Current Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message,

                 Toast.LENGTH_LONG).show();

     }

 }

 private class MyLocationListener implements LocationListener {

     public void onLocationChanged(Location location) {

         String message = String.format(

                 "New Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();

     }

     public void onStatusChanged(String s, int i, Bundle b) {

         Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderDisabled(String s) {
         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider disabled by the user. GPS turned off",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderEnabled(String s) {

         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider enabled by the user. GPS turned on",

                 Toast.LENGTH_LONG).show();

     }
 }
 }


问:
Print values from HashMap
Currently, I am trying to write a method to locate the highest value product in my hashmap.

I am looking for a push in the right direction if that is possible. I appreciate any help that might be pointed my way. Thank you.

答:
In order to be consistent, I would suggest you using horizontal tab \t as the divider.

To align the text in the right columns, I would also create a method which adds some whitespaces right after the product name (e.g jeans). The number of input whitespaces should be equal to the subtraction of the column title (e.g Description) and the product name (e.g jeans).

Try this code:

```<code>fun addWhitespaces(input: String, referencedWord: String = "Description"): String
{
    var ws = ""
    (0..(referencedWord.length - input.length)).map { ws += " " }
    return ws
}
</code>```

The method addWhitespaces() is called within the last print.

```<code>products.maxBy { it.value.second } ?.let { (key, value) ->
    println("The highest priced product is: ")
    println()
    println("Item#\tDescription\tPrice")
    println("-----\t-----------\t-----")
    println("$key \t${value.first}${addWhitespaces(value.first)}\t${value.second}")
}
</code>```

Also as Ali Gelenler mentioned, you should check for the null condition as the result of maxBy() may be null.

Title: Print values from HashMap

Body:
In order to be consistent, I would suggest you using horizontal tab \t as the divider.

To align the text in the right columns, I would also create a method which adds some whitespaces right after the product name (e.g jeans). The number of input whitespaces should be equal to the subtraction of the column title (e.g Description) and the product name (e.g jeans).

Try this code:

fun addWhitespaces(input: String, referencedWord: String = "Description"): String
{
    var ws = ""
    (0..(referencedWord.length - input.length)).map { ws += " " }
    return ws
}

The method addWhitespaces() is called within the last print.

products.maxBy { it.value.second } ?.let { (key, value) ->
    println("The highest priced product is: ")
    println()
    println("Item#\tDescription\tPrice")
    println("-----\t-----------\t-----")
    println("$key \t${value.first}${addWhitespaces(value.first)}\t${value.second}")
}

Also as Ali Gelenler mentioned, you should check for the null condition as the result of maxBy() may be null.


问:
How can I print all the products attributes in product.html
This is my models.py

```<code>class Product(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(blank=True, null=True)
    price = models.FloatField()
    summary = models.TextField(blank=False, null=False)
    image = models.ImageField(blank=True, null=True)
</code>```

This is my Django views.py

```<code>def products_view(request,*args, **kwargs):
    print(Product.objects.values())
    myDict = list()
    for product in Product.objects.all():
        my_product = {
        "product_id": product.id,
        "product_title":product.title,
        "product_description":product.description,
        "product_price":product.price,
        "product_summary":product.summary,
        "product_image":product.image
        }
        print(my_product)
    return render(request, "products.html", my_product)
</code>```

This my products.html

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

{% block content %}
<h1>Products Page</h1>

<ul>
{% for product in my_product %}
<div class="card" style="width: 18rem;">
  <img src="{{ product_image }}" class="card-img-top" alt="{{ product_id }}">
  <div class="card-body">
    <h5 class="card-title">{{ product_title }}</h5>
    <p class="card-text">{{ product_description }}</p>
    <a href="/cart" class="btn btn-primary">Add to Basket</a>
  </div>
</div>
{% endfor %}
</ul>

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

My Product.html page only show the "h1" tag, do not show the Products attributes. How can I achieve this problem?
Products.objects.all() gives me QuerySet and I tried to change into dict. but I cannot print the dict elements' attributes .

答:
Your view should send products through context

```<code>def products_view(request,*args, **kwargs):
    products = Product.objects.all()
    context = {'products': products }
    return render(request, "products.html", context)
</code>```

also in template then you can use

```<code>{% for product in products %}
<div class="card" style="width: 18rem;">
  <img src="{{ product.image.url}}" class="card-img-top" alt="{{ product.id}}">
  <div class="card-body">
    <h5 class="card-title">{{ product.title}}</h5>
    <p class="card-text">{{ product.description}}</p>
    <a href="/cart" class="btn btn-primary">Add to Basket</a>
  </div>
</div>
{% endfor %}
</code>```

Body:
This is my models.py

class Product(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(blank=True, null=True)
    price = models.FloatField()
    summary = models.TextField(blank=False, null=False)
    image = models.ImageField(blank=True, null=True)

This is my Django views.py

def products_view(request,*args, **kwargs):
    print(Product.objects.values())
    myDict = list()
    for product in Product.objects.all():
        my_product = {
        "product_id": product.id,
        "product_title":product.title,
        "product_description":product.description,
        "product_price":product.price,
        "product_summary":product.summary,
        "product_image":product.image
        }
        print(my_product)
    return render(request, "products.html", my_product)

This my products.html

{% extends 'base.html' %}

{% block content %}

Products Page

{% for product in my_product %}

{{ product_title }}

{{ product_description }}

    Add to Basket

{% endfor %}

{% endblock %}

My Product.html page only show the "h1" tag, do not show the Products attributes. How can I achieve this problem?
Products.objects.all() gives me QuerySet and I tried to change into dict. but I cannot print the dict elements' attributes .

Body:
Your view should send products through context

def products_view(request,*args, **kwargs):
    products = Product.objects.all()
    context = {'products': products }
    return render(request, "products.html", context)

also in template then you can use

{% for product in products %}
<div class="card" style="width: 18rem;">
  <img src="{{ product.image.url}}" class="card-img-top" alt="{{ product.id}}">
  <div class="card-body">
    <h5 class="card-title">{{ product.title}}</h5>
    <p class="card-text">{{ product.description}}</p>
    <a href="/cart" class="btn btn-primary">Add to Basket</a>
  </div>
</div>
{% endfor %}


问:
Django::OperationalError at /admin/login/ unable to open database file
I know there's already a same question, i too tried the solutions given their but it dint work for me hence i am writing my own question.
Hii all, i am deploying django server using apache2 server and when i tried my host Ip address it works fine as it displays it Worked page, it works for IPADRESS/admin also but after filling in the credentials and hit on enter will produce this error

```<code>***OperationalError at /admin/login/
unable to open database file***
</code>```

and my error looks like

```<code>Environment:

Request Method: POST
Request URL: http://192.168.1.105/admin/login/?next=/admin/

Django Version: 1.7.4
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'managementdashboard')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/admin/sites.py" in login
  361.         return login(request, **defaults)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/auth/views.py" in login
  44.             auth_login(request, form.get_user())
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
  96.         request.session.cycle_key()
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in cycle_key
  279.         self.create()
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in create
  41.                 self.save(must_create=True)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in save
  64.                 obj.save(force_insert=must_create, using=using)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in save
  589.                        force_update=force_update, update_fields=update_fields)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  617.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  698.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  731.                                using=using, raw=raw)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  92.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  921.         return query.get_compiler(using=using).execute_sql(return_id)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  920.                 cursor.execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  81.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute
  485.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/login/
Exception Value: unable to open database file
</code>```

Need help as son as possible, thank you in advance.

答: go to your project directory, just share permission with IIS user and that should do the job - if you have deployed on IIS windows server</p>

Body:
I know there's already a same question, i too tried the solutions given their but it dint work for me hence i am writing my own question.
Hii all, i am deploying django server using apache2 server and when i tried my host Ip address it works fine as it displays it Worked page, it works for IPADRESS/admin also but after filling in the credentials and hit on enter will produce this error

***OperationalError at /admin/login/
unable to open database file***

and my error looks like

Environment:

Request Method: POST
Request URL: http://192.168.1.105/admin/login/?next=/admin/

Django Version: 1.7.4
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'managementdashboard')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/admin/sites.py" in login
  361.         return login(request, **defaults)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/auth/views.py" in login
  44.             auth_login(request, form.get_user())
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
  96.         request.session.cycle_key()
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in cycle_key
  279.         self.create()
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in create
  41.                 self.save(must_create=True)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in save
  64.                 obj.save(force_insert=must_create, using=using)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in save
  589.                        force_update=force_update, update_fields=update_fields)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  617.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  698.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  731.                                using=using, raw=raw)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  92.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  921.         return query.get_compiler(using=using).execute_sql(return_id)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  920.                 cursor.execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  81.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)
File "/var/www/dashboardapp/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute
  485.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/login/
Exception Value: unable to open database file

Need help as son as possible, thank you in advance.


问:
How do i put a link in a table
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.

index.php:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">
       <!-- jQuery library -->
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <!-- Popper JS -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
        <!-- Latest compiled JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>
<body>

    <button class="back" onclick="window.location='../'">
      <img src="/src/icons/back.png">
    </button> <!-- Tilbake knapp -->

    <button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">
      <img src="/src/icons/add.png">
    </button> <!-- Ny Bruker knapp -->

    <div class="container-fluid" id="utskjekkcontainer">
      <div class="row justify-content-center">
        <div class="col-mv-10 bg-light mt-5 rounded p-3">
          <h1 class="text-primary p-2">Brukere</h1>
          <hr>
          <div class="form-inline">
            <label for="search" class="font-weight-bold lead text-dark">Søk</label>
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
          </div>
          <hr>
          <?php
            include "../../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM brukere");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>
          <table class="table table-hover table-light table-striped" id="table_data">
            <thead>
              <tr>
                <th>#</th>
                <th>Fornavn</th>
                <th>Etternavn</th>
                <th>Utskjekket</th>
                <th>Admin</th>
                <th>Slett</th>
              </tr>
            </thead>
            <tbody>
              <?php while($row=$result->fetch_assoc()){ ?>
                <tr>
                  <td><?php echo $row["id"]; ?></td>
                  <td><?php echo $row["fornavn"]; ?></td>
                  <td><?php echo $row["etternavn"]; ?></td>
                  <td><?php echo $row["utskjekket"]; ?></td>
                  <td><?php echo $row["is_admin"]; ?></td>
                  <td><a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a></td>
                </tr>
              <?php }
              $conn->close();
              ?>
             </tbody>

           </table>

        </div>
      </div>
    </div>

    <script type="text/javascript">
      $(document).ready(function(){
        $('#search_text').keyup(function(){
          var search = $(this).val();
          $.ajax({
            url:'action.php',
            method:'post',
            data:{query:search},
            success:function(response){
              $('#table_data').html(response);
            }
          });
        });
      });
    </script>

</body>
</html>
</code>```

action.php:

```<code><?php

    include "../../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM brukere");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "<thead>
                    <tr>
                    <th>#</th>
                    <th>Fornavn</th>
                    <th>Etternavn</th>
                    <th>Utskjekket</th>
                    <th>Admin</th>
                    <th>Slett</th>
                    </tr>
                </thead>
                <tbody>";

        while($row=$result->fetch_assoc()){
            $output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td>".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a>."</td>
                </tr>";
        };
        $output .= "</tbody>";
        echo $output;
    } else {
        echo "<h3>No match found!</h3>";
    };

?>
</code>```

This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.

答:
The a tag is not added as a plain-text to the output string, you need to rewrite that line, concatenate strings parts to variables parts correctly.

Try replacing:

```<code>$output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td>".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a>."</td>
                </tr>";
</code>```

with:

```<code>$output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td><a href='delete.php?id=".urlencode($row['id'])."' onclick='return confirm('Er du sikker?');'>Slett</a></td>
                </tr>";
</code>```

Title: How do i put a link in a table

Body:
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.

index.php:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">

    <button class="back" onclick="window.location='../'">

    </button>

    <button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">

    </button>

Brukere

            Søk
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">

          <?php
            include "../../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM brukere");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>

                #
                Fornavn
                Etternavn
                Utskjekket
                Admin
                Slett

              <?php while($row=$result->fetch_assoc()){ ?>

                  <?php echo $row["id"]; ?>
                  <?php echo $row["fornavn"]; ?>
                  <?php echo $row["etternavn"]; ?>
                  <?php echo $row["utskjekket"]; ?>
                  <?php echo $row["is_admin"]; ?>
                  <a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett

              <?php }
              $conn->close();
              ?>

action.php:

<?php

    include "../../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM brukere");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "

                    #
                    Fornavn
                    Etternavn
                    Utskjekket
                    Admin
                    Slett

";

        while($row=$result->fetch_assoc()){
            $output .= "

                    ".$row["id"]."
                    ".$row["fornavn"]."
                    ".$row["etternavn"]."
                    ".$row["utskjekket"]."
                    ".$row["is_admin"]."
                    ".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett."

";
        };
        $output .= "
";
        echo $output;
    } else {
        echo "
No match found!
";
    };

?>

This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.

Body:
The a tag is not added as a plain-text to the output string, you need to rewrite that line, concatenate strings parts to variables parts correctly.

Try replacing:

$output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td>".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a>."</td>
                </tr>";

with:

$output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td><a href='delete.php?id=".urlencode($row['id'])."' onclick='return confirm('Er du sikker?');'>Slett</a></td>
                </tr>";


问:
How Can I Convert of String To Integer Value in a List in Python?
This is my code which i did for my project and it takes values from csv file. I got a error from which the data u=in the csv file is taken as string instead of integer. How can i convert it to integer values or float values?

import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)

proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper[order_id] = country
print(proper)

def get_hash(key):
    hash = 0
    for i in range(key):
        hash += 1
    return hash % 100000
get_hash('8469376')
```

This is the error which I get
TypeError: 'str' object cannot be interpreted as an integer

答:
the int class take two parameters int(str, base=). And dont use hash as variable as
it is a function in python so have it as a rule, "never use functions as variables"

try:

```<code>def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100000
get_hash('8469376')
</code>```

Body:
This is my code which i did for my project and it takes values from csv file. I got a error from which the data u=in the csv file is taken as string instead of integer. How can i convert it to integer values or float values?

import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)

proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper[order_id] = country
print(proper)

def get_hash(key):
    hash = 0
    for i in range(key):
        hash += 1
    return hash % 100000
get_hash('8469376')

This is the error which I get
TypeError: 'str' object cannot be interpreted as an integer

Body:
the int class take two parameters int(str, base=). And dont use hash as variable as
it is a function in python so have it as a rule, "never use functions as variables"

try:

def get_hash(key):
    key = int(key, base=10)
    hash_key = 0
    for i in range(key):
        hash_key += 1
    return hash_key % 100000
get_hash('8469376')


问:
How to make repeading 3D ball on Y coordinate in processing?
I was making an animation on processing. Then, I confused about on a problem. I prepare a simple code for you. Also, I think the question can helpfull for the beginners.

PShape ball;
float ballSpeed = random(0.5, 1);
float ballSize = random(5, 10);
float x = 200, y = 300, z = 0;

void setup() {
  size(400, 400, P3D);
  noStroke();         // That's for "not see details on sphere"
  ball = createShape(SPHERE, ballSize);
}

void draw() {
  background(0);
  translate(x, y, z); // rotate the ball
  println(y);         // checking the y coordinates
  fill(255);
  shape(ball);
  y -= ballSpeed;     // the ball can go to top
}
```

So, I want to make a condition for if the ball reach the 100, the ball should return or start its first position and then again it should go to 100 again. I tried many if conditions but couldn’t figure out it.
If you help me I will be happy.
Thanks.

答:
Just invert ballSpeed, if the y coordinate of the ball is less or equal 100 respectively greater or equal 300:

y -= ballSpeed;
if (y <= 100 || y >= 300) {
    ballSpeed = -ballSpeed;
}
```

<p>Note the ball is moving upwards. When the ball reaches 100, <code>ballSpeed</code> is inverted, the ball changes direction and moves downwards. If the ball reaches is original position (300), <code>ballSpeed</code> is inverted again and the ball changes the direction again. </p>

<hr>

<p>If you want that the ball restarts at 300, when it reaches a <code>y</code> coordinate of 100, then it is sufficient to set <code>y = 300</code>:</p>

<pre class="lang-java prettyprint-override"><code>y -= ballSpeed;
if (y <= 100) {
    y = 300;
}
</code>```

Body:
I was making an animation on processing. Then, I confused about on a problem. I prepare a simple code for you. Also, I think the question can helpfull for the beginners.

PShape ball;
float ballSpeed = random(0.5, 1);
float ballSize = random(5, 10);
float x = 200, y = 300, z = 0;

void setup() {
  size(400, 400, P3D);
  noStroke();         // That's for "not see details on sphere"
  ball = createShape(SPHERE, ballSize);
}

void draw() {
  background(0);
  translate(x, y, z); // rotate the ball
  println(y);         // checking the y coordinates
  fill(255);
  shape(ball);
  y -= ballSpeed;     // the ball can go to top
}

So, I want to make a condition for if the ball reach the 100, the ball should return or start its first position and then again it should go to 100 again. I tried many if conditions but couldn’t figure out it.
If you help me I will be happy.
Thanks.

Body:
Just invert ballSpeed, if the y coordinate of the ball is less or equal 100 respectively greater or equal 300:

y -= ballSpeed;
if (y <= 100 || y >= 300) {
    ballSpeed = -ballSpeed;
}

Note the ball is moving upwards. When the ball reaches 100, ballSpeed is inverted, the ball changes direction and moves downwards. If the ball reaches is original position (300), ballSpeed is inverted again and the ball changes the direction again.

If you want that the ball restarts at 300, when it reaches a y coordinate of 100, then it is sufficient to set y = 300:

y -= ballSpeed;
if (y <= 100) {
    y = 300;
}


问:
Service Broker error handling simulation
I work now in project in which multiple POSes should be synchronized to main server by using Server Broker feature. Now i prepare error handling for this solution and want to show to client how it works. That means i will prepare test scripts for every kind of errors and client runs it on test POS to see if it errors processed correctly.

We will use SQL Server 2008R2 with poison message = OFF.

Message type=XML (but inside can be different type of data, some nodes will contain BLOBs).

POSes will be outside of domen so transport will be secured (but no dialog encryption).

I divide errors on several sub-groups:

Logical error (e.g. string instead
of number) .It will be processed by
TRY-CATCH block on server side.It is
easy to simulate

Service Broker configuration error
    (message or will be not returned or
    cannot reach destination). I think
    it can be handled by using SQl
    Server Service Broker events and
    simulation will be some kind of "bad
    configuration" (SB GUID,service name
    etc)

Transport error. This is when we
    have a broken message. In fact it is
    client opinion to test such kind of
    error. I do not know if we have
    secured transport level
    (certificate) we are protected from
    such kind of error. Another question
    how can I simulate this.

Questions:

are there another error types?

is #2 error handling logic described good enough?

how to handle and simulate #3?

答:
The second part of my article here goes into a discussion of Service Broker errors, how they occur and how to handle them. The important thing for you is to distinguish between two categories of errors:

recoverable: transport problems, most configuration errors like bad routing, an unreachable server. All these will result not in a SSB error, but in a delay. Messages will stay in transmission_queue expecting that the problem is transient and can be solved, including some configuration problems. Once the problem is solved, SSB will retry and the message gets delivered.

unrecoverable: these are problems SSB deems as non-recoverable, eg. a bad message format. In such a case the conversation will be aborted and both endpoints receive a Error message.

I also have an article Error Handling in Service Broker procedures that discusses some of the topics particular to exception handling in SSB activated context.

A final note: I strongly discourage you from turning poison message detection OFF. It is much better to disable the processing than to spin ad-nauseam w/o making progress because of a poison message.

As on the topic on how to simulate a corrupted message: is hard to simulate (you can try with setting up a port forwarder that lets all traffic pass by, but randomly corrupts some of it) but is rather pointless. All SSB traffic, even when in clear text, is cryptographically signed and any message corruption would result in an abrupt disconnect due to message signing validation failure.


答:
Drop the loop in your view function and try something like this below.  There is no need to loop through each object in the view - your query has retrieved everything, and it's available to your template when you pass it through as context.  Use the template language to access each object's attribute.

```<code>def products_view(request,*args, **kwargs):

    products = Product.objects.all()
    return render(request, "products.html", products)
</code>```

And in your HTML, do something like:

```<code>{% for product in products %}

  {{product.title}}
  {{product.description}}
  {{product.price}}
  {{product.summary}}
  {{product.image}}

{% endfor %}

</code>```

This HTML will render weird in my example, but you can see what's going on.

Title: How can I print all the products attributes in product.html

Body:
Drop the loop in your view function and try something like this below.  There is no need to loop through each object in the view - your query has retrieved everything, and it's available to your template when you pass it through as context.  Use the template language to access each object's attribute.

def products_view(request,*args, **kwargs):

    products = Product.objects.all()
    return render(request, "products.html", products)

And in your HTML, do something like:

{% for product in products %}

  {{product.title}}
  {{product.description}}
  {{product.price}}
  {{product.summary}}
  {{product.image}}

{% endfor %}

This HTML will render weird in my example, but you can see what's going on.


问:
fadeOut with jQuery .removeClass
Good day! I'm new here! For now, sorry for stupid :-)

Function: Header becomes visible when scrolling down. And hidden when you scroll to the top. Code works but I can't make soft fade-outs with removeClass.
Can someone help me?

```<code><script type="text/javascript">
jQuery( document ).ready(function() {

  var header_fixed = jQuery(".header-fixed")
  jQuery( header_fixed ).wrap( "<div class='header-f-wrapper'></div>" );
  var header_f_wrapper = jQuery (".header-f-wrapper");
  var height = jQuery(".et-l--header").height()+(20);

    jQuery(window).scroll(function(){
    if(jQuery(this).scrollTop()>height){
    header_f_wrapper.addClass("header-show");
    }
    else{
    header_f_wrapper.removeClass("header-show");
    }
  })
})
</script>
<style>
@keyframes fadein {
    from { opacity: 0; }
    to { opacity: 1; }
}
.header-f-wrapper {
display:none;
}
.header-f-wrapper {
z-index: 999; /* display at the top */
position: fixed;
width:100%;
top: 0;
-webkit-animation: fadein 0.9s ease-in;
-moz-animation: fadein 0.9s ease-in;
animation: fadein 0.9s ease-in;
}
.header-f-wrapper.header-show {
display:block;
}}

}}
</style>
</code>```

答:
why dont you use the jQuery fadeOut and fadeIn functions? :https://api.jquery.com/fadeOut/, this is the official documentation link, in your case, maybe this might work:

```<code>    if(jQuery(this).scrollTop()>height){
      header_f_wrapper.fadeIn('slow',function(){
      //do something here
     }else{
           header_f_wrapper.fadeOut('slow',function(){
      //do something else here
         });
        }
</code>```

I don't know if this will exactly work, as I don't know the exact cases, but I hope you get some help from this

Title: fadeOut with jQuery .removeClass

Body:
why dont you use the jQuery fadeOut and fadeIn functions? :https://api.jquery.com/fadeOut/, this is the official documentation link, in your case, maybe this might work:

    if(jQuery(this).scrollTop()>height){
      header_f_wrapper.fadeIn('slow',function(){
      //do something here
     }else{
           header_f_wrapper.fadeOut('slow',function(){
      //do something else here
         });
        }

I don't know if this will exactly work, as I don't know the exact cases, but I hope you get some help from this


问:
Variant with unique types
While writing a cpp library I ended up with possiblity that std::variants shall contain repeating types, that is for example, std::variant<int, double, int, std::string, int>. It may be useful in some occasions but in case of my library I find this unnecessary. And so I would like to filter type reptitions like this:

std::variant<int, double, int, std::string, int> -> std::variant<int, double, std::string>

std::variant<std::string, std::string, int> -> std::variant<std::string, int>

How can this be done?

答:
```<code>#include <type_traits>
#include <variant>

template <typename T, typename... Ts>
struct filter_duplicates { using type = T; };

template <template <typename...> class C, typename... Ts, typename U, typename... Us>
struct filter_duplicates<C<Ts...>, U, Us...>
    : std::conditional_t<(std::is_same_v<U, Ts> || ...)
                       , filter_duplicates<C<Ts...>, Us...>
                       , filter_duplicates<C<Ts..., U>, Us...>> {};

template <typename T>
struct unique_variant;

template <typename... Ts>
struct unique_variant<std::variant<Ts...>> : filter_duplicates<std::variant<>, Ts...> {};

template <typename T>
using unique_variant_t = typename unique_variant<T>::type;
</code>```

DEMO

Title: Variant with unique types

Body:
#include <type_traits>
#include <variant>

template <typename T, typename... Ts>
struct filter_duplicates { using type = T; };

template <template <typename...> class C, typename... Ts, typename U, typename... Us>
struct filter_duplicates<C<Ts...>, U, Us...>
    : std::conditional_t<(std::is_same_v<U, Ts> || ...)
                       , filter_duplicates<C<Ts...>, Us...>
                       , filter_duplicates<C<Ts..., U>, Us...>> {};

template <typename T>
struct unique_variant;

template <typename... Ts>
struct unique_variant<std::variant<Ts...>> : filter_duplicates<std::variant<>, Ts...> {};

template <typename T>
using unique_variant_t = typename unique_variant<T>::type;

DEMO


问:
In my project I have two table one is stream another is branch, stream_id on branch page?
stream_id is a foreign key in the branch table, I can click on the branch and directly go on add branch option. How can we get stream_id on the branch page for saving in the database with a foreign key?

答:
You can pass stream_id from View to Controller in a hidden field:

```<code>@Html.HiddenFor(model => model.stream_id)
</code>```

And in Controller, use the stream_id to get Stream and create associated Branch and then the foreign key will be automatically inserted.

```<code>using (var dataContext = new DBContextModel())
{
   var stream = dataContext.YourStreamDBSet.SingleOrDefault(s => s.Id == stream_id);
   stream.BranchList.Add(YourNewBranch);
   dataContext.SaveChanges();
}
</code>```

This is assuming you are using EF.

Body:
You can pass stream_id from View to Controller in a hidden field:

@Html.HiddenFor(model => model.stream_id)

And in Controller, use the stream_id to get Stream and create associated Branch and then the foreign key will be automatically inserted.

using (var dataContext = new DBContextModel())
{
   var stream = dataContext.YourStreamDBSet.SingleOrDefault(s => s.Id == stream_id);
   stream.BranchList.Add(YourNewBranch);
   dataContext.SaveChanges();
}

This is assuming you are using EF.


问:
Why does Jenkins always access the AD server mail group during the build job?
I use Jenkins ldaps configured by my OA account, and all functions are well. But my MIS colleague told me that during my colleague build the job, my OA account always accessed the LDAPs server mail group.
Can someone give me some advice? Thanks</p>

答:
I can only guess, that Jenkins is trying get infos for the user triggering the build. Commonly this is used to send a mail to the user, who broke the build.

You can turn off this behavior under Jenkins -> Configure Jenkins -> Global Security -> LDAP -> "Disable Ldap Email Resolver". You can also try to enable the cache on the same page, which will reduce the queries made to your Active Directory/LDAP.


问:
How Can I save a blob file with a form submission using React.js + Django Rest Framework
I am trying to submit a cropped an image generated in a react app using react-image-crop,and save it to a Django Rest Api using Axios.

The app uses React, Redux and Axios on the frontend and Django Rest Framework on the backend.

The form was submitting fine without the file and saving in django without the code for the file added.

Now that the file is added to the form submission the server returns a 400 error.

I suspect that I am not submitting the blob in the correct format to the django server, but I am unsure on how to proceed.

Update: I have used axios below to convert the blob url to a blob and now I am trying to a file that I can submit to a django rest api.  The form submits to the django rest API without the file, but when the file is add into the form submission, I receive a 400 error.  I have Updated the code to reflect my latest integrations. I have included the code where I set the headers to multipart/form-data.  The error seems to be in the file conversion process in the onSubmit() method below.

Here is my relevant code:
Importing the react-image-crop library.

```<code>// Cropper
import 'react-image-crop/dist/ReactCrop.css';
import ReactCrop from 'react-image-crop';
</code>```

Function inside of a react hook:

```<code>const AdCreator = ({ addFBFeedAd }) => {
  const [title, setTitle] = useState('');
  const [headline, setHeadline] = useState('');
  const [ad_text, setAdText] = useState('');
  const cropper = useRef();

  // Cropper
  const [upImg, setUpImg] = useState();
  const imgRef = useRef(null);
  const [crop, setCrop] = useState({ unit: '%', width: 30, aspect: 1.91 / 1 });
  const [previewUrl, setPreviewUrl] = useState();

  const onSelectFile = e => {
    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.addEventListener('load', () => setUpImg(reader.result));
      reader.readAsDataURL(e.target.files[0]);
    }
  };

  const onLoad = useCallback(img => {
    imgRef.current = img;
  }, []);

  const makeClientCrop = async crop => {
    if (imgRef.current && crop.width && crop.height) {
      createCropPreview(imgRef.current, crop, 'newFile.jpeg');
    }
  };
  const makePostCrop = async crop => {
    if (imgRef.current && crop.width && crop.height) {
      createCropPreview(imgRef.current, crop, 'newFile.jpeg');
    }
  };

  const createCropPreview = async (image, crop, fileName) => {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

    ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (!blob) {
          reject(new Error('Canvas is empty'));
          return;
        }
        blob.name = fileName;
        window.URL.revokeObjectURL(previewUrl);
        setPreviewUrl(window.URL.createObjectURL(blob));
      }, 'image/jpeg');
    });
 };

  const onSubmit = (e) => {
    e.preventDefault();
    const config = { responseType: 'blob' };
    let file = axios.get(previewUrl, config).then(response => {
        new File([response.data], title, {type:"image/jpg", lastModified:new Date()});
    });
    let formData = new FormData();
    formData.append('title', title);
    formData.append('headline', headline);
    formData.append('ad_text', ad_text);
    formData.append('file', file);
    addFBFeedAd(formData);

  };
  return (
</code>```

The Form portion:

```<code><form method="post" id='uploadForm'>
          <div className="input-field">
            <label for="id_file">Upload Your Image</label>
            <br/>
            {/* {{form.file}} */}
          </div>
          <div>
            <div>
              <input type="file" accept="image/*" onChange={onSelectFile} />
            </div>
            <ReactCrop
              src={upImg}
              onImageLoaded={onLoad}
              crop={crop}
              onChange={c => setCrop(c)}
              onComplete={makeClientCrop}
              ref={cropper}
            />
            {previewUrl && <img alt="Crop preview" src={previewUrl} />}
          </div>

            <button className="btn darken-2 white-text btn-large teal btn-extend" id='savePhoto' onClick={onSubmit} value="Save Ad">Save Ad</button>

        </form>
</code>```

Here is the Axios Call:

```<code> export const addFBFeedAd = (fbFeedAd) => (dispatch, getState) => {
  setLoading();
  axios
    .post(`http://localhost:8000/api/fb-feed-ads/`, fbFeedAd, tokenMultiPartConfig(getState))
    .then((res) => {
      dispatch(createMessage({ addFBFeedAd: 'Ad Added' }));
      dispatch({
        type: SAVE_AD,
        payload: res,
      });
    })
    .catch((err) => dispatch(returnErrors(err)));
}
</code>```

Here Is where I set the headers to multipart form data

```<code>export const tokenMultiPartConfig = (getState) => {
 // Get token from state
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      "Content-type": "multipart/form-data",
    },
  };

  // If token, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`;
  }

  return config;
};
</code>```

The Model:

```<code>class FB_Feed_Ad(models.Model):
    title = models.CharField(max_length=100, blank=True)
    headline = models.CharField(max_length=25, blank=True)
    ad_text = models.CharField(max_length=125, blank=True)
    file = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
</code>```

The crop preview blob:

```<code>blob:http://localhost:3000/27bb58e5-4d90-481d-86ab-7baa717cc023
</code>```

I console.log-ed the Cropped Image after the axios call.

```<code>File:
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined
AdCreator.js:169 formData:
FormData {}
__proto__: FormData
</code>```

As you can see I am trying to submit the blob image file generated by the react-image-cropper, as part of the form data when the form is submitted.  I want to save the cropped image to the Django Rest API.

Any suggestions?

答:
you should send it as "Content-Type": "multipart/form-data" to django imageField. So you should convert your blob file appropriately:</p>

```<code>let cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
let arr = this.cropImg.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);

while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
}

let imageCrop = new File([u8arr], 'imagename', { type: mime });

const fd = new FormData();
fd.append("avatar", imageCrop);

// send fd to axios post method.
// You should pass in post request "Content-Type": "multipart/form-data" inside headers.
</code>```

Body:
I am trying to submit a cropped an image generated in a react app using react-image-crop,and save it to a Django Rest Api using Axios.

The app uses React, Redux and Axios on the frontend and Django Rest Framework on the backend.

The form was submitting fine without the file and saving in django without the code for the file added.

Now that the file is added to the form submission the server returns a 400 error.

I suspect that I am not submitting the blob in the correct format to the django server, but I am unsure on how to proceed.

Update: I have used axios below to convert the blob url to a blob and now I am trying to a file that I can submit to a django rest api.  The form submits to the django rest API without the file, but when the file is add into the form submission, I receive a 400 error.  I have Updated the code to reflect my latest integrations. I have included the code where I set the headers to multipart/form-data.  The error seems to be in the file conversion process in the onSubmit() method below.

Here is my relevant code:
Importing the react-image-crop library.

// Cropper
import 'react-image-crop/dist/ReactCrop.css';
import ReactCrop from 'react-image-crop';

Function inside of a react hook:

const AdCreator = ({ addFBFeedAd }) => {
  const [title, setTitle] = useState('');
  const [headline, setHeadline] = useState('');
  const [ad_text, setAdText] = useState('');
  const cropper = useRef();

  // Cropper
  const [upImg, setUpImg] = useState();
  const imgRef = useRef(null);
  const [crop, setCrop] = useState({ unit: '%', width: 30, aspect: 1.91 / 1 });
  const [previewUrl, setPreviewUrl] = useState();

  const onSelectFile = e => {
    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.addEventListener('load', () => setUpImg(reader.result));
      reader.readAsDataURL(e.target.files[0]);
    }
  };

  const onLoad = useCallback(img => {
    imgRef.current = img;
  }, []);

  const makeClientCrop = async crop => {
    if (imgRef.current && crop.width && crop.height) {
      createCropPreview(imgRef.current, crop, 'newFile.jpeg');
    }
  };
  const makePostCrop = async crop => {
    if (imgRef.current && crop.width && crop.height) {
      createCropPreview(imgRef.current, crop, 'newFile.jpeg');
    }
  };

  const createCropPreview = async (image, crop, fileName) => {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

    ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (!blob) {
          reject(new Error('Canvas is empty'));
          return;
        }
        blob.name = fileName;
        window.URL.revokeObjectURL(previewUrl);
        setPreviewUrl(window.URL.createObjectURL(blob));
      }, 'image/jpeg');
    });
 };

  const onSubmit = (e) => {
    e.preventDefault();
    const config = { responseType: 'blob' };
    let file = axios.get(previewUrl, config).then(response => {
        new File([response.data], title, {type:"image/jpg", lastModified:new Date()});
    });
    let formData = new FormData();
    formData.append('title', title);
    formData.append('headline', headline);
    formData.append('ad_text', ad_text);
    formData.append('file', file);
    addFBFeedAd(formData);

  };
  return (

The Form portion:

<form method="post" id='uploadForm'>

            Upload Your Image

            {/* {{form.file}} */}

              <input type="file" accept="image/*" onChange={onSelectFile} />

            <ReactCrop
              src={upImg}
              onImageLoaded={onLoad}
              crop={crop}
              onChange={c => setCrop(c)}
              onComplete={makeClientCrop}
              ref={cropper}
            />
            {previewUrl && }

            <button className="btn darken-2 white-text btn-large teal btn-extend" id='savePhoto' onClick={onSubmit} value="Save Ad">Save Ad</button>

        </form>

Here is the Axios Call:

 export const addFBFeedAd = (fbFeedAd) => (dispatch, getState) => {
  setLoading();
  axios
    .post(`http://localhost:8000/api/fb-feed-ads/`, fbFeedAd, tokenMultiPartConfig(getState))
    .then((res) => {
      dispatch(createMessage({ addFBFeedAd: 'Ad Added' }));
      dispatch({
        type: SAVE_AD,
        payload: res,
      });
    })
    .catch((err) => dispatch(returnErrors(err)));
}

Here Is where I set the headers to multipart form data

export const tokenMultiPartConfig = (getState) => {
 // Get token from state
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      "Content-type": "multipart/form-data",
    },
  };

  // If token, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`;
  }

  return config;
};

The Model:

class FB_Feed_Ad(models.Model):
    title = models.CharField(max_length=100, blank=True)
    headline = models.CharField(max_length=25, blank=True)
    ad_text = models.CharField(max_length=125, blank=True)
    file = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)

The crop preview blob:

blob:http://localhost:3000/27bb58e5-4d90-481d-86ab-7baa717cc023

I console.log-ed the Cropped Image after the axios call.

File:
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined
AdCreator.js:169 formData:
FormData {}
__proto__: FormData

As you can see I am trying to submit the blob image file generated by the react-image-cropper, as part of the form data when the form is submitted.  I want to save the cropped image to the Django Rest API.

Any suggestions?

Body:
you should send it as "Content-Type": "multipart/form-data" to django imageField. So you should convert your blob file appropriately:

let cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
let arr = this.cropImg.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);

while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
}

let imageCrop = new File([u8arr], 'imagename', { type: mime });

const fd = new FormData();
fd.append("avatar", imageCrop);

// send fd to axios post method.
// You should pass in post request "Content-Type": "multipart/form-data" inside headers.


问:
JavaScript - Force select element to dropdown?
How can I force the select element to dropdown using Javascript? Is it possible?

```<code><select id="MiamiPlayers">
    <option value="0">Bosh</option>
    <option value="1">Wade</option>
    <option value="2">LeBron</option>
</select>

<input type="button" onclick="Show()" />

<script type="text/javascript">
    function Show()
    {
        //force the select to dropdown...
    }
</script>
</code>```

Thanks in advance!

答: See Display DropDown options on Focus</p>

Body:
How can I force the select element to dropdown using Javascript? Is it possible?

<select id="MiamiPlayers">
    <option value="0">Bosh</option>
    <option value="1">Wade</option>
    <option value="2">LeBron</option>
</select>

<input type="button" onclick="Show()" />

Thanks in advance!

Body: See Display DropDown options on Focus


问:
What is "lpConsoleScreenBufferInfo" on function GetConsoleScreenBufferInfo()?
I've just wanted to get the window Width and the window Height using the returned struct of the function GetConsoleScreenBufferInfo(); from header ConsoleApi2.h. I referenced this question. But then I discovered that this function needs a type _Out_ PCONSOLE_SCREEN_BUFFER_INFO parameter called lpConsoleScreenBufferInfo. Which values do I need to pass as that parameter?

Here is the function head:

```<code>WINBASEAPI
BOOL
WINAPI
GetConsoleScreenBufferInfo(
    _In_ HANDLE hConsoleOutput,
    _Out_ PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
    );
</code>```

Or if there is any other way to get the window Width and Height?

THANKS.

答:
You need to give the function a pointer to a CONSOLE_SCREEN_BUFFER_INFO variable for it to fill in, eg:

```<code>HANDLE hConsole = ...;
CONSOLE_SCREEN_BUFFER_INFO info = {};
if (GetConsoleScreenBufferInfo(hConsole, &info)) {
    // use info as needed...
}
</code>```

Body:
I've just wanted to get the window Width and the window Height using the returned struct of the function GetConsoleScreenBufferInfo(); from header ConsoleApi2.h. I referenced this question. But then I discovered that this function needs a type _Out_ PCONSOLE_SCREEN_BUFFER_INFO parameter called lpConsoleScreenBufferInfo. Which values do I need to pass as that parameter?

Here is the function head:

WINBASEAPI
BOOL
WINAPI
GetConsoleScreenBufferInfo(
    _In_ HANDLE hConsoleOutput,
    _Out_ PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
    );

Or if there is any other way to get the window Width and Height?

THANKS.

Body:
You need to give the function a pointer to a CONSOLE_SCREEN_BUFFER_INFO variable for it to fill in, eg:

HANDLE hConsole = ...;
CONSOLE_SCREEN_BUFFER_INFO info = {};
if (GetConsoleScreenBufferInfo(hConsole, &info)) {
    // use info as needed...
}