问:
TypeError: can only concatenate str (not "int") to str: What does it mean?
```<code>from tkinter import*
import random
from tkinter import messagebox
window=Tk()
window.title("Random Tools")
window.configure(background="light green")
textvaria = IntVar()
textvaria2 = IntVar()

label0 = Label(window, text = "Min", bg ="light green")
label0.grid(row=1, column=0)

spinboxmin = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria)
spinboxmin.grid(row=2, column=0)
a = spinboxmin.get()

label1 = Label(window, text="Max", bg="light green")
label1.grid(row=3, column=0)

spinboxmax = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria2)
spinboxmax.grid(row = 4, column =0)
b = spinboxmax.get()

def submit2():
    if a <= b:
        answertext.delete('1.0', END)
    else:
        messagebox.showerror("Error", "Max must be greater than min!")

submit = Button(text="Submit", command=submit2)
submit.grid(row=4, column=2)

n = random.randint(a, b+1)

answertext = Text(text=n)
answertext.grid(row=5, column=0)

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

I'm doing a GUI for randoming numbers. But when I run this in Python Module, it said:
"TypeError: can only concatenate str (not "int") to str"
Can someone help me with this?
Thank a lot.

答:
The documentation on spinbox states that get() method returns the current contents of the spinbox as a string. You can't add a number to a string like you are trying to do on here

```<code>n = random.randint(a, b+1)
</code>```

So you must convert b to int then add to it.

```<code>n = random.randint(a, int(b)+1)
</code>```

Body:
from tkinter import*
import random
from tkinter import messagebox
window=Tk()
window.title("Random Tools")
window.configure(background="light green")
textvaria = IntVar()
textvaria2 = IntVar()

label0 = Label(window, text = "Min", bg ="light green")
label0.grid(row=1, column=0)

spinboxmin = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria)
spinboxmin.grid(row=2, column=0)
a = spinboxmin.get()

label1 = Label(window, text="Max", bg="light green")
label1.grid(row=3, column=0)

spinboxmax = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria2)
spinboxmax.grid(row = 4, column =0)
b = spinboxmax.get()

def submit2():
    if a <= b:
        answertext.delete('1.0', END)
    else:
        messagebox.showerror("Error", "Max must be greater than min!")

submit = Button(text="Submit", command=submit2)
submit.grid(row=4, column=2)

n = random.randint(a, b+1)

answertext = Text(text=n)
answertext.grid(row=5, column=0)

window.mainloop()

I'm doing a GUI for randoming numbers. But when I run this in Python Module, it said:
"TypeError: can only concatenate str (not "int") to str"
Can someone help me with this?
Thank a lot.

Body:
The documentation on spinbox states that get() method returns the current contents of the spinbox as a string. You can't add a number to a string like you are trying to do on here

n = random.randint(a, b+1)

So you must convert b to int then add to it.

n = random.randint(a, int(b)+1)


来源: stackexchange

问:
Onclick event on list item
I'm trying to follow this answer, but rather than using a button as he does in his jsfiddle, I'm trying to use list items:

http://jsfiddle.net/hqvDT/108/

It looks like it should work, but when I try to select some text and then press B (for bold), it doesn't actually bold the text.

What's wrong?

HTML:

```<code><div id="myarea" contenteditable="true"></div>

<ul>
    <li onclick="MakeBold();">B</li>
    <li><i>I</i></li>
</ul>
</code>```

CSS:

```<code>#myarea {
   border:1px solid #000;
   padding:5px;
   height:150px;
   width:400px;
   overflow:scroll;
}

ul {
    list-style: none;
}

ul li {
    width: 35px;
    height: 35px;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 32px;
    font-size: 14px;
    color: #999;
    cursor: pointer;
    display: inline-block;
    margin-right: -5px;
    font-weight: bold;
    font-size: 18px;
}

ul li:hover {
    color: black;
}
</code>```

JS:

```<code>function MakeBold() {
    document.execCommand('bold', null, false);
}
</code>```

答:
With mousedown and preventDefault.

HTML:

```<code><div id="myarea" contenteditable="true">Mark a word of this paragraph and bold or italiced it</div>
    <ul>
        <li id="bolded">B</li>
        <li id="italiced"><i>I</i></li>
    </ul>
</code>```

JS:

```<code>document.getElementById("bolded").addEventListener("mousedown", function(event){
  event.preventDefault()
  document.execCommand('bold', false, null)
})

document.getElementById("italiced").addEventListener("mousedown", function(event){
  event.preventDefault()
  document.execCommand('italic', false, null)
})
</code>```

codepen: https://codepen.io/harivera/pen/wvodZOR

ContentLicense: CC BY-SA 3.0

Title: Onclick event on list item

Body:
I'm trying to follow this answer, but rather than using a button as he does in his jsfiddle, I'm trying to use list items:

http://jsfiddle.net/hqvDT/108/

It looks like it should work, but when I try to select some text and then press B (for bold), it doesn't actually bold the text.

What's wrong?

HTML:

B

I

CSS:

#myarea {
   border:1px solid #000;
   padding:5px;
   height:150px;
   width:400px;
   overflow:scroll;
}

ul {
    list-style: none;
}

ul li {
    width: 35px;
    height: 35px;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 32px;
    font-size: 14px;
    color: #999;
    cursor: pointer;
    display: inline-block;
    margin-right: -5px;
    font-weight: bold;
    font-size: 18px;
}

ul li:hover {
    color: black;
}

JS:

function MakeBold() {
    document.execCommand('bold', null, false);
}

Body:
With mousedown and preventDefault.

HTML:

<div id="myarea" contenteditable="true">Mark a word of this paragraph and bold or italiced it</div>
    <ul>
        <li id="bolded">B</li>
        <li id="italiced"><i>I</i></li>
    </ul>

JS:

document.getElementById("bolded").addEventListener("mousedown", function(event){
  event.preventDefault()
  document.execCommand('bold', false, null)
})

document.getElementById("italiced").addEventListener("mousedown", function(event){
  event.preventDefault()
  document.execCommand('italic', false, null)
})

codepen: https://codepen.io/harivera/pen/wvodZOR

ContentLicense: CC BY-SA 4.0


问:
python code number_list = [1, 239, 949, 0, 84, 0, 1] output: True number_list = [1, 239, 949, 0, 84, 0, 13] output: False
This function should return true if the value at the beginning and the end of the list are equal. False otherwise.

Example:

number_list = [1, 239, 949, 0, 84, 0, 1]
```

<p>output:</p>

<pre class="lang-py prettyprint-override"><code>True
</code>```

number_list = [1, 239, 949, 0, 84, 0, 13]
```

<p>output:</p>

<pre class="lang-py prettyprint-override"><code>False
</code>```

答:
Here's how you can do it using higher order function.It's clean to do like this sometimes whenever you are passing this function as a comparison function in a sort like function.

Note: In-line lambda statements are mostly slow.

li = [1, 239, 949, 0, 84, 0, 1]
c = lambda x : x[-1]==x[0] #this took 188ns to execute
print(c(li))
```

<p>However, @ritika's and @TranGiaBao's answers are more perform-ant.</p>

<pre class="lang-py prettyprint-override"><code>def check(l):
    return l[0] == l[-1]

check(l)  #this took 121ns to execute

</code>```

Body:
This function should return true if the value at the beginning and the end of the list are equal. False otherwise.

Example:

number_list = [1, 239, 949, 0, 84, 0, 1]

output:

True

number_list = [1, 239, 949, 0, 84, 0, 13]

output:

False

Body:
Here's how you can do it using higher order function.It's clean to do like this sometimes whenever you are passing this function as a comparison function in a sort like function.

Note: In-line lambda statements are mostly slow.

li = [1, 239, 949, 0, 84, 0, 1]
c = lambda x : x[-1]==x[0] #this took 188ns to execute
print(c(li))

However, @ritika's and @TranGiaBao's answers are more perform-ant.

def check(l):
    return l[0] == l[-1]

check(l)  #this took 121ns to execute


问:
create 3d surface graph without all the points
I have some (X, Y, Z) data points, for which I want to make a surface plot. X,Y,Z are integers. X ranges from 1 to 6, Y ranges from 1 to 6. I have Z data for all the (X,Y) points except (5,6) and (6,6). so I have to set Z = 0 for those two points. Is there a way that I don't plot the graph only for those two points, but plot the graph for all other points? Here is the code:

```<code>import matplotlib.pyplot as plt
import numpy as np

v = [
    (1,1,1),
    (1,2,1),
    (1,3,1),
    (1,4,1),
    (1,5,1),
    (1,6,1),
    (2,1,2),
    (2,2,3),
    (2,3,4),
    (2,4,4),
    (2,5,5),
    (2,6,6),
    (3,1,3),
    (3,2,4),
    (3,3,4),
    (3,4,4),
    (3,5,4),
    (3,6,5),
    (4,1,4),
    (4,2,4),
    (4,3,4),
    (4,4,4),
    (4,5,5),
    (4,6,6),
    (5,1,5),
    (5,2,5),
    (5,3,5),
    (5,4,5),
    (5,5,6),
    (6,1,6),
    (6,2,5),
    (6,3,5),
    (6,4,5),
    (6,5,6),
]

def f(x, y):
    for xt,yt,z in v:
        if xt == x and yt == y:
            return z
    return 0

x = np.arange(1, 7, 1)
y = np.arange(1, 7, 1)

# X, Y = np.meshgrid(x, y)
# print(X)
# print(Y)

X = [
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6]
]
X = np.array(X)

Y = [
    [1, 1, 1, 1, 1, 1],
    [2, 2, 2, 2, 2, 2],
    [3, 3, 3, 3, 3, 3],
    [4, 4, 4, 4, 4, 4],
    [5, 5, 5, 5, 5, 5],
    [6, 6, 6, 6, 6, 6]
]
Y = np.array(Y)

Z = []
for yi in y:
    Z.append([])
    for xi in x:
        Z[yi-1].append(f(xi, yi))
Z = np.array(Z)

# print(Z)

ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_title('surface')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
</code>```

Here is the plot I got:

I want to remove the 0's I have to put for points (5,6) and (6,6)

答:
Unfortunately the plot_surface method in matplotlib ignores masks (see this open issue), so you will need to use np.nan in place of the 0's for these particular Z values to not show up. This doesn't work perfectly, and may result in rendering artifacts like the colormap not working properly — but you can see that the surface plot displays except at the points (X,Y) = (5,6), (6,6).

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

v = [
    (1,1,1),
    (1,2,1),
    (1,3,1),
    (1,4,1),
    (1,5,1),
    (1,6,1),
    (2,1,2),
    (2,2,3),
    (2,3,4),
    (2,4,4),
    (2,5,5),
    (2,6,6),
    (3,1,3),
    (3,2,4),
    (3,3,4),
    (3,4,4),
    (3,5,4),
    (3,6,5),
    (4,1,4),
    (4,2,4),
    (4,3,4),
    (4,4,4),
    (4,5,5),
    (4,6,6),
    (5,1,5),
    (5,2,5),
    (5,3,5),
    (5,4,5),
    (5,5,6),
    (6,1,6),
    (6,2,5),
    (6,3,5),
    (6,4,5),
    (6,5,6),
]

def f(x, y):
    for xt,yt,z in v:
        if xt == x and yt == y:
            return z
    return np.nan

x = np.arange(1, 7, 1)
y = np.arange(1, 7, 1)

# X, Y = np.meshgrid(x, y)
# print(X)
# print(Y)

X = [
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6]
]
X = np.array(X)

Y = [
    [1, 1, 1, 1, 1, 1],
    [2, 2, 2, 2, 2, 2],
    [3, 3, 3, 3, 3, 3],
    [4, 4, 4, 4, 4, 4],
    [5, 5, 5, 5, 5, 5],
    [6, 6, 6, 6, 6, 6]
]
Y = np.array(Y)

Z = []
for yi in y:
    Z.append([])
    for xi in x:
        Z[yi-1].append(f(xi, yi))
# Z = np.array(Z)
# prepare the masked array
Z = np.ma.array(Z)
Z_masked = np.ma.masked_where(Z == np.nan, Z)
# print(Z)

ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z_masked, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_title('surface')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
</code>```

Body:
I have some (X, Y, Z) data points, for which I want to make a surface plot. X,Y,Z are integers. X ranges from 1 to 6, Y ranges from 1 to 6. I have Z data for all the (X,Y) points except (5,6) and (6,6). so I have to set Z = 0 for those two points. Is there a way that I don't plot the graph only for those two points, but plot the graph for all other points? Here is the code:

import matplotlib.pyplot as plt
import numpy as np

v = [
    (1,1,1),
    (1,2,1),
    (1,3,1),
    (1,4,1),
    (1,5,1),
    (1,6,1),
    (2,1,2),
    (2,2,3),
    (2,3,4),
    (2,4,4),
    (2,5,5),
    (2,6,6),
    (3,1,3),
    (3,2,4),
    (3,3,4),
    (3,4,4),
    (3,5,4),
    (3,6,5),
    (4,1,4),
    (4,2,4),
    (4,3,4),
    (4,4,4),
    (4,5,5),
    (4,6,6),
    (5,1,5),
    (5,2,5),
    (5,3,5),
    (5,4,5),
    (5,5,6),
    (6,1,6),
    (6,2,5),
    (6,3,5),
    (6,4,5),
    (6,5,6),
]

def f(x, y):
    for xt,yt,z in v:
        if xt == x and yt == y:
            return z
    return 0

x = np.arange(1, 7, 1)
y = np.arange(1, 7, 1)

# X, Y = np.meshgrid(x, y)
# print(X)
# print(Y)

X = [
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6]
]
X = np.array(X)

Y = [
    [1, 1, 1, 1, 1, 1],
    [2, 2, 2, 2, 2, 2],
    [3, 3, 3, 3, 3, 3],
    [4, 4, 4, 4, 4, 4],
    [5, 5, 5, 5, 5, 5],
    [6, 6, 6, 6, 6, 6]
]
Y = np.array(Y)

Z = []
for yi in y:
    Z.append([])
    for xi in x:
        Z[yi-1].append(f(xi, yi))
Z = np.array(Z)

# print(Z)

ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_title('surface')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

Here is the plot I got:

I want to remove the 0's I have to put for points (5,6) and (6,6)

Body:
Unfortunately the plot_surface method in matplotlib ignores masks (see this open issue), so you will need to use np.nan in place of the 0's for these particular Z values to not show up. This doesn't work perfectly, and may result in rendering artifacts like the colormap not working properly — but you can see that the surface plot displays except at the points (X,Y) = (5,6), (6,6).

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

v = [
    (1,1,1),
    (1,2,1),
    (1,3,1),
    (1,4,1),
    (1,5,1),
    (1,6,1),
    (2,1,2),
    (2,2,3),
    (2,3,4),
    (2,4,4),
    (2,5,5),
    (2,6,6),
    (3,1,3),
    (3,2,4),
    (3,3,4),
    (3,4,4),
    (3,5,4),
    (3,6,5),
    (4,1,4),
    (4,2,4),
    (4,3,4),
    (4,4,4),
    (4,5,5),
    (4,6,6),
    (5,1,5),
    (5,2,5),
    (5,3,5),
    (5,4,5),
    (5,5,6),
    (6,1,6),
    (6,2,5),
    (6,3,5),
    (6,4,5),
    (6,5,6),
]

def f(x, y):
    for xt,yt,z in v:
        if xt == x and yt == y:
            return z
    return np.nan

x = np.arange(1, 7, 1)
y = np.arange(1, 7, 1)

# X, Y = np.meshgrid(x, y)
# print(X)
# print(Y)

X = [
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6]
]
X = np.array(X)

Y = [
    [1, 1, 1, 1, 1, 1],
    [2, 2, 2, 2, 2, 2],
    [3, 3, 3, 3, 3, 3],
    [4, 4, 4, 4, 4, 4],
    [5, 5, 5, 5, 5, 5],
    [6, 6, 6, 6, 6, 6]
]
Y = np.array(Y)

Z = []
for yi in y:
    Z.append([])
    for xi in x:
        Z[yi-1].append(f(xi, yi))
# Z = np.array(Z)
# prepare the masked array
Z = np.ma.array(Z)
Z_masked = np.ma.masked_where(Z == np.nan, Z)
# print(Z)

ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z_masked, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
ax.set_title('surface')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()


问:
heroku: set SSL certificates on Free Plan?
I would like to set some SSL certificates for one app I have on heroku (a simple application based on nodeJS + Vue).

I know if I upgrade to the Hobby Plan (7$ for month) I can have it automatically.

But for now it would too much money for a test application, so I am wondering if I can achieve some similar goal also with a Free Plan.

so:
Is it possible to set SSL certificate for an app on Heroku JUST with the Free Plan?
Maybe in a complicated/tricky way via CLI?

From the Heroku pages and documentation it looks not possible.
But I have to ask :)

答:
Here's how you get FULL SSL using Cloudflare for FREE.

Step 1: Point Your domain to CloudFlare. You basically open an account an enter your domain when prompted. You may be given instructions to change your domain name servers.

Step 2: Add Cname Record of Heroku Server in DNS of Cloudflare. Instructions are here. Here You will get Some SSL Security Issue.

Step 3: Now Change Your SSL/TLS encryption mode to Full

Step 4: In your DNS settings, you’ll want to create a CNAME: yourdomain.com -> yourapp.herokuapp.com.

(I learned about the general approach here https://mikecoutermarsh.com/adding-ssl-to-heroku-with-cloudflare/ Although it's old, it still works.


问:
How do I store data into localStorage after a fetch call to an API?
I am new to using React and JSX and was having a problem storing data from my API call into local storage. I call fetch asynchronously and my call returns a JSON of a user object (this is for a user-based web app). When I store that JSON item into local storage (after converting it to a string) and I try to access that item later, localStorage.getItem returns null and I am unable to retrieve the data. Any help or insight as to what I am doing incorrectly will be greatly appreciated.

Login.js

```<code>import React, { Component, useState } from "react";
import {Button, Form, FormGroup, Label, Input} from 'reactstrap';
import {useHistory} from 'react-router-dom';
export const Login = () => {
    const [email_or_username, setName] = useState('');
    const [password, setPassword] = useState('');
    const [is_contributor, setContributor] = useState(false);
    const history = useHistory();
    return (
        <div>
            <Form className="login-form">
                <h1>
                <div className="text-right">
                    <Button
                        href="/register"
                        className=" btn-dark text-right">
                        sign up
                    </Button>
                </div>
                <span className="font-weight-bold">Mindify</span>
                </h1>
                <FormGroup>
                    <Label>Username or Email</Label>
                    <h2></h2>
                    <Input
                        value={email_or_username}
                        placeholder = "Username or Email"
                        onChange={e => setName(e.target.value)}/>
                </FormGroup>

                <FormGroup>
                    <label>Password</label>
                    <h2></h2>
                    <Input
                        value={password}
                        placeholder = "Password"
                        onChange={e => setPassword(e.target.value)}/>
                </FormGroup>

                <FormGroup>
                    <div className="text-center">
                    <Input
                        type="checkbox"
                        value={is_contributor}
                        onChange={e => setContributor(e.target.checked)}/>
                        Contributor
                    </div>
                </FormGroup>

                <Button onClick={async () =>{
                     const login = {email_or_username, password, is_contributor};
                     const response = await fetch('http://127.0.0.1:5000/api/login', {
                         method: 'POST',
                         headers:{
                            'Content-Type': 'application/json'
                         },
                         body: JSON.stringify(login)
                     })
                     .then(response => {
                         if (response.status === 201) {

                            response.json().then(data => { // store user in localStorage as token
                                window.localStorage.setItem("user", JSON.stringify(data.user));
                                console.log(JSON.parse(window.localStorage.getItem("user"))); // prints correctly here
                            })
                            console.log("Successful Login");
                            console.log(JSON.parse(window.localStorage.getItem("user"))); // prints null here

                            const ref="/homepage";
                            history.push(ref);
                            //redirect to home page
                         }
                         else if (response.status === 204) {
                            console.log("Invalid Username or Password or Incorrect Permissions");
                            const ref="/";
                            history.push(ref);
                            // reload login page
                         }
                     })
                     .catch(error => console.log(error))

                    }}
                    className="btn-lg btn-dark btn-block">
                    Log in</Button>
            </Form>
        </div>);
}
</code>```

答:
That is because response.json() is asynchronous, thus you will need the wait for response.json() to be returned before you can carry out any subsequent logic. If any subsequent logic is dependent on response.json(), you should  modify your statement such that the required logic is handed only after it is returned.

```<code>response.json().then(data => {
  window.localStorage.setItem("user", JSON.stringify(data.user));
  console.log(JSON.parse(window.localStorage.getItem("user")));
  const ref="/homepage";
  history.push(ref);
  // carry out other logic below
})
</code>```

Body:
I am new to using React and JSX and was having a problem storing data from my API call into local storage. I call fetch asynchronously and my call returns a JSON of a user object (this is for a user-based web app). When I store that JSON item into local storage (after converting it to a string) and I try to access that item later, localStorage.getItem returns null and I am unable to retrieve the data. Any help or insight as to what I am doing incorrectly will be greatly appreciated.

Login.js

import React, { Component, useState } from "react";
import {Button, Form, FormGroup, Label, Input} from 'reactstrap';
import {useHistory} from 'react-router-dom';
export const Login = () => {
    const [email_or_username, setName] = useState('');
    const [password, setPassword] = useState('');
    const [is_contributor, setContributor] = useState(false);
    const history = useHistory();
    return (

            <Form className="login-form">

                    <Button
                        href="/register"
                        className=" btn-dark text-right">
                        sign up
                    </Button>

                Mindify

                <FormGroup>
                    Username or Email

                    <Input
                        value={email_or_username}
                        placeholder = "Username or Email"
                        onChange={e => setName(e.target.value)}/>
                </FormGroup>

                <FormGroup>
                    Password

                    <Input
                        value={password}
                        placeholder = "Password"
                        onChange={e => setPassword(e.target.value)}/>
                </FormGroup>

                <FormGroup>

                    <Input
                        type="checkbox"
                        value={is_contributor}
                        onChange={e => setContributor(e.target.checked)}/>
                        Contributor

                </FormGroup>

                <Button onClick={async () =>{
                     const login = {email_or_username, password, is_contributor};
                     const response = await fetch('http://127.0.0.1:5000/api/login', {
                         method: 'POST',
                         headers:{
                            'Content-Type': 'application/json'
                         },
                         body: JSON.stringify(login)
                     })
                     .then(response => {
                         if (response.status === 201) {

                            response.json().then(data => { // store user in localStorage as token
                                window.localStorage.setItem("user", JSON.stringify(data.user));
                                console.log(JSON.parse(window.localStorage.getItem("user"))); // prints correctly here
                            })
                            console.log("Successful Login");
                            console.log(JSON.parse(window.localStorage.getItem("user"))); // prints null here

                            const ref="/homepage";
                            history.push(ref);
                            //redirect to home page
                         }
                         else if (response.status === 204) {
                            console.log("Invalid Username or Password or Incorrect Permissions");
                            const ref="/";
                            history.push(ref);
                            // reload login page
                         }
                     })
                     .catch(error => console.log(error))

                    }}
                    className="btn-lg btn-dark btn-block">
                    Log in</Button>
            </Form>

);
}

Body:
That is because response.json() is asynchronous, thus you will need the wait for response.json() to be returned before you can carry out any subsequent logic. If any subsequent logic is dependent on response.json(), you should  modify your statement such that the required logic is handed only after it is returned.

response.json().then(data => {
  window.localStorage.setItem("user", JSON.stringify(data.user));
  console.log(JSON.parse(window.localStorage.getItem("user")));
  const ref="/homepage";
  history.push(ref);
  // carry out other logic below
})


问:
How to echo item from geoip array in php
I want to get each item from geoplugin array separately.

Here is my example code -

```<code>$location_info = file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']);

    echo$location_info;
</code>```

and here the response in array

```<code>a:24:{s:17:"geoplugin_request";s:12:"76.180.83.10";s:16:"geoplugin_status";i:200;s:15:"geoplugin_delay";s:3:"1ms";s:16:"geoplugin_credit";s:145:"Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.";s:14:"geoplugin_city";s:7:"Buffalo";s:16:"geoplugin_region";s:8:"New York";s:20:"geoplugin_regionCode";s:2:"NY";s:20:"geoplugin_regionName";s:8:"New York";s:18:"geoplugin_areaCode";s:0:"";s:17:"geoplugin_dmaCode";s:3:"514";s:21:"geoplugin_countryCode";s:2:"US";s:21:"geoplugin_countryName";s:13:"United States";s:14:"geoplugin_inEU";i:0;s:19:"geoplugin_euVATrate";b:0;s:23:"geoplugin_continentCode";s:2:"NA";s:23:"geoplugin_continentName";s:13:"North America";s:18:"geoplugin_latitude";s:7:"42.9297";s:19:"geoplugin_longitude";s:8:"-78.7434";s:32:"geoplugin_locationAccuracyRadius";s:1:"5";s:18:"geoplugin_timezone";s:16:"America/New_York";s:22:"geoplugin_currencyCode";s:3:"USD";s:24:"geoplugin_currencySymbol";s:5:"$";s:29:"geoplugin_currencySymbol_UTF8";s:1:"$";s:27:"geoplugin_currencyConverter";s:1:"1";}
</code>```

Example - I want to get city and echo it from this array

```<code>$city = ['geoplugin_city'];
echo$city;
</code>```

答: You forgot to do $location_info = unserialize($location_info); right after the connection.

Body:
I want to get each item from geoplugin array separately.

Here is my example code -

$location_info = file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']);

    echo$location_info;

and here the response in array

a:24:{s:17:"geoplugin_request";s:12:"76.180.83.10";s:16:"geoplugin_status";i:200;s:15:"geoplugin_delay";s:3:"1ms";s:16:"geoplugin_credit";s:145:"Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.";s:14:"geoplugin_city";s:7:"Buffalo";s:16:"geoplugin_region";s:8:"New York";s:20:"geoplugin_regionCode";s:2:"NY";s:20:"geoplugin_regionName";s:8:"New York";s:18:"geoplugin_areaCode";s:0:"";s:17:"geoplugin_dmaCode";s:3:"514";s:21:"geoplugin_countryCode";s:2:"US";s:21:"geoplugin_countryName";s:13:"United States";s:14:"geoplugin_inEU";i:0;s:19:"geoplugin_euVATrate";b:0;s:23:"geoplugin_continentCode";s:2:"NA";s:23:"geoplugin_continentName";s:13:"North America";s:18:"geoplugin_latitude";s:7:"42.9297";s:19:"geoplugin_longitude";s:8:"-78.7434";s:32:"geoplugin_locationAccuracyRadius";s:1:"5";s:18:"geoplugin_timezone";s:16:"America/New_York";s:22:"geoplugin_currencyCode";s:3:"USD";s:24:"geoplugin_currencySymbol";s:5:"$";s:29:"geoplugin_currencySymbol_UTF8";s:1:"$";s:27:"geoplugin_currencyConverter";s:1:"1";}

Example - I want to get city and echo it from this array

$city = ['geoplugin_city'];
echo$city;


问:
How can I link to a node.js application listening on a port other than 80 from a static webpage?
I'm learning about web development and I'm wondering how to integrate some different technologies together. Assume I've got a static webpage hosted on a server with Apache. I've also got a node.js application running on that server, listening on port 9091. I want to be able to have a link on the static page that sends a get request to some route on the node.js app, and displays the html that's returned. Of course, Apache is listening on port 80.

Is what I'm describing possible? Is it the best way to do what I'm trying to do? I'm aware that I can do away with Apache entirely and just have the node.js application serve the static pages, but I've been told that's a bad practice because node.js is so much less efficient at hosting static pages.

Thanks

答:
You can link to a URL to a specific port number on a server by just putting the port number in the URL:

http://someserver.com:9091/somepath

The browser will contact that host on that port and send it the http request.

However, you probably don't want to do that because that will look messy on your site if the static pages show one port number in the URL and the dynamic pages show a different port number and it could really complicate maintenance of your  site.

First off, you should probably not go to a separate server for serving static pages until you've actually proven you have a need for that.  Express can certainly be beaten by Apache of NGINX for serving static resources, but it's not horrible at it so unless you've maxed out your Express server, I wouldn't recommend adding complication until you've proven you need it.  You can always add that extra scale later without making a big architectural change.

Second off, a better way to handle static resources is with a proxy you put in front of your web server (NGINX is very often what is used with node.js).  Then, you put your proxy on port 80.  It examines the URL and if it's a pattern in the URL that indicates a static resource, then it takes the request and serves the static resource.  If not, it forwards the request to your Express server which handles it.  The Express server will be running on either a different host or (if no the same host as the proxy), then on a different port.  But, the Express server's port is not visible to the outside world, only the proxy and it's port 80 is visible to the outside world.  Everything goes to/from port 80 on the proxy.  Nice and simple.

The one thing you should do from the beginning is to make sure that there's an identifiable pattern in the URL that indicates whether the resource is static or dynamic.  This would be true whether using NGINX as a proxy or using express.static() to serve your static files from Express.  One common trick is to use one or more path prefixes for all static resources such as /img, /css, /font, /script, etc... or put everything behind one prefix such as /static  Then, it's easy to configure a future proxy for exactly which URLs it should grab for static resources and which it should forward on to the Express server.


问:
Convert datetime to timestamp in Neo4j
How to convert datetime in data loaded in Neo4j to timestamp?
Example datetime format: 2020-04-07T12:39:38.027Z
Please assist.</p>

答:
Neo4's temporal instants (like datetime) have a special variable, epochMillis, that provides the equivalent epoch time.

For example:

```<code>RETURN datetime('2020-04-07T12:39:38.027Z').epochMillis
</code>```

returns

```<code>1586263178027
</code>```

Title: Convert datetime to timestamp in Neo4j

Body:
Neo4's temporal instants (like datetime) have a special variable, epochMillis, that provides the equivalent epoch time.

For example:

RETURN datetime('2020-04-07T12:39:38.027Z').epochMillis

returns

1586263178027


问:
Problem in Executing Mulesoft Batch Component
I am facing problem in executing batch functionality in MuleSoft 4, I am trying to print the final payload but I am not able to print the final processed payload.Request anyone to help on the same .The code xml is given below .

Thanks.

Code XML :

```<code><http:listener-config name="parentListener" doc:name="HTTP Listener config" doc:id="fbfff994-e442-42eb-84f7-0d6481ef1198" basePath="/" >
    <http:listener-connection host="0.0.0.0" port="8085" />
</http:listener-config>
<http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="742dd6a4-706e-473d-96f9-9719f34ed2b6" >
    <http:request-connection host="0.0.0.0" port="8086" />
</http:request-config>
<flow name="parent" doc:id="a8cb06bf-866d-4ec6-9f9f-0f492cc05044" >
    <scheduler doc:name="Scheduler" doc:id="c2a54ae1-7de0-4daf-962c-99a5eef5b78a" >
        <scheduling-strategy >
            <fixed-frequency frequency="10000"/>
        </scheduling-strategy>
    </scheduler>
    <set-payload value="#[['Apple','Banana']]" doc:name="[Apple,Banana]" doc:id="5694f264-e91d-4f2e-81aa-1267cb45f250" />
    <batch:job jobName="processRecordsBatch_Job" doc:id="c3290b63-08ba-4abc-a963-02089df89b7a" >
        <batch:process-records >
            <batch:step name="Batch_Step1" doc:id="79158da3-251b-46ec-b276-0421308fe34c" >
                <set-payload value='"1" ++ payload' doc:name="Step One" doc:id="8cb8905c-4e62-4115-995f-5416ac3a26bd" />
            </batch:step>
            <batch:step name="Batch_Step2" doc:id="00e4f7a3-83a8-46be-8b58-9e5d38850fec" >
                <set-payload value='"2"  ++ payload' doc:name='"StepTwo" ' doc:id="41a80eda-d4db-4a6a-9b0e-b79fade09f45" />
            </batch:step>
        </batch:process-records>
        <batch:on-complete >
            <logger level="INFO" doc:name="Logger" doc:id="56feea1f-6e23-4979-b66b-9d08037b56ef" message='#[payload]'/>
        </batch:on-complete>
    </batch:job>
</flow>
</code>```

Flow Screenshot:

答:
You will not see the 'output' of the batch because the batch scope doesn't return. The batch scope is processed asynchronously with respect to the flow, and doesn't return a value.

You can add loggers in the On Complete stage to print the results of the batch process execution (records processed, failures, etc).

Body:
I am facing problem in executing batch functionality in MuleSoft 4, I am trying to print the final payload but I am not able to print the final processed payload.Request anyone to help on the same .The code xml is given below .

Thanks.

Code XML :

<http:listener-config name="parentListener" doc:name="HTTP Listener config" doc:id="fbfff994-e442-42eb-84f7-0d6481ef1198" basePath="/" >
    <http:listener-connection host="0.0.0.0" port="8085" />
</http:listener-config>
<http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="742dd6a4-706e-473d-96f9-9719f34ed2b6" >
    <http:request-connection host="0.0.0.0" port="8086" />
</http:request-config>
<flow name="parent" doc:id="a8cb06bf-866d-4ec6-9f9f-0f492cc05044" >
    <scheduler doc:name="Scheduler" doc:id="c2a54ae1-7de0-4daf-962c-99a5eef5b78a" >
        <scheduling-strategy >
            <fixed-frequency frequency="10000"/>
        </scheduling-strategy>
    </scheduler>
    <set-payload value="#[['Apple','Banana']]" doc:name="[Apple,Banana]" doc:id="5694f264-e91d-4f2e-81aa-1267cb45f250" />
    <batch:job jobName="processRecordsBatch_Job" doc:id="c3290b63-08ba-4abc-a963-02089df89b7a" >
        <batch:process-records >
            <batch:step name="Batch_Step1" doc:id="79158da3-251b-46ec-b276-0421308fe34c" >
                <set-payload value='"1" ++ payload' doc:name="Step One" doc:id="8cb8905c-4e62-4115-995f-5416ac3a26bd" />
            </batch:step>
            <batch:step name="Batch_Step2" doc:id="00e4f7a3-83a8-46be-8b58-9e5d38850fec" >
                <set-payload value='"2"  ++ payload' doc:name='"StepTwo" ' doc:id="41a80eda-d4db-4a6a-9b0e-b79fade09f45" />
            </batch:step>
        </batch:process-records>
        <batch:on-complete >
            <logger level="INFO" doc:name="Logger" doc:id="56feea1f-6e23-4979-b66b-9d08037b56ef" message='#[payload]'/>
        </batch:on-complete>
    </batch:job>
</flow>

Flow Screenshot:


问:
Comparing Objects Realm Swift
I'm trying to compare 2 Realm Objects in Swift.

```<code>// Object 1 Prints:

currentObject:  Optional(ObjectClass {
    order = 0;
    number = 010;
    temp = 903;
    state = 6;

})

// Object 2 Prints:

 lastObject:  Optional(ObjectClass {
        order = 0;
        number = 010;
        temp = 903;
        state = 6;

    })
</code>```

Obviously the values are equal. But the Objects are not.

```<code>print(lastObject?.number == currentObject?.number) // Prints True
print(lastObject == currentObject) // Prints False
</code>```

I tried to implement equatable in the object class. But Xcode isn't liking it due to Realm.

Redundant conformance of 'ObjectClass' to protocol 'Equatable'

How can I compare the variables of lastObject to currentObject? I imagine theres a better way than checking each object's variable against each other. But I don't know what it is.

Object Class:

```<code>import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

}
</code>```

答:
Realm objects already conform to Equatable and Hashable since they are subclasses of NSObject. The only thing you need to do is override the isEqual method:</p>

```<code>import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

    override func isEqual(_ object: Any?) -> Bool {
        if let object = object as? ObjectClass {
            return self.order == object.order && self.number == object.number
                   && self.temp == object.temp && self.state == object.state
        } else {
            return false
        }
    }
}
</code>```

Title: Comparing Objects Realm Swift

Body:
I'm trying to compare 2 Realm Objects in Swift.

// Object 1 Prints:

currentObject:  Optional(ObjectClass {
    order = 0;
    number = 010;
    temp = 903;
    state = 6;

})

// Object 2 Prints:

 lastObject:  Optional(ObjectClass {
        order = 0;
        number = 010;
        temp = 903;
        state = 6;

    })

Obviously the values are equal. But the Objects are not.

print(lastObject?.number == currentObject?.number) // Prints True
print(lastObject == currentObject) // Prints False

I tried to implement equatable in the object class. But Xcode isn't liking it due to Realm.

Redundant conformance of 'ObjectClass' to protocol 'Equatable'

How can I compare the variables of lastObject to currentObject? I imagine theres a better way than checking each object's variable against each other. But I don't know what it is.

Object Class:

import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

}

Body:
Realm objects already conform to Equatable and Hashable since they are subclasses of NSObject. The only thing you need to do is override the isEqual method:

import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

    override func isEqual(_ object: Any?) -> Bool {
        if let object = object as? ObjectClass {
            return self.order == object.order && self.number == object.number
                   && self.temp == object.temp && self.state == object.state
        } else {
            return false
        }
    }
}


问:
Is a private member secure in javascript?
I'm following freecodecamp JavaScript oop course. The course describes how you should declare a private variable inside objects for cases like passwords and bank accounts which cannot be changed from outside. the only access to private variables is through public method that has access to the private variable. then it gives this demo code to illustrate the point.

```<code>function Bird() {
  let hatchedEgg = 10; // private variable

  /* publicly available method that a bird object can use */
  this.getHatchedEggCount = function() {
    return hatchedEgg;
  };
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10
</code>```

What i don't understand is how can the hatchedEgg variable be called as secured.
As a user/hacker all i have to do is to guess the variable name that is being returned from the function getHatchedEggCount() . in this case hatchedEgg (which is not too difficult for a hacker) and then i can use this line to modify the private variable;

```<code>Bird.hatchedEgg = 20;
console.log(Bird) // returns { [Function: Bird] hatchedEgg : 20 }
</code>```

Am i missing something ?

```<code>//-------------- Clarification Edit
</code>```

Apparently the problem was with the freecodecamp console (A Bug) , it was changing the value of a private variable .
if you want you can try pasting the above code in this link and you will see. freecodeConsoleLink

答:
As stated in the freecodecamp topic, it is called closure. Just think of it this way using very trivial programming concepts:

Variables declared inside a function are scoped to that function, there is no way to access those from outside the function. This is not only true for JavaScript, for all other languages.

Now as to why we can get the value of that scoped variable from outside is the magic of the closure. Since the question does not mention the word "closure" let alone ask about it, I will not go into the details of closure here.

And as for the code you said that a hacker could use to hack it, the line

```<code>Bird.hatchedEgg = 20;
</code>```

only creates a property inside the object Bird. Another basic concept here - the function Bird is also a first class object in JavaScript, meaning it can have properties as well as functions just like any other objects. Bird.hatchedEgg refers to the property of the Bird object, whereas the variable declared inside the Bird function (with let hatchedEgg = 10;) is a local variable of the function, and the two are distinct. If that line were to change the value of the local variable declared inside the function, you should get the same result when you console log ducky.getHatchedEggCount(), but you wouldn't.

Body:
I'm following freecodecamp JavaScript oop course. The course describes how you should declare a private variable inside objects for cases like passwords and bank accounts which cannot be changed from outside. the only access to private variables is through public method that has access to the private variable. then it gives this demo code to illustrate the point.

function Bird() {
  let hatchedEgg = 10; // private variable

  /* publicly available method that a bird object can use */
  this.getHatchedEggCount = function() {
    return hatchedEgg;
  };
}
let ducky = new Bird();
ducky.getHatchedEggCount(); // returns 10

What i don't understand is how can the hatchedEgg variable be called as secured.
As a user/hacker all i have to do is to guess the variable name that is being returned from the function getHatchedEggCount() . in this case hatchedEgg (which is not too difficult for a hacker) and then i can use this line to modify the private variable;

Bird.hatchedEgg = 20;
console.log(Bird) // returns { [Function: Bird] hatchedEgg : 20 }

Am i missing something ?

//-------------- Clarification Edit

Apparently the problem was with the freecodecamp console (A Bug) , it was changing the value of a private variable .
if you want you can try pasting the above code in this link and you will see. freecodeConsoleLink

Body:
As stated in the freecodecamp topic, it is called closure. Just think of it this way using very trivial programming concepts:

Variables declared inside a function are scoped to that function, there is no way to access those from outside the function. This is not only true for JavaScript, for all other languages.

Now as to why we can get the value of that scoped variable from outside is the magic of the closure. Since the question does not mention the word "closure" let alone ask about it, I will not go into the details of closure here.

And as for the code you said that a hacker could use to hack it, the line

Bird.hatchedEgg = 20;

only creates a property inside the object Bird. Another basic concept here - the function Bird is also a first class object in JavaScript, meaning it can have properties as well as functions just like any other objects. Bird.hatchedEgg refers to the property of the Bird object, whereas the variable declared inside the Bird function (with let hatchedEgg = 10;) is a local variable of the function, and the two are distinct. If that line were to change the value of the local variable declared inside the function, you should get the same result when you console log ducky.getHatchedEggCount(), but you wouldn't.


问:
How to give a C# DLL a C-compliant interface?
A third-party app I have can call extension DLLs if they have C-compliant interfaces as described below.

I would like the third-party app to call my C# DLL, since I would rather write in C# than C. (Maybe my other choice would be to write a C DLL wrapper to call my C# DLL, which is an extra step that I might not get right).

I've searched the net and SO but haven't found (or recognized) a good match to my question.

The best suggestion seemed to be this special marshalling declarations in the C# code here: Calling a C# DLL from C; linking problems

Is it possible to write a C# DLL that has a C-compliant interface like the one below? If so, could someone tell me what I have to do or point me to some documentation?

The third-party app documentation says, "The DLL function must be a PASCAL function that takes a single LPCSTR (long pointer to a constant string) argument. C or C++ DLL functions called must have prototypes equivalent to:

```<code>extern "C" __declspec(dllexport) void __stdcall fn(LPCTSTR szParam );
</code>```

答:
Take a look at this article: https://www.codeproject.com/Articles/12512/Using-the-CDECL-calling-convention-in-C-changing

It discusses a different problem (opposite to yours) but also explains the linkage of C# functions - by default C# uses __stdcall (and it cannot be overridden). This means your third party app should be able to call the C# function as it stands. Have you tried it? Did you get any errors?

Body:
A third-party app I have can call extension DLLs if they have C-compliant interfaces as described below.

I would like the third-party app to call my C# DLL, since I would rather write in C# than C. (Maybe my other choice would be to write a C DLL wrapper to call my C# DLL, which is an extra step that I might not get right).

I've searched the net and SO but haven't found (or recognized) a good match to my question.

The best suggestion seemed to be this special marshalling declarations in the C# code here: Calling a C# DLL from C; linking problems

Is it possible to write a C# DLL that has a C-compliant interface like the one below? If so, could someone tell me what I have to do or point me to some documentation?

The third-party app documentation says, "The DLL function must be a PASCAL function that takes a single LPCSTR (long pointer to a constant string) argument. C or C++ DLL functions called must have prototypes equivalent to:

extern "C" __declspec(dllexport) void __stdcall fn(LPCTSTR szParam );


问:
Finding trouble in links in html not working
```<code><body >
    <div class="outer-container">
        <div class="container">
            <div class="header">
               <a href="#">HOME</a>
               <a href="#">ABOUT</a>
               <a href="#">CONTACT</a>
               <a href="">RESUME</a>
            </div>
            <div class="big-heading">
                <h2 style=color:white>
                   I'm Ankit Soni.
                </h2>
            </div>

            <div class="social-media">
                    <a href="https://www.linkedin.com/in/ankit-soni-991495152/">
                    <i class="fa fa-linkedin"></i></a>
                    <a href="https://github.com/ankysony">
                    <i class="fa fa-github"></i></a>
                    <a href="mailto:ankit.soni.che16@iitbhu.ac.in">
                    <i class="fa fa-envelope"></i></a>
            </div>
            <div class="scrolldown">
                <a href="">
                    <i class="fa fa-arrow-circle-down"></i>
                </a>
            </div>
        </div>
    </div>
</body>
</code>```

I cannot find any type of mistake in it but my links in it are not working (no cursor pointer no redirects). Only the last one with arrow circle is working. The links under class social-media are not.

I got a part of css which is creating the error please see to it and suggest the possible way to fix error.

```<code>.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}
</code>```

and the entire css code is below.

```<code> *
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.outer-container
{
    height: 792px;
    width: 1440px;
}
h2{
    font-family: sans-serif;
}
html {
    background: url(../images/banner.jpg);
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
    overflow: scroll;
    overflow-x: hidden;
  }
.outer-container .container .header
{
    text-align: center;
    word-spacing: 100px;
    padding-top: 10px;
}
.outer-container .container .header a
{
    font-family: sans-serif;
    text-decoration: none;
    color: white;
}
.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}
.outer-container .container .social-media
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
}
.outer-container .container .social-media i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 30px;
}
.outer-container .container .scrolldown
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 300px;
}
 .outer-container .container .scrolldown i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 50px;
}
</code>```

答:
In the header class, your href is not redirecting you anywhere, because you only specified href="#", which neither points to another page nor points to any specific id on your page. You should add your url to to navigate to another page (or, in this case maybe an id on your own page):

```<code>href="www.site.com"
</code>```

Also, it seems like in the social-media class, you did not specify any text for the link, which is why they aren't showing up.
You should put some text between the opening and closing tags:

```<code><a href="url">link text</a>
</code>```

Body:
               HOME
               ABOUT
               CONTACT
               RESUME

                   I'm Ankit Soni.

I cannot find any type of mistake in it but my links in it are not working (no cursor pointer no redirects). Only the last one with arrow circle is working. The links under class social-media are not.

I got a part of css which is creating the error please see to it and suggest the possible way to fix error.

.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}

and the entire css code is below.

 *
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.outer-container
{
    height: 792px;
    width: 1440px;
}
h2{
    font-family: sans-serif;
}
html {
    background: url(../images/banner.jpg);
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
    overflow: scroll;
    overflow-x: hidden;
  }
.outer-container .container .header
{
    text-align: center;
    word-spacing: 100px;
    padding-top: 10px;
}
.outer-container .container .header a
{
    font-family: sans-serif;
    text-decoration: none;
    color: white;
}
.outer-container .container .big-heading
{
  height: 100%;
  width: 100%;
  display: flex;
  font-size: 3em;
  position: absolute;
  align-items: center;
  justify-content: center;
  margin-top: -50px;
}
.outer-container .container .social-media
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
}
.outer-container .container .social-media i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 30px;
}
.outer-container .container .scrolldown
{
    height: 100%;
    width: 100%;
    display: flex;
    position: absolute;
    align-items: center;
    justify-content: center;
    margin-top: 300px;
}
 .outer-container .container .scrolldown i
{
    padding: 20px;
    margin: 20px;
    color: white;
    text-shadow: 1px 1px 1px #ccc;
    font-size: 50px;
}

Body:
In the header class, your href is not redirecting you anywhere, because you only specified href="#", which neither points to another page nor points to any specific id on your page. You should add your url to to navigate to another page (or, in this case maybe an id on your own page):

href="www.site.com"

Also, it seems like in the social-media class, you did not specify any text for the link, which is why they aren't showing up.
You should put some text between the opening and closing tags:

<a href="url">link text</a>


问:
AssertionError: error message must contain revert
While I run test I get this error..

I am trying to make my own cryptocurrency using the DAPPuniversity tutorial, however, my code keeps throwing an exception.

```<code>  Contract: ValleyToken
    √ initialize the contract with correct values (363ms)
    √ sets the initial supply upon deployment (363ms)
    1) transfers token ownership
    > No events were emitted

  2 passing (869ms)
  1 failing

  1) Contract: ValleyToken
       transfers token ownership:
     ReferenceError: Faicoin is not defined
      at Context.<anonymous> (test\ValleyToken.js:47:5)
      at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

答:
Replace this code with your test : )</p>

```<code>   it("transfers token ownership", function () {
        return ValleyToken.deployed()
          .then(function (instance) {
            tokenInstance = instance;
            return tokenInstance.transfer.call(accounts[1], 9999999999999999);
          })
          .then(assert.fail)
          .catch(function (error) {
            assert(error.message, "error message must contain revert");
            return tokenInstance.transfer.call(accounts[1], 250000, {
              from: accounts[0],
            });
          })
          .then(function (success) {
            assert(success, true, "it returns true");
            return tokenInstance.transfer(accounts[1], 250000, {
              from: accounts[0],
            });
          })
          .then(function (receipt) {
            assert.equal(receipt.logs.length, 1, "triggers one event");
            assert.equal(
              receipt.logs[0].event,
              "Transfer",
              'should be the "Transfer" event'
            );
            assert.equal(
              receipt.logs[0].args._from,
              accounts[0],
              "logs the account the tokens are transferred from"
            );
            assert.equal(
              receipt.logs[0].args._to,
              accounts[1],
              "logs the account the tokens are transferred to"
            );
            assert.equal(
              receipt.logs[0].args._value,
              250000,
              "logs the transfer amount"
            );
            return tokenInstance.balanceOf(accounts[1]);
          })
          .then(function (reciept) {
            return tokenInstance.balanceOf(accounts[1]);
          })
          .then(function (balance) {
            assert.equal(
              balance.toNumber(),
              250000,
              "adds the amount to the recieving amount"
            );
            return tokenInstance.balanceOf(accounts[0]);
          })
          .then(function (balance) {
            assert.equal(
              balance.toNumber(),
              750000,
              "deducts the amount from the sending account"
            );
          });
      });
</code>```

Body:
While I run test I get this error..

I am trying to make my own cryptocurrency using the DAPPuniversity tutorial, however, my code keeps throwing an exception.

  Contract: ValleyToken
    √ initialize the contract with correct values (363ms)
    √ sets the initial supply upon deployment (363ms)
    1) transfers token ownership
    > No events were emitted

  2 passing (869ms)
  1 failing

  1) Contract: ValleyToken
       transfers token ownership:
     ReferenceError: Faicoin is not defined
      at Context.<anonymous> (test\ValleyToken.js:47:5)
      at process._tickCallback (internal/process/next_tick.js:68:7)

Body:
Replace this code with your test : )

   it("transfers token ownership", function () {
        return ValleyToken.deployed()
          .then(function (instance) {
            tokenInstance = instance;
            return tokenInstance.transfer.call(accounts[1], 9999999999999999);
          })
          .then(assert.fail)
          .catch(function (error) {
            assert(error.message, "error message must contain revert");
            return tokenInstance.transfer.call(accounts[1], 250000, {
              from: accounts[0],
            });
          })
          .then(function (success) {
            assert(success, true, "it returns true");
            return tokenInstance.transfer(accounts[1], 250000, {
              from: accounts[0],
            });
          })
          .then(function (receipt) {
            assert.equal(receipt.logs.length, 1, "triggers one event");
            assert.equal(
              receipt.logs[0].event,
              "Transfer",
              'should be the "Transfer" event'
            );
            assert.equal(
              receipt.logs[0].args._from,
              accounts[0],
              "logs the account the tokens are transferred from"
            );
            assert.equal(
              receipt.logs[0].args._to,
              accounts[1],
              "logs the account the tokens are transferred to"
            );
            assert.equal(
              receipt.logs[0].args._value,
              250000,
              "logs the transfer amount"
            );
            return tokenInstance.balanceOf(accounts[1]);
          })
          .then(function (reciept) {
            return tokenInstance.balanceOf(accounts[1]);
          })
          .then(function (balance) {
            assert.equal(
              balance.toNumber(),
              250000,
              "adds the amount to the recieving amount"
            );
            return tokenInstance.balanceOf(accounts[0]);
          })
          .then(function (balance) {
            assert.equal(
              balance.toNumber(),
              750000,
              "deducts the amount from the sending account"
            );
          });
      });


问:
ModuleNotFoundError: No Module Named cant figure out why
going to retrieve a simple httpresponse from view at nested app, but some how having this error which cant figure out what the problem.

project urls.py

```<code>from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse, HttpRequest
# from .corex import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('corex.urls')),
]
</code>```

app[corex] urls.py

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

urlpatterns = [
    path('', views.testcorex, name='testcorex'),
]
</code>```

app views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def testcorex(request):
    return HttpResponse('module passed')
</code>```

traceback error

```<code>File "/home/differentmonster/App/x_house_project/x_house_backend/x_house_cms/urls.py", line 11, in <module>
    path('', include('corex.urls')),
  File "/root/.cache/pypoetry/virtualenvs/x-house-cms-p6EwdKv_-py3.8/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'corex
</code>```

the installedApp should be no problem cause, if i import corex.views directly into root urls.py, the response works. but after i added the url.py into app, the module cant be found. and i am using poetry for venveniroment and django 3.0.6.

thanks guys

答:
Okay i figure out the problem came from structuralize folder.

```<code>x_house_project[level_1]

-x_house_project[level_2]

  --corex[level_3]
  --urls.py
  --views.py

-urls.py
-settings.py

manage.py
</code>```

in root urls, if i change the corex into x_house_project/corex, things are good, but i cant figure it out the django logical, cause if the settings.py INSTALLED_APPS already setup the path and the logic run from root urls.py, isit more weird putting in the folder path x_house_project ?

Body:
going to retrieve a simple httpresponse from view at nested app, but some how having this error which cant figure out what the problem.

project urls.py

from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse, HttpRequest
# from .corex import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('corex.urls')),
]

app[corex] urls.py

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.testcorex, name='testcorex'),
]

app views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def testcorex(request):
    return HttpResponse('module passed')

traceback error

File "/home/differentmonster/App/x_house_project/x_house_backend/x_house_cms/urls.py", line 11, in <module>
    path('', include('corex.urls')),
  File "/root/.cache/pypoetry/virtualenvs/x-house-cms-p6EwdKv_-py3.8/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'corex

the installedApp should be no problem cause, if i import corex.views directly into root urls.py, the response works. but after i added the url.py into app, the module cant be found. and i am using poetry for venveniroment and django 3.0.6.

thanks guys

Body:
Okay i figure out the problem came from structuralize folder.

x_house_project[level_1]

-x_house_project[level_2]

  --corex[level_3]
  --urls.py
  --views.py

-urls.py
-settings.py

manage.py

in root urls, if i change the corex into x_house_project/corex, things are good, but i cant figure it out the django logical, cause if the settings.py INSTALLED_APPS already setup the path and the logic run from root urls.py, isit more weird putting in the folder path x_house_project ?


问:
How to filter Spark sql by nested array field (array within array)?
My spark Dataframe schema

```<code>|-- goods: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- brand_id: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- product_id: string (nullable = true)
</code>```

I'm able to filter the Dataframe by product_id

```<code>select * from goodsInfo where array_contains(goods.product_id, 'f31ee3f8-9ba2-49cb-86e2-ceb44e34efd9')
</code>```

But I'm unable to filter by brand_id which is an array within array..

I get the error when I try

```<code>select * from goodsInfo where array_contains(goods.brand_id, '45c060b9-3645-49ad-86eb-65f3cd4e9081')
</code>```

Error:

```<code>function array_contains should have been array followed by a value with same element type, but it's [array<array<string>>, string].; line 1 pos 45;
</code>```

Can someone please help ?

Thanks in advance

答:
One more altervative approach, which is not there in the other answers-

Code is self-explanatory

    val data=
      """
        |{
        |   "goods": [{
        |       "brand_id": ["brand1", "brand2", "brand3"],
        |       "product_id": "product1"
        |   }]
        |}
      """.stripMargin
    val df = spark.read.json(Seq(data).toDS())
    df.show(false)
    df.printSchema()
    df.createOrReplaceTempView("goodsInfo")

    /**
      * +--------------------------------------+
      * |goods                                 |
      * +--------------------------------------+
      * |[[[brand1, brand2, brand3], product1]]|
      * +--------------------------------------+
      *
      * root
      * |-- goods: array (nullable = true)
      * |    |-- element: struct (containsNull = true)
      * |    |    |-- brand_id: array (nullable = true)
      * |    |    |    |-- element: string (containsNull = true)
      * |    |    |-- product_id: string (nullable = true)
      */

    // filter Dataframe by product_id
    spark.sql("select * from goodsInfo where array_contains(goods.product_id, 'product1')").show(false)

    /**
      * +--------------------------------------+
      * |goods                                 |
      * +--------------------------------------+
      * |[[[brand1, brand2, brand3], product1]]|
      * +--------------------------------------+
      */
    // filter Dataframe by brand_id which is an array within array..
    // positive case
    spark.sql("select * from goodsInfo where array_contains(flatten(goods.brand_id), 'brand3')")
      .show(false)

    /**
      * +--------------------------------------+
      * |goods                                 |
      * +--------------------------------------+
      * |[[[brand1, brand2, brand3], product1]]|
      * +--------------------------------------+
      */
    // negative case
    spark.sql("select * from goodsInfo where array_contains(flatten(goods.brand_id), 'brand4')")
      .show(false)

    /**
      * +-----+
      * |goods|
      * +-----+
      * +-----+
      */
```

Body:
My spark Dataframe schema

|-- goods: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- brand_id: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true)
 |    |    |-- product_id: string (nullable = true)

I'm able to filter the Dataframe by product_id

select * from goodsInfo where array_contains(goods.product_id, 'f31ee3f8-9ba2-49cb-86e2-ceb44e34efd9')

But I'm unable to filter by brand_id which is an array within array..

I get the error when I try

select * from goodsInfo where array_contains(goods.brand_id, '45c060b9-3645-49ad-86eb-65f3cd4e9081')

Error:

function array_contains should have been array followed by a value with same element type, but it's [array<array<string>>, string].; line 1 pos 45;

Can someone please help ?

Thanks in advance


问:
integer constant long long int?
```<code>long long int
</code>```

It seems to be valid in C. but is this valid in c++?

答: It's in the C++0x standard. This answers your question: http://en.wikipedia.org/wiki/Long_integer</p>

Title: integer constant long long int?

Body:
long long int

It seems to be valid in C. but is this valid in c++?


问:
Is there a way to count and calculate mean for text columns using groupby?
I have been using pandas.groupby to pivot data and create descriptive charts and tables for my data. While doing groupby for three variables, I keep running into a DataError: No numeric types to aggregate error while working with the cancelled column.

To describe my data, Year and Month contain yearly and monthly data for multiple columns (multiple years, all months), Type contains the type of order item (Clothes, Appliances, etc.), and cancelled contains yes or no string values to determine whether a order was cancelled or not.

I am hoping to plot a graph and show a table to show what the cancellation rate (and success rate) is by order item. The following is what I'm using so far

```<code>df.groupby(['Year', 'Month', 'Type'])['cancelled'].mean()
</code>```

But this doesn't seem to be working.

Sample

```<code>Year    Month        Type          cancelled
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes
</code>```

答:
Use:

```<code>df = pd.DataFrame({
         'Year':[2020] * 6,
         'Month':[7,8,7,8,7,8],
         'cancelled':['yes','no'] * 3,
         'Type':list('aaaaba')
})
print (df)
</code>```

Get counts per Year, Month, Type columns:

```<code>df1 = df.groupby(['Year', 'Month', 'Type','cancelled']).size().unstack(fill_value=0)
print (df1)
cancelled        no  yes
Year Month Type
2020 7     a      0    2
           b      0    1
     8     a      3    0
</code>```

And then divide by sum of values for ratio:

```<code>df2 = df1.div(df1.sum()).mul(100)
print (df2)
cancelled           no        yes
Year Month Type
2020 7     a       0.0  66.666667
           b       0.0  33.333333
     8     a     100.0   0.000000
</code>```

Body:
I have been using pandas.groupby to pivot data and create descriptive charts and tables for my data. While doing groupby for three variables, I keep running into a DataError: No numeric types to aggregate error while working with the cancelled column.

To describe my data, Year and Month contain yearly and monthly data for multiple columns (multiple years, all months), Type contains the type of order item (Clothes, Appliances, etc.), and cancelled contains yes or no string values to determine whether a order was cancelled or not.

I am hoping to plot a graph and show a table to show what the cancellation rate (and success rate) is by order item. The following is what I'm using so far

df.groupby(['Year', 'Month', 'Type'])['cancelled'].mean()

But this doesn't seem to be working.

Sample

Year    Month        Type          cancelled
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes

Body:
Use:

df = pd.DataFrame({
         'Year':[2020] * 6,
         'Month':[7,8,7,8,7,8],
         'cancelled':['yes','no'] * 3,
         'Type':list('aaaaba')
})
print (df)

Get counts per Year, Month, Type columns:

df1 = df.groupby(['Year', 'Month', 'Type','cancelled']).size().unstack(fill_value=0)
print (df1)
cancelled        no  yes
Year Month Type
2020 7     a      0    2
           b      0    1
     8     a      3    0

And then divide by sum of values for ratio:

df2 = df1.div(df1.sum()).mul(100)
print (df2)
cancelled           no        yes
Year Month Type
2020 7     a       0.0  66.666667
           b       0.0  33.333333
     8     a     100.0   0.000000


问:
Why, I can't update my react app hosted on Digital Ocean?
I hosted my website on Digital Ocean and I installed Nginx to serve it,
when I tried to update my react app it did not work
I tried to restart Nginx with :

```<code>sudo service nginx restart
</code>```

It did not work it is still the old version that is served
so I removed the cache of Nginx with

```<code>sudo rm -rf /var/cache/nginx/
</code>```

Then I restarted but it is still the old version
so I tried to stop Nginx

```<code>sudo service nginx stop
</code>```

Then

```<code>sudo service nginx  status
</code>```

To see if it worked, and even if the status of Nginx is not active the web site is still working and the old version of the website is still here
I tried several think like

```<code>sudo nginx -s stop
sudo nginx -s quit
</code>```

same think , the old version is still here
even when I shut off the digital ocean droplet(VM) the link to the website still work with the old version even if when I ping to it I don't have a response

please help me understand what is going on

答:
Have you tried to clean the cache from your local browser?

If you do not want to clean local browser cache, open a new browser in incognito mode.

For debugging without risk of cache local, i would recommend open a browser in developer console (F12), change to tab network and click button disable cache.

The disable cache option is only active if developer console is open.

Body:
I hosted my website on Digital Ocean and I installed Nginx to serve it,
when I tried to update my react app it did not work
I tried to restart Nginx with :

sudo service nginx restart

It did not work it is still the old version that is served
so I removed the cache of Nginx with

sudo rm -rf /var/cache/nginx/

Then I restarted but it is still the old version
so I tried to stop Nginx

sudo service nginx stop

Then

sudo service nginx  status

To see if it worked, and even if the status of Nginx is not active the web site is still working and the old version of the website is still here
I tried several think like

sudo nginx -s stop
sudo nginx -s quit

same think , the old version is still here
even when I shut off the digital ocean droplet(VM) the link to the website still work with the old version even if when I ping to it I don't have a response

please help me understand what is going on


问:
Indexing error when comparing numbers in list
I'm trying to build a function that given a list or string of numbers (for the string the numbers are separated by ",") and a target number finds the number of values in the last that can get to the target. Numbers can increase by 1 only by eating a number equal or smaller than themselves, after eating the smaller number the smaller number is removed from the list. The list resets to it's original for every number. I am close but I keep getting an index error and I'm not sure how to fix it

def cannibal(l, target):

    newl = l
    count = 0
    i = 0
    listlen = len(newl)

    try:
        newl = l.split(",")
        newl.sort(reverse = True)
        newl = list(map(int, newl))
        print (newl)

    except:
        newl.sort(reverse = True)
        print (newl)

    finally:
        while i < len(newl):

            print ("index is ",i)

            if newl[i] == target:
                print ("match found at ", i)
                count += 1
                i += 1
                continue

            if newl[i] > target:
                i += 1
                continue

            for j in range(i+1,listlen-1):

                print ("list length is",listlen)
                while newl[i] > newl [j] and j<listlen:

                    print (newl[i]," is eating ",newl[i+1])
                    newl.remove(newl [i+1])
                    newl[i] = newl[i]+1
                    listlen = len(newl)
                    print (newl)

                    if newl[i] == target:
                        print ("match found at ", i)
                        count += 1
                        i += 1
                        break
            i += 1

        print (count)
        return count
```

When cannibal([27, 9, 3, 8, 11], 50) is given it returns IndexError: list index out of range and points to while newl[i] > newl [j] and j<listlen:

答:
>>> cannibal([27, 9, 3, 8, 11], 50)
[27, 11, 9, 8, 3]
index is  0
list length is 5
27  is eating  11
[28, 9, 8, 3]
28  is eating  9
[29, 8, 3]
29  is eating  8
[30, 3]
30  is eating  3
[31]
Traceback (most recent call last):
  File "<pyshell#169>", line 1, in <module>
    cannibal([27, 9, 3, 8, 11], 50)
  File "<pyshell#168>", line 36, in cannibal
    while newl[i] > newl [j] and j<listlen:
IndexError: list index out of range
```

<p>I ran the testcase you mentioned was failing. At first glance it looks like there is an improper exit condition. Upon further inspection, it seems like your innermost while loop is eventually forced to evaluate a condition that would raise an IndexError.</p>

<p>When I stick a <code>print(newl, i, j)</code> at the end of that while loop, here's what we get:</p>

<pre class="lang-py prettyprint-override"><code>>>> cannibal([27, 9, 3, 8, 11], 50)
[27, 11, 9, 8, 3]
index is  0
list length is 5
27  is eating  11
[28, 9, 8, 3]
[28, 9, 8, 3] 0 1
28  is eating  9
[29, 8, 3]
[29, 8, 3] 0 1
29  is eating  8
[30, 3]
[30, 3] 0 1
30  is eating  3
[31]
[31] 0 1
Traceback (most recent call last):
  File "<pyshell#175>", line 1, in <module>
    cannibal([27, 9, 3, 8, 11], 50)
  File "<pyshell#174>", line 37, in cannibal
    while newl[i] > newl [j] and j<listlen:
IndexError: list index out of range
</code>```

Hopefully now it's clear what the issue is.

At a point during that while loop, you end up with newl = [31], i = 0, and j = 1.

When the condition while newl[i] > newl [j] and j<listlen is evaluated, of course newl[0] > newl[1] is going to break the function because newl[1] doesn't exist.

To stop the error from happening, the easiest thing was to add a flag to break out of the for loop.

def cannibal(l, target):

    newl = l
    count = 0
    i = 0
    listlen = len(newl)

    try:
        newl = l.split(",")
        newl.sort(reverse = True)
        newl = list(map(int, newl))
        print (newl)

    except:
        newl.sort(reverse = True)
        print (newl)

    finally:
        while i < len(newl):

            print ("index is ",i)

            if newl[i] == target:
                print ("match found at ", i)
                count += 1
                i += 1
                continue

            if newl[i] > target:
                i += 1
                continue

            break_out = False

            for j in range(i+1,listlen-1):

                if break_out: break

                print ("list length is",listlen)

                while newl[i] > newl [j] and j<listlen:

                    print (newl[i]," is eating ",newl[i+1])
                    newl.remove(newl [i+1])
                    newl[i] = newl[i]+1
                    listlen = len(newl)
                    print (newl)
                    print(newl, i, j)
                    if newl[i] == target:
                        print ("match found at ", i)
                        count += 1
                        i += 1
                        print(newl, i, j)
                        break
                    if i >= len(newl) or j >= len(newl):
                        print ("loop is broken")
                        break_out = True
                        break
            i += 1

        print (count)
        return count
```

However, I believe the problem goes a little deeper. I don't entirely understand how you intended this function to work but I have a hunch you don't want newl to become [31] permanently after the first iteration of your for loop.

Body:
I'm trying to build a function that given a list or string of numbers (for the string the numbers are separated by ",") and a target number finds the number of values in the last that can get to the target. Numbers can increase by 1 only by eating a number equal or smaller than themselves, after eating the smaller number the smaller number is removed from the list. The list resets to it's original for every number. I am close but I keep getting an index error and I'm not sure how to fix it

def cannibal(l, target):

    newl = l
    count = 0
    i = 0
    listlen = len(newl)

    try:
        newl = l.split(",")
        newl.sort(reverse = True)
        newl = list(map(int, newl))
        print (newl)

    except:
        newl.sort(reverse = True)
        print (newl)

    finally:
        while i < len(newl):

            print ("index is ",i)

            if newl[i] == target:
                print ("match found at ", i)
                count += 1
                i += 1
                continue

            if newl[i] > target:
                i += 1
                continue

            for j in range(i+1,listlen-1):

                print ("list length is",listlen)
                while newl[i] > newl [j] and j<listlen:

                    print (newl[i]," is eating ",newl[i+1])
                    newl.remove(newl [i+1])
                    newl[i] = newl[i]+1
                    listlen = len(newl)
                    print (newl)

                    if newl[i] == target:
                        print ("match found at ", i)
                        count += 1
                        i += 1
                        break
            i += 1

        print (count)
        return count

When cannibal([27, 9, 3, 8, 11], 50) is given it returns IndexError: list index out of range and points to while newl[i] > newl [j] and j<listlen:

Body:
>>> cannibal([27, 9, 3, 8, 11], 50)
[27, 11, 9, 8, 3]
index is  0
list length is 5
27  is eating  11
[28, 9, 8, 3]
28  is eating  9
[29, 8, 3]
29  is eating  8
[30, 3]
30  is eating  3
[31]
Traceback (most recent call last):
  File "<pyshell#169>", line 1, in <module>
    cannibal([27, 9, 3, 8, 11], 50)
  File "<pyshell#168>", line 36, in cannibal
    while newl[i] > newl [j] and j<listlen:
IndexError: list index out of range

I ran the testcase you mentioned was failing. At first glance it looks like there is an improper exit condition. Upon further inspection, it seems like your innermost while loop is eventually forced to evaluate a condition that would raise an IndexError.

When I stick a print(newl, i, j) at the end of that while loop, here's what we get:

>>> cannibal([27, 9, 3, 8, 11], 50)
[27, 11, 9, 8, 3]
index is  0
list length is 5
27  is eating  11
[28, 9, 8, 3]
[28, 9, 8, 3] 0 1
28  is eating  9
[29, 8, 3]
[29, 8, 3] 0 1
29  is eating  8
[30, 3]
[30, 3] 0 1
30  is eating  3
[31]
[31] 0 1
Traceback (most recent call last):
  File "<pyshell#175>", line 1, in <module>
    cannibal([27, 9, 3, 8, 11], 50)
  File "<pyshell#174>", line 37, in cannibal
    while newl[i] > newl [j] and j<listlen:
IndexError: list index out of range

Hopefully now it's clear what the issue is.

At a point during that while loop, you end up with newl = [31], i = 0, and j = 1.

When the condition while newl[i] > newl [j] and j<listlen is evaluated, of course newl[0] > newl[1] is going to break the function because newl[1] doesn't exist.

To stop the error from happening, the easiest thing was to add a flag to break out of the for loop.

def cannibal(l, target):

    newl = l
    count = 0
    i = 0
    listlen = len(newl)

    try:
        newl = l.split(",")
        newl.sort(reverse = True)
        newl = list(map(int, newl))
        print (newl)

    except:
        newl.sort(reverse = True)
        print (newl)

    finally:
        while i < len(newl):

            print ("index is ",i)

            if newl[i] == target:
                print ("match found at ", i)
                count += 1
                i += 1
                continue

            if newl[i] > target:
                i += 1
                continue

            break_out = False

            for j in range(i+1,listlen-1):

                if break_out: break

                print ("list length is",listlen)

                while newl[i] > newl [j] and j<listlen:

                    print (newl[i]," is eating ",newl[i+1])
                    newl.remove(newl [i+1])
                    newl[i] = newl[i]+1
                    listlen = len(newl)
                    print (newl)
                    print(newl, i, j)
                    if newl[i] == target:
                        print ("match found at ", i)
                        count += 1
                        i += 1
                        print(newl, i, j)
                        break
                    if i >= len(newl) or j >= len(newl):
                        print ("loop is broken")
                        break_out = True
                        break
            i += 1

        print (count)
        return count

However, I believe the problem goes a little deeper. I don't entirely understand how you intended this function to work but I have a hunch you don't want newl to become [31] permanently after the first iteration of your for loop.


问:
Android "Getting Started" Tutorial Splash Screen
I'm trying to build a scrollable splash screen like the ones that exist in many Google apps.  Where a user can swipe between introductory information and an indicator is given at the bottom of the page for status.

Using a ViewFlipper seems possible, as outlined here: http://tekartlife.blogspot.com/2014/04/changing-screen-with-viewflipper-and.html

I'm curious what the "standard" or preferred implementation is?

答:
You can use ViewPager for the getting started screen and use indicators for the indicators.

You can also use best graphics like color hex codes for showing your "Getting Started" screen best.


问:
trying to implement a text filter to a ag-grid in a react component
I can't figure out how to implement a simple search bar to the ag-grid i set. I would like to let my input filter the results in my grid based on every columns I couldn't figure out a good documentation with example for that. Here is my code. Feel free to redirect me to a proper example or another question similar.</p>

```<code>import React from 'react';

import { AgGridReact } from 'ag-grid-react';
import axios from 'axios';

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

class ListTableClients extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      defaultColDef: {
        flex: 1,
        cellClass: 'cell-wrap-text',
        autoHeight: true,
        sortable: true,
        resizable: true,
      },

      columnDefs: [
        { headerName: "id", field: "id", maxWidth: 100 },
        { headerName: "name", field: "name"},
        { headerName: "email", field: "email"}],

      rowData: [
        { id: 1, name: 'maison du café', email: 'maisonducafe@gamil.com' },
        { id: 2, name: 'Warehouse', email: 'contact@warehouse.fr' },
        { id: 3, name: 'Maestro', email: 'maestro@gmail.com' }],
      rowHeight: 275,
    }
  }

  componentDidMount() {
    console.log('test');
    axios.get('http://localhost:8080/listClients').then((res) => {
      this.setState({ rowData: res.data });
    }).catch((error) => { console.log(error) });
  }

  render() {
    return (
        <div style={{width: '100%', paddingLeft: '50px', paddingRight: '50px', paddingTop: '50px'}} className="ag-theme-alpine">
          <input type="text" placeholder="Filter..." onInput={this.onFilterTextBoxChanged}/>
          <AgGridReact
            domLayout='autoHeight'
            columnDefs={this.state.columnDefs}
            defaultColDef={this.state.defaultColDef}
            getRowHeight={this.state.getRowHeight}
            rowData={this.state.rowData}>
          </AgGridReact>
        </div>
    );
  }
}

export default ListTableClients;
</code>```

答:
Refer this demo

If the cell data in object format then you have to format it Ag-Grid Value Formatters

Body:
I can't figure out how to implement a simple search bar to the ag-grid i set. I would like to let my input filter the results in my grid based on every columns I couldn't figure out a good documentation with example for that. Here is my code. Feel free to redirect me to a proper example or another question similar.

import React from 'react';

import { AgGridReact } from 'ag-grid-react';
import axios from 'axios';

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

class ListTableClients extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      defaultColDef: {
        flex: 1,
        cellClass: 'cell-wrap-text',
        autoHeight: true,
        sortable: true,
        resizable: true,
      },

      columnDefs: [
        { headerName: "id", field: "id", maxWidth: 100 },
        { headerName: "name", field: "name"},
        { headerName: "email", field: "email"}],

      rowData: [
        { id: 1, name: 'maison du café', email: 'maisonducafe@gamil.com' },
        { id: 2, name: 'Warehouse', email: 'contact@warehouse.fr' },
        { id: 3, name: 'Maestro', email: 'maestro@gmail.com' }],
      rowHeight: 275,
    }
  }

  componentDidMount() {
    console.log('test');
    axios.get('http://localhost:8080/listClients').then((res) => {
      this.setState({ rowData: res.data });
    }).catch((error) => { console.log(error) });
  }

  render() {
    return (

          <input type="text" placeholder="Filter..." onInput={this.onFilterTextBoxChanged}/>
          <AgGridReact
            domLayout='autoHeight'
            columnDefs={this.state.columnDefs}
            defaultColDef={this.state.defaultColDef}
            getRowHeight={this.state.getRowHeight}
            rowData={this.state.rowData}>
          </AgGridReact>

    );
  }
}

export default ListTableClients;