问:
Elastic Beanstalk custom AMI can't see environment variables
I'm using a custom AMI for Elastic Beanstalk because of some large package requirements.

When I SSH into the EC2 instance none of my environment variables (specified in the Elastic Beanstalk web console settings) are available to my app.

My app in production can access the variables just fine, but I cannot do so in the console, which is really making debugging anything very difficult.

How do I make all of the environment variables available when I'm using the SSH console?

答:
For Node.js I had to manually add them with:

```<code>export VARNAME="my value"
</code>```

Check with:

```<code>printenv VARNAME
</code>```

Body:
For Node.js I had to manually add them with:

export VARNAME="my value"

Check with:

printenv VARNAME


来源: stackexchange

问:
How to save the array field in database
here producerId value [3,5], and i want to save in database like { "id" :"1","userId" :"3"},{"id":"2","userId":"5"}

```<code>  const Ids =  _.map(req.body.producerId, (user) => ({
    const projectList =  await ProjectTeam.create({
      userId: user,
      });
      return res.json({
        success: true,
        message: 'added successfully! ',
      });
</code>```

答:
multiple insert at the database with a loop it's a bad idea because it's multiple request to database.

i suggest you to organise your objects  and insert all in one rquest like :

```<code>var ids = req.body.producerId;
var users = [];
for(let i = 0; i<ids.length ;i++){
    users.push({
    userId: ids[i],
  })
}

ProjectTeam.bulkCreate([
  users
]).then(()=>{
  return res.json({
    success: true,
    message: 'added successfully! ',
  });
});
</code>```

for you problems check if req.body.producerId it's not empty

ContentLicense: CC BY-SA 4.0

Title: How to save the array field in database

Body:
here producerId value [3,5], and i want to save in database like { "id" :"1","userId" :"3"},{"id":"2","userId":"5"}

  const Ids =  _.map(req.body.producerId, (user) => ({
    const projectList =  await ProjectTeam.create({
      userId: user,
      });
      return res.json({
        success: true,
        message: 'added successfully! ',
      });

Body:
multiple insert at the database with a loop it's a bad idea because it's multiple request to database.

i suggest you to organise your objects  and insert all in one rquest like :

var ids = req.body.producerId;
var users = [];
for(let i = 0; i<ids.length ;i++){
    users.push({
    userId: ids[i],
  })
}

ProjectTeam.bulkCreate([
  users
]).then(()=>{
  return res.json({
    success: true,
    message: 'added successfully! ',
  });
});

for you problems check if req.body.producerId it's not empty


问:
How to integrate my code into a sitefinity project
We have a sitefinity Customer Portal. Now we need to add MVC pages to it. I understand how to add a page, and how to drag e.g. a list to the page's content. But I don't understand how I can create a controller and other c# code to populate the list and do other custom things. We cannot open the project in Visual Studio, and we have no access to the existing code. </p>

答:
You need to get access to the code then, controllers\models need to be compiled.  You can get away with a lot directly in a cshtml file though which DOESN'T need to be compiled.

Could you download a new blank SF project that's on your version and start from scratch pointed at your DB?  Copy over /App_Data and /ResourcePackages to the new project and just run it.  Should work fine, but any page that has a custom widget on it that uses custom code would tank.  Sorry I'm just not sure why you don't have the code.  Could use JustDecompile to retrieve the actual code for custom widgets too I suppose.


问:
Where is Tkapp located?
I'm working on creating an interface between tkinter and JSON. I need to look through the code of Tkapp to do so because I need to understand its attributes. Failing that, how can I import it?

```<code>from tkinter import _tkinter
from _tkinter import tkapp
</code>```

Returns an ImportError

答: _tkinter is a C-based module. tkapp is defined in its source code which you can find here on GitHub.

Title: Where is Tkapp located?

Body:
I'm working on creating an interface between tkinter and JSON. I need to look through the code of Tkapp to do so because I need to understand its attributes. Failing that, how can I import it?

from tkinter import _tkinter
from _tkinter import tkapp

Returns an ImportError


问:
Why can't we use/refer to derived table in subquery
I wonder why can't a subquery use a derived table as its derived table (Query2), even though it can access the attribute of the derived table (Query1)?

Query1

```<code>select B.col1, col2 from dummy B
where B.col1 = (select col1 from dummy A where B.col1 = 'aa' and A.col1 = B.col1 limit 1);
</code>```

Here we can use B.col1.

Query2

```<code>select B.col1, col2 from dummy B
where B.col1 = (select col1 from B where B.col1 = 'aa' limit 1);
</code>```

Here we can't use B. The error says B doesn't exist.

You can find the sqlfiddle here.

答:
Because the first reference is a correlated reference.  A table alias is a reference to a particular "instance" of a table in the query, not another "table" itself.

If you want that ability, use a CTE:

```<code>with b as (
      select d.*
      from dummy d
     )
</code>```

Then you can use b multiple times in the ensuing query.

Body:
I wonder why can't a subquery use a derived table as its derived table (Query2), even though it can access the attribute of the derived table (Query1)?

Query1

select B.col1, col2 from dummy B
where B.col1 = (select col1 from dummy A where B.col1 = 'aa' and A.col1 = B.col1 limit 1);

Here we can use B.col1.

Query2

select B.col1, col2 from dummy B
where B.col1 = (select col1 from B where B.col1 = 'aa' limit 1);

Here we can't use B. The error says B doesn't exist.

You can find the sqlfiddle here.

Body:
Because the first reference is a correlated reference.  A table alias is a reference to a particular "instance" of a table in the query, not another "table" itself.

If you want that ability, use a CTE:

with b as (
      select d.*
      from dummy d
     )

Then you can use b multiple times in the ensuing query.


答:
The problem is that in your second query you are trying to select from the table that does not exist and in your first query you are referring to the column that does.

In both query's the B and the A letters are only aliases not tables.
Having that in mind, lets remove the aliases in the second query:

```<code>select col1, col2 from dummy
where col1 = (select col1 from  where col1 = 'aa' limit 1);
</code>```

Do you see something missing now in the query structure ?

To conclude, from your question it seems you do not understand which B is the problem. This one: FROM B and not this one where B.col1.

Hope this helps...

Title: Why can't we use/refer to derived table in subquery

Body:
The problem is that in your second query you are trying to select from the table that does not exist and in your first query you are referring to the column that does.

In both query's the B and the A letters are only aliases not tables.
Having that in mind, lets remove the aliases in the second query:

select col1, col2 from dummy
where col1 = (select col1 from  where col1 = 'aa' limit 1);

Do you see something missing now in the query structure ?

To conclude, from your question it seems you do not understand which B is the problem. This one: FROM B and not this one where B.col1.

Hope this helps...


问:
Function requires a double pointer and uses a representation of 2D array inside
I'm trying to use a function that requires as input a double pointer **B, and inside the function it uses a 2D array representation of the pointer, I keep getting segmentation fault error no matter how much memory I allocate to the pointer. Here is a reproducible example.
Thanks.

```<code>#include <stdlib.h>
#include <stdio.h>

void Bk(float **B) {
    int n=2;
    for (int i = n-1; i >= 0; i--)
    {
        for (int j = n-1; j >= 0; j--){
            printf("i: %d, j: %d\n", i, j);
            printf("B: %f\n", B[i][j]);
        }
    }
}

void main() {
    int n=2;
    float *B;
    B = (float *) malloc((n*n)*sizeof(float));
    B[0]=0; B[1]=1; B[2]=2; B[3]=3;
    Bk(&B);
}
</code>```

Output:

```<code>i: 2, j: 2
B: 55641428.000000
i: 2, j: 1
B: 26.942034
i: 1, j: 2
Segmentation fault (core dumped)
</code>```

答:
The function Bk expects the parameter B to be an array of pointers, each of which points to an array of float.  But that's not what you're passing to it.   You're passing a pointer to a single array of float.

You need to redefine B in main to be an float **, allocate space for the array of pointers, then allocate space for each subarray.

```<code>int n=2, i;
float **B;
B = malloc(n * sizeof(float*));
for (i=0;i<n;i++) {
    B[i] = malloc(n * sizeof(float));
}
B[0][0]=0; B[0][1]=1; B[1][0]=2; B[1][1]=3;
Bk(B);
for (i=0;i<n;i++) {
    free(B[i]);
}
free(B);
</code>```

Body:
I'm trying to use a function that requires as input a double pointer **B, and inside the function it uses a 2D array representation of the pointer, I keep getting segmentation fault error no matter how much memory I allocate to the pointer. Here is a reproducible example.
Thanks.

#include <stdlib.h>
#include <stdio.h>

void Bk(float **B) {
    int n=2;
    for (int i = n-1; i >= 0; i--)
    {
        for (int j = n-1; j >= 0; j--){
            printf("i: %d, j: %d\n", i, j);
            printf("B: %f\n", B[i][j]);
        }
    }
}

void main() {
    int n=2;
    float *B;
    B = (float *) malloc((n*n)*sizeof(float));
    B[0]=0; B[1]=1; B[2]=2; B[3]=3;
    Bk(&B);
}

Output:

i: 2, j: 2
B: 55641428.000000
i: 2, j: 1
B: 26.942034
i: 1, j: 2
Segmentation fault (core dumped)

Body:
The function Bk expects the parameter B to be an array of pointers, each of which points to an array of float.  But that's not what you're passing to it.   You're passing a pointer to a single array of float.

You need to redefine B in main to be an float **, allocate space for the array of pointers, then allocate space for each subarray.

int n=2, i;
float **B;
B = malloc(n * sizeof(float*));
for (i=0;i<n;i++) {
    B[i] = malloc(n * sizeof(float));
}
B[0][0]=0; B[0][1]=1; B[1][0]=2; B[1][1]=3;
Bk(B);
for (i=0;i<n;i++) {
    free(B[i]);
}
free(B);


问:
setState doesn't execute the callback
I have a select filter, I want to filter my products by category. The state gets updated but the callback of setState is not executed. Basically I want to update my list immediately when the state is changed. Code line 31 doesn't get executed in the try blok, it's also not catching any error.

HTML

```<code><div className="col-md-4 w-25 mt-3 ml-5">
                <Select
                  onChange={this.handleChange}
                  value={selectedCategory}
                  placeholder="Select Category"
                  options={categories}
                />
   </div>
</code>```

JavaScript

```<code>    handleChange = event => {
    console.log(event.value);
    this.setState({ selectedCategory: event.value }, () => {
      try {
        products.pipe(
          map(products =>
            products
              .filter(
                product => product.category === this.state.selectedCategory
              )
              .subscribe(products => {
                console.log(products);
                this.setState({
                  items: products,
                  isLoaded: true
                });
              })
          )
        );
      } catch (error) {
        console.error(error);
      }
    });
  };
</code>```

答:
```<code>  handleChange = event => {
    console.log(event.value);
    this.setState({ selectedCategory: event.value }, () => { // this line right here
      products.pipe(
        map(products =>
          products
            .filter(product => product.category === this.state.selectedCategory)
            .subscribe(products => {
              console.log(products);
              this.setState({
                items: products,
                isLoaded: true
              });
            })
        )
      );
    });
  };
</code>```

Change this line: this.setState({ selectedCategory: event.value }, function() { to this this.setState({ selectedCategory: event.value }, () => {

Calling it 'function' changes the this context.

Title: setState doesn't execute the callback

Body:
I have a select filter, I want to filter my products by category. The state gets updated but the callback of setState is not executed. Basically I want to update my list immediately when the state is changed. Code line 31 doesn't get executed in the try blok, it's also not catching any error.

HTML

                <Select
                  onChange={this.handleChange}
                  value={selectedCategory}
                  placeholder="Select Category"
                  options={categories}
                />

JavaScript

    handleChange = event => {
    console.log(event.value);
    this.setState({ selectedCategory: event.value }, () => {
      try {
        products.pipe(
          map(products =>
            products
              .filter(
                product => product.category === this.state.selectedCategory
              )
              .subscribe(products => {
                console.log(products);
                this.setState({
                  items: products,
                  isLoaded: true
                });
              })
          )
        );
      } catch (error) {
        console.error(error);
      }
    });
  };

Body:
  handleChange = event => {
    console.log(event.value);
    this.setState({ selectedCategory: event.value }, () => { // this line right here
      products.pipe(
        map(products =>
          products
            .filter(product => product.category === this.state.selectedCategory)
            .subscribe(products => {
              console.log(products);
              this.setState({
                items: products,
                isLoaded: true
              });
            })
        )
      );
    });
  };

Change this line: this.setState({ selectedCategory: event.value }, function() { to this this.setState({ selectedCategory: event.value }, () => {

Calling it 'function' changes the this context.


问:
Access denied when trying to write a file
Hi I'm trying to write a file but when I run the program it says access denied, I already tried checking the security proprietes and opening VS as admin but doens't work here's the funtion that builds the file

```<code>public void fazfich() {
    string createText = "\"" + this.Companhia + "\",\"" + this.NrFuncionario + "\",\"" + this.Nome1 + "\",\"" + this.Nome2 + "\",\"" + this.DtNascimento + "\",\"" + this.Sexo +
        "\",\"" + this.PIN + "\",\"" + this.EMAIL + "\",\"" + this.TpColaborador + "\",\"" + this.CodLingua + "\",\"" + this.CodLingualSO + "\",\"" + this.CodCentroCst +
        "\",\"" + this.CodEscala + "\",\"" + this.CodSector + "\",\"" + this.CodCentroTrb + "\",\"" + this.CodDirecao + "\",\"" + this.CodCategoria + "\",\"" + this.CodCompnhiaExt +
        "\",\"" + this.DsCompanhiaExt + "\",\"" + this.Telefone + "\",\"" + this.InfAutomaticas + "\",\"" + this.HorasExtra + "\",\"" + this.TpControlo +
        "\",\"" + this.CodGrpControlo + "\",\"" + this.NrFuncionarioAlt + "\",\"" + this.TpHorario + "\",\"" + this.TolAtrasoDia + "\",\"" + this.TolAtrasoPrd +
        "\",\"" + this.TolSaidaDia + "\",\"" + this.TolSaidaPrd + "\",\"" + this.SaldoDia + "\",\"" + this.SaldoPrd + "\",\"" + this.TemSaldo + "\",\"" + this.Sistema +
        "\",\"" + this.Saldo + "\",\"" + this.TemCredito + "\",\"" + this.PrecoRefeicao + "\",\"" + this.Subsidio + "\",\"" + this.NrRefeircoes + "\",\"" + this.TpPaga +
        "\",\"" + this.CodPaga + "\",\"" + this.Info + "\",\"" + this.Obs + "\",\"" + this.DtAdmissao + "\",\"" + this.DtDemissao + "\",\"" + this.SisLogico + "\",\"" +
        this.Cartao + "\",\"" + this.DtValidadeIni + "\",\"" + this.DtValidadeFim + "\",\"" + this.Versao + "\",\"" + this.NomeCartao + "\",\"" + this.CodGrpPermissao +
        "\",\"" + this.CodPerfil + "\",\"" + this.PINCARTAO + "\",\"" + this.Status + "\",\"" + this.Info1 + "\",\"" + this.Info2 + "\",\"" + this.Info3 + "\",\"" +
        this.Info4 + "\",\"" + this.Info5 + "\",\"" + this.Info6 + "\",\"" + this.Info7 + "\",\"" + this.Info8 + "\",\"" + this.Info9 + "\",\"" + this.Info10 + "\",\"" +
        this.Msg1 + "\",\"" + this.Msg2 + "\",\"" + this.Provisorio + "\",\"" + this.IDAplicaçã o + "\",\"" + this.AgrpSalarios + "\",\"" + this.Visitante + "\",\"" +
        this.Empresa + "\"\r\n";
    File.WriteAllText(@"C:\Users\ec2ac9097\Documents\estagio\WebApplicationAPI", createText);
}
</code>```

the program is a Web API

答:
The API will run under some specific user, which you can check under the IIS setup. That particular user won't have the right to create something in a user folder like where you're trying to write the file.

You can verify this by trying to write somewhere else where IIS has full access like inetpub or maybe your temp folder.

Definitely do not test this with IIS Express, set it up in IIS from the very beginning. In the end you'll have to setup specific users with specific rights if you want to create files on disk.

Body:
Hi I'm trying to write a file but when I run the program it says access denied, I already tried checking the security proprietes and opening VS as admin but doens't work here's the funtion that builds the file

public void fazfich() {
    string createText = "\"" + this.Companhia + "\",\"" + this.NrFuncionario + "\",\"" + this.Nome1 + "\",\"" + this.Nome2 + "\",\"" + this.DtNascimento + "\",\"" + this.Sexo +
        "\",\"" + this.PIN + "\",\"" + this.EMAIL + "\",\"" + this.TpColaborador + "\",\"" + this.CodLingua + "\",\"" + this.CodLingualSO + "\",\"" + this.CodCentroCst +
        "\",\"" + this.CodEscala + "\",\"" + this.CodSector + "\",\"" + this.CodCentroTrb + "\",\"" + this.CodDirecao + "\",\"" + this.CodCategoria + "\",\"" + this.CodCompnhiaExt +
        "\",\"" + this.DsCompanhiaExt + "\",\"" + this.Telefone + "\",\"" + this.InfAutomaticas + "\",\"" + this.HorasExtra + "\",\"" + this.TpControlo +
        "\",\"" + this.CodGrpControlo + "\",\"" + this.NrFuncionarioAlt + "\",\"" + this.TpHorario + "\",\"" + this.TolAtrasoDia + "\",\"" + this.TolAtrasoPrd +
        "\",\"" + this.TolSaidaDia + "\",\"" + this.TolSaidaPrd + "\",\"" + this.SaldoDia + "\",\"" + this.SaldoPrd + "\",\"" + this.TemSaldo + "\",\"" + this.Sistema +
        "\",\"" + this.Saldo + "\",\"" + this.TemCredito + "\",\"" + this.PrecoRefeicao + "\",\"" + this.Subsidio + "\",\"" + this.NrRefeircoes + "\",\"" + this.TpPaga +
        "\",\"" + this.CodPaga + "\",\"" + this.Info + "\",\"" + this.Obs + "\",\"" + this.DtAdmissao + "\",\"" + this.DtDemissao + "\",\"" + this.SisLogico + "\",\"" +
        this.Cartao + "\",\"" + this.DtValidadeIni + "\",\"" + this.DtValidadeFim + "\",\"" + this.Versao + "\",\"" + this.NomeCartao + "\",\"" + this.CodGrpPermissao +
        "\",\"" + this.CodPerfil + "\",\"" + this.PINCARTAO + "\",\"" + this.Status + "\",\"" + this.Info1 + "\",\"" + this.Info2 + "\",\"" + this.Info3 + "\",\"" +
        this.Info4 + "\",\"" + this.Info5 + "\",\"" + this.Info6 + "\",\"" + this.Info7 + "\",\"" + this.Info8 + "\",\"" + this.Info9 + "\",\"" + this.Info10 + "\",\"" +
        this.Msg1 + "\",\"" + this.Msg2 + "\",\"" + this.Provisorio + "\",\"" + this.IDAplicaçã o + "\",\"" + this.AgrpSalarios + "\",\"" + this.Visitante + "\",\"" +
        this.Empresa + "\"\r\n";
    File.WriteAllText(@"C:\Users\ec2ac9097\Documents\estagio\WebApplicationAPI", createText);
}

the program is a Web API


问:
Show file path using WX
I am trying to show the file path after it been dropped in NewText label
but it only show me the path on the top window...
what can i do to make it work.

This is my code
I am  trying to show path where is 'Path will be' staticText

```<code>import wx

class MyFileDropTarget(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filename):
        #self.window.SetInsertionPointEnd()
        TempTxt = filename
        print(TempTxt)
        print(type(TempTxt))
        TempTxt = str(TempTxt)
        print(type(TempTxt))
        self.window.LabelTextUpdate(TempTxt)
        return True

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)
        self.InitUI()
        self.Center()

    def InitUI(self):
        panel = wx.Panel(self)
        FileDrTr = MyFileDropTarget(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        verBox = wx.BoxSizer(wx.VERTICAL)
        horBoxOne = wx.BoxSizer(wx.HORIZONTAL)
        TextLabel = wx.StaticText(panel, label = 'Drop file hear')
        TextLabel.SetFont(font)
        horBoxOne.Add(TextLabel, flag=wx.RIGHT, border=10)
        DropePlace = wx.TextCtrl(panel)
        DropePlace.SetDropTarget(FileDrTr)
        horBoxOne.Add(DropePlace, proportion=1)
        verBox.Add(horBoxOne, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        verBox.Add((-1, 10))
        horBoxTwo = wx.BoxSizer(wx.HORIZONTAL)
        NewText = wx.StaticText(panel, label = 'Path will be')
        horBoxTwo.Add(NewText, flag=wx.RIGHT, border=5)
        verBox.Add(horBoxTwo, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        panel.SetSizer(verBox)

    def LabelTextUpdate(self, txt):
        print(txt)
        print(type(txt))
        NewText = wx.StaticText(self, label = txt)

def main():
    app = wx.App()
    ex = Example(None, title = 'drope and see file path')
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()
</code>```

答:
Because we are reacting to an event a file drop, it makes sense to assign the processing to an event as well.

Introducing wx.lib.newevent:

here we create our own event (EVT_DROP_EVENT) and assign it a label (drop_event).

```<code>drop_event, EVT_DROP_EVENT = wx.lib.newevent.NewEvent()
</code>```

We now have an event to bind to and we can assign it a callback routine, in this case LabelTextUpdate.

```<code>self.Bind(EVT_DROP_EVENT, self.LabelTextUpdate)
</code>```

When the file is dropped, we set the event and fire it off:

```<code>    evt = drop_event(data=TempTxt)
    wx.PostEvent(self.obj,evt)
</code>```

The callback routine is called due to binding to the EVT_DROP_EVENT and in this routine we process the data.

Hope that's clear (see below).

```<code>import wx

import wx.lib.newevent
drop_event, EVT_DROP_EVENT = wx.lib.newevent.NewEvent()

class MyFileDropTarget(wx.FileDropTarget):
    def __init__(self, obj):
        wx.FileDropTarget.__init__(self)
        self.obj = obj

    def OnDropFiles(self, x, y, filename):
        #filename is a list of 1 or more files
        #here we are assuming only 1 file
        TempTxt = filename[0]
        evt = drop_event(data=TempTxt)
        wx.PostEvent(self.obj,evt)

        return True

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)
        self.InitUI()
        self.Center()

    def InitUI(self):
        panel = wx.Panel(self)
        FileDrTr = MyFileDropTarget(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        verBox = wx.BoxSizer(wx.VERTICAL)
        horBoxOne = wx.BoxSizer(wx.HORIZONTAL)
        TextLabel = wx.StaticText(panel, label = 'Drop file here')
        TextLabel.SetFont(font)
        horBoxOne.Add(TextLabel, flag=wx.RIGHT, border=10)
        DropePlace = wx.TextCtrl(panel)
        DropePlace.SetDropTarget(FileDrTr)

        #Bind the drop event listener
        self.Bind(EVT_DROP_EVENT, self.LabelTextUpdate)

        horBoxOne.Add(DropePlace, proportion=1)
        verBox.Add(horBoxOne, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        verBox.Add((-1, 10))
        horBoxTwo = wx.BoxSizer(wx.HORIZONTAL)
        self.NewText = wx.StaticText(panel, label = 'Path will be')
        horBoxTwo.Add(self.NewText, flag=wx.RIGHT, border=5)
        verBox.Add(horBoxTwo, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        panel.SetSizer(verBox)

    def LabelTextUpdate(self, event):
        txt = event.data
        self.NewText.SetLabel(txt)

def main():
    app = wx.App()
    ex = Example(None, title = 'drop and see file path')
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()
</code>```

Title: Show file path using WX

Body:
I am trying to show the file path after it been dropped in NewText label
but it only show me the path on the top window...
what can i do to make it work.

This is my code
I am  trying to show path where is 'Path will be' staticText

import wx

class MyFileDropTarget(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filename):
        #self.window.SetInsertionPointEnd()
        TempTxt = filename
        print(TempTxt)
        print(type(TempTxt))
        TempTxt = str(TempTxt)
        print(type(TempTxt))
        self.window.LabelTextUpdate(TempTxt)
        return True

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)
        self.InitUI()
        self.Center()

    def InitUI(self):
        panel = wx.Panel(self)
        FileDrTr = MyFileDropTarget(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        verBox = wx.BoxSizer(wx.VERTICAL)
        horBoxOne = wx.BoxSizer(wx.HORIZONTAL)
        TextLabel = wx.StaticText(panel, label = 'Drop file hear')
        TextLabel.SetFont(font)
        horBoxOne.Add(TextLabel, flag=wx.RIGHT, border=10)
        DropePlace = wx.TextCtrl(panel)
        DropePlace.SetDropTarget(FileDrTr)
        horBoxOne.Add(DropePlace, proportion=1)
        verBox.Add(horBoxOne, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        verBox.Add((-1, 10))
        horBoxTwo = wx.BoxSizer(wx.HORIZONTAL)
        NewText = wx.StaticText(panel, label = 'Path will be')
        horBoxTwo.Add(NewText, flag=wx.RIGHT, border=5)
        verBox.Add(horBoxTwo, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        panel.SetSizer(verBox)

    def LabelTextUpdate(self, txt):
        print(txt)
        print(type(txt))
        NewText = wx.StaticText(self, label = txt)

def main():
    app = wx.App()
    ex = Example(None, title = 'drope and see file path')
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

Body:
Because we are reacting to an event a file drop, it makes sense to assign the processing to an event as well.

Introducing wx.lib.newevent:

here we create our own event (EVT_DROP_EVENT) and assign it a label (drop_event).

drop_event, EVT_DROP_EVENT = wx.lib.newevent.NewEvent()

We now have an event to bind to and we can assign it a callback routine, in this case LabelTextUpdate.

self.Bind(EVT_DROP_EVENT, self.LabelTextUpdate)

When the file is dropped, we set the event and fire it off:

    evt = drop_event(data=TempTxt)
    wx.PostEvent(self.obj,evt)

The callback routine is called due to binding to the EVT_DROP_EVENT and in this routine we process the data.

Hope that's clear (see below).

import wx

import wx.lib.newevent
drop_event, EVT_DROP_EVENT = wx.lib.newevent.NewEvent()

class MyFileDropTarget(wx.FileDropTarget):
    def __init__(self, obj):
        wx.FileDropTarget.__init__(self)
        self.obj = obj

    def OnDropFiles(self, x, y, filename):
        #filename is a list of 1 or more files
        #here we are assuming only 1 file
        TempTxt = filename[0]
        evt = drop_event(data=TempTxt)
        wx.PostEvent(self.obj,evt)

        return True

class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title)
        self.InitUI()
        self.Center()

    def InitUI(self):
        panel = wx.Panel(self)
        FileDrTr = MyFileDropTarget(self)
        font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)
        verBox = wx.BoxSizer(wx.VERTICAL)
        horBoxOne = wx.BoxSizer(wx.HORIZONTAL)
        TextLabel = wx.StaticText(panel, label = 'Drop file here')
        TextLabel.SetFont(font)
        horBoxOne.Add(TextLabel, flag=wx.RIGHT, border=10)
        DropePlace = wx.TextCtrl(panel)
        DropePlace.SetDropTarget(FileDrTr)

        #Bind the drop event listener
        self.Bind(EVT_DROP_EVENT, self.LabelTextUpdate)

        horBoxOne.Add(DropePlace, proportion=1)
        verBox.Add(horBoxOne, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        verBox.Add((-1, 10))
        horBoxTwo = wx.BoxSizer(wx.HORIZONTAL)
        self.NewText = wx.StaticText(panel, label = 'Path will be')
        horBoxTwo.Add(self.NewText, flag=wx.RIGHT, border=5)
        verBox.Add(horBoxTwo, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        panel.SetSizer(verBox)

    def LabelTextUpdate(self, event):
        txt = event.data
        self.NewText.SetLabel(txt)

def main():
    app = wx.App()
    ex = Example(None, title = 'drop and see file path')
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()


问:
How to copy a row from a table to another table which have more columns than the first one in mysql?
Please read my problem carefully because i am very bad at explaining it and please help me out of this problem .

Let suppose I made 2 tables named table1, which has only 2 columns, and second table named table2 which has 3 columns but in the 3 columns , 2 columns are same as the 2 columns of table1.

So I want to copy a row from the 2 columns of table1 to the same type of 2 columns of table2 and keeping 3rd column as null in mysql.

So please tell how to do it .

答:
Consider the insert ... select syntax:

```<code>insert into table2(col1, col2)
select col1, col2 from table1
</code>```

Body:
Consider the insert ... select syntax:

insert into table2(col1, col2)
select col1, col2 from table1


问:
Golang - create an object of the same type as passed
I'm trying to build a generic function which will parse input (in JSON) into a specified structure.  The structure may vary at run-time, based on parameters which are passed to the function.  I'm currently trying to achieve this by passing an object of the right type and using reflect.New() to create a new output object of the same type.

I'm then parsing the JSON into this object, and scanning the fields.

If I create the object and specify the type in code, everything works.  If I pass an object and try to create a replica, I get an "invalid indirect" error a few steps down (see code).

```<code>import (
    "fmt"
    "reflect"
    "encoding/json"
    "strings"
)

type Test struct {
    FirstName   *string `json:"FirstName"`
    LastName    *string `json:"LastName"`
}

func genericParser(incomingData *strings.Reader, inputStructure interface{}) (interface{}, error) {
    //******* Use the line below and things work *******
    //parsedInput := new(Test)

    //******* Use vvv the line below and things don't work *******
    parsedInput := reflect.New(reflect.TypeOf(inputStructure))

    decoder := json.NewDecoder(incomingData)
    err := decoder.Decode(&parsedInput)
    if err != nil {
        //parsing error
        return nil, err
    }

    //******* This is the line that generates the error "invalid indirect of parsedInput (type reflect.Value)" *******
    contentValues := reflect.ValueOf(*parsedInput)
    for i := 0; i < contentValues.NumField(); i++ {
        //do stuff with each field
        fmt.Printf("Field name was: %s\n", reflect.TypeOf(parsedInput).Elem().Field(i).Name)
    }
    return parsedInput, nil
}

func main() {
    inputData := strings.NewReader("{\"FirstName\":\"John\", \"LastName\":\"Smith\"}")
    exampleObject := new(Test)
    processedData, err := genericParser(inputData, exampleObject)
    if err != nil {
        fmt.Println("Parsing error")
    } else {
        fmt.Printf("Success: %v", processedData)
    }
}
</code>```

If I can't create a replica of the object, then a way of updating / returning the one supplied would be feasible.  The key thing is that this function must be completely agnostic to the different structures available.

答:
reflect.New isn't a direct analog to new, as it can't return a specific type, it only can return a reflect.Value. This means that you are attempting to unmarshal into a *reflect.Value, which obviously isn't going to work (even if it did, your code would have passed in **Type, which isn't what you want either).

Use parsedInput.Interface() to get the underlying value after creating the new value to unmarshal into. You then don't need to reflect on the same value a second time, as that would be a reflect.Value of a reflect.Value, which again isn't going to do anything useful.

Finally, you need to use parsedInput.Interface() before you return, otherwise you are returning the reflect.Value rather than the value of the input type.

For example:

```<code>func genericParser(incomingData io.Reader, inputStructure interface{}) (interface{}, error) {
    parsedInput := reflect.New(reflect.TypeOf(inputStructure).Elem())

    decoder := json.NewDecoder(incomingData)
    err := decoder.Decode(parsedInput.Interface())
    if err != nil {
        return nil, err
    }

    for i := 0; i < parsedInput.Elem().NumField(); i++ {
        fmt.Printf("Field name was: %s\n", parsedInput.Type().Elem().Field(i).Name)
    }
    return parsedInput.Interface(), nil
}
</code>```

https://play.golang.org/p/CzDrj6sgQNt

Body:
I'm trying to build a generic function which will parse input (in JSON) into a specified structure.  The structure may vary at run-time, based on parameters which are passed to the function.  I'm currently trying to achieve this by passing an object of the right type and using reflect.New() to create a new output object of the same type.

I'm then parsing the JSON into this object, and scanning the fields.

If I create the object and specify the type in code, everything works.  If I pass an object and try to create a replica, I get an "invalid indirect" error a few steps down (see code).

import (
    "fmt"
    "reflect"
    "encoding/json"
    "strings"
)

type Test struct {
    FirstName   *string `json:"FirstName"`
    LastName    *string `json:"LastName"`
}

func genericParser(incomingData *strings.Reader, inputStructure interface{}) (interface{}, error) {
    //******* Use the line below and things work *******
    //parsedInput := new(Test)

    //******* Use vvv the line below and things don't work *******
    parsedInput := reflect.New(reflect.TypeOf(inputStructure))

    decoder := json.NewDecoder(incomingData)
    err := decoder.Decode(&parsedInput)
    if err != nil {
        //parsing error
        return nil, err
    }

    //******* This is the line that generates the error "invalid indirect of parsedInput (type reflect.Value)" *******
    contentValues := reflect.ValueOf(*parsedInput)
    for i := 0; i < contentValues.NumField(); i++ {
        //do stuff with each field
        fmt.Printf("Field name was: %s\n", reflect.TypeOf(parsedInput).Elem().Field(i).Name)
    }
    return parsedInput, nil
}

func main() {
    inputData := strings.NewReader("{\"FirstName\":\"John\", \"LastName\":\"Smith\"}")
    exampleObject := new(Test)
    processedData, err := genericParser(inputData, exampleObject)
    if err != nil {
        fmt.Println("Parsing error")
    } else {
        fmt.Printf("Success: %v", processedData)
    }
}

If I can't create a replica of the object, then a way of updating / returning the one supplied would be feasible.  The key thing is that this function must be completely agnostic to the different structures available.

Body:
reflect.New isn't a direct analog to new, as it can't return a specific type, it only can return a reflect.Value. This means that you are attempting to unmarshal into a *reflect.Value, which obviously isn't going to work (even if it did, your code would have passed in **Type, which isn't what you want either).

Use parsedInput.Interface() to get the underlying value after creating the new value to unmarshal into. You then don't need to reflect on the same value a second time, as that would be a reflect.Value of a reflect.Value, which again isn't going to do anything useful.

Finally, you need to use parsedInput.Interface() before you return, otherwise you are returning the reflect.Value rather than the value of the input type.

For example:

func genericParser(incomingData io.Reader, inputStructure interface{}) (interface{}, error) {
    parsedInput := reflect.New(reflect.TypeOf(inputStructure).Elem())

    decoder := json.NewDecoder(incomingData)
    err := decoder.Decode(parsedInput.Interface())
    if err != nil {
        return nil, err
    }

    for i := 0; i < parsedInput.Elem().NumField(); i++ {
        fmt.Printf("Field name was: %s\n", parsedInput.Type().Elem().Field(i).Name)
    }
    return parsedInput.Interface(), nil
}

https://play.golang.org/p/CzDrj6sgQNt


问:
Android emulator can no longer connect to localhost
I have a server on my computer running on localhost:8080, previously I was able to access this in the Android emulator under 10.0.2.2:8080 and it worked great. I went to load it again at some point today and it no longer works. No configuration has changed to my knowledge.

I can still access localhost when I use a browser on my computer, so the server is still running okay. But on the emulator, whether using my app or a browser it will not connect.

Any suggestions would be appreciated. Thanks.

答:
In case anyone comes across this in a search, this is how I fixed the problem:

Open terminal and enter sudo nano /private/etc/hosts

Delete the line ::1     localhost

Ctrl-O then enter to save. Ctrl-X to exit.

Restarted my local server and after that it worked.


问:
Controlling Carousel Slider from Stream (Flutter)
I have data coming from a stream mainly a queue and current mediaItem of the queue. So the mediaItem is always changing.
I got the index using

index = queue.indexOf(mediaItem);

now I want to set the carousel's current page to my index, I added the index on the initialPage of the Carousel but it works only once when the index changes it doesn't change the current page.

My Stream looks like this

```<code>//this stream is initialized inside initState()
stream = Rx.combineLatest3<List<MediaItem>, MediaItem, PlaybackState, ScreenState>(
  AudioService.queueStream,
  AudioService.currentMediaItemStream,
  AudioService.playbackStateStream,
      (queue, mediaItem, playbackState) => ScreenState(queue, mediaItem, playbackState)
);

Scaffold(
  body: new Center(
    child: StreamBuilder<ScreenState>(
      stream: stream,
      builder: (context, snapshot) {
        final screenState = snapshot.data;
        final queue = screenState?.queue;
        final mediaItem = screenState?.mediaItem;
        final state = screenState?.playbackState;
        final basicState = state?.basicState ?? BasicPlaybackState.none;
        int index = queue?.indexWhere((MediaItem mediaItemX){return (mediaItem?.id == mediaItemX.id);});
        return (queue!=null&& mediaItem!=null && basicState != null && index != null)
          ? mainView(queue, mediaItem, basicState, state, index)
          : Container(
            child: Center(
              child: SpinKitWave(
                color: Colors.white70,
              ),
            ),
          );
      },
    ),
  ),
),
</code>```

Main view

```<code>Widget mainView(List<MediaItem> queue, MediaItem mediaItemX, BasicPlaybackState basicState, PlaybackState state, int index){
  return CarouselSlider.builder(
    itemCount: queue.length,
    initialPage: queue.indexOf(mediaItemX),//only works first time
    itemBuilder: (BuildContext context, int itemIndex) {
      Stack(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Container(
              padding: EdgeInsets.fromLTRB(0,0,0,0),
              child: CachedNetworkImage(
                height: ScreenUtil().setWidth(1200),
                width: ScreenUtil().setWidth(1200),
                imageUrl: queue[itemIndex].artUri,
                fit: BoxFit.cover,
                placeholder: (context, url) => new SpinKitWave(color: Colors.white30, size: 30.0,),
                errorWidget: (context, url, error) => new Image.asset(
                  'images/addplaylist.png',
                  color: Colors.white30,
                ),
              ),
            )
          )
        ],
      ),
    }
  );
}
</code>```

The issue is when mediaItem changes from another place, the carousel is needed to change its index based on the stream change of data, In other words, a functionality almost same as currentPage inside Carousel so that every time index changes then the currentPage is set to the new data from the stream or to control the Carousel from the stream.
A solution or a hint with an example is highly appreciated.

Additional Information: I am using carousel_slider: ^1.4.1

答:
initialPage works properly with empty containers (see code below), seems to me that is missing some key maybe in cached image network or your container, try put a UniqueKey() to ensure that widget tree will detect the change when new snapshot comes...

Example working with StreamBuilder and slider:

```<code>import 'dart:async';
import 'dart:math';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: MyHomePage()),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final StreamController sc = StreamController();
  final rng = Random();

  final containers = [
    Container(color: Colors.pink),
    Container(color: Colors.black),
    Container(color: Colors.yellow),
    Container(color: Colors.brown),
  ];
  @override
  void initState() {
    super.initState();

    Timer.periodic(
      Duration(seconds: 5),
      (t) {
        sc.add(rng.nextInt(containers.length));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: sc.stream,
      builder: (context, snapshot) {
        if (snapshot.hasData == false) {
          return CircularProgressIndicator();
        }
        return Container(
          child: mainView(containers, containers[snapshot.data]),
        );
      },
    );
  }

  Widget mainView(
    List<Container> queue,
    Container mediaItemX,
  ) {
    return CarouselSlider.builder(
      itemCount: queue.length,
      initialPage: queue.indexOf(mediaItemX), //only works first time
      itemBuilder: (BuildContext context, int itemIndex) {
        print('changed');

        return mediaItemX;
      },
    );
  }
}
</code>```

Body:
I have data coming from a stream mainly a queue and current mediaItem of the queue. So the mediaItem is always changing.
I got the index using

index = queue.indexOf(mediaItem);

now I want to set the carousel's current page to my index, I added the index on the initialPage of the Carousel but it works only once when the index changes it doesn't change the current page.

My Stream looks like this

//this stream is initialized inside initState()
stream = Rx.combineLatest3<List<MediaItem>, MediaItem, PlaybackState, ScreenState>(
  AudioService.queueStream,
  AudioService.currentMediaItemStream,
  AudioService.playbackStateStream,
      (queue, mediaItem, playbackState) => ScreenState(queue, mediaItem, playbackState)
);

Scaffold(
  body: new Center(
    child: StreamBuilder<ScreenState>(
      stream: stream,
      builder: (context, snapshot) {
        final screenState = snapshot.data;
        final queue = screenState?.queue;
        final mediaItem = screenState?.mediaItem;
        final state = screenState?.playbackState;
        final basicState = state?.basicState ?? BasicPlaybackState.none;
        int index = queue?.indexWhere((MediaItem mediaItemX){return (mediaItem?.id == mediaItemX.id);});
        return (queue!=null&& mediaItem!=null && basicState != null && index != null)
          ? mainView(queue, mediaItem, basicState, state, index)
          : Container(
            child: Center(
              child: SpinKitWave(
                color: Colors.white70,
              ),
            ),
          );
      },
    ),
  ),
),

Main view

Widget mainView(List<MediaItem> queue, MediaItem mediaItemX, BasicPlaybackState basicState, PlaybackState state, int index){
  return CarouselSlider.builder(
    itemCount: queue.length,
    initialPage: queue.indexOf(mediaItemX),//only works first time
    itemBuilder: (BuildContext context, int itemIndex) {
      Stack(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Container(
              padding: EdgeInsets.fromLTRB(0,0,0,0),
              child: CachedNetworkImage(
                height: ScreenUtil().setWidth(1200),
                width: ScreenUtil().setWidth(1200),
                imageUrl: queue[itemIndex].artUri,
                fit: BoxFit.cover,
                placeholder: (context, url) => new SpinKitWave(color: Colors.white30, size: 30.0,),
                errorWidget: (context, url, error) => new Image.asset(
                  'images/addplaylist.png',
                  color: Colors.white30,
                ),
              ),
            )
          )
        ],
      ),
    }
  );
}

The issue is when mediaItem changes from another place, the carousel is needed to change its index based on the stream change of data, In other words, a functionality almost same as currentPage inside Carousel so that every time index changes then the currentPage is set to the new data from the stream or to control the Carousel from the stream.
A solution or a hint with an example is highly appreciated.

Additional Information: I am using carousel_slider: ^1.4.1

Body:
initialPage works properly with empty containers (see code below), seems to me that is missing some key maybe in cached image network or your container, try put a UniqueKey() to ensure that widget tree will detect the change when new snapshot comes...

Example working with StreamBuilder and slider:

import 'dart:async';
import 'dart:math';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: MyHomePage()),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final StreamController sc = StreamController();
  final rng = Random();

  final containers = [
    Container(color: Colors.pink),
    Container(color: Colors.black),
    Container(color: Colors.yellow),
    Container(color: Colors.brown),
  ];
  @override
  void initState() {
    super.initState();

    Timer.periodic(
      Duration(seconds: 5),
      (t) {
        sc.add(rng.nextInt(containers.length));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: sc.stream,
      builder: (context, snapshot) {
        if (snapshot.hasData == false) {
          return CircularProgressIndicator();
        }
        return Container(
          child: mainView(containers, containers[snapshot.data]),
        );
      },
    );
  }

  Widget mainView(
    List<Container> queue,
    Container mediaItemX,
  ) {
    return CarouselSlider.builder(
      itemCount: queue.length,
      initialPage: queue.indexOf(mediaItemX), //only works first time
      itemBuilder: (BuildContext context, int itemIndex) {
        print('changed');

        return mediaItemX;
      },
    );
  }
}


问:
How to encrypt a column in Oracle without passing the key to the Oracle Server?
How to encrypt a column in Oracle without giving the key to Oracle Server? I need to encrypt a column in my table, but I don't want that the DBA can know the key, is it possible to do this and how ?</p>

答: A typical way to do this would be to just encrypt the data from an application connected to your Oracle database.  Then, insert/update your Oracle table, making sure to keep the key away from Oracle.  In terms of where you might want to store the key, Amazon's S3 would be one option, or you could keep it on premise somewhere in a place not accessible by your DBAs.</p>


问:
Decorator assignment
Suppose decorator

```<code>@app.callback(
    Output("plot_1", "figure"),
    [Input("checklist", "value"),
     Input("radio", "value")])
</code>```

which is repeated in code several times. The only difference between the copies is different plot names.

How is it possible to assign that decorator to another decorator and use the latter?

```<code>@new_callback("plot_1")
</code>```

答:
You can wrap a decorator in its own decorator and use arguments you pass in any of the sub-functions, like so:

```<code>def decorator_wrapper(arg1):

    # do something with arg1:
    print('Inside decorator_wrapper, arg1: ' + str(arg1))

    def decorator(function):

        print('Inside decorator, arg1: ' + str(arg1))

        def wrapper(*args, **kwargs):

            print('Inside wrapper, arg1: ' + str(arg1))

            # execute decorated function:
            result = function(*args, **kwargs)

            return result

        return wrapper

    return decorator

@decorator_wrapper('a')
def MyFunction():

    print('This is my function')

MyFunction()
</code>```

This will result in:

```<code>Inside decorator_wrapper, arg1: a
Inside decorator, arg1: a
Inside wrapper, arg1: a
This is my function
</code>```

More here: https://www.geeksforgeeks.org/decorators-with-parameters-in-python/

Title: Decorator assignment

Body:
Suppose decorator

@app.callback(
    Output("plot_1", "figure"),
    [Input("checklist", "value"),
     Input("radio", "value")])

which is repeated in code several times. The only difference between the copies is different plot names.

How is it possible to assign that decorator to another decorator and use the latter?

@new_callback("plot_1")

Body:
You can wrap a decorator in its own decorator and use arguments you pass in any of the sub-functions, like so:

def decorator_wrapper(arg1):

    # do something with arg1:
    print('Inside decorator_wrapper, arg1: ' + str(arg1))

    def decorator(function):

        print('Inside decorator, arg1: ' + str(arg1))

        def wrapper(*args, **kwargs):

            print('Inside wrapper, arg1: ' + str(arg1))

            # execute decorated function:
            result = function(*args, **kwargs)

            return result

        return wrapper

    return decorator

@decorator_wrapper('a')
def MyFunction():

    print('This is my function')

MyFunction()

This will result in:

Inside decorator_wrapper, arg1: a
Inside decorator, arg1: a
Inside wrapper, arg1: a
This is my function

More here: https://www.geeksforgeeks.org/decorators-with-parameters-in-python/


问:
Where is git.exe located?
I have PyCharm and I am looking around trying to find git.exe to set it up with my repo.

What is the PATH to git.exe?

答: Sometimes it can be at: C:\Users\user-name\AppData\Local\Programs\Git\cmd. Checking your PATH environment variable for USER and for SYSTEM can give you that.

ContentLicense: CC BY-SA 3.0

Title: Where is git.exe located?


问:
Not able to configure Moxy using JAXB
I am using Moxy Implementation of JAXB in my codeset and trying to create paths using @XMLPath but it seems to be not working. I have a Spring bassed Project and I have created jaxb.properties under /project/WEB/src/main/resources having content :

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

My classes are placed under /project/WEB/src/main/java
I have configured my pom.xml to download the dependancy.
persistence.moxy -->

```<code><dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
     <version>2.4.0</version>
</dependency>
</code>```

When I run the code on WAS server, Moxy is not recongnized and the path is not created. Not sure what am I doing wrong.

I even tried testing my JAXBContext class but what I get on the console is :

```<code>JAXBContext jaxbContext = JAXBContext.newInstance(DocGenerator.class);
System.out.println(jaxbContext.getClass());
</code>```

class com.sun.xml.bind.v2.runtime.JAXBContextImpl

Can someone please help ?

答:
In case this helps anyone else, the following fixed my recent "MOXy is configured but is being ignored" problem.

I tested it on Java 11 (Open JDK) by implementing the first example shown in the @XmlPath Javadoc.

In line with the instructions here, I added the required properties file to the package containing my domain classes (the annotated beans which I wanted to serialize).

Solution for my IDE

The step I initially forgot to do was this:

My IDE only copies compiled .class files to the target directory - it does not copy anything else (such as my properties file).

Duh.

How you fix that depends on your IDE. For me, it was a simple change to the ant build configuration for my project.

If you are using Maven, then the build step in the pom.xml would be as follows:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
    </resources>
</build>
```
<h2>Solution for the JAR</h2>
<p>Similarly, Maven needs to be instructed to copy the file to that folder in your JAR.  There are various ways to do this.  See this question for some answers.</p>
<h2>Resources Directory</h2>
<p>Placing this specific config file into a <code>resources</code> directory does <em><strong>not</strong></em> work (at least, it did not work for me). The MOXy instructions are quite specific - and need to be followed exactly.</p>
<h2>POM Dependencies</h2>
<p>In Java 11, the module java.se.ee has been removed. See JEP-320. This module includes JAXB (and JAX-WS). To use JAXB in Java 11 and newer, you need to add it to your project as a separate library.</p>
<p>Given that, here are my POM dependencies, for the record:</p>
```        <dependency>
            <groupId>com.sun.activation</groupId>
            <artifactId>javax.activation</artifactId>
            <version>1.2.0</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.3.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.7.6</version>
        </dependency>
```
<hr />
<h2><strong>UPDATES</strong> for MOXy version 3</h2>
<p>The above notes work for MOXy version 2.7.6.</p>
<p>To work with version 3+, you need to take into account the recent transfer of many <code>javax</code> packages to Jakarta. You can read the background to this move here.</p>
<p>Steps to upgrade your project:</p>
<ol>
<li>Change the <code>jaxb.properties</code> file to the following:</li>
</ol>
```jakarta.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
```
<p>Note the changed reference to <code>jakarta</code> here, for the bind context.</p>
<ol start="2">
<li>Change <strong>all</strong> of your jaxb imports to refer to <code>jakarta</code> instead of <code>javax</code>. So, for example, change this:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>import javax.xml.bind.JAXBContext; // old import
</code>```

to this:

import jakarta.xml.bind.JAXBContext; // new import
```
<ol start="3">
<li>Use the following two dependencies in your <code>pom.xml</code>:</li>
</ol>
<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>3.0.1</version>
</dependency>

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>3.0.0</version>
</dependency>
</code>```

These two dependencies are sufficient to support an updated version of the code example presented here: XPath Based Mapping using MOXy.

Title: Not able to configure Moxy using JAXB

Body:
I am using Moxy Implementation of JAXB in my codeset and trying to create paths using @XMLPath but it seems to be not working. I have a Spring bassed Project and I have created jaxb.properties under /project/WEB/src/main/resources having content :

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

My classes are placed under /project/WEB/src/main/java
I have configured my pom.xml to download the dependancy.
persistence.moxy -->

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
     <version>2.4.0</version>
</dependency>

When I run the code on WAS server, Moxy is not recongnized and the path is not created. Not sure what am I doing wrong.

I even tried testing my JAXBContext class but what I get on the console is :

JAXBContext jaxbContext = JAXBContext.newInstance(DocGenerator.class);
System.out.println(jaxbContext.getClass());

class com.sun.xml.bind.v2.runtime.JAXBContextImpl

Can someone please help ?

Body:
In case this helps anyone else, the following fixed my recent "MOXy is configured but is being ignored" problem.

I tested it on Java 11 (Open JDK) by implementing the first example shown in the @XmlPath Javadoc.

In line with the instructions here, I added the required properties file to the package containing my domain classes (the annotated beans which I wanted to serialize).

Solution for my IDE

The step I initially forgot to do was this:

My IDE only copies compiled .class files to the target directory - it does not copy anything else (such as my properties file).

Duh.

How you fix that depends on your IDE. For me, it was a simple change to the ant build configuration for my project.

If you are using Maven, then the build step in the pom.xml would be as follows:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Solution for the JAR

Similarly, Maven needs to be instructed to copy the file to that folder in your JAR.  There are various ways to do this.  See this question for some answers.

Resources Directory

Placing this specific config file into a resources directory does not work (at least, it did not work for me). The MOXy instructions are quite specific - and need to be followed exactly.

POM Dependencies

In Java 11, the module java.se.ee has been removed. See JEP-320. This module includes JAXB (and JAX-WS). To use JAXB in Java 11 and newer, you need to add it to your project as a separate library.

Given that, here are my POM dependencies, for the record:

        <dependency>
            <groupId>com.sun.activation</groupId>
            <artifactId>javax.activation</artifactId>
            <version>1.2.0</version>
        </dependency>

        <!--
             Use 2.3.1 below to prevent "illegal
             reflective access operation" warnings.
        -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.3.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.7.6</version>
        </dependency>

UPDATES for MOXy version 3

The above notes work for MOXy version 2.7.6.

To work with version 3+, you need to take into account the recent transfer of many javax packages to Jakarta. You can read the background to this move here.

Steps to upgrade your project:

Change the jaxb.properties file to the following:

jakarta.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Note the changed reference to jakarta here, for the bind context.

Change all of your jaxb imports to refer to jakarta instead of javax. So, for example, change this:

import javax.xml.bind.JAXBContext; // old import

to this:

import jakarta.xml.bind.JAXBContext; // new import

Use the following two dependencies in your pom.xml:

<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>3.0.1</version>
</dependency>

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>3.0.0</version>
</dependency>

These two dependencies are sufficient to support an updated version of the code example presented here: XPath Based Mapping using MOXy.


问:
Memory allocation for objects in arrays
so this is my code [ notice that I commented the cstr and destructor]

```<code>#include <iostream>
#include <stdlib.h>
#include <array>

class MyIntClass
{
    int _mymember;

  public:

// MyIntClass(){}
// ~MyIntClass(){}

void *operator new(size_t size)
{
    std::cout << "new: Allocating " << size << " bytes of memory" << std::endl;
    void *p = malloc(size);

    return p;
}
void operator delete(void *p)
{
    std::cout << "delete: Memory is freed again " << std::endl;
    free(p);
}

void *operator new[](size_t size)
{
    std::cout << "new: Allocating " << size << " bytes of memory" << std::endl;
    void *p = malloc(size);

    return p;
}

  void operator delete[](void *p)
    {
        std::cout << "delete: Memory is freed again " << std::endl;
        free(p);
    }
};

void line(){
        std::cout << "\n--------------------------------------------------\n" << std::endl;
}

int main()
{
    line();
    std::cout << "Using new overloading and malloc\nWe will create one object of MyIntClass that is supposed to be 4 bytes" << std::endl;
    MyIntClass *m1 = new MyIntClass();

    line();
    //I want to create an array of the MyIntClass of two objects
    std::cout << "Now we create array of MyIntClass using <array> header" << std::endl;
    std::array<MyIntClass, 2> z = {};

    std::cout << " The elements in the array z = "<< z.size() <<std::endl;

    std::cout << "The memory allocated for  array z = " << sizeof(z) << std::endl;

    line();

    std::cout << "\nNow we create array using new[] overloading and malloc " << std::endl;

    MyIntClass *i = new MyIntClass[2]();
    delete[] i;
}
</code>```

now the result is as follow:

Using new overloading and malloc

    We will create one object of MyIntClass that is supposed to be 4 bytes

new: Allocating 4 bytes of
  memory

Now we create array of MyIntClass using <array> header

  The elements in the array z = 2

  The memory allocated for  array z = 8

Now we create array using new[] overloading and malloc

   new: Allocating  8 bytes of memory

To me as inexperienced C++ programmer I think every thing is working as expected

Now If I uncomment the constructor the same result will happen

however when I uncomment the destructor different result will occur

Now we create array using new[] overloading and malloc

   new: Allocating  12 bytes of memory

So my question is what is the explanation for this:
creating array of two objects each is 4 bytes will result in 8byte memory allocation for the array in both methods using the array library or the overloading the new[] and malloc.

however when we have a destructor for the object the malloc will allocate 12 bytes not 8 bytes for this array of 2 elements.

I saw this  question on SO but it didn't explain my case

following is my compiler version :

gcc version 8.2.0 (MinGW.org GCC-8.2.0-3)

答: The reason for extra allocated memory is that the compiler needs to know the number of elements in the array in order to be able to call destructors on each element of the array when you call delete[]. For trivially destructible types the compiler doesn't need to call destructor, so the extra space for the array size is not needed.

Title: Memory allocation for objects in arrays

Body:
so this is my code [ notice that I commented the cstr and destructor]

#include <iostream>
#include <stdlib.h>
#include <array>

class MyIntClass
{
    int _mymember;

  public:

// MyIntClass(){}
// ~MyIntClass(){}

void *operator new(size_t size)
{
    std::cout << "new: Allocating " << size << " bytes of memory" << std::endl;
    void *p = malloc(size);

    return p;
}
void operator delete(void *p)
{
    std::cout << "delete: Memory is freed again " << std::endl;
    free(p);
}

void *operator new[](size_t size)
{
    std::cout << "new: Allocating " << size << " bytes of memory" << std::endl;
    void *p = malloc(size);

    return p;
}

  void operator delete[](void *p)
    {
        std::cout << "delete: Memory is freed again " << std::endl;
        free(p);
    }
};

void line(){
        std::cout << "\n--------------------------------------------------\n" << std::endl;
}

int main()
{
    line();
    std::cout << "Using new overloading and malloc\nWe will create one object of MyIntClass that is supposed to be 4 bytes" << std::endl;
    MyIntClass *m1 = new MyIntClass();

    line();
    //I want to create an array of the MyIntClass of two objects
    std::cout << "Now we create array of MyIntClass using <array> header" << std::endl;
    std::array<MyIntClass, 2> z = {};

    std::cout << " The elements in the array z = "<< z.size() <<std::endl;

    std::cout << "The memory allocated for  array z = " << sizeof(z) << std::endl;

    line();

    std::cout << "\nNow we create array using new[] overloading and malloc " << std::endl;

    MyIntClass *i = new MyIntClass[2]();
    delete[] i;
}

now the result is as follow:

Using new overloading and malloc

    We will create one object of MyIntClass that is supposed to be 4 bytes

new: Allocating 4 bytes of
  memory

Now we create array of MyIntClass using <array> header

  The elements in the array z = 2

  The memory allocated for  array z = 8

Now we create array using new[] overloading and malloc

   new: Allocating  8 bytes of memory

To me as inexperienced C++ programmer I think every thing is working as expected

Now If I uncomment the constructor the same result will happen

however when I uncomment the destructor different result will occur

Now we create array using new[] overloading and malloc

   new: Allocating  12 bytes of memory

So my question is what is the explanation for this:
creating array of two objects each is 4 bytes will result in 8byte memory allocation for the array in both methods using the array library or the overloading the new[] and malloc.

however when we have a destructor for the object the malloc will allocate 12 bytes not 8 bytes for this array of 2 elements.

I saw this  question on SO but it didn't explain my case

following is my compiler version :

gcc version 8.2.0 (MinGW.org GCC-8.2.0-3)


问:
.rprofile not source when creating RStudio project
In Windows 7, I have my .Rprofile in a custom location (not R_HOME, not HOME). I informed the OS of this location via the user environment variable R_ENVIRON_USER pointing to this location. There is no other .Rprofile anywhere else.

In RStudio, I set the default working directory (when not in a project) to this same location

When not in a project, the .Rprofile is properly sourced. However, when inside another project or when creating a new one, the .Rprofile is not sourced.

How do I ensure, that my .RProfile is properly sourced even inside projects (assuming there is no project-specific .RProfile inside the project dir)? I thought the environment variable would take care of that.

Answer & Update

I had to set the environment variable R_PROFILE_USER and provide the full path and filename of the .Rprofile. In a command prompt, I typed:

SETX R_PROFILE_USER "C:\Users\tspeidel\OneDrive\.Rprofile"

答:
You misunderstand what R_ENVIRON_USER is for; it sets a value to source an (optional) .Renviron file for the user from the location it provies.

It does not affect what the system thinks your home directory is.  That is still governed by HOME which you set on Windows with the same UI. And you can't just substitute R_HOME for it.

You can however read very carefully what R tells you about its process in help(Startup).  Which is, as often, somewhat dense and terse but it does get to the real meat.  In short, I think you may want to use another variable to point to alternate Rprofile.

None of this has anything to do with RStudio which, after all, just calls R for  you (and cannot, as a running process, alter HOME).


问:
Searching For String Literals
In the quest for localization I need to find all the string literals littered amongst our source code. I was looking for a way to script this into a post-modification source repository check. (I.E. after some one checks something in have a box setup to check this stat) I'll probably use NAnt and CruiseControl or something to handle the management of the CVS (Well StarTeam in my case :( ) But do you know of any scriptable (or command line) utility to accurately cycle through source code looking for string literals? I realize I could do simple string look up based on regular expressions but want a little more bang for my buck. (Maybe analyze the string or put it into categories) Because a lot of times the string may not necessarily require translation. Any ideas?</p>

答:
Find In Files (CTRL+SHIFT+F)

Find options -> Check Use Regular Expressions

For specific text within the literal:

Find what: "+.*(MYSPECIFICTEXT)+.*"+

For all literals

Find what: "+.*"+

Then

Find All

OwnerDisplayName: Adam Driscoll

ContentLicense: CC BY-SA 2.5

Title: Searching For String Literals


问:
How to delete all ?source line code in URL with rewrite rule for the 301 redirect
Please help me to write the correct RewriteRule for the 301 redirect (.htaccess under subdomain blog.example.com) for the links like:

from

```<code>https://blog.example.com/?source=tag_archive---------0-----------
</code>```

redirect to

```<code>https://example.com/blog/
</code>```

I use these lines in .htaccess:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST}  ^blog\.example\.com$ [NC]
RewriteCond %{QUERY_STRING}  ^source=tag_archive---------0-----------(&.*)?$ [NC]
RewriteRule ^(.*)$ https://example.com/blog/  [R=301,NE,NC,L]
</code>```

With the example above I got

```<code>https://example.com/blog/?source=tag_archive---------0-----------
</code>```

but need

```<code>https://example.com/blog/
</code>```

(without part ?source=tag_archive---------0-----------)

答:
On Apache 2.4+ you need to add the QSD (Query String Discard) flag to the RewriteRule directive:

```<code>RewriteRule ^ https://domainname.com/blog/  [QSD,R=301,L]
</code>```

(Alternatively, if you are still on Apache 2.2, then append a ? to the end of the substitution string - effectively an empty query string. The ? itself will not be in the redirect response.)

^(.*)$ (the RewriteRule pattern) - since you are matching any URL-path and not using the backreference, this can be simplified to ^.

The NC and NE flags are not required here.

However, as noted above, this redirects any URL-path. If you specifically want to redirect https://blog.example.com/?source=tag... only then change the RewriteRule pattern to ^$ (an empty URL-path). For example:

```<code>RewriteRule ^$ https://domainname.com/blog/  [QSD,R=301,L]
</code>```

Body:
Please help me to write the correct RewriteRule for the 301 redirect (.htaccess under subdomain blog.example.com) for the links like:

from

https://blog.example.com/?source=tag_archive---------0-----------

redirect to

https://example.com/blog/

I use these lines in .htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST}  ^blog\.example\.com$ [NC]
RewriteCond %{QUERY_STRING}  ^source=tag_archive---------0-----------(&.*)?$ [NC]
RewriteRule ^(.*)$ https://example.com/blog/  [R=301,NE,NC,L]

With the example above I got

https://example.com/blog/?source=tag_archive---------0-----------

but need

https://example.com/blog/

(without part ?source=tag_archive---------0-----------)

Body:
On Apache 2.4+ you need to add the QSD (Query String Discard) flag to the RewriteRule directive:

RewriteRule ^ https://domainname.com/blog/  [QSD,R=301,L]

(Alternatively, if you are still on Apache 2.2, then append a ? to the end of the substitution string - effectively an empty query string. The ? itself will not be in the redirect response.)

^(.*)$ (the RewriteRule pattern) - since you are matching any URL-path and not using the backreference, this can be simplified to ^.

The NC and NE flags are not required here.

However, as noted above, this redirects any URL-path. If you specifically want to redirect https://blog.example.com/?source=tag... only then change the RewriteRule pattern to ^$ (an empty URL-path). For example:

RewriteRule ^$ https://domainname.com/blog/  [QSD,R=301,L]


问:
Multiple Project in Same Solution with inter-project depedencies - Deploy using Azure DevOps - CICD Pipeline
I have a Github repo that contains Visual Studio solution having multiple projects and want to setup Azure DevOps pipelines separately for the projects which will trigger according to the commit.

Solution

1) DataFactory

2) BusinessLogic

3) DataAcessLayer

4) WebAPI

5) UI

Also, One project have inter-project dependencies for other projects like

1 WebAPI => DataFactory & BusinessLogic

2 BusinessLogic => DataFactory & DataAcessLayer

So, This can be managed?
- I already tried paths

I'm not able to see any path filter here:

Please let me know how it can be done.

答: You are using "Other Git" as source (repository) and that does not provide path filters. Try using Azure Repos Git / GitHub / GitHub Enterprise as source, those do provide path filters.</p>


问:
how to Change my app's target API level from 23 to 26
I have a problem when i try to upload my app to google play console and it is the API level that is must be 26 and my app is just developped with 23 version and now i don't know how to change this API version from 23 to 26 to make it works without errors.

Help me please!

答:
For those looking at this in Android Studio 3.5.3

Go to File >Project Structure.

Select Modules on the left panel

Select app on center panel

On the right panel, click on Default Config

Change Target SDK Version to the required version


问:
How can I debug a Dataflow error that does not produce logs?
I am writing at Google Dataflow batch pipeline using the Python SDK and I have come across a pipeline failure that does not appear to have any logs in Stackdriver. The failure occurs while running beam.combiners.ToList() on a dataset ~300MB.

Stackdriver outputs:

The job failed because a work item has failed 4 times. Look in previous log entries for the cause of each one of the 4 failures. For more information, see https://cloud.google.com/dataflow/docs/guides/common-errors. The work item was attempted on these workers:

However there are no logs I can find on why this is failing. I am running python3.6 and apache_beam==2.19.0. I am also running --experiments=shuffle_mode=service, which I am not sure is related.

What are my next steps for debugging?

答:
I can see that you have already tried to search for previous logs entries, but I was wondering if you have filtered by Error-level and Fatal-level as recommended in The job failed because a work item failed 4 times? In this link you will find that there could be 4 similar errors which can be the cause of the failure.

In addition, you can add debug messages to verify your steps are flowing well, please refer to Adding log messages to your pipeline for more information about it.


问:
How to update xlsm file since DataFrame?
I need to update an xlsm file using python from a DataFrame. How can I modify that file without errors? My principal problem is this: I overwrite the file and save it, and I when go to open it, the file is corrupt and I can't open it.

def write_data(self, sheet, col_start, row_start):
        with ExcelWriter('TEST.xlsm') as writer:
            self.get_data2post(sheet).to_excel(writer,
                                               startcol = col_start,
                                               startrow = row_start,
                                               sheet_name = sheet,
                                               header = False,
                                               index = False)
        writer.save()
        writer.close()
```

答: At the moment, it can't save an excel file with macros from pandas or ExcelWriter. So, I've had to use a different library, _openpyxl_ and with this, I can read and write an excel file with macros, but... this has a few problems like losing some images, and formulas are not calculated


问:
Android Silent Mode Toggle
I started reading Android for dummies and I am trying to make my first app that is Silent Mode Toggle.

Now the problem I'm facing is:

In the layout, I need something like only one button should be there. If the phone is on silent the text should read "Silent Mode Activated" and when the phone is in normal mode "Normal Mode Activated".

It should ask the user that He/She wants to activate vibration mode or not.

Below is my code :

XML Layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" >

    <ImageView
        android:id="@+id/phone_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="7dp"
        android:src="@drawable/phone_on" />

    <Button
        android:id="@+id/silent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="35dp"
        android:text="@string/silent_off" />

</LinearLayout>
</code>```

Java Code

```<code>public class MainActivity extends Activity {
    private AudioManager mAudioManager;
    private boolean mPhoneIsSilent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        checkIfPhoneIsSilent();
        setButtonClickListener();
        Log.d("SilentModeApp", "This is a test");
    }

    private void setButtonClickListener() {
        Button toggleButton = (Button)findViewById(R.id.silent);
        toggleButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mPhoneIsSilent) {
                    //change back to normal mode
                    mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    mPhoneIsSilent = false;
                }
                else
                {
                    //change to silent mode
                    mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                    mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                    mPhoneIsSilent = true;
                }
                // Now toggle the UI again
                toggleUi();
            }
        });
    }

    private void checkIfPhoneIsSilent() {
        int ringermode = mAudioManager.getRingerMode();
        if (ringermode == AudioManager.RINGER_MODE_SILENT) {
            mPhoneIsSilent = true;
        }
        else
        {
            mPhoneIsSilent = false;
        }
    }

    private void toggleUi() {
        ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
        Drawable newPhoneImage;
        if (mPhoneIsSilent){
            newPhoneImage =
                    getResources().getDrawable(R.drawable.phone_silent);
        }
        else
        {
            newPhoneImage =
                    getResources().getDrawable(R.drawable.phone_on);

        }
        imageView.setImageDrawable(newPhoneImage);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkIfPhoneIsSilent();
        toggleUi();
    }
}
</code>```

Update

Now I removed "mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); " and its going to vibration mode from normal mode.

I need help with the layout thing.

I need 3 buttons and a text status text - I know how to create buttons and text message, what I dont know is how to integrate it with java.

I need if the phone is in normal mode there should be a status message below image above buttons : (XXX MODE IS ACTIVATED ) where XXX is Silent, Normal Or Vibrate.

The if the phone is in normal mode then there should be only 2 buttons : Switch to silent mode and Switch to vibration mode.

And the same thing with other modes too.

答:
```<code>AndriodManifest.xml
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>

package com.example.myapplication;

import android.Manifest;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.provider.Settings;
import android.service.notification.StatusBarNotification;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import static android.app.NotificationManager.*;

public class MainActivity extends AppCompatActivity {
    AudioManager audioManager;
    //private int CAMREA_CODE = 1;

    private int MOD_ADO_CODE=1;
    private NotificationManager mNotificationManager;
    private StatusBarNotification[] mText;
    private int MZenMode;
    private static final String TAG = "ZenModeObserver";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        setContentView(R.layout.activity_main);
        FrameLayout contentView = (FrameLayout) findViewById(R.id.content);
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        contentView.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        //RingerHelper.performToggle(audioManager);
                        //Toast.makeText(MainActivity.this, Policy, Toast.LENGTH_SHORT).show();
                        try {
                            MZenMode=logZenModeState();
                        } catch (Settings.SettingNotFoundException e) {
                            e.printStackTrace();
                        }
                        if (MZenMode==2)
                            changeInterruptionFiler(INTERRUPTION_FILTER_ALL);
                        else
                            changeInterruptionFiler(INTERRUPTION_FILTER_NONE);
                        updateUi();
                    }
                }
        );
    }
    private void updateUi() {
        ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
        int phoneImage = MZenMode==2?R.drawable.ringer_off : R.drawable.ringer_on;
        //int phoneImage = RingerHelper.isPhoneSilent(audioManager) ? R.drawable.ringer_off : R.drawable.ringer_on;
        imageView.setImageResource(phoneImage);
    }

    protected void changeInterruptionFiler(int interruptionFilter) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (mNotificationManager.isNotificationPolicyAccessGranted()) {
                mNotificationManager.setInterruptionFilter(interruptionFilter);

            } else {
                Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                startActivity(intent);
            }
        }
    }

    private int logZenModeState() throws Settings.SettingNotFoundException {
        int zenModeValue = Settings.Global.getInt(getContentResolver(), "zen_mode");
        return zenModeValue;
    }

    private class ZenModeObserver extends ContentObserver {

        ZenModeObserver(Handler handler) {
            super(handler);
        }
    }
        @Override
    protected void onResume()
    {
        super.onResume();
        updateUi();
    }

}
</code>```

Title: Android Silent Mode Toggle

Body:
I started reading Android for dummies and I am trying to make my first app that is Silent Mode Toggle.

Now the problem I'm facing is:

In the layout, I need something like only one button should be there. If the phone is on silent the text should read "Silent Mode Activated" and when the phone is in normal mode "Normal Mode Activated".

It should ask the user that He/She wants to activate vibration mode or not.

Below is my code :

XML Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" >

    <ImageView
        android:id="@+id/phone_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="7dp"
        android:src="@drawable/phone_on" />

    <Button
        android:id="@+id/silent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="35dp"
        android:text="@string/silent_off" />

</LinearLayout>

Java Code

public class MainActivity extends Activity {
    private AudioManager mAudioManager;
    private boolean mPhoneIsSilent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        checkIfPhoneIsSilent();
        setButtonClickListener();
        Log.d("SilentModeApp", "This is a test");
    }

    private void setButtonClickListener() {
        Button toggleButton = (Button)findViewById(R.id.silent);
        toggleButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mPhoneIsSilent) {
                    //change back to normal mode
                    mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                    mPhoneIsSilent = false;
                }
                else
                {
                    //change to silent mode
                    mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                    mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                    mPhoneIsSilent = true;
                }
                // Now toggle the UI again
                toggleUi();
            }
        });
    }

    private void checkIfPhoneIsSilent() {
        int ringermode = mAudioManager.getRingerMode();
        if (ringermode == AudioManager.RINGER_MODE_SILENT) {
            mPhoneIsSilent = true;
        }
        else
        {
            mPhoneIsSilent = false;
        }
    }

    private void toggleUi() {
        ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
        Drawable newPhoneImage;
        if (mPhoneIsSilent){
            newPhoneImage =
                    getResources().getDrawable(R.drawable.phone_silent);
        }
        else
        {
            newPhoneImage =
                    getResources().getDrawable(R.drawable.phone_on);

        }
        imageView.setImageDrawable(newPhoneImage);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkIfPhoneIsSilent();
        toggleUi();
    }
}

Update

Now I removed "mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); " and its going to vibration mode from normal mode.

I need help with the layout thing.

I need 3 buttons and a text status text - I know how to create buttons and text message, what I dont know is how to integrate it with java.

I need if the phone is in normal mode there should be a status message below image above buttons : (XXX MODE IS ACTIVATED ) where XXX is Silent, Normal Or Vibrate.

The if the phone is in normal mode then there should be only 2 buttons : Switch to silent mode and Switch to vibration mode.

And the same thing with other modes too.


问:
java force an extending class
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

```<code>public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}
</code>```

答: No Constructors aren't inherited, so each Class needs to provide its own, unless you don't specify a constructor and get the default no args constructor.</p>

Title: java force an extending class

Body:
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}


问:
Laravel - Exception thrown at Guzzle function when running seeder
Running php artisan db:seed throws the following error: GuzzleHttp\Exception\InvalidArgumentException  : IDN conversion failed (errors: IDNA_ERROR_EMPTY_LABEL) at vendor/guzzlehttp/guzzle/src/functions.php:384

Never seen this error before and it doesn't appear to be an issue with my seeder syntax.

The partial exception trace is:

```<code>1   GuzzleHttp\_idn_uri_convert()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:220

2   GuzzleHttp\Client::buildUri()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:113
</code>```

I'm running commands within a vagrant/homestead environment. Could this be a version incompatibility?

答:
Please, try to upgrade to the latest stable version (6.5.2 at the moment). We did our best to consider all possible installation details, so you should not have this error anymore.

If the error still occurs, please report it as a bug here: https://github.com/guzzle/guzzle/issues.

Body:
Running php artisan db:seed throws the following error: GuzzleHttp\Exception\InvalidArgumentException  : IDN conversion failed (errors: IDNA_ERROR_EMPTY_LABEL) at vendor/guzzlehttp/guzzle/src/functions.php:384

Never seen this error before and it doesn't appear to be an issue with my seeder syntax.

The partial exception trace is:

1   GuzzleHttp\_idn_uri_convert()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:220

2   GuzzleHttp\Client::buildUri()
      /home/vagrant/code/companion-2.0/vendor/guzzlehttp/guzzle/src/Client.php:113

I'm running commands within a vagrant/homestead environment. Could this be a version incompatibility?