问:
How to save image in django media root storage from python
I'm trying to save my images to the media root folder which I've named pictures in the media folder. This is my code and I want whenever my function is making the screenshot it should save the screenshots in my media root folder.

```<code>from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404,render,redirect
import time
import random
from django.db import models
import pyautogui
import sys
from shots.models import pictures
from .models import pictures
from shots.forms.forms import DocumentForm

def button(request):
    import pyautogui
    myScreenshot = pyautogui.screenshot()
    storage=pictures.pictures2
    myScreenshot.save(storage)

    return render(request,'index.html')

def output(request):
    return HttpResponse("""Hello, world. You're at the polls index.
    your Screenshot should start now""")
</code>```

This is my models.py:

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

class pictures(models.Model):
    pub_date = models.DateTimeField('date published')
    pictures2 = models.ImageField(upload_to='pictures')
</code>```

答:
You will find this answer helpful.

The files for FileField and ImageField are uploaded relative to settings.MEDIA_ROOT and should be accessible by the same relative filename appended to settings.MEDIA_URL.

That being said, if you named your settings.MEDIA_ROOT = 'pictures' and you are telling your models to upload_to='pictures' So files uploaded by django will end up in:

**/pictures/pictures/myScreenshot.png**
```

<pre class="lang-python prettyprint-override"><code>import pyautogui

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

from .models import pictures

def button(request):
    myScreenshot = pyautogui.screenshot()

    """
    The path and filename are relative o where you execute this script.
    """
    filename = settings.MEDIA_ROOT+'pictures/myScreenshot.png'
    myScreenshot.save(filename)

    return render(request,'index.html')
</code>```

Your models.py:

from django.db import models
import random

class pictures(models.Model):
    pub_date = models.DateTimeField('date published')
    pictures2 = models.ImageField(upload_to='pictures')
```

Body:
I'm trying to save my images to the media root folder which I've named pictures in the media folder. This is my code and I want whenever my function is making the screenshot it should save the screenshots in my media root folder.

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404,render,redirect
import time
import random
from django.db import models
import pyautogui
import sys
from shots.models import pictures
from .models import pictures
from shots.forms.forms import DocumentForm

def button(request):
    import pyautogui
    myScreenshot = pyautogui.screenshot()
    storage=pictures.pictures2
    myScreenshot.save(storage)

    return render(request,'index.html')

def output(request):
    return HttpResponse("""Hello, world. You're at the polls index.
    your Screenshot should start now""")

This is my models.py:

from django.db import models
import random

class pictures(models.Model):
    pub_date = models.DateTimeField('date published')
    pictures2 = models.ImageField(upload_to='pictures')

Body:
You will find this answer helpful.

The files for FileField and ImageField are uploaded relative to settings.MEDIA_ROOT and should be accessible by the same relative filename appended to settings.MEDIA_URL.

That being said, if you named your settings.MEDIA_ROOT = 'pictures' and you are telling your models to upload_to='pictures' So files uploaded by django will end up in:

**/pictures/pictures/myScreenshot.png**

import pyautogui

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

from .models import pictures

def button(request):
    myScreenshot = pyautogui.screenshot()

    """
    The path and filename are relative o where you execute this script.
    """
    filename = settings.MEDIA_ROOT+'pictures/myScreenshot.png'
    myScreenshot.save(filename)

    return render(request,'index.html')

Your models.py:

from django.db import models
import random

class pictures(models.Model):
    pub_date = models.DateTimeField('date published')
    pictures2 = models.ImageField(upload_to='pictures')


来源: stackexchange

问:
How to allow only a specific user to push commits to master branch
I'm trying to setup a git server and I want to allow only a specific user to push commits to master branch.

I have tried to use the Linux group permission setting to meet the requirement above but it seems not a correct way.

And I even don't know what are the key words for searching the answer for this.

Any help would be appreciated.

答:
You have two options:

By far the easiest solution is to use hosting software that already provides this functionality.  You might want to look at GitLab, which has free options for both SaaS (hosted at gitlab.com) and self-managed instances (running your own gitlab instance).  Or github.  Or bitbucket.  Or I'm sure there are others I'm not thinking of.

If you really don't want to use any of those, you can implement access control on a simple git server, but it's not so simple.  The short (or rather, glib) answer is "hooks" - but a hook is just a script that runs when something happens - like in this case you'd use the prereceive hook, which runs when someone's trying to push and decides whether to accept the push.  Now, how does your hook know who is pushing?  (The commit metadata does not indicate who's pushing.  What you need is authentication around the actual connection, and visibility of the authentication in your script so that the script may implement your authorization rules.  That very quickly breaks down into "it depends on your environment".)

Since it's not really possible to exhaustively cover every scenario for doing this manually, hopefully either you'll find a pre-packaged solution you like, or you'll find the above to be enough to get you pointed in the right direction to do it manually.

ContentLicense: CC BY-SA 4.0


问:
flask not responding with template
I am running a flask server in testing but the render_template() method is not responding

Here is my app.py

```<code>from flask import Flask, render_template, jsonify, request
from feeders import feeder

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def feed():
    if request.method == "GET":
        data = feeder.all_feed()
        return render_template("feed.html", allfeed=data)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

</code>```

I am using ThreadPoolExecutor for some of my tasks, here is how the all_feed() method looks like.

```<code>def all_feed():
    with ThreadPoolExecutor(max_workers=7) as executor:
        results = list(executor.map(get_feed, feeder_site_urls.values()))

    print(results)

    return results
</code>```

I can see results on the terminal but the template is not rendering.
And yes all my templates are under templates/.
Edit: I can see that the flask is consuming memory (gradually increasing)

答:
Apparently there was a bug in one of my templates
Always remember to run in DEBUG Mode.
Also create a .flaskenv file with following contents

```<code>FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_PORT=8000
FLASK_RUN_HOST=0.0.0.0
</code>```

Thanks to one of my friend

Title: flask not responding with template

Body:
I am running a flask server in testing but the render_template() method is not responding

Here is my app.py

from flask import Flask, render_template, jsonify, request
from feeders import feeder

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def feed():
    if request.method == "GET":
        data = feeder.all_feed()
        return render_template("feed.html", allfeed=data)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

I am using ThreadPoolExecutor for some of my tasks, here is how the all_feed() method looks like.

def all_feed():
    with ThreadPoolExecutor(max_workers=7) as executor:
        results = list(executor.map(get_feed, feeder_site_urls.values()))

    print(results)

    return results

I can see results on the terminal but the template is not rendering.
And yes all my templates are under templates/.
Edit: I can see that the flask is consuming memory (gradually increasing)

Body:
Apparently there was a bug in one of my templates
Always remember to run in DEBUG Mode.
Also create a .flaskenv file with following contents

FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_PORT=8000
FLASK_RUN_HOST=0.0.0.0

Thanks to one of my friend


问:
svg interfering with the button
I use a svg in the background of my page, but this svg is interfering with the style of a button. The button should be all green, but the svg lines are appearing inside the button.
The svg and the button are in separate divs.
I've tried using z-index to throw svg behind all components, but it didn't work.

How the button looks:

How the button should look:

HTML code:

```<code>export default function LoginPage() {
  return (
    <Container>
      <PositionLoginImage>
        <Login color="#fff" />
      </PositionLoginImage>
      <Content>
        <CardLogin>
          <PositionLogo>
            <Logo color={theme.colors.marketplace} />
          </PositionLogo>
          <PositionInputUser>
            <p>Usuário</p>
            <Input>
              <span>
                <IconUsers color={theme.colors.marketplace} />
              </span>
              <input type="text" placeholder="Usuário" />
            </Input>
          </PositionInputUser>
          <PositionInputPassword>
            <p>Senha</p>
            <Input>
              <span>
                <IconKey color={theme.colors.marketplace} />
              </span>
              <input type="password" placeholder="Senha" />
            </Input>
          </PositionInputPassword>
          <PositionButton>
            <Link to="/dashboard">
              <Button>Entrar</Button>
            </Link>
          </PositionButton>
        </CardLogin>
      </Content>
    </Container>
  );
}
</code>```

CSS:

```<code>const Container = styled.div`
  min-height: 100vh;
  background-color: ${props => props.theme.colors.marketplace};
  display: flex;
  align-items: center;
  justify-content: center;
`;

const Content = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
`;

const PositionLoginImage = styled.div`
  position: absolute;
  top: 147px;
  left: -0.00048828125px;

  svg {
    width: 100vw;
    height: 40vw;
  }
`;

const PositionLogo = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40px;
`;

const CardLogin = styled.div`
  width: 581px;
  height: 722px;
  background: #fff;
  box-shadow: 0px 4px 16px #455b630f;
  border-radius: 10px;
`;

const PositionInputUser = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionInputPassword = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 35px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionButton = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;
`;

export const Button = styled.button`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding-top: 4px;
  padding-left: 15px;
  padding-right: 15px;
  width: 206px;
  height: 54px;
  border-radius: 10px;
  border: 1px solid ${props => props.theme.colors.marketplace};
  background-color: ${props => props.theme.colors.marketplace};

  font-size: 18px;
  line-height: 22px;
  color: #fff;
`;

export const Input = styled.div`
  display: grid;
  grid-template-columns: 64px 1fr;
  width: 445px;
  height: 55px;
  border-radius: 10px;

  span {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
  }

  input {
    background-color: #f8f8f8;
  }

  input::-webkit-input-placeholder {
    color: ${props => props.theme.colors.primary};
    opacity: 0.3;
  }
`;
</code>```

答:
I added a position: relative; in the Content div and it worked.

Code:

```<code>const Content = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
`;
</code>```

Title: svg interfering with the button

Body:
I use a svg in the background of my page, but this svg is interfering with the style of a button. The button should be all green, but the svg lines are appearing inside the button.
The svg and the button are in separate divs.
I've tried using z-index to throw svg behind all components, but it didn't work.

How the button looks:

How the button should look:

HTML code:

export default function LoginPage() {
  return (
    <Container>
      <PositionLoginImage>
        <Login color="#fff" />
      </PositionLoginImage>
      <Content>
        <CardLogin>
          <PositionLogo>
            <Logo color={theme.colors.marketplace} />
          </PositionLogo>
          <PositionInputUser>

Usuário

            <Input>

                <IconUsers color={theme.colors.marketplace} />

              <input type="text" placeholder="Usuário" />
            </Input>
          </PositionInputUser>
          <PositionInputPassword>

Senha

            <Input>

                <IconKey color={theme.colors.marketplace} />

              <input type="password" placeholder="Senha" />
            </Input>
          </PositionInputPassword>
          <PositionButton>
            <Link to="/dashboard">
              <Button>Entrar</Button>
            </Link>
          </PositionButton>
        </CardLogin>
      </Content>
    </Container>
  );
}

CSS:

const Container = styled.div`
  min-height: 100vh;
  background-color: ${props => props.theme.colors.marketplace};
  display: flex;
  align-items: center;
  justify-content: center;
`;

const Content = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
`;

const PositionLoginImage = styled.div`
  position: absolute;
  top: 147px;
  left: -0.00048828125px;

  svg {
    width: 100vw;
    height: 40vw;
  }
`;

const PositionLogo = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40px;
`;

const CardLogin = styled.div`
  width: 581px;
  height: 722px;
  background: #fff;
  box-shadow: 0px 4px 16px #455b630f;
  border-radius: 10px;
`;

const PositionInputUser = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionInputPassword = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 35px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionButton = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;
`;

export const Button = styled.button`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding-top: 4px;
  padding-left: 15px;
  padding-right: 15px;
  width: 206px;
  height: 54px;
  border-radius: 10px;
  border: 1px solid ${props => props.theme.colors.marketplace};
  background-color: ${props => props.theme.colors.marketplace};

  font-size: 18px;
  line-height: 22px;
  color: #fff;
`;

export const Input = styled.div`
  display: grid;
  grid-template-columns: 64px 1fr;
  width: 445px;
  height: 55px;
  border-radius: 10px;

  span {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
  }

  input {
    background-color: #f8f8f8;
  }

  input::-webkit-input-placeholder {
    color: ${props => props.theme.colors.primary};
    opacity: 0.3;
  }
`;

Body:
I added a position: relative; in the Content div and it worked.

Code:

const Content = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
`;


问:
Eclipse complying "Unresolved generator name" but all works fine
I use a hibernate @GenericGenerator(name="myGenerator") to setup a generator and use it with @GeneratedValue(generator = "myGenerator").

The application runs fine, but Eclipse reports an error of 'Unresolved generator name "myGenerator"'.

Is there either a way to disable this error check or to configure the project so that it recognized the "MySeq" generator?

PREVIOUS ENVIRONMENT:

Windows + Java5 + Eclipse = No additional config for this bug

ACTUAL ENVIRONMENT:

Linux + Java5 + Eclipse -
I'm using Linux+Eclipse now on my environment and in all GenericGenerator of my classes start to bug me up.

I don't know if this is due to my change of environment or Eclipse version.

Thanks in advance for any tip provided.

答: The answer to your question is quite simple. The error is caused by the built-in Java Persistence Validator. In order to prevent Eclipse showing the error you just have to set the validation level for "Unresolved generator name" to warning or lower. See "Java Persistence - Errors/Warnings - Queries and generators" in Eclipse preferences dialogue.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Finding Path (like Dijkstra) in Relation with SQL
i'm quite new to SQL so here's my question:

Let's assume we have a Table T with columns A and B

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

Now there is a path between A and B. I'll just call them nodes for now. You can get from node A to B but not from B to A unless there is are rows like:

```<code>1 | 2
2 | 1
</code>```

But in our example we don't have any circles.

My goal is to find the ends of a path starting in 1.
I used recursion query like:

```<code>with rec (start, end)  as (
    (select A, B
    from T
    where A = '1')
    union all
    ( select A, B
     from T, rec
     where T.A = re.end
    )
)
</code>```

which result in rec output (select * from rec)looking like this:

```<code>1 | 2
2 | 3
3 | 5
3 | 8
</code>```

I'm struggling to retrieve start and ends only from this output

smth like

```<code>1 | 5,8
</code>```

Can someone help?
If I can retrieve start and end, I won't need the recursion cause I'm only interested in these Nodes (not the path)

//edited, now more accurate

答:
Provided no circle exists, using Sql Server 2017

```<code>with rec (root, start, [end])  as (
    (select A root, A , B
    from T
    where A = '1')
    union all
    ( select root, A, B
     from T
     join rec ON T.A = rec.[end]
    )
)
select root A, string_agg([end], ',') B
from rec
where not exists (select 1 from T where T.A = rec.[end])
group by root;
</code>```

When using another DBMS use different string aggregation, all the rest should work as is.

Db fiddle

Body:
i'm quite new to SQL so here's my question:

Let's assume we have a Table T with columns A and B

A | B
1 | 2
2 | 3
4 | 6
3 | 5
3 | 8
7 | 8

Now there is a path between A and B. I'll just call them nodes for now. You can get from node A to B but not from B to A unless there is are rows like:

1 | 2
2 | 1

But in our example we don't have any circles.

My goal is to find the ends of a path starting in 1.
I used recursion query like:

with rec (start, end)  as (
    (select A, B
    from T
    where A = '1')
    union all
    ( select A, B
     from T, rec
     where T.A = re.end
    )
)

which result in rec output (select * from rec)looking like this:

1 | 2
2 | 3
3 | 5
3 | 8

I'm struggling to retrieve start and ends only from this output

smth like

1 | 5,8

Can someone help?
If I can retrieve start and end, I won't need the recursion cause I'm only interested in these Nodes (not the path)

//edited, now more accurate

Body:
Provided no circle exists, using Sql Server 2017

with rec (root, start, [end])  as (
    (select A root, A , B
    from T
    where A = '1')
    union all
    ( select root, A, B
     from T
     join rec ON T.A = rec.[end]
    )
)
select root A, string_agg([end], ',') B
from rec
where not exists (select 1 from T where T.A = rec.[end])
group by root;

When using another DBMS use different string aggregation, all the rest should work as is.

Db fiddle


问:
Update data using sequelize
I'm working on a Reactjs project. There is login/register forms after login I am able to display the user's data in an Account page.

On the Account page the user will be able to update the data he filled in when he signed up.

The form contains :

First name

Last name

Email

Phone

Delivery address

I want to update the data using the Reactjs form.

My code

Front

```<code>class Account extends Component {
  constructor() {
    super();
    this.state = {
      first_name: "",
      last_name: "",
      email: "",
      phone: "",
      deliveryAddress: "",
      errors: {}
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

  handleSubmit(e) {
    e.preventDefault();

    const { first_name, last_name, email, phone, deliveryAddress } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    const json = JSON.stringify(body);
    console.log(json);

    axios.put("http://localhost:5000/users/:id", json).then(res => {
      console.log(res);
    });
  }
</code>```

UserController.ts

```<code>export const updateUser = (req, res) => {
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: req.body.id
      }
    }
  ).then(user => {
    res.json(user);
  });
};
</code>```

I think my issue is in my where attribute because when I click on the Save Button I got : Executing (default): UPDATE users SET updatedAt='2020-02-18 14:30:03' WHERE id = NULL and nothing happens, nothing is updated.

EDIT

UserController.ts

```<code>export const updateUser = (req, res) => {
  const id = req.params.id;
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: id
      }
    }
  ).then(user => {
    if (user == 1) {
      res.send({
        message: "User was updated successfully"
      });
    } else {
      res.send({
        message: `Cannot update User with id=${id}. Maybe User was not found or req.body is empty!`
      });
    }
  });
};
</code>```

When I use Postman and the request PUT on http://localhost:5000/users/10 I correctly update the user. My issue is that I can't get the id if I use my Reactjs code.

EDIT 2

I added the id in the state and in the componentDidMount() function as follows :

```<code>  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      id: decoded.id,
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const {
      id,
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    const json = JSON.stringify(body);
    console.log(json);

    axios.put(`http://localhost:5000/users/${id}`, json).then(res => {
      console.log(res);
    });
  }
</code>```

I'm now able to get the current id : Executing (default): UPDATE users SET updatedAt='2020-02-19 08:48:57' WHERE id = '15' but nothing happens because the first_name field is not modified like I do with Postman : Executing (default): UPDATE users SET first_name='Quentin',updatedAt='2020-02-19 08:50:57' WHERE id = '15'

答:
You're not sending an id field from the app, so you cannot do

```<code>where: {
  id: req.body.id
}
</code>```

You can either make sure you save the id locally too and send it so your API endpoint can use it or you can do an upsert instead.

Another option is to find the user by email instead of ID:

```<code>where: {
  email: req.body.email
}
</code>```

You would have to make sure to not allow your user to change their email from this page. Or, you can even add another field called oldEmail if you really need that.

EDIT: After seeing your new edit and more code, I believe I see the issue, you're not sending the ID correctly from React. You're doing:

```<code>axios.put("http://localhost:5000/users/:id", json).then(res => {
</code>```

When you should really be doing the following:

```<code>axios.put(`http://localhost:5000/users/${this.state.id}`, json).then(res => {
</code>```

Assuming you have the id field in your state and that it's an existing user.

Title: Update data using sequelize

Body:
I'm working on a Reactjs project. There is login/register forms after login I am able to display the user's data in an Account page.

On the Account page the user will be able to update the data he filled in when he signed up.

The form contains :

First name

Last name

Email

Phone

Delivery address

I want to update the data using the Reactjs form.

My code

Front

class Account extends Component {
  constructor() {
    super();
    this.state = {
      first_name: "",
      last_name: "",
      email: "",
      phone: "",
      deliveryAddress: "",
      errors: {}
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

  handleSubmit(e) {
    e.preventDefault();

    const { first_name, last_name, email, phone, deliveryAddress } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    const json = JSON.stringify(body);
    console.log(json);

    axios.put("http://localhost:5000/users/:id", json).then(res => {
      console.log(res);
    });
  }

UserController.ts

export const updateUser = (req, res) => {
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: req.body.id
      }
    }
  ).then(user => {
    res.json(user);
  });
};

I think my issue is in my where attribute because when I click on the Save Button I got : Executing (default): UPDATE users SET updatedAt='2020-02-18 14:30:03' WHERE id = NULL and nothing happens, nothing is updated.

EDIT

UserController.ts

export const updateUser = (req, res) => {
  const id = req.params.id;
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: id
      }
    }
  ).then(user => {
    if (user == 1) {
      res.send({
        message: "User was updated successfully"
      });
    } else {
      res.send({
        message: `Cannot update User with id=${id}. Maybe User was not found or req.body is empty!`
      });
    }
  });
};

When I use Postman and the request PUT on http://localhost:5000/users/10 I correctly update the user. My issue is that I can't get the id if I use my Reactjs code.

EDIT 2

I added the id in the state and in the componentDidMount() function as follows :

  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      id: decoded.id,
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const {
      id,
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    const json = JSON.stringify(body);
    console.log(json);

    axios.put(`http://localhost:5000/users/${id}`, json).then(res => {
      console.log(res);
    });
  }

I'm now able to get the current id : Executing (default): UPDATE users SET updatedAt='2020-02-19 08:48:57' WHERE id = '15' but nothing happens because the first_name field is not modified like I do with Postman : Executing (default): UPDATE users SET first_name='Quentin',updatedAt='2020-02-19 08:50:57' WHERE id = '15'

Body:
You're not sending an id field from the app, so you cannot do

where: {
  id: req.body.id
}

You can either make sure you save the id locally too and send it so your API endpoint can use it or you can do an upsert instead.

Another option is to find the user by email instead of ID:

where: {
  email: req.body.email
}

You would have to make sure to not allow your user to change their email from this page. Or, you can even add another field called oldEmail if you really need that.

EDIT: After seeing your new edit and more code, I believe I see the issue, you're not sending the ID correctly from React. You're doing:

axios.put("http://localhost:5000/users/:id", json).then(res => {

When you should really be doing the following:

axios.put(`http://localhost:5000/users/${this.state.id}`, json).then(res => {

Assuming you have the id field in your state and that it's an existing user.


问:
how to select distinct values from 2 tables in sql
table1

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

table2

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

I want to result in this way:

```<code>id
1
2
3
6
7
8
</code>```

答:
This might run faster than the solution by GMB.</p>

```<code>select table1.id
from table1 left join table2 on table1.id = table2.id
where table2.id IS NULL
union all
select table2.id
from table2 left join table1 on table1.id = table2.id
where table1.id IS NULL
</code>```

Body:
table1

id
1
2
3
4
5

table2

id
4
5
6
7
8

I want to result in this way:

id
1
2
3
6
7
8

Body:
This might run faster than the solution by GMB.

select table1.id
from table1 left join table2 on table1.id = table2.id
where table2.id IS NULL
union all
select table2.id
from table2 left join table1 on table1.id = table2.id
where table1.id IS NULL


Title: convert values in text file to array in python

Body:
I have a text file data.txt which looks as such:

ADMAS      8.046E+03 8.206E-03 1.532E+04 1.066E-01 6.982E+06-2.820E+00 \n
ADMAS     -6.868E-03 2.009E+05 1.454E-02 9.516E+05-1.209E+00 6.058E+06 \n
ADMAS      1.543E+04 9.179E-01 1.459E+06 5.463E+00 3.918E+07-2.904E+01 \n
ADMAS     -2.267E-01 9.537E+05 3.902E+00 3.071E+07-1.344E+02 1.073E+08 \n
ADMAS      7.005E+06 2.260E+01 3.978E+07 6.296E+01 7.586E+09-2.125E+03 \n
ADMAS      1.093E+00 6.052E+06-6.178E+00 1.065E+08-1.416E+03 1.941E+09 \n
FAMP       3.824E+03 7.120E-02 1.848E+05 7.317E-01 5.406E+06 4.096E+00 \n
FEPS       9.039E+01 3.571E+02 2.838E+00 3.580E+02 4.098E+01 1.892E+02 \n

(etc. In a recurring pattern). I want to have only the ADMAS values and put them in a 6x6 array.
I tried the following:

filename = "data.txt"
string_fnd_1 = "ADMAS"
textfile = open(filename, 'r')
file_lines = textfile.readlines()
textfile.close()
matches_admas = [line for line in file_lines if string_fnd_1 in line]

I get the following:

['ADMAS      8.046E+03 8.206E-03 1.532E+04 1.066E-01 6.982E+06-2.820E+00\n', 'ADMAS     -6.868E-03 2.009E+05 1.454E-02 9.516E+05-1.209E+00 6.058E+06\n',....]

Now, I want to get rid of the string "ADMAS", convert the values to float and reshape into a 6x6 array. Does someone know how to do this? Help would be appreciated.

Body:
According to your requirements, I came up with the following solution:

import re
filename = "data.txt"
string_fnd_1 = "ADMAS"

matrix = [] # 6x6 matrix of dtype float
with open(filename, "r") as f:
    for line in f:
        if string_fnd_1 in line:
            # cleaning the bad chars in line
            line = line.strip()
            line = line.strip(" \\n")
            line = re.sub(r"ADMAS\s*", "", line)
            line = re.sub(r"(-[0-9]+\.)", r" \1", line)

            values = [float(value) for value in line.split()]
            matrix.append(values)

And output will be:

[
[8046.0, 0.008206, 15320.0, 0.1066, 6982000.0, -2.82],
[-0.006868, 200900.0, 0.01454, 951600.0, -1.209, 6058000.0],
[15430.0, 0.9179, 1459000.0, 5.463, 39180000.0, -29.04],
[-0.2267, 953700.0, 3.902, 30710000.0, -134.4, 107300000.0],
[7005000.0, 22.6, 39780000.0, 62.96, 7586000000.0, -2125.0],
[1.093, 6052000.0, -6.178, 106500000.0, -1416.0, 1941000000.0]
]

Hope it addresses your problem!


问:
inline meaning in module interfaces
Consider the header file:

```<code>class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept : ID(ID_) {}

  int GetID() const noexcept { return ID; }
};
</code>```

or, alternatively:

```<code>class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept;

  int GetID() const noexcept;
};

inline T::T(int const ID_) noexcept : ID(ID_) {}

inline int T::GetID() const noexcept { return ID; }
</code>```

In a pre-modules world, these headers might be textually included in multiple TU without ODR violations. Furthermore, since the involved member functions are relatively small, the compiler would likely "inline" (avoid function calls when using) those functions, or even optimize away some instances of T altogether.

In a recent report on the meeting where C++20 was finished, I could read the following statement:

We clarified the meaning of inline in module interfaces: the intent is that bodies of functions that are not explicitly declared inline are not part of the ABI of a module, even if those function bodies appear in the module interface. In order to give module authors more control over their ABI, member functions defined in class bodies in module interfaces are no longer implicitly inline.

I'm not sure I'm not mistaken that. Does that mean that, in a modules world, for the compiler to be able to optimize away function calls we have to annotate them as inline even if they are defined in-class?

If so, would the following module interface be equivalent to the headers above?

```<code>export module M;

export
class T
{
private:
  int const ID;

public:
  inline explicit T(int const ID_) noexcept : ID(ID_) {}

  inline int GetID() const noexcept { return ID; }
};
</code>```

Even though I still don't have a compiler with modules support, I would like to start using inline like so when appropriate, to minimize future refactoring.

答:
Does that mean that, in a modules world, for the compiler to be able to optimize away function calls we have to annotate them as inline even if they are defined in-class?

To some degree.

Inlining is an "as if" optimization, and inlining can happen even between translation units if the compiler is clever enough.

That being said, inlining is easiest when working within a single translation unit. Thus, to promote easy inlining, an inline-declared function has to have its definition provided in any translation unit where it is used. This doesn't mean the compiler will certainly inline it (or certainly not inline any non-inline-qualified function), but it does make things a lot easier on the inlining process, since the inlining is happening within a TU rather than between them.

Class member definitions defined within a class, in a pre-module world, are declared inline implicitly. Why? Because the definition is within the class. In a pre-module world, class definitions that are shared among TUs are shared by textual inclusion. Members defined in a class would therefore be defined in the header shared among those TUs. So if multiple TUs use the same class, those multiple TUs are doing so by including the class definition and the definition of its members declared in the header.

That is, you're including the definition anyway, so why not make it inline?

Of course, this means that the definition of a function is now a part of the class's text. If you change the definition of a member declared in a header, this forces the recompilation of every file that includes that header, recursively. Even if the class's interface itself isn't changing, you still need to do a recompile. So making such functions implicitly inline doesn't change this, so you may as well do that.

To avoid this in a pre-module world, you can simply define the member in the C++ file, which won't get included in other files. You lose easy inlining, but you gain compile-time.

But here's the thing: this is an artifact of using textual inclusion as a means to deliver a class to multiple places.

In a modular world, you would probably want to define each member function within the class itself, as we see in other languages like Java, C#, Python, and the like. This keeps code locality reasonable, and it prevents having to re-type the same function signature, thus serving the needs of DRY.

But if all members are defined within the class definition, then under the old rules, all of those members would be inline. And in order for a module to allow a function to be inline, the binary module artifact would have to include the definition of those functions. Which means that any time you change even one line of code in such a function definition, the module will have to be built, along with every module depending on it, recursively.

Removing implicit-inline in modules gives users the same powers they had in the textual inclusion days, without having to move the definition out of the class. You can pick which function definitions are part of the module and which ones are not.

Title: inline meaning in module interfaces

Body:
Consider the header file:

class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept : ID(ID_) {}

  int GetID() const noexcept { return ID; }
};

or, alternatively:

class T
{
private:
  int const ID;

public:
  explicit T(int const ID_) noexcept;

  int GetID() const noexcept;
};

inline T::T(int const ID_) noexcept : ID(ID_) {}

inline int T::GetID() const noexcept { return ID; }

In a pre-modules world, these headers might be textually included in multiple TU without ODR violations. Furthermore, since the involved member functions are relatively small, the compiler would likely "inline" (avoid function calls when using) those functions, or even optimize away some instances of T altogether.

In a recent report on the meeting where C++20 was finished, I could read the following statement:

We clarified the meaning of inline in module interfaces: the intent is that bodies of functions that are not explicitly declared inline are not part of the ABI of a module, even if those function bodies appear in the module interface. In order to give module authors more control over their ABI, member functions defined in class bodies in module interfaces are no longer implicitly inline.

I'm not sure I'm not mistaken that. Does that mean that, in a modules world, for the compiler to be able to optimize away function calls we have to annotate them as inline even if they are defined in-class?

If so, would the following module interface be equivalent to the headers above?

export module M;

export
class T
{
private:
  int const ID;

public:
  inline explicit T(int const ID_) noexcept : ID(ID_) {}

  inline int GetID() const noexcept { return ID; }
};

Even though I still don't have a compiler with modules support, I would like to start using inline like so when appropriate, to minimize future refactoring.


问:
Re-render sibling on selection or a better?
I am kind of new to react & TypeScript.

I am trying to modify some functionality but having hard time doing that.

Currently we show all the subscriptions and all the transactions on the same page instead what I want to do is that based on the subscription selection i want show all the transactions (Currently both subscriptions and transactions are siblings).

I have created an on click event on subscription which is calling handleViewTransaction

The problem is that I am not able to re-render TransactionsTable from the handleViewTransaction.

Do I need to make it parent-child or there is a way to achieve it without much code refactoring?

```<code>import * as React from 'react'
import {RouteComponentProps} from 'react-router-dom'
import * as _ from 'lodash'
import * as cx from 'classnames'
import {Accordion, AccordionItem} from 'react-light-accordion'
import * as dcbApi from '../../../components/dcbApi'
import {Page} from '../../components/page'
import {Loader} from '../../components/loader'
import {Modal} from '../../components/modal'
import {SubscriptionStore, SubscriptionStoreState, useSubscriptionStore} from '../../../stores/subscription'
import {TransactionsTable} from '../../components/tables/transactions'
import {SubscriptionsTable} from '../../components/tables/subscriptions'
import {TransactionsPage} from './transactions'
import {BokuSubscription, BokuTransaction} from '../../../types'

export interface ResultPageProps extends RouteComponentProps<{}> {
    userId?: string
    subscriptions?: BokuSubscription[]
    transactions?: BokuTransaction[]
    isLoading?: boolean
    onRefetch?: () => any
}

export const ResultPage = ({ isLoading: isLoadingParent, history, userId, subscriptions, transactions, onRefetch }: ResultPageProps) => {
    const [isLoading, setIsLoading] = React.useState(false);
    const [subscriptionCancellationSent, setSubscriptionCancellationSent] = React.useState(false);
    const [transactionCancellationSent, setTransactionCancellationSent] = React.useState(false);
    const [selectedTransaction, setSelectedTransaction] = React.useState(null);
    const hasTransactions = false;
    const navigateHome = () =>
        history.push('/');

    const handleViewTransaction = async (daznUserId: string, subscriptionId: string, aggregator: string) => {
        // TODO: Show subscription specific transactions
    };

    const handleSubsctiptionCancel = async (userId: string, subscriptionId: string) => {
        try {
            setIsLoading(true);
            const response = await dcbApi.cancelSubscription(userId, 'boku', subscriptionId);
            setIsLoading(false);
            setSubscriptionCancellationSent(true);
            Modal.info({
                title: `Your cancellation request has been submited for ${userId}`,
                okText: 'OK',
                content: (
                    <div>
                        <span>Transaction Id:</span> {response.transactionId}<br/>
                        <span>Subscription Id:</span> {response.subscriptionId}<br/>
                        <span>Aggregator:</span> {response.aggregator}<br/>
                        <span>Status:</span> {response.status}<br/>
                    </div>
                ),
            })
            //this.setState({ cancellationSent: true })
        } catch (err) {
            setIsLoading(false);
            console.error(err);
            Modal.info({
                title: `Your cancellation request for ${userId} has failed`,
                okText: 'OK',
                content: (
                    <div>
                        {_.get(err, 'message') && <div>Error message: {err.message}</div>}
                        <Accordion atomic={true}>
                            <AccordionItem title='Toggle detailed error'>
                                ```{JSON.stringify(err, null, 2)}```
                            </AccordionItem>
                        </Accordion>
                    </div>
                ),
            })
        } finally {
            if (typeof onRefetch === 'function') {
                onRefetch()
            }
        }
    };

    const handleChargeRefund = async (userId: string, chargeId: string, reasonCode: number) => {
        try {
            setIsLoading(true);
            const response = await dcbApi.refund(userId, 'boku', chargeId, reasonCode)
            setIsLoading(false);
            setTransactionCancellationSent(true);
            Modal.info({
                title: `Your refund request has been submited`,
                okText: 'OK',
                content: (
                    <div>
                        <span>Charge Id:</span> {response.chargeId}<br/>
                        <span>Country:</span> {response.country}<br/>
                        <span>Refund status:</span> {response.refundStatus}<br/>
                        <span>Refund Id:</span> {response.refundId}<br/>
                    </div>
                ),
            })
            //this.setState({ cancellationSent: true })
        } catch (err) {
            setIsLoading(false);
            console.error(err);
            Modal.info({
                title: `Your refund request has failed`,
                okText: 'OK',
                content: (
                    <div>
                        {_.get(err, 'message') && <div>Error message: {err.message}</div>}
                        <Accordion atomic={true}>
                            <AccordionItem title='Toggle detailed error'>
                                ```{JSON.stringify(err, null, 2)}```
                            </AccordionItem>
                        </Accordion>
                    </div>
                ),
            })
        } finally {
            if (typeof onRefetch === 'function') {
                onRefetch()
            }
        }
    };

    return (
        <Page
            theme='dark' // light|dark
            title='Back to home'
            onLogoClick={navigateHome}
            onTitleClick={navigateHome}
            overlay={(!isLoading && !isLoadingParent) ? undefined :
                <div style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    background: 'rgba(130,131,134,.34)'
                }}>
                    <div style={{
                        textAlign: 'center',
                        position: 'relative',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%,-50%)'
                    }}>
                        <Loader/><br/><br/>
                        <span style={{
                            color: 'white',
                            fontSize: 22,
                            fontFamily: 'Trim',
                            textAlign: 'center'
                        }}>Loading</span>
                    </div>
                </div>}
        >
            <div style={{width: '100%'}}>
                <div
                    style={{
                        textAlign: 'center',
                        marginBottom: 24,
                        fontFamily: 'Trim',
                        fontWeight: 500,
                        fontSize: '26px'
                    }}
                >Subscription statuses for user: {userId}</div>
                <SubscriptionsTable
                    userId={userId}
                    data={subscriptions}
                    cancellationSent={subscriptionCancellationSent}
                    onCancelSubscription={handleSubsctiptionCancel}
                    onViewTransaction={handleViewTransaction}
                />
                <div id="transactions">
                    <div
                        style={{
                            textAlign: 'center',
                            marginTop: 24,
                            marginBottom: 24,
                            fontFamily: 'Trim',
                            fontWeight: 500,
                            fontSize: '26px',
                        }}
                    >
                        {hasTransactions ?
                            `Transactions for user: ${userId}` :
                            <i>This user does not have transactions linked to their subscription</i>}
                    </div>
                    {hasTransactions &&

                    <TransactionsTable
                        userId={userId}
                        data={transactions}
                        cancellationSent={transactionCancellationSent}
                        onRefundCharge={handleChargeRefund}
                    />}
                </div>
            </div>
        </Page>
    )
};

</code>```

答:
What if you add a filtered state inside ResultPage and pass this to TransactionsTable? handleViewTransaction will do the filtering depending on subscriptionId. Some "pseudo code":

First, set default with all transactions.

```<code>const [filteredTransactions, setFilteredTransactions] = useState(transactions);
</code>```

In the handleViewTransactions, do something like:

```<code>const filteredData = transactions.filter((item) => item.subscriptionId === subscriptionId);
setFilteredTransactions(filteredData);
</code>```

The TransactionsTable component will use the filtered transactions instead:

```<code><TransactionsTable
    ...
    data={filteredTransactions}
    ...
/>
</code>```

Body:
I am kind of new to react & TypeScript.

I am trying to modify some functionality but having hard time doing that.

Currently we show all the subscriptions and all the transactions on the same page instead what I want to do is that based on the subscription selection i want show all the transactions (Currently both subscriptions and transactions are siblings).

I have created an on click event on subscription which is calling handleViewTransaction

The problem is that I am not able to re-render TransactionsTable from the handleViewTransaction.

Do I need to make it parent-child or there is a way to achieve it without much code refactoring?

import * as React from 'react'
import {RouteComponentProps} from 'react-router-dom'
import * as _ from 'lodash'
import * as cx from 'classnames'
import {Accordion, AccordionItem} from 'react-light-accordion'
import * as dcbApi from '../../../components/dcbApi'
import {Page} from '../../components/page'
import {Loader} from '../../components/loader'
import {Modal} from '../../components/modal'
import {SubscriptionStore, SubscriptionStoreState, useSubscriptionStore} from '../../../stores/subscription'
import {TransactionsTable} from '../../components/tables/transactions'
import {SubscriptionsTable} from '../../components/tables/subscriptions'
import {TransactionsPage} from './transactions'
import {BokuSubscription, BokuTransaction} from '../../../types'

export interface ResultPageProps extends RouteComponentProps<{}> {
    userId?: string
    subscriptions?: BokuSubscription[]
    transactions?: BokuTransaction[]
    isLoading?: boolean
    onRefetch?: () => any
}

export const ResultPage = ({ isLoading: isLoadingParent, history, userId, subscriptions, transactions, onRefetch }: ResultPageProps) => {
    const [isLoading, setIsLoading] = React.useState(false);
    const [subscriptionCancellationSent, setSubscriptionCancellationSent] = React.useState(false);
    const [transactionCancellationSent, setTransactionCancellationSent] = React.useState(false);
    const [selectedTransaction, setSelectedTransaction] = React.useState(null);
    const hasTransactions = false;
    const navigateHome = () =>
        history.push('/');

    const handleViewTransaction = async (daznUserId: string, subscriptionId: string, aggregator: string) => {
        // TODO: Show subscription specific transactions
    };

    const handleSubsctiptionCancel = async (userId: string, subscriptionId: string) => {
        try {
            setIsLoading(true);
            const response = await dcbApi.cancelSubscription(userId, 'boku', subscriptionId);
            setIsLoading(false);
            setSubscriptionCancellationSent(true);
            Modal.info({
                title: `Your cancellation request has been submited for ${userId}`,
                okText: 'OK',
                content: (

                        Transaction Id: {response.transactionId}

                        Subscription Id: {response.subscriptionId}

                        Aggregator: {response.aggregator}

                        Status: {response.status}

                ),
            })
            //this.setState({ cancellationSent: true })
        } catch (err) {
            setIsLoading(false);
            console.error(err);
            Modal.info({
                title: `Your cancellation request for ${userId} has failed`,
                okText: 'OK',
                content: (

                        {_.get(err, 'message') &&
Error message: {err.message}
}
                        <Accordion atomic={true}>
                            <AccordionItem title='Toggle detailed error'>

{JSON.stringify(err, null, 2)}

                            </AccordionItem>
                        </Accordion>

                ),
            })
        } finally {
            if (typeof onRefetch === 'function') {
                onRefetch()
            }
        }
    };

    const handleChargeRefund = async (userId: string, chargeId: string, reasonCode: number) => {
        try {
            setIsLoading(true);
            const response = await dcbApi.refund(userId, 'boku', chargeId, reasonCode)
            setIsLoading(false);
            setTransactionCancellationSent(true);
            Modal.info({
                title: `Your refund request has been submited`,
                okText: 'OK',
                content: (

                        Charge Id: {response.chargeId}

                        Country: {response.country}

                        Refund status: {response.refundStatus}

                        Refund Id: {response.refundId}

                ),
            })
            //this.setState({ cancellationSent: true })
        } catch (err) {
            setIsLoading(false);
            console.error(err);
            Modal.info({
                title: `Your refund request has failed`,
                okText: 'OK',
                content: (

                        {_.get(err, 'message') &&
Error message: {err.message}
}
                        <Accordion atomic={true}>
                            <AccordionItem title='Toggle detailed error'>

{JSON.stringify(err, null, 2)}

                            </AccordionItem>
                        </Accordion>

                ),
            })
        } finally {
            if (typeof onRefetch === 'function') {
                onRefetch()
            }
        }
    };

    return (
        <Page
            theme='dark' // light|dark
            title='Back to home'
            onLogoClick={navigateHome}
            onTitleClick={navigateHome}
            overlay={(!isLoading && !isLoadingParent) ? undefined :

                        <Loader/>

                        Loading

}
        >

Subscription statuses for user: {userId}

                <SubscriptionsTable
                    userId={userId}
                    data={subscriptions}
                    cancellationSent={subscriptionCancellationSent}
                    onCancelSubscription={handleSubsctiptionCancel}
                    onViewTransaction={handleViewTransaction}
                />

                        {hasTransactions ?
                            `Transactions for user: ${userId}` :
                            This user does not have transactions linked to their subscription}

                    {hasTransactions &&

                    <TransactionsTable
                        userId={userId}
                        data={transactions}
                        cancellationSent={transactionCancellationSent}
                        onRefundCharge={handleChargeRefund}
                    />}

        </Page>
    )
};

Body:
What if you add a filtered state inside ResultPage and pass this to TransactionsTable? handleViewTransaction will do the filtering depending on subscriptionId. Some "pseudo code":

First, set default with all transactions.

const [filteredTransactions, setFilteredTransactions] = useState(transactions);

In the handleViewTransactions, do something like:

const filteredData = transactions.filter((item) => item.subscriptionId === subscriptionId);
setFilteredTransactions(filteredData);

The TransactionsTable component will use the filtered transactions instead:

<TransactionsTable
    ...
    data={filteredTransactions}
    ...
/>


问:
How can I implement a 'random mine placer' in PHP
For a project im making a minesweeper game. So im looking to implement a random mine placer in my PHP code. I made a dynamic table using the following code:

```<code><?php

$rows = 6; //  amount of rows
$cols = 6;  //  amount of columns

echo "<table border='1'>";

for($tr=1;$tr<=$rows;$tr++){

    echo "<tr>";
    for($td=1;$td<=$cols;$td++){
        echo "<td></td>";
    }
    echo "</tr>";
}

echo "</table>";

?>
</code>```

Now the thing is that I need to be able to let the mines spawn in a random cell every time I would restart the game. Anyone that could help me out?

答:
I would recommend taking a look at the rand() function: https://www.php.net/manual/en/function.rand.php

You could use that to generate random row + column numbers for where the bombs should be placed, or to randomly decide if a cell should or shouldn't have a bomb in it, depending on how you want to do it.

Body:
For a project im making a minesweeper game. So im looking to implement a random mine placer in my PHP code. I made a dynamic table using the following code:

<?php

$rows = 6; //  amount of rows
$cols = 6;  //  amount of columns

echo "
";

for($tr=1;$tr<=$rows;$tr++){

    echo "
";
    for($td=1;$td<=$cols;$td++){
        echo "	";
    }
    echo "
";
}

echo "
";

?>

Now the thing is that I need to be able to let the mines spawn in a random cell every time I would restart the game. Anyone that could help me out?


问:
VS Code IntelliSense not working for Unity3d
Problem: IntelliSense is not working for Unity specific methods and functions (i.e., Update, FixedUpdate, Awake, etc.).

It does work, however, for non Unity specific methods (i.e., IEnumerator, void, public, float, int, etc.) and for Unity specific variables (i.e., Gameobject, transform, camera, etc.) and Unity specific namespaces (i.e., UnityEngine, UnityEditor, Unity, etc.).

I am using: Visual Studio Code 1.41, Unity 3d 2018.4.15f1 (I have the same problem when using 2019.2.x).

I have tried the following solutions to no results:

Using different versions of .NET

Deleted vscode file within the project.

Uninstalled and reinstalled both Unity and Visual studio.

Changed  <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion> to  <TargetFrameworkVersion>(Currently installed version)</TargetFrameworkVersion> but unity automatically defaults back to v4.7.1

Possible problems:

The sln file the project creates reads

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Assembly-CSharp", "Assembly-CSharp.csproj", "{B2B58FB2-4462-6B0C-A872-40DD957E5FE0}"
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Release|Any CPU.Build.0 = Release|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(MonoDevelopProperties) = preSolution
        StartupItem = Assembly-CSharp.csproj
    EndGlobalSection
EndGlobal
```

<p>For some reason, the sln file seems to be used for Visual Studio 2010. I do not know if this is intentional or if this is the problem.</p></li>
<li><p>When attempting solution 4, as stated above, Unity (or VS Code for all I know) automatically changes .NET version from whatever I manually typed to 4.7.1. I have 4.7.1 already installed so this may not be the problem.</p></li>
</ol>

<p>Extra information:</p>

<p>Here is the omnisharp log:</p>

<pre class="lang-none prettyprint-override"><code>Starting OmniSharp server at 2020. 1. 20. 오후 9:08:43
    Target: c:\Users\stpau\New Unity Project\New Unity Project.sln

OmniSharp server started.
    Path: C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\OmniSharp.exe
    PID: 2232

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 6.2.9200.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: StandAlone 16.3 - "C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        MSBUILD_EXE_PATH environment variable set to 'C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin\MSBuild.exe'
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: StandAlone 16.3 - "C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin"
            CscToolExe = csc.exe
            CscToolPath = C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin\Roslyn
            MSBuildExtensionsPath = C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild
            MSBuildToolsPath = C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in 'c:\Users\stpau\New Unity Project'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Could not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in 'c:\Users\stpau\New Unity Project\New Unity Project.sln'.
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for 'c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj'
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in 'c:\Users\stpau\New Unity Project'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Could not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider, Order: 100
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.EditorConfigWorkspaceOptionsProvider, Order: 200
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location 'c:\Users\stpau\New Unity Project' on host 8980.
[info]: OmniSharp.MSBuild.ProjectManager
        Successfully loaded project file 'c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj'.
[info]: OmniSharp.MSBuild.ProjectManager
        Adding project 'c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj'
[info]: OmniSharp.MSBuild.ProjectManager
        Update project: Assembly-CSharp
</code>```

How can I solve this problem? I also asked this question on both reddit and the Unity forums with no success.

答:
In the latest version of VS Code and Omnisharp, I had the same problem and solved enabling this option in Unity:

Edit > Preferences > External Tools > Generate all .csproj files.

Body:
Problem: IntelliSense is not working for Unity specific methods and functions (i.e., Update, FixedUpdate, Awake, etc.).

It does work, however, for non Unity specific methods (i.e., IEnumerator, void, public, float, int, etc.) and for Unity specific variables (i.e., Gameobject, transform, camera, etc.) and Unity specific namespaces (i.e., UnityEngine, UnityEditor, Unity, etc.).

I am using: Visual Studio Code 1.41, Unity 3d 2018.4.15f1 (I have the same problem when using 2019.2.x).

I have tried the following solutions to no results:

Using different versions of .NET

Deleted vscode file within the project.

Uninstalled and reinstalled both Unity and Visual studio.

Changed  <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion> to  <TargetFrameworkVersion>(Currently installed version)</TargetFrameworkVersion> but unity automatically defaults back to v4.7.1

Possible problems:

The sln file the project creates reads

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Assembly-CSharp", "Assembly-CSharp.csproj", "{B2B58FB2-4462-6B0C-A872-40DD957E5FE0}"
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {B2B58FB2-4462-6B0C-A872-40DD957E5FE0}.Release|Any CPU.Build.0 = Release|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
    GlobalSection(MonoDevelopProperties) = preSolution
        StartupItem = Assembly-CSharp.csproj
    EndGlobalSection
EndGlobal

For some reason, the sln file seems to be used for Visual Studio 2010. I do not know if this is intentional or if this is the problem.

When attempting solution 4, as stated above, Unity (or VS Code for all I know) automatically changes .NET version from whatever I manually typed to 4.7.1. I have 4.7.1 already installed so this may not be the problem.

Extra information:

Here is the omnisharp log:

Starting OmniSharp server at 2020. 1. 20. 오후 9:08:43
    Target: c:\Users\stpau\New Unity Project\New Unity Project.sln

OmniSharp server started.
    Path: C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\OmniSharp.exe
    PID: 2232

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 6.2.9200.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: StandAlone 16.3 - "C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        MSBUILD_EXE_PATH environment variable set to 'C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin\MSBuild.exe'
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: StandAlone 16.3 - "C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin"
            CscToolExe = csc.exe
            CscToolPath = C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin\Roslyn
            MSBuildExtensionsPath = C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild
            MSBuildToolsPath = C:\Users\stpau\.vscode\extensions\ms-vscode.csharp-1.21.9\.omnisharp\1.34.9\.msbuild\Current\Bin
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in 'c:\Users\stpau\New Unity Project'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Could not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in 'c:\Users\stpau\New Unity Project\New Unity Project.sln'.
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for 'c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj'
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in 'c:\Users\stpau\New Unity Project'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Could not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider, Order: 100
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.EditorConfigWorkspaceOptionsProvider, Order: 200
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location 'c:\Users\stpau\New Unity Project' on host 8980.
[info]: OmniSharp.MSBuild.ProjectManager
        Successfully loaded project file 'c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj'.
[info]: OmniSharp.MSBuild.ProjectManager
        Adding project 'c:\Users\stpau\New Unity Project\Assembly-CSharp.csproj'
[info]: OmniSharp.MSBuild.ProjectManager
        Update project: Assembly-CSharp

How can I solve this problem? I also asked this question on both reddit and the Unity forums with no success.


问:
Using RAII to re-allocate a resource after a given number of iterations
I need to process a large number of items. To do this, a resource is required which in this case is an external software program.

Due to memory leaks of the external software it is not possible to process all items with a single instance of the resource. Creating a new instance of the resource is not an option for performance reasons. Therefore I need to process the items in portions of a given size N. This means I create an instance of the resource, process the next N items, then deallocate the resource. This process is repeated until all items have been processed.

Processing of an item is actually a complicated process which can cause different types of failures (exceptions). Therefore I like to use the RAII idiom to manage the resource and make sure each instance is cleanly deallocated.

It is no big deal to implement this with two nested loops as in this example:

```<code>#include <iostream>
#include <vector>

class ResourceAllocator {
public:
    ResourceAllocator() { std::cout << "Allocating resource\n"; }
    ~ResourceAllocator() { std::cout << "Deallocating resource\n"; }
    void Process(int n) { std::cout << "Processing item " << n << "\n"; }
};

int main()
{
    const int totalSize = 20;
    const int portionSize = 6;

    std::vector<int> items(totalSize);
    int count = 0;
    bool complete = false;
    while (!complete) {
        ResourceAllocator a;
        for (int i = 0; i < portionSize; i++) {
            a.Process(items[i]);
            count++;
            if (count >= totalSize) {
                complete = true;
                break;
            }
        }
    }
}
</code>```

However I keep wondering if there is a solution that requires only a single loop.

答:
I create an instance of the resource, process the next N items, then deallocate the resource. This process is repeated until all items have been processed.

You can use move semantics for transferring the ownership of a resource. When an object following the RAII idiom is the target of a move assignment, it releases the resource it owns (if any) and takes ownership of the resource being assigned to it – the source of the assignment operation:

```<code>Resource r(/* 1st resource */);
// ...
r = Resource(/* 2nd resource */);
</code>```

The assignment should release the resource r owns and obtain the ownership of the new resource being created (i.e., Resource(/* 2nd resource */)).

You should implement a move assignment operator for your class.  When the objects have been processed, you use these objects as the targets of move assignment.

Body:
I need to process a large number of items. To do this, a resource is required which in this case is an external software program.

Due to memory leaks of the external software it is not possible to process all items with a single instance of the resource. Creating a new instance of the resource is not an option for performance reasons. Therefore I need to process the items in portions of a given size N. This means I create an instance of the resource, process the next N items, then deallocate the resource. This process is repeated until all items have been processed.

Processing of an item is actually a complicated process which can cause different types of failures (exceptions). Therefore I like to use the RAII idiom to manage the resource and make sure each instance is cleanly deallocated.

It is no big deal to implement this with two nested loops as in this example:

#include <iostream>
#include <vector>

class ResourceAllocator {
public:
    ResourceAllocator() { std::cout << "Allocating resource\n"; }
    ~ResourceAllocator() { std::cout << "Deallocating resource\n"; }
    void Process(int n) { std::cout << "Processing item " << n << "\n"; }
};

int main()
{
    const int totalSize = 20;
    const int portionSize = 6;

    std::vector<int> items(totalSize);
    int count = 0;
    bool complete = false;
    while (!complete) {
        ResourceAllocator a;
        for (int i = 0; i < portionSize; i++) {
            a.Process(items[i]);
            count++;
            if (count >= totalSize) {
                complete = true;
                break;
            }
        }
    }
}

However I keep wondering if there is a solution that requires only a single loop.

Body:
I create an instance of the resource, process the next N items, then deallocate the resource. This process is repeated until all items have been processed.

You can use move semantics for transferring the ownership of a resource. When an object following the RAII idiom is the target of a move assignment, it releases the resource it owns (if any) and takes ownership of the resource being assigned to it – the source of the assignment operation:

Resource r(/* 1st resource */);
// ...
r = Resource(/* 2nd resource */);

The assignment should release the resource r owns and obtain the ownership of the new resource being created (i.e., Resource(/* 2nd resource */)).

You should implement a move assignment operator for your class.  When the objects have been processed, you use these objects as the targets of move assignment.


问:
how can manipulate the different kind of array (string, int, char) as same format such as string in C#?
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

```<code>UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}
</code>```

答:
Does this help?</p>

```<code>void WriteToConsole<T>(IEnumerable<T> items)
{
    foreach (var item in items)
        Console.WriteLine("Capabilities: " + item);
}
</code>```

Body:
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}

Body:
Does this help?

void WriteToConsole<T>(IEnumerable<T> items)
{
    foreach (var item in items)
        Console.WriteLine("Capabilities: " + item);
}


问:
In a junction table, should I use a Primary key and a unique constraint, or a compound/composite key?
I have read through handfuls of what would seem to make this a duplicate question. But reading through all of these has left me uncertain. I'm hoping to get an answer based on the absolute example below, as many questions/answers trail off into debates back and forth.

If I have:

```<code>dbo.Book
--------
BookID PK int identity(1,1)

dbo.Author
----------
AuthorID PK int identity(1,1)
</code>```

Now I have two choices for a simple junction table:

```<code>dbo.BookAuthor
--------------
BookID CPK and FK
AuthorID CPK and FK
</code>```

The above would be a compound/composite key on both FKs, as well as set up the FK relationships for both columns - also using Cascade on delete.

OR

```<code>dbo.BookAuthor
--------------
RecordID PK int identity(1,1)
BookID FK
AuthorID FK
</code>```

Foreign key relationships on BookID and AuthorID, along with Cascade on delete. Also set up a unique constraint on BookID and AuthorID.

I'm looking for a simple answer as to why one method is better than another in the ABOVE particular example. The answers that I'm reading are very detailed, and I was just about to settle on a compound key, but then watched a video where the example used an Identity column like my first example.

It seems this topic is slightly torn in half, but my gut is telling me that I should just use a composite key.

What's more efficient for querying? It seems having a PK identity column along with setting up a unique constraint on the two columns, AND the FK relationships would be more costly, even if a little.

答:
Depending on the amount of data in the junction table, a compound key might end up causing poor performance over an auto generated sequential primary key.

The primary key is the clustered index for the table, which means that it determines the order in which rows are stored on disc. If the primary key's values are not generated sequentially (e.g. it is a composite key comprised of foreign keys from tables where rows do not fall in the same order as the junction table's rows, or it is a GUID or other random key) then each time a row is added to the junction table a reshuffle of the junction table's rows will be necessary.

Body:
I have read through handfuls of what would seem to make this a duplicate question. But reading through all of these has left me uncertain. I'm hoping to get an answer based on the absolute example below, as many questions/answers trail off into debates back and forth.

If I have:

dbo.Book
--------
BookID PK int identity(1,1)

dbo.Author
----------
AuthorID PK int identity(1,1)

Now I have two choices for a simple junction table:

dbo.BookAuthor
--------------
BookID CPK and FK
AuthorID CPK and FK

The above would be a compound/composite key on both FKs, as well as set up the FK relationships for both columns - also using Cascade on delete.

OR

dbo.BookAuthor
--------------
RecordID PK int identity(1,1)
BookID FK
AuthorID FK

Foreign key relationships on BookID and AuthorID, along with Cascade on delete. Also set up a unique constraint on BookID and AuthorID.

I'm looking for a simple answer as to why one method is better than another in the ABOVE particular example. The answers that I'm reading are very detailed, and I was just about to settle on a compound key, but then watched a video where the example used an Identity column like my first example.

It seems this topic is slightly torn in half, but my gut is telling me that I should just use a composite key.

What's more efficient for querying? It seems having a PK identity column along with setting up a unique constraint on the two columns, AND the FK relationships would be more costly, even if a little.