问:
How can I keep the tooltip position on any screen using extjs 3.4?
I need to keep the tooltip position on any screen using extjs 3.4

Notebook Example (the right way):

notebook screen image

Monitor Example (the wrong way):

monitor screen image

I want to keep the tooltip on the right side as in the first image, but if I change the page to the monitor, the tooltip changes its position

I have the tooltip in a tbar of a grid:

```<code>tbar :  [{
                      text: '<b>DEFINIR METAS</b>',
                      id    : 'id_btn_definir_metas',
                      itemId: 'id_btn_definir_metas',
                      icon: '../icons/add.png',
                      scope: this,
                      scale: 'small',
                      iconAlign: 'left',
                      disabled: true,
                      handler: function(){

                            modal_ventana_definir_metas();
                            Ext.getCmp('id_textarea_observacion_metas').setValue(obs_general_de_metas);

                      }
                    },{
                      xtype: 'tbseparator',
                    },{
                      icon: '../icons/question-frame.png',
                      itemId: 'id_btn_agregar_metas',
                      disabled : true,
                      listeners: {
                          render: function(c) {
                              new Ext.ToolTip({
                                  dismissDelay: 50000,
                                  target: c.getEl(),
                                  getTargetXY: function() {
                                    return [290,300];
                                  },
                                  html: 'Presione el botón "DEFINIR METAS" para iniciar el proceso de definición de metas.'
                              });
                          }
                      },
}],
</code>```

Sorry by my english

答:
the problem was that I was specifying the position.

Of this way work perfectly:

```<code>tbar :  [{
                      text: '<b>DEFINIR METAS</b>',
                      id    : 'id_btn_definir_metas',
                      itemId: 'id_btn_definir_metas',
                      icon: '../icons/add.png',
                      scope: this,
                      scale: 'small',
                      iconAlign: 'left',
                      disabled: true,
                      handler: function(){

                            modal_ventana_definir_metas();
                            Ext.getCmp('id_textarea_observacion_metas').setValue(obs_general_de_metas);

                      }
                    },{
                      xtype: 'tbseparator',
                    },{
                      icon: '../icons/question-frame.png',
                      itemId: 'id_btn_agregar_metas',
                      disabled : true,
                      listeners: {
                          render: function(c) {
                              new Ext.ToolTip({
                                  dismissDelay: 50000,
                                  target: c.getEl(),
                                  //target: targetId,
                                  //html: 'ToolTip',
                                  anchor: 'left',
                                  //dismissDelay: 0,
                                  showDelay: 0,
                                  //autoHide: false,
                                  // getTargetXY: function() {
                                  //   return [290,300];
                                  // },
                                  html: 'Presione el botón "DEFINIR METAS" para iniciar el proceso de definición de metas.'
                              });
                          }
                      },
                    }],
</code>```

Body:
I need to keep the tooltip position on any screen using extjs 3.4

Notebook Example (the right way):

notebook screen image

Monitor Example (the wrong way):

monitor screen image

I want to keep the tooltip on the right side as in the first image, but if I change the page to the monitor, the tooltip changes its position

I have the tooltip in a tbar of a grid:

tbar :  [{
                      text: 'DEFINIR METAS',
                      id    : 'id_btn_definir_metas',
                      itemId: 'id_btn_definir_metas',
                      icon: '../icons/add.png',
                      scope: this,
                      scale: 'small',
                      iconAlign: 'left',
                      disabled: true,
                      handler: function(){

                            modal_ventana_definir_metas();
                            Ext.getCmp('id_textarea_observacion_metas').setValue(obs_general_de_metas);

                      }
                    },{
                      xtype: 'tbseparator',
                    },{
                      icon: '../icons/question-frame.png',
                      itemId: 'id_btn_agregar_metas',
                      disabled : true,
                      listeners: {
                          render: function(c) {
                              new Ext.ToolTip({
                                  dismissDelay: 50000,
                                  target: c.getEl(),
                                  getTargetXY: function() {
                                    return [290,300];
                                  },
                                  html: 'Presione el botón "DEFINIR METAS" para iniciar el proceso de definición de metas.'
                              });
                          }
                      },
}],

Sorry by my english

Body:
the problem was that I was specifying the position.

Of this way work perfectly:

tbar :  [{
                      text: '<b>DEFINIR METAS</b>',
                      id    : 'id_btn_definir_metas',
                      itemId: 'id_btn_definir_metas',
                      icon: '../icons/add.png',
                      scope: this,
                      scale: 'small',
                      iconAlign: 'left',
                      disabled: true,
                      handler: function(){

                            modal_ventana_definir_metas();
                            Ext.getCmp('id_textarea_observacion_metas').setValue(obs_general_de_metas);

                      }
                    },{
                      xtype: 'tbseparator',
                    },{
                      icon: '../icons/question-frame.png',
                      itemId: 'id_btn_agregar_metas',
                      disabled : true,
                      listeners: {
                          render: function(c) {
                              new Ext.ToolTip({
                                  dismissDelay: 50000,
                                  target: c.getEl(),
                                  //target: targetId,
                                  //html: 'ToolTip',
                                  anchor: 'left',
                                  //dismissDelay: 0,
                                  showDelay: 0,
                                  //autoHide: false,
                                  // getTargetXY: function() {
                                  //   return [290,300];
                                  // },
                                  html: 'Presione el botón "DEFINIR METAS" para iniciar el proceso de definición de metas.'
                              });
                          }
                      },
                    }],


来源: stackexchange

问:
QGridLayout with PlotWidget-pyqtgraph
I have 3 PlotWidget (from the pyqtgraph library), obj1, obj2 and obj3, which I try to insert in a QGridLayout. I want to display all three objects in a single row, but obj1 must be twice as large as obj2 and obj3.

Thus I wrote:

```<code>layout.addWIdget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)
</code>```

However, visually, obj1 is much smaller than obj2 and obj3 which do have the same size:

```<code>---------------------------------------------------
| obj1 |     obj2           |         obj3         |
---------------------------------------------------
</code>```

However, if I write:

```<code>layout.addWIdget(obj1, 0, 0, 1, 1)
layout.addWidget(obj2, 0, 1, 1, 6)
layout.addWidget(obj3, 0, 7, 1, 6)
</code>```

obj1 appears bigger than obj2 and obj3 which are still of the same size, which is the expected behavior:

```<code>---------------------------------------------------
|          obj1           |    obj2   |    obj3   |
---------------------------------------------------
</code>```

It seems totally contradictory to the doc of addWidget as my first solution should yield the expected behavior, no?

EDIT: Piece of code

```<code>import pyqtgraph as qtg

obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

layout = QGridLayout()

layout.addWIdget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)

box = QGroupBox()
box.setLayout(layout)
self.setCentralWidget(box)
</code>```

答:
When you use void QGridLayout::addWidget(QWidget* widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0), rowSpan and columnSpan refers to the other row or another column, and as in your case you have just given a row the rowSpan is not applied, for example if you add a new row you get the following:

```<code>obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

obj4 = qtg.PlotWidget()
obj5 = qtg.PlotWidget()
obj6 = qtg.PlotWidget()
obj7 = qtg.PlotWidget()

layout = QGridLayout()

layout.addWidget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)
layout.addWidget(obj4, 1, 0, 1, 1)
layout.addWidget(obj5, 1, 1, 1, 1)
layout.addWidget(obj6, 1, 2, 1, 1)
layout.addWidget(obj7, 1, 3, 1, 1)

box = QGroupBox(self)
box.setLayout(layout)
self.setCentralWidget(box)
</code>```

If you need to establish the proportions you must use stretch, in this case setColumnStretch():

```<code>obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

layout = QGridLayout()

layout.addWidget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)
layout.setColumnStretch(0, 2)
layout.setColumnStretch(2, 1)
layout.setColumnStretch(3, 1)

box = QGroupBox(self)
box.setLayout(layout)
self.setCentralWidget(box)
</code>```

The same effect you could get through QHBoxLayout:

```<code>obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

layout = QHBoxLayout()

layout.addWidget(obj1, stretch=2)
layout.addWidget(obj2, stretch=1)
layout.addWidget(obj3, stretch=1)

box = QGroupBox(self)
box.setLayout(layout)
self.setCentralWidget(box)
</code>```

ContentLicense: CC BY-SA 3.0

Title: QGridLayout with PlotWidget-pyqtgraph

Body:
I have 3 PlotWidget (from the pyqtgraph library), obj1, obj2 and obj3, which I try to insert in a QGridLayout. I want to display all three objects in a single row, but obj1 must be twice as large as obj2 and obj3.

Thus I wrote:

layout.addWIdget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)

However, visually, obj1 is much smaller than obj2 and obj3 which do have the same size:

---------------------------------------------------
| obj1 |     obj2           |         obj3         |
---------------------------------------------------

However, if I write:

layout.addWIdget(obj1, 0, 0, 1, 1)
layout.addWidget(obj2, 0, 1, 1, 6)
layout.addWidget(obj3, 0, 7, 1, 6)

obj1 appears bigger than obj2 and obj3 which are still of the same size, which is the expected behavior:

---------------------------------------------------
|          obj1           |    obj2   |    obj3   |
---------------------------------------------------

It seems totally contradictory to the doc of addWidget as my first solution should yield the expected behavior, no?

EDIT: Piece of code

import pyqtgraph as qtg

obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

layout = QGridLayout()

layout.addWIdget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)

box = QGroupBox()
box.setLayout(layout)
self.setCentralWidget(box)

Body:
When you use void QGridLayout::addWidget(QWidget* widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0), rowSpan and columnSpan refers to the other row or another column, and as in your case you have just given a row the rowSpan is not applied, for example if you add a new row you get the following:

obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

obj4 = qtg.PlotWidget()
obj5 = qtg.PlotWidget()
obj6 = qtg.PlotWidget()
obj7 = qtg.PlotWidget()

layout = QGridLayout()

layout.addWidget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)
layout.addWidget(obj4, 1, 0, 1, 1)
layout.addWidget(obj5, 1, 1, 1, 1)
layout.addWidget(obj6, 1, 2, 1, 1)
layout.addWidget(obj7, 1, 3, 1, 1)

box = QGroupBox(self)
box.setLayout(layout)
self.setCentralWidget(box)

If you need to establish the proportions you must use stretch, in this case setColumnStretch():

obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

layout = QGridLayout()

layout.addWidget(obj1, 0, 0, 1, 2)
layout.addWidget(obj2, 0, 2, 1, 1)
layout.addWidget(obj3, 0, 3, 1, 1)
layout.setColumnStretch(0, 2)
layout.setColumnStretch(2, 1)
layout.setColumnStretch(3, 1)

box = QGroupBox(self)
box.setLayout(layout)
self.setCentralWidget(box)

The same effect you could get through QHBoxLayout:

obj1 = qtg.PlotWidget()
obj2 = qtg.PlotWidget()
obj3 = qtg.PlotWidget()

layout = QHBoxLayout()

layout.addWidget(obj1, stretch=2)
layout.addWidget(obj2, stretch=1)
layout.addWidget(obj3, stretch=1)

box = QGroupBox(self)
box.setLayout(layout)
self.setCentralWidget(box)


问:
cudaOccupancyMaxPotentialBlockSizeVariableSMem Unary Function
I am trying to automate grid and block size choices in my Cuda code. In my case, the amount of shared memory needed depends on the number of threads.The function has the following syntax.

```<code>__host__ cudaError_t cudaOccupancyMaxPotentialBlockSizeVariableSMem ( int* minGridSize, int* blockSize, T func, UnaryFunction blockSizeToDynamicSMemSize, int  blockSizeLimit = 0 )
</code>```

I tried defining a unary function as following.

```<code>struct unaryfn: std::unary_function<int, int> {
    int operator()(int i) const { return 12* i; }

};
</code>```

Then, I call the CUDA API function as following.

```<code>  int blockSize;   // The launch configurator returned block size
    int minGridSize; // The minimum grid size needed to achieve the
    // maximum occupancy for a full device launch
    int gridSize;    // The actual grid size needed, based on input size
    unaryfn::argument_type blk;
    unaryfn::result_type result;
    unaryfn ufn;
    cudaOccupancyMaxPotentialBlockSizeVariableSMem(&minGridSize, &blockSize,
                                                   CUDAExclVolRepulsionenergy, ufn(), 0);
    std::cout<<(nint +blockSize -1) / blockSize<<" "<<blockSize<<endl;
</code>```

When I compile, I get an error

error: function "unaryfn::operator()" cannot be called with the given argument list
              object type is: unaryfn
  How do I fix this issue?

答: Solved! Removing parenthesis on the unary function in function call helped. cudaOccupancyMaxPotentialBlockSizeVariableSMem(&minGridSize, &blockSize, CUDAExclVolRepulsionenergy, ufn(), 0);</p>

Body:
I am trying to automate grid and block size choices in my Cuda code. In my case, the amount of shared memory needed depends on the number of threads.The function has the following syntax.

__host__ cudaError_t cudaOccupancyMaxPotentialBlockSizeVariableSMem ( int* minGridSize, int* blockSize, T func, UnaryFunction blockSizeToDynamicSMemSize, int  blockSizeLimit = 0 )

I tried defining a unary function as following.

struct unaryfn: std::unary_function<int, int> {
    int operator()(int i) const { return 12* i; }

};

Then, I call the CUDA API function as following.

  int blockSize;   // The launch configurator returned block size
    int minGridSize; // The minimum grid size needed to achieve the
    // maximum occupancy for a full device launch
    int gridSize;    // The actual grid size needed, based on input size
    unaryfn::argument_type blk;
    unaryfn::result_type result;
    unaryfn ufn;
    cudaOccupancyMaxPotentialBlockSizeVariableSMem(&minGridSize, &blockSize,
                                                   CUDAExclVolRepulsionenergy, ufn(), 0);
    std::cout<<(nint +blockSize -1) / blockSize<<" "<<blockSize<<endl;

When I compile, I get an error

error: function "unaryfn::operator()" cannot be called with the given argument list
              object type is: unaryfn
  How do I fix this issue?


问:
Xaml Dynamic Grid with Viewmodels
Hello i am trying to create a grid in xmal that is populated via a ViewModel.
The grid is a 5x5 grid, and my ViewModel contains a list of "MyObject". This object contains 2 int variables Row and Column witch indicates where in the grid the Object should be.
MyObject is also a view models, and the grid space should be filled with Data Template names MyTemplate with the MyObject as the DataContext.
Now I pretty new to xaml and view models, but how would the best way of doing the be?</p>

答:
Let's see...

Put an ObservableCollection into the VM, then...

Option 1:

...a simple Grid into V. Subscribe to it's CollectionChanged event from xaml.cs, add ContentControls for each Added object to grid, bind the ContentControl's Grid.Row and Grid.Column property to each object's properties, and set the DataContext to the object itself and ContentTemplate to Resources["MyTemplate"]. (Also, for any removed objects find the corresponding ContentControl and remove it.)

Pro: easy

Con: .cs, no designer support

Option 2:

...an ItemsControl into V. Set its ItemPanelTemplate to a Grid, and bind your ObservableCollection to its ItemsSource. Then set your Itemtemplate to MyTemplate. Now, the trick is to make the items put in the correct cell, based on your values. For that, use the ItemsControl's ItemContainerStyle property, and bind the container's Grid.Row and Column to those properties.

Pro: nice xaml and easily extended

Con: ItemContainerStyle is tricky in WPF and missing in Silverlight, so in case of the latter, you can forget it

Option 3:

...a custom panel which you write. Inherit it from Grid perhaps. Than if an element is put into it, check if it's DataContext implements an interface which contains your properties. Then use this as an ItemsPanel in Option 2...

Pro: it should work perfectly

Con: You have to write a new Panel for this...

Hopefully one of these 3 will be ok for you.

ContentLicense: CC BY-SA 2.5

Title: Xaml Dynamic Grid with Viewmodels


问:
calculated field using to values column in a pivot
I have a pivot table

Year and Week are Rows.  Orders and Return Loaded are calculations based on sum(OrderSum) and sum(Reutilized) respectively

What I need is a third calculation based on the division of Return Loaded and Orders.  This is to show what % Reutilized represent of the total orders.  In the first case would be 14.04% (8 represent 14% of 57).

答:
That type of calculation is not possible within the pivot itself. There are two general workarounds.

You can setup the calculation in the underlying data in a way that lets you pull the value through to the pivot. I would need to know how that is laid out to explain further.

You can create an additional table where you read the values from your pivot using GetPivot() formulas and then do your calculation there. You would manually add new rows here for new weeks.


问:
Pandas Dataframe Slice using iloc or ix
I am trying to find a better way to separate the first half of my dataframe which has a variable number of columns.  I have tried using both the iloc and ix methods, but effectively I am writing the following for many dataframes.  Is there a better way to shorthand this?

```<code>df.iloc[:, [0,1,2,3,4,5,6,7,8,9,10,11]] #df.ix works this way as well
</code>```

What I'd like to do is below...

```<code>df.iloc[:, [0:df.shape[1]/2] #this will allow column number flexibility
</code>```

Do any of you have an idea of a good workaround for this?

答:
Like Scott mentioned in his comment, do not use ix because it is deprecated. Although ix works for now, it may not in the future, use iloc instead.

However, try using array_split() from numpy. It is very readable. This will split the dataframe in half evenly (array_split will allow an uneven number and return as close to half as possible):

```<code>import numpy as np

df_split = np.array_split(df, 2)
# This will return a list of dataframes.
# if you need single datframes you could always use df_split[0] for first half
# and df_split[1] for other half
</code>```

If you needed to split the columns as well you could also do:

```<code>df_split = np.array_split(df.columns, 2) # <--- Notice the df.columns in the argument
first_half = df[df_split[0].tolist()]
second_half = df[df_split[1].tolist()]
</code>```

Title: Pandas Dataframe Slice using iloc or ix

Body:
I am trying to find a better way to separate the first half of my dataframe which has a variable number of columns.  I have tried using both the iloc and ix methods, but effectively I am writing the following for many dataframes.  Is there a better way to shorthand this?

df.iloc[:, [0,1,2,3,4,5,6,7,8,9,10,11]] #df.ix works this way as well

What I'd like to do is below...

df.iloc[:, [0:df.shape[1]/2] #this will allow column number flexibility

Do any of you have an idea of a good workaround for this?

Body:
Like Scott mentioned in his comment, do not use ix because it is deprecated. Although ix works for now, it may not in the future, use iloc instead.

However, try using array_split() from numpy. It is very readable. This will split the dataframe in half evenly (array_split will allow an uneven number and return as close to half as possible):

import numpy as np

df_split = np.array_split(df, 2)
# This will return a list of dataframes.
# if you need single datframes you could always use df_split[0] for first half
# and df_split[1] for other half

If you needed to split the columns as well you could also do:

df_split = np.array_split(df.columns, 2) # <--- Notice the df.columns in the argument
first_half = df[df_split[0].tolist()]
second_half = df[df_split[1].tolist()]


问:
Displaying stats and calculating the average from certain user inputs
I have this application that I needed to create for my class project and I am down to my last part (minus the int validation for the scanner).

This app needs to be able to accept any amount of user input from the scanner, but the user can only enter numbers that are between 0-100 (for example, 10 100's, 20 0's, etc). To stop it, the user will type in "999" and when they type in "999", that is when the application will stop asking for numbers.

At that point, I have to display certain stats for the valid numbers (aka the numbers that are between 0-100). The stats that I need to show is this: The total numbers that was entered, the highest number, the lowest number, and the average of all of those numbers.

Can't figure out how I would do that.

Here is the code:
https://gist.github.com/tcipack/8f1ed6bd0d7d79b158ee191d228b0a24

答:
Here is something that can possibly help you get started, based on your current code.

Create a new List at the beginning, and then add the scores to it if it is within the range of 0-100. Then, when "999" is entered, use that list to calculate the results.

The lines that are commented out are the lines I added:

```<code>public static void main(String[] args) {
    Scanner input =  new Scanner(System.in);
    System.out.println("Enter a score or \"999\" to end the program.");
    int score;
//  List<Integer> numbers = new ArrayList<>();
    do {
        score = input.nextInt();

        if(score != 999) {
            if(score<0 || score >100) {
                System.out.println("Only use scores that are between 0-100.");
//          } else {
//              numbers.add(score);
            }
            System.out.println("Enter another score or \"999\" to end the program.");
        } else {
//          HERE: Use the numbers list to calculate the results
            System.out.println("END THE PROGRAM. Results:");
        }
    } while (score != 999);
}
</code>```

An example of how you can calculate the results:

```<code>int max     = numbers.stream().mapToInt(Integer::intValue).max().getAsInt();
int min     = numbers.stream().mapToInt(Integer::intValue).min().getAsInt();
int average = numbers.stream().mapToInt(Integer::intValue).average().getAsDouble();
int size    = numbers.size();
</code>```

Body:
Here is something that can possibly help you get started, based on your current code.

Create a new List at the beginning, and then add the scores to it if it is within the range of 0-100. Then, when "999" is entered, use that list to calculate the results.

The lines that are commented out are the lines I added:

public static void main(String[] args) {
    Scanner input =  new Scanner(System.in);
    System.out.println("Enter a score or \"999\" to end the program.");
    int score;
//  List<Integer> numbers = new ArrayList<>();
    do {
        score = input.nextInt();

        if(score != 999) {
            if(score<0 || score >100) {
                System.out.println("Only use scores that are between 0-100.");
//          } else {
//              numbers.add(score);
            }
            System.out.println("Enter another score or \"999\" to end the program.");
        } else {
//          HERE: Use the numbers list to calculate the results
            System.out.println("END THE PROGRAM. Results:");
        }
    } while (score != 999);
}

An example of how you can calculate the results:

int max     = numbers.stream().mapToInt(Integer::intValue).max().getAsInt();
int min     = numbers.stream().mapToInt(Integer::intValue).min().getAsInt();
int average = numbers.stream().mapToInt(Integer::intValue).average().getAsDouble();
int size    = numbers.size();


问:
AttributeError: 'function' object has no attribute 'move'

I'm very new to using python and trying to start on my final project for an intro to computing class. I'm using the Zelle graphics module to try to create a python game. I have created a face using the graphics module, and I want to clone this face and have the cloned version moved 50 spaces to the right. I have imported time in order to move the objects.

Here is the code in question:

```<code>from graphics import *
</code>```

import time

def main():
    win = GraphWin("Guess the Faces", 1000, 500)
    win.yUp()
    win.setBackground(color_rgb(20, 20, 20))

```<code>def robotFaces():
    robot1 = Rectangle(Point(25, 350), Point(100, 425))
    robot1.setOutline(color_rgb(0, 0, 0))
    robot1.setFill(color_rgb(180, 180, 180))
    robot1.draw(win)
    r1eye1 = Rectangle(Point(35, 390), Point(55, 415))
    r1eye1.setOutline(color_rgb(0, 0, 0))
    r1eye1.setFill(color_rgb(255, 255, 255))
    r1eye1.draw(win)
    r1eye2 = Rectangle(Point(70, 390), Point(90, 415))
    r1eye2.setOutline(color_rgb(0, 0, 0))
    r1eye2.setFill(color_rgb(255, 255, 255))
    r1eye2.draw(win)
    r1pupil1 = Rectangle(Point(42, 390), Point(48, 408))
    r1pupil1.setFill(color_rgb(0, 0, 0))
    r1pupil1.draw(win)
    r1pupil2 = Rectangle(Point(77, 390), Point(83, 408))
    r1pupil2.setFill(color_rgb(0, 0, 0))
    r1pupil2.draw(win)
    r1mouth = Polygon(Point(35, 360),
        Point(90, 360),
        Point(90, 370),
        Point(85, 370),
        Point(85, 365),
        Point(40, 365),
        Point(40, 370),
        Point(35, 370))
    r1mouth.setFill(color_rgb(255, 255, 255))
    r1mouth.setOutline(color_rgb(0, 0, 0))
    r1mouth.draw(win)

    robot2 = robot1.clone
    robot2.move(50, 0)
    robot2.draw(win)
    r2eye1 = r1eye1.clone
    r2eye1.move(50, 0)
    r2eye1.draw(win)
    r2eye2 = r1eye2.clone
    r2eye2.move(50, 0)
    r2eye2.draw(win)
    r2pupil1 = r1pupil1.clone
    r2pupil1.move(50, 0)
    r2pupil1.draw(win)
    r2pupil2 = r1pupil2.clone
    r2pupil2.move(50, 0)
    r2pupil2.draw(win)
    r2mouth = r1mouth.clone
    r2mouth.move(50, 0)
    r2mouth.draw(win)

robotFaces()

win.getMouse()
win.promptClose(win.getWidth()/2, 10)
</code>```

main()

I expect there to be a second robot face, 50 spaces to the right of the original one.

What actually happens is I get this attribute error:

AttributeError: 'function' object has no attribute 'move'

Is there something else I need to do to make the object movable?

答:
You didn't call the clone method.

```<code>robot2 = robot1.clone()
</code>```

In future, please cut down your code to the minimum necessary to demonstrate the problem, and post the full traceback.

Body:
I'm very new to using python and trying to start on my final project for an intro to computing class. I'm using the Zelle graphics module to try to create a python game. I have created a face using the graphics module, and I want to clone this face and have the cloned version moved 50 spaces to the right. I have imported time in order to move the objects.

Here is the code in question:

from graphics import *

import time

def main():
    win = GraphWin("Guess the Faces", 1000, 500)
    win.yUp()
    win.setBackground(color_rgb(20, 20, 20))

def robotFaces():
    robot1 = Rectangle(Point(25, 350), Point(100, 425))
    robot1.setOutline(color_rgb(0, 0, 0))
    robot1.setFill(color_rgb(180, 180, 180))
    robot1.draw(win)
    r1eye1 = Rectangle(Point(35, 390), Point(55, 415))
    r1eye1.setOutline(color_rgb(0, 0, 0))
    r1eye1.setFill(color_rgb(255, 255, 255))
    r1eye1.draw(win)
    r1eye2 = Rectangle(Point(70, 390), Point(90, 415))
    r1eye2.setOutline(color_rgb(0, 0, 0))
    r1eye2.setFill(color_rgb(255, 255, 255))
    r1eye2.draw(win)
    r1pupil1 = Rectangle(Point(42, 390), Point(48, 408))
    r1pupil1.setFill(color_rgb(0, 0, 0))
    r1pupil1.draw(win)
    r1pupil2 = Rectangle(Point(77, 390), Point(83, 408))
    r1pupil2.setFill(color_rgb(0, 0, 0))
    r1pupil2.draw(win)
    r1mouth = Polygon(Point(35, 360),
        Point(90, 360),
        Point(90, 370),
        Point(85, 370),
        Point(85, 365),
        Point(40, 365),
        Point(40, 370),
        Point(35, 370))
    r1mouth.setFill(color_rgb(255, 255, 255))
    r1mouth.setOutline(color_rgb(0, 0, 0))
    r1mouth.draw(win)

    robot2 = robot1.clone
    robot2.move(50, 0)
    robot2.draw(win)
    r2eye1 = r1eye1.clone
    r2eye1.move(50, 0)
    r2eye1.draw(win)
    r2eye2 = r1eye2.clone
    r2eye2.move(50, 0)
    r2eye2.draw(win)
    r2pupil1 = r1pupil1.clone
    r2pupil1.move(50, 0)
    r2pupil1.draw(win)
    r2pupil2 = r1pupil2.clone
    r2pupil2.move(50, 0)
    r2pupil2.draw(win)
    r2mouth = r1mouth.clone
    r2mouth.move(50, 0)
    r2mouth.draw(win)

robotFaces()

win.getMouse()
win.promptClose(win.getWidth()/2, 10)

main()

I expect there to be a second robot face, 50 spaces to the right of the original one.

What actually happens is I get this attribute error:

AttributeError: 'function' object has no attribute 'move'

Is there something else I need to do to make the object movable?

Body:
You didn't call the clone method.

robot2 = robot1.clone()

In future, please cut down your code to the minimum necessary to demonstrate the problem, and post the full traceback.


问:
Disassembler Visual Studio C++
I am using debugging in Visual Studio and disassembler window to get the instruction code in hex, but when the main call a function (as Fig.1), the function instructions appear in a sperate section (as Fig. 2)
Is there any way to show the function instructions appears as a part of the main?

main section in dissasembler window

function section in dissasembler window

Thanks,

答: Disassembly is always going to be a separate window, there are options on the context menu for the disassembly window that allows you to control what is shown (source code or not, or instruction addresses or not, for example).</p>

Title: Disassembler Visual Studio C++


问:
Errorbars in gnuplot change the location of my points
My graph originally look like this:

without errorbars

But with error bars i get something like this:

with errorbars

This clearly isn't the same graph while in my description I just simply added "with errorbars".

My code is following :

```<code>plot "m20gnu.txt" using 1:2 title"Massa 20 g" pt 1 ps 0.8 lt 9,f(x) title  "Best passende rechte bij massa 20 g"
</code>```

and with errorbars:

```<code>plot "m20gnu.txt" using 1:2 title"Massa 20 g" with errorbars pt 1 ps 0.8 lt 9,f(x) title  "Best passende rechte bij massa 20 g"
</code>```

The data file looks like this:

```<code>0.16975     0.058823529     0.005   1

0.165       0.061728395     0.005   1

0.1415      0.047169811     0.005   1

0.13825     0.048543689     0.005   1

0.13975     0.045454545     0.005   1

0.1265      0.054945055     0.005   1

0.146791667 0.052083333     0.005   1
</code>```

Does someone know what goes wrong here ?
Thanks a lot already

答:
When plotting without errorbars, you have using 1:2, which  means: use the first column as x, and the second column as y value.

Now, plotting with errorbars requires three values. So by using the same using statement again, you are missing one value. Depending on the selected plotting style, gnuplot tries to guess the third value, if you don't specify all. The documentation for yerrorbars says:

```<code>2 columns: [implicit x] y ydelta
3 columns: x y ydelta
4 columns: x y ylow yhigh
</code>```

In your case

```<code>plot "m20gnu.txt" using 1:2:3 with errorbars
</code>```

should work.

Body:
My graph originally look like this:

without errorbars

But with error bars i get something like this:

with errorbars

This clearly isn't the same graph while in my description I just simply added "with errorbars".

My code is following :

plot "m20gnu.txt" using 1:2 title"Massa 20 g" pt 1 ps 0.8 lt 9,f(x) title  "Best passende rechte bij massa 20 g"

and with errorbars:

plot "m20gnu.txt" using 1:2 title"Massa 20 g" with errorbars pt 1 ps 0.8 lt 9,f(x) title  "Best passende rechte bij massa 20 g"

The data file looks like this:

0.16975     0.058823529     0.005   1

0.165       0.061728395     0.005   1

0.1415      0.047169811     0.005   1

0.13825     0.048543689     0.005   1

0.13975     0.045454545     0.005   1

0.1265      0.054945055     0.005   1

0.146791667 0.052083333     0.005   1

Does someone know what goes wrong here ?
Thanks a lot already

Body:
When plotting without errorbars, you have using 1:2, which  means: use the first column as x, and the second column as y value.

Now, plotting with errorbars requires three values. So by using the same using statement again, you are missing one value. Depending on the selected plotting style, gnuplot tries to guess the third value, if you don't specify all. The documentation for yerrorbars says:

2 columns: [implicit x] y ydelta
3 columns: x y ydelta
4 columns: x y ylow yhigh

In your case

plot "m20gnu.txt" using 1:2:3 with errorbars

should work.


问:
How to generate SHA3-256 in .NET Core?
Is there an option to calculate SHA3-256 hashes in .NET Core? The goal is to recreate the isChecksumAddress util function in web3.js

答:
No, there is no way of doing that now with pure dotnet core.

It's been on the watch list since it was announced. Since we don't implement cryptographic algorithms within .NET we're waiting on support from the underlying platforms (Windows CNG, Apple Security.framework, and OpenSSL).

See this issue.

But you might have a better luck with BouncyCastle. It has an implementation here but I don't know if it is out yet (in nuget).

ContentLicense: CC BY-SA 4.0

Title: How to generate SHA3-256 in .NET Core?


问:
Adding 10k users to 20 AD Groups 500 each using powershell
I am trying to add a list of 10k users to 20 AD Groups 500 in each group using powershell.

If the users are only 9k, adding 500 users in each group will make 18 groups and the remaining 2 groups should be left empty.

I tried using "SKIP" command but it is repetitive.

Any Better way to Code ? Please suggest.

答:
Get-Content $DL | select -first 400 -skip 500 | out-file $ScriptDir"\ADGroupMembers.txt"

This line skips first 500 lines and then displays 501 to 900 lines.


问:
C# Inheritance & Casting
I get the following exception:

InvalidCastException: Unable to cast object of type 'Employee' to type
'EmployeeProfile'.

I have the following code:

```<code>    private class Employee
    {
        public string Name { get; private set; }

        public Employee()
        {
            this.Name = "employee";
        }

        public override string ToString()
        {
            return this.Name;
        }
    }

    private class EmployeeProfile : Employee
    {
        public string Profile { get; private set; }

        public EmployeeProfile() : base()
        {
            this.Profile = string.Format("{0}'s profile", this.Name);
        }

        public override string ToString()
        {
            return this.Profile;
        }
    }

    public void RunTest()
    {
        Employee emp = new Employee();
        EmployeeProfile prof = (EmployeeProfile)emp; // InvalidCastException here

        System.Console.WriteLine(emp);
        System.Console.WriteLine(prof);
    }
</code>```

Maybe my brain is burned out, but I thought you can cast a subtype to its base type? What am I missing here? Maybe it is a vacation... thank you!

答:
You need to use a library like Automapper . This library can fill the matched properties for an object:</p>

```<code>Mapper.Initialize(cfg => {
    cfg.CreateMap<EmployeeProfile,Employee>();
});

EmployeeProfile prof = Mapper.Map<EmployeeProfile>(emp);
</code>```

Title: C# Inheritance & Casting

Body:
I get the following exception:

InvalidCastException: Unable to cast object of type 'Employee' to type
'EmployeeProfile'.

I have the following code:

    private class Employee
    {
        public string Name { get; private set; }

        public Employee()
        {
            this.Name = "employee";
        }

        public override string ToString()
        {
            return this.Name;
        }
    }

    private class EmployeeProfile : Employee
    {
        public string Profile { get; private set; }

        public EmployeeProfile() : base()
        {
            this.Profile = string.Format("{0}'s profile", this.Name);
        }

        public override string ToString()
        {
            return this.Profile;
        }
    }

    public void RunTest()
    {
        Employee emp = new Employee();
        EmployeeProfile prof = (EmployeeProfile)emp; // InvalidCastException here

        System.Console.WriteLine(emp);
        System.Console.WriteLine(prof);
    }

Maybe my brain is burned out, but I thought you can cast a subtype to its base type? What am I missing here? Maybe it is a vacation... thank you!

Body:
You need to use a library like Automapper . This library can fill the matched properties for an object:

Mapper.Initialize(cfg => {
    cfg.CreateMap<EmployeeProfile,Employee>();
});

EmployeeProfile prof = Mapper.Map<EmployeeProfile>(emp);


问:
Function that check if letters and or whole word is a contained in a given string
I want to solve the following problem through regular expression

All 5 letters 'g', 'o', 'l', 'd','e','n' are included (in any
sequence) and

The string 'golden' is a substring of the given string.

If 1 holds (but 2 does not), return 1.

If both 1 and 2 hold, return 2.
Otherwise return 0.

here is my code.

```<code>function checkstrling($input, $substring)
{
    $voodoo = preg_match("(".implode("(.*?)",array_map('preg_quote',str_split($substring))).")",$input,$matches);
    if( !$voodoo) return 0; // no match
    $pieces = implode("",array_slice($matches,1)); // in-between bits
    if( $pieces !=="") return 1; // there was stuff in between
    return 2; // substring found without interruption
}

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));
</code>```

The function work find when i call and provide the following parameter it work fine.

```<code>var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));
</code>```

But does not work properly when i call the function again with the following paramenter.

```<code>var_dump(checkstrling("somegxoxdxlxnmme","golden"));
var_dump(checkstrling("somegxoxlxdxemnmgoldenv","golden"));
</code>```

答:
You could use multiple lookaheads:

```<code>(?=[^g]*g)
(?=[^o]*o)
(?=[^l]*l)
(?=[^d]*d)
(?=[^e]*e)
(?=[^n]*n)
</code>```

The pattern is always the same: look for anything not g zero or more times, than look for g.

In PHP:

```<code><?php

function checkstrling($input, $substring) {
    $regex = '~(?=[^g]*g)(?=[^o]*o)(?=[^l]*l)(?=[^d]*d)(?=[^e]*e)(?=[^n]*n).+~';

    if ((preg_match($regex, $input) && (strpos($input, $substring) !== false))) {
        return 2;
    } else if (preg_match($regex, $input)) {
        return 1;
    }
    return 0;
}

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));
var_dump(checkstrling("somegxoxdxlxnmme","golden"));
var_dump(checkstrling("somegxoxlxdxemnmgoldenv","golden"));
?>
</code>```

Which yields

```<code>int(0)
int(1)
int(2)
int(1)
int(2)
</code>```

Body:
I want to solve the following problem through regular expression

All 5 letters 'g', 'o', 'l', 'd','e','n' are included (in any
sequence) and

The string 'golden' is a substring of the given string.

If 1 holds (but 2 does not), return 1.

If both 1 and 2 hold, return 2.
Otherwise return 0.

here is my code.

function checkstrling($input, $substring)
{
    $voodoo = preg_match("(".implode("(.*?)",array_map('preg_quote',str_split($substring))).")",$input,$matches);
    if( !$voodoo) return 0; // no match
    $pieces = implode("",array_slice($matches,1)); // in-between bits
    if( $pieces !=="") return 1; // there was stuff in between
    return 2; // substring found without interruption
}

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));

The function work find when i call and provide the following parameter it work fine.

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));

But does not work properly when i call the function again with the following paramenter.

var_dump(checkstrling("somegxoxdxlxnmme","golden"));
var_dump(checkstrling("somegxoxlxdxemnmgoldenv","golden"));

Body:
You could use multiple lookaheads:

(?=[^g]*g)
(?=[^o]*o)
(?=[^l]*l)
(?=[^d]*d)
(?=[^e]*e)
(?=[^n]*n)

The pattern is always the same: look for anything not g zero or more times, than look for g.

In PHP:

<?php

function checkstrling($input, $substring) {
    $regex = '~(?=[^g]*g)(?=[^o]*o)(?=[^l]*l)(?=[^d]*d)(?=[^e]*e)(?=[^n]*n).+~';

    if ((preg_match($regex, $input) && (strpos($input, $substring) !== false))) {
        return 2;
    } else if (preg_match($regex, $input)) {
        return 1;
    }
    return 0;
}

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));
var_dump(checkstrling("somegxoxdxlxnmme","golden"));
var_dump(checkstrling("somegxoxlxdxemnmgoldenv","golden"));
?>

Which yields

int(0)
int(1)
int(2)
int(1)
int(2)


问:
Using JavaScript to change were a link is pointing to based on screen size
I am creating a mobile-first site using the Bootstrap 4 framework. I am trying to create a JavaScript function which will change where a  tag is pointing to based upon the screen size of the browser. The following is just a very small portion of the HTML code for the page:

```<code><div class="col-md">
    <div id="accordion" class="form-group text-dark mt-3">
        <!-- Cold Card -->
        <div class="card">
            <!-- Cold Temps -->
            <!-- Temps include Make line temps, Refrigerator temps,
                 Freezer temps, and Beffet temps -->
            <div class="card-header">
                <a class="card-link"
                   data-toggle="collapse"
                   data-parent="#accordion"
                   href="#cold"
                   id="coldlink">
                    <h3>Cold Temps Management</h3>
                </a>
            </div>

            <!-- Cold Card -->
            <div class="collapse" id="cold">
</code>```

I have been trying several different JavaScript functions, and the following is the most recent set of functions which I have used:

```<code>const mq = window.matchMedia( "(min-width: 767px)");

if(mq.matches) {
    document.getElementById("coldlink").href = "#cold";
} else {
    document.getElementById("coldlink").href = "cold.php";
}
</code>```

From what I have read across many different sites, this code should change the href attribute of the element "coldlink" to "#cold" when the screen size is 767px or larger, and "cold.php" when it is smaller than 767px. Howerver, when I run this code (in the full page) and inspect the page using the developer tools, I get an error message saying "TypeError: document.getElementById(...) is null"

I have used the .getElementById(...) method in several other functions without getting this same error message so I do not know where I went wrong this time.

if there is a way to change the href attribute using Bootstrap, I would be more than willing to give it a shot as I have not discovered how to do this yet

答:
Add window onload, in order to let your DOMs in the page to completely load, than you can get your anchor element and change its href, if you want to do DOM manipulation with javascript, you better make sure that they are all loaded first.

window.onload = function () {
            const mq = window.matchMedia("(min-width: 400px)").matches
            if (mq) {
                console.log('More')
                document.getElementById("coldlink").href = "#cold";
            } else {
                console.log('Less')
                document.getElementById("coldlink").href = "cold.php";
            }
        }```

Body:
I am creating a mobile-first site using the Bootstrap 4 framework. I am trying to create a JavaScript function which will change where a  tag is pointing to based upon the screen size of the browser. The following is just a very small portion of the HTML code for the page:

Cold Temps Management

I have been trying several different JavaScript functions, and the following is the most recent set of functions which I have used:

const mq = window.matchMedia( "(min-width: 767px)");

if(mq.matches) {
    document.getElementById("coldlink").href = "#cold";
} else {
    document.getElementById("coldlink").href = "cold.php";
}

From what I have read across many different sites, this code should change the href attribute of the element "coldlink" to "#cold" when the screen size is 767px or larger, and "cold.php" when it is smaller than 767px. Howerver, when I run this code (in the full page) and inspect the page using the developer tools, I get an error message saying "TypeError: document.getElementById(...) is null"

I have used the .getElementById(...) method in several other functions without getting this same error message so I do not know where I went wrong this time.

if there is a way to change the href attribute using Bootstrap, I would be more than willing to give it a shot as I have not discovered how to do this yet


问:
Exporting JAR projects that use a common project
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

```<code>Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain
</code>```

答:
Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.

How do you create it? A jar file is just renamed zip with manifest file, so consider building it yourself in case your tool doesn't suit your need.

Body:
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain


问:
Return a promise without waiting for a dependant promise in function in nodejs
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

```<code>createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}
</code>```

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

```<code>async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}
</code>```

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

答:
You can write your function as-is and then it depends on how it's called. You can't use await because that blocks in the current scope. You can introduce a new scope using .then, though:

```<code>async function createUser() {
  address = await createAddress();
  return User.create({ name: 'foo', address });
}
...
createUser().then(() => { /* handle user creation */ });
// code here will not wait for `createUser` to finish
</code>```

Body:
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

Body:
You can write your function as-is and then it depends on how it's called. You can't use await because that blocks in the current scope. You can introduce a new scope using .then, though:

async function createUser() {
  address = await createAddress();
  return User.create({ name: 'foo', address });
}
...
createUser().then(() => { /* handle user creation */ });
// code here will not wait for `createUser` to finish


问:
Django translations RTL language
I am trying to set my django project to support Arabic language , but I am still not getting anything right .

my settings.py:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                ],
            },
        },
    ]

    USE_I18N = True

    LANGUAGES = (

        ('ar', _('Arabic')),
        ('en', _('English')),
    )

    LANGUAGE_CODE = 'en-us'

    LOCAL_PATHS = (
        os.path.join(BASE_DIR, 'locale'),
    )
</code>```

my index.html

```<code>{% trans "Hello and welcome" %}
<p>{% blocktrans %}
    hello  dear friends, i would be very happy if you
    can help!!
{% endblocktrans %}</p>
</br>
{{ request.LANGUAGE_CODE }}
</code>```

urls.py

```<code>urlpatterns += i18n_patterns(
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home, name='home'),

)
</code>```

after that to make the .po file I used the command:

```<code>python manage.py makemessages -l 'ar'
</code>```

and after I get the .po file , i have added my translations in 'msgstr',
then used the following command to compile the translated string :

python manage.py compilemassages

then i logged in , and changed the language code to 'ar',  in the url(127.0.0.1:8000/ar) , but still i am getting the english strings , and not its translation , so any idea about what is that I am doing wrong .

答:
Finally i fixed my mistake and it was just a typo, instead of LOCALE_PATHS , I  wrote LOCAL_PATHS ..
thanks anyway guys</p>

Title: Django translations RTL language

Body:
I am trying to set my django project to support Arabic language , but I am still not getting anything right .

my settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                ],
            },
        },
    ]

    USE_I18N = True

    LANGUAGES = (

        ('ar', _('Arabic')),
        ('en', _('English')),
    )

    LANGUAGE_CODE = 'en-us'

    LOCAL_PATHS = (
        os.path.join(BASE_DIR, 'locale'),
    )

my index.html

{% trans "Hello and welcome" %}

{% blocktrans %}
    hello  dear friends, i would be very happy if you
    can help!!
{% endblocktrans %}

{{ request.LANGUAGE_CODE }}

urls.py

urlpatterns += i18n_patterns(
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home, name='home'),

)

after that to make the .po file I used the command:

python manage.py makemessages -l 'ar'

and after I get the .po file , i have added my translations in 'msgstr',
then used the following command to compile the translated string :

python manage.py compilemassages

then i logged in , and changed the language code to 'ar',  in the url(127.0.0.1:8000/ar) , but still i am getting the english strings , and not its translation , so any idea about what is that I am doing wrong .


问:
Preserve Encapsulation while Displaying Information
Suppose I've got the following class to represent a Car and Tire:

```<code>public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;
    }

    //getters and toString() for tire attributes
}

public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;
    }

    public String getName(){
        return this.name;
    }
}
</code>```

I'm fully aware that my Car and Tire example are lacking notable attributes, but that's not the focus of my question, it's the simplest MCVE I could come up with.

From Effective Java(p. 53):

Whether or not you specify the format, provide programmatic access to
  all of the information contained in the value returned by toString.

In my Car class, the toString() method will obviously return the name, and according to Effective Java, as quoted above I should provide a getter as well. My problem is when returning the details of the Tire.

Question:

Given the advice quoted from Effective Java, how would I properly return the details of my car including the Tire for display purposes?

Would I do this:

```<code>public Tire getTire(){
    return this.tire
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;
}
</code>```

Or to put it another way, when you have a class, in my case(Tire), that is also an attribute of another class, in my case(Car), when returning the details to be printed in a GUI, how would I do so and perverse encapsulation?

答:
Check the below code</p>

```<code>public class Tire
{
    private string m_brand;
    private string m_type;
    public Tire(string brand, string type)
    {
        this.m_brand = brand;
        this.m_type = type;
    }

    public string getTireBrand()
    {
        return this.m_brand;
    }

    public string getTireType()
    {
        return this.m_type;
    }

    public override string ToString()
    {
        return "brand - " + this.m_brand + ", type - " + this.m_type;
    }
}

public class Car
{
    private string m_name;
    private Tire m_tire;

    public Car(string name, Tire tire)
    {
        this.m_name = name;
        this.m_tire = tire;
    }

    public string getCarDetails()
    {
        string car = this.m_name;
        string tireBrand = this.m_tire.getTireBrand();
        string tireType = this.m_tire.getTireType();

        return "Name:  " + car + " Tire: brand - " + tireBrand + ", type - " + tireType;
    }

    public string _getCarDetails()
    {
        return "Name:  " + this.m_name + " Tire: " + this.m_tire.ToString();
    }
}
</code>```

Body:
Suppose I've got the following class to represent a Car and Tire:

public final class Tire{

    private final String brand
    private final TireType type;

    public Tire(String brand, type)
    {
      this.brand = brand
      this.type = type;
    }

    //getters and toString() for tire attributes
}

public final class Car{

    private final String name;
    private final Tire tire;

    public Car(String name, Tire tire){
        this.name = name;
        this.tire = tire;
    }

    public String getName(){
        return this.name;
    }
}

I'm fully aware that my Car and Tire example are lacking notable attributes, but that's not the focus of my question, it's the simplest MCVE I could come up with.

From Effective Java(p. 53):

Whether or not you specify the format, provide programmatic access to
  all of the information contained in the value returned by toString.

In my Car class, the toString() method will obviously return the name, and according to Effective Java, as quoted above I should provide a getter as well. My problem is when returning the details of the Tire.

Question:

Given the advice quoted from Effective Java, how would I properly return the details of my car including the Tire for display purposes?

Would I do this:

public Tire getTire(){
    return this.tire
}

public String toString(){
     return  "Name:  " + this.name + " Tire: " + this.tire;
}

Or to put it another way, when you have a class, in my case(Tire), that is also an attribute of another class, in my case(Car), when returning the details to be printed in a GUI, how would I do so and perverse encapsulation?

Body:
Check the below code

public class Tire
{
    private string m_brand;
    private string m_type;
    public Tire(string brand, string type)
    {
        this.m_brand = brand;
        this.m_type = type;
    }

    public string getTireBrand()
    {
        return this.m_brand;
    }

    public string getTireType()
    {
        return this.m_type;
    }

    public override string ToString()
    {
        return "brand - " + this.m_brand + ", type - " + this.m_type;
    }
}

public class Car
{
    private string m_name;
    private Tire m_tire;

    public Car(string name, Tire tire)
    {
        this.m_name = name;
        this.m_tire = tire;
    }

    public string getCarDetails()
    {
        string car = this.m_name;
        string tireBrand = this.m_tire.getTireBrand();
        string tireType = this.m_tire.getTireType();

        return "Name:  " + car + " Tire: brand - " + tireBrand + ", type - " + tireType;
    }

    public string _getCarDetails()
    {
        return "Name:  " + this.m_name + " Tire: " + this.m_tire.ToString();
    }
}


问:
Python turtle moving platform
I'm working on Python game using turtles.

I have a player object that moves up and down (jump) on key press. I'm trying to add a moving platform that the player has to jump on.

I tried putting the moving platform in a while loop. The problem is since the while loop is running to keep the platform moving, the program does not detect key press.

I tried moving turtle.listen() inside the main while loop but that didn't work.

How do I keep the platform moving, in a while True loop, and have the listener active?

```<code># moving platform
while True:
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < -200:
        s13.setheading(180)

...
turtle.listen()
turtle.onkey(jump, "Up")
</code>```

Any advice is appreciated...

答:
A while True: statement has no place in an event driven environment like turtle.  There are at least a couple of solutions available to you.  The most straight forward is to use turtle's built-in ontimer() events to have a function independently run at a fixed (or variable) interval.

Another option is to introduce threading to the program.  However, since turtle is tkinter-based, you have to channel all the graphics operations through the main thread, which complicates things.

Try searching StackOverflow for:

python turtle ontimer

python turtle threading

A crude example:

```<code>from turtle import Turtle, Screen

screen = Screen()

s13 = Turtle('square')
s13.color('red', 'blue')
s13.shapesize(1, 3, 2)
s13.penup()

def jump():
    s13.color(*reversed(s13.color()))

# moving platform
def move_platform():
    s13.backward(3)

    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < -200:
        s13.setheading(180)

    screen.ontimer(move_platform, 100)

# ...
screen.onkey(jump, "Up")
screen.listen()

move_platform()

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

The platform floats back and forth.  If you hit the up arrow (after clicking on the window to make it active) you'll see the platform swap its fill and outline colors as it floats.

Title: Python turtle moving platform

Body:
I'm working on Python game using turtles.

I have a player object that moves up and down (jump) on key press. I'm trying to add a moving platform that the player has to jump on.

I tried putting the moving platform in a while loop. The problem is since the while loop is running to keep the platform moving, the program does not detect key press.

I tried moving turtle.listen() inside the main while loop but that didn't work.

How do I keep the platform moving, in a while True loop, and have the listener active?

# moving platform
while True:
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < -200:
        s13.setheading(180)

...
turtle.listen()
turtle.onkey(jump, "Up")

Any advice is appreciated...

Body:
A while True: statement has no place in an event driven environment like turtle.  There are at least a couple of solutions available to you.  The most straight forward is to use turtle's built-in ontimer() events to have a function independently run at a fixed (or variable) interval.

Another option is to introduce threading to the program.  However, since turtle is tkinter-based, you have to channel all the graphics operations through the main thread, which complicates things.

Try searching StackOverflow for:

python turtle ontimer

python turtle threading

A crude example:

from turtle import Turtle, Screen

screen = Screen()

s13 = Turtle('square')
s13.color('red', 'blue')
s13.shapesize(1, 3, 2)
s13.penup()

def jump():
    s13.color(*reversed(s13.color()))

# moving platform
def move_platform():
    s13.backward(3)

    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < -200:
        s13.setheading(180)

    screen.ontimer(move_platform, 100)

# ...
screen.onkey(jump, "Up")
screen.listen()

move_platform()

screen.mainloop()

The platform floats back and forth.  If you hit the up arrow (after clicking on the window to make it active) you'll see the platform swap its fill and outline colors as it floats.


答:
Its really weird case and conditions but here is an idea:

```<code>CREATE TABLE T (
    ID INT IDENTITY (1,1),
    GRADE VARCHAR(25)
    );
INSERT INTO T VALUES
('Copper'),
('Copper'),
('Copper Bonded'),
('Fiber'),
('Fiber');
with cte as (
SELECT ID, GRADE, row_number () over (partition by grade order by id) rn
FROM T
),
Final as (
select id, case when grade = 'Copper'and rn = 1 then 'A'
                when grade= 'Copper Bonded' then 'B'
                when grade = 'Fiber' then 'C' end k
from cte)

select  row_number () over (order by k) id,k as Copper
from final
where k is not null
</code>```

Results:

```<code>+----+--------+
| id | Copper |
+----+--------+
|  1 | A      |
|  2 | B      |
|  3 | C      |
|  4 | C      |
+----+--------+
</code>```

Title: Creating a pivot based on rules

Body:
I have a dataset like:

+---------------+----+
| Grade         | ID |
+---------------+----+
| Copper        | 1  |
+---------------+----+
| Copper        | 2  |
+---------------+----+
| Copper Bonded | 2  |
+---------------+----+
| Fiber         | 3  |
+---------------+----+
| Fiber         | 4  |
+---------------+----+

I would like a result like this:

+----+--------+
| ID | Copper |
+----+--------+
| 1  | A      |
+----+--------+
| 2  | B      |
+----+--------+
| 3  | C      |
+----+--------+
| 4  | C      |
+----+--------+

The ruleset is something like this:

A :  Copper only
B :  Copper and Copper Bonded
C :  Fiber only

Is this a candidate for a pivot, how do I express this as a sql query?

Body:
Its really weird case and conditions but here is an idea:

CREATE TABLE T (
    ID INT IDENTITY (1,1),
    GRADE VARCHAR(25)
    );
INSERT INTO T VALUES
('Copper'),
('Copper'),
('Copper Bonded'),
('Fiber'),
('Fiber');
with cte as (
SELECT ID, GRADE, row_number () over (partition by grade order by id) rn
FROM T
),
Final as (
select id, case when grade = 'Copper'and rn = 1 then 'A'
                when grade= 'Copper Bonded' then 'B'
                when grade = 'Fiber' then 'C' end k
from cte)

select  row_number () over (order by k) id,k as Copper
from final
where k is not null

Results:

+----+--------+
| id | Copper |
+----+--------+
|  1 | A      |
|  2 | B      |
|  3 | C      |
|  4 | C      |
+----+--------+


问:
Swift CNCopySupportedInterfaces not valid
Trying to get the SSID of current device. I have found plenty of examples on how to do it however I am struggling with getting the CNCopySupportedInterfaces to autocomplete. I have 'import SystemConfiguration' at the top of my swift file but no success. Can't seem to figure out what I am doing wrong.</p>

答:
Swift:

```<code>import SystemConfiguration.CaptiveNetwork

func currentSSIDs() -> [String] {
        guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
            return []
        }
        return interfaceNames.flatMap { name in
            guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
                return nil
            }
            guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
                return nil
            }
            return ssid
        }
    }
</code>```

Then print(currentSSIDs()), not working on simulator, only real devices.

Taken from https://forums.developer.apple.com/thread/50302

Body:
Swift:

import SystemConfiguration.CaptiveNetwork

func currentSSIDs() -> [String] {
        guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
            return []
        }
        return interfaceNames.flatMap { name in
            guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
                return nil
            }
            guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
                return nil
            }
            return ssid
        }
    }

Then print(currentSSIDs()), not working on simulator, only real devices.

Taken from https://forums.developer.apple.com/thread/50302


问:
see all history of git
Let's say, my current git log is

commit3

commit2

commit1

I reset the head to commit2.

Now I want to go back to commit3, but I forget the sha-1 of commit3, so I want to look at the log , but "git log" will only show commit2, commit1, my question is how to reset to commit3 or let the log show also commit3 now?

Thanks

答:
The command

```<code>git reflog
</code>```

will show you a list of SHAs that have been the HEAD. In other words, it shows a list of commits in the order that they have been checked out. In that list you will also see the syntax HEAD@{1}, HEAD@{2} etc. That is a way to address the previous HEADs.

I your case git checkout HEAD@{1} should check out commit3, because it was the HEAD before the current HEAD.

Title: see all history of git

Body:
The command

git reflog

will show you a list of SHAs that have been the HEAD. In other words, it shows a list of commits in the order that they have been checked out. In that list you will also see the syntax HEAD@{1}, HEAD@{2} etc. That is a way to address the previous HEADs.

I your case git checkout HEAD@{1} should check out commit3, because it was the HEAD before the current HEAD.


答:
I used a delimited trick and evaluated that:

```<code>create table #temp  (grade varchar(100),id int)
insert into #temp
values
('Copper',1)
,('Copper',2)
,('Copper bonded',2)
,('Fiber',3)
,('Fiber',4)

;with cte as
(
select distinct id,stuff((select '|' + grade
                from #temp
                where id = t1.id
                group by grade
                order by grade
                for xml path('')
                ),1,1,'') as Combined
from #temp t1
)

select id,
    case combined
        when 'Copper' then 'A'
        when 'Copper|Copper Bonded' then 'B'
        when 'Fiber' then 'C'
        else 'Unknown'
    end as Copper
from cte

drop table #temp
</code>```

Results:

```<code>id  Copper
1   A
2   B
3   C
4   C
</code>```

Title: Creating a pivot based on rules

Body:
I used a delimited trick and evaluated that:

create table #temp  (grade varchar(100),id int)
insert into #temp
values
('Copper',1)
,('Copper',2)
,('Copper bonded',2)
,('Fiber',3)
,('Fiber',4)

;with cte as
(
select distinct id,stuff((select '|' + grade
                from #temp
                where id = t1.id
                group by grade
                order by grade
                for xml path('')
                ),1,1,'') as Combined
from #temp t1
)

select id,
    case combined
        when 'Copper' then 'A'
        when 'Copper|Copper Bonded' then 'B'
        when 'Fiber' then 'C'
        else 'Unknown'
    end as Copper
from cte

drop table #temp

Results:

id  Copper
1   A
2   B
3   C
4   C


问:
How do I use arrow functions filtering a property by a list
I have an array of objects and I am trying to remove several elements by a list of ids in another array.

Say I have

```<code>transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

ids = [12, 98];
</code>```

Then I want to end up with

```<code>transactions = [{id:18, name:'trs18'}, {id:45, name:'trs145'}];
</code>```

I am trying to remove the elements from the transactions array that have the id specified in the ids array.

I am thinking of creating a sub array doing a filter and replacing the original array with this new sub array which does not contains the elements included in the ids array.

Something like

```<code>var subArray = transactions.filter(trans => trans.id != ids)
transactions = subArray;
</code>```

But I am new to arrow functions and I don't know how to accomplish this. In the documentation I only see that they use == as the comparison operator. But I am looking for something that compares against a list of elements.

答:
You can use Array#filter with Array#includes to check if the ids array doesn't contain an id:

const transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

const ids = [12, 98];

const result = transactions.filter(({ id }) => !ids.includes(id));

console.log(result);```
</div>
</div>
</p>

<p>Another options is to create a Set from the <code>ids</code> array, and check if the set doesn't have the <code>id</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

const ids = [12, 98];
const idsSet = new Set([12, 98]);

const result = transactions.filter(({ id }) => !idsSet.has(id));

console.log(result);</code>```

Body:
I have an array of objects and I am trying to remove several elements by a list of ids in another array.

Say I have

transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

ids = [12, 98];

Then I want to end up with

transactions = [{id:18, name:'trs18'}, {id:45, name:'trs145'}];

I am trying to remove the elements from the transactions array that have the id specified in the ids array.

I am thinking of creating a sub array doing a filter and replacing the original array with this new sub array which does not contains the elements included in the ids array.

Something like

var subArray = transactions.filter(trans => trans.id != ids)
transactions = subArray;

But I am new to arrow functions and I don't know how to accomplish this. In the documentation I only see that they use == as the comparison operator. But I am looking for something that compares against a list of elements.

Body:
You can use Array#filter with Array#includes to check if the ids array doesn't contain an id:

const transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

const ids = [12, 98];

const result = transactions.filter(({ id }) => !ids.includes(id));

console.log(result);

Another options is to create a Set from the ids array, and check if the set doesn't have the id:

const transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];

const ids = [12, 98];
const idsSet = new Set([12, 98]);

const result = transactions.filter(({ id }) => !idsSet.has(id));

console.log(result);


问:
incorrect string to date conversion swift 3.0
I am converting a format like 10/24 12:00 PM in string to the equivalent in Date format. I am using the following code:

```<code>let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd hh:mm aa"

   self.dateCompleted = dateFormatter.date(from: self.DeliverBy!)
</code>```

dateCompleted is a Date variable whereas self.DeliveryBy is a String variable.

I am getting an output like 2000-10-24 17:00:00 UTC where as it should be something like 2017-10-24 12:00:00 UTC.  Am i doing something wrong?

I referred http://userguide.icu-project.org/formatparse/datetime

答:
Your date string does not specify a year, which is therefore
determined from the default date. What you can do is to set the
default date to the (start of the) current day:

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mm aa"
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
    print(dateCompleted) // 2017-10-24 10:00:00 +0000
}
</code>```

(I am in the Europe/Berlin timezone, therefore 12:00 PM is printed
as 10:00 GMT.)

Body:
I am converting a format like 10/24 12:00 PM in string to the equivalent in Date format. I am using the following code:

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd hh:mm aa"

   self.dateCompleted = dateFormatter.date(from: self.DeliverBy!)

dateCompleted is a Date variable whereas self.DeliveryBy is a String variable.

I am getting an output like 2000-10-24 17:00:00 UTC where as it should be something like 2017-10-24 12:00:00 UTC.  Am i doing something wrong?

I referred http://userguide.icu-project.org/formatparse/datetime

Body:
Your date string does not specify a year, which is therefore
determined from the default date. What you can do is to set the
default date to the (start of the) current day:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mm aa"
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
    print(dateCompleted) // 2017-10-24 10:00:00 +0000
}

(I am in the Europe/Berlin timezone, therefore 12:00 PM is printed
as 10:00 GMT.)


问:
Angular erasing all query parameters
Related to but not a duplicate of: How to keep query string parameters in URL when accessing a route of an Angular 2 app?

I have a very basic Angular app, and when I add a query parameter, it's erased (from the browser's url and everywhere else it would seem) before the code hits the app.component constructor.

Note: it is on the initial load (and subsequent reloads) that query parameters appear to be stripped

Example: navigating to localhost:8081/calculator?a=1 is changed to localhost:8081/calculator

I've tried this in Angular 4.3.1, 4.4.6 and 5.0.4, with the same result.

Here's my route config:

```<code>const appRoutes: Routes = [
    {
        path: 'calculator',
        component: CalculatorComponent
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

Here's the main app component's constructor:

```<code>public constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered app constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('app', params);
    });
}
</code>```

Here's the calculator component's constructor:

```<code>constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered calc constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('calc', params);
    });
}
</code>```

Here's the log I see in chrome:

Why is my query parameter erased?

UPDATE
I do have navigation configured in the app component like so:

```<code>let navigationExtras: NavigationExtras = {
    queryParamsHandling: 'preserve',
    preserveFragment: true
};
this.router.navigate(['/calculator'], navigationExtras);
</code>```

Note that the query parameters are already gone before it gets here though...

答:
You need to assign your query params to the queryParams Object.

Try:

```<code>this.router.navigate(['/calculator'], {queryParams: {a: 1}});
</code>```

or add this to your navigation extras:

```<code>let navigationExtras: NavigationExtras = {
    queryParamsHandling: 'preserve',
    preserveFragment: true,
    queryParams: {a:1}
};
</code>```

Title: Angular erasing all query parameters

Body:
Related to but not a duplicate of: How to keep query string parameters in URL when accessing a route of an Angular 2 app?

I have a very basic Angular app, and when I add a query parameter, it's erased (from the browser's url and everywhere else it would seem) before the code hits the app.component constructor.

Note: it is on the initial load (and subsequent reloads) that query parameters appear to be stripped

Example: navigating to localhost:8081/calculator?a=1 is changed to localhost:8081/calculator

I've tried this in Angular 4.3.1, 4.4.6 and 5.0.4, with the same result.

Here's my route config:

const appRoutes: Routes = [
    {
        path: 'calculator',
        component: CalculatorComponent
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Here's the main app component's constructor:

public constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered app constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('app', params);
    });
}

Here's the calculator component's constructor:

constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered calc constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('calc', params);
    });
}

Here's the log I see in chrome:

Why is my query parameter erased?

UPDATE
I do have navigation configured in the app component like so:

let navigationExtras: NavigationExtras = {
    queryParamsHandling: 'preserve',
    preserveFragment: true
};
this.router.navigate(['/calculator'], navigationExtras);

Note that the query parameters are already gone before it gets here though...

Body:
You need to assign your query params to the queryParams Object.

Try:

this.router.navigate(['/calculator'], {queryParams: {a: 1}});

or add this to your navigation extras:

let navigationExtras: NavigationExtras = {
    queryParamsHandling: 'preserve',
    preserveFragment: true,
    queryParams: {a:1}
};


问:
What happened to the .pull-left and .pull-right classes in Bootstrap 4?
In the newest version the pull-left and pull-right have been replaced by .pull-{xs,sm,md,lg,xl}-{left,right,none}

That means that instead of writing a simple class="pull-right", I will have now to write class="pull-md-right pull-xl-right pull-lg-right pull-sm-right pull-xs-right"

Is there a less tedious way to do it?

答:
I was able to do this with the following classes in my project</p>

```<code>d-flex justify-content-end

<div class="col-lg-6 d-flex justify-content-end">
</code>```

Body:
I was able to do this with the following classes in my project

d-flex justify-content-end

<div class="col-lg-6 d-flex justify-content-end">


问:
Angular - How to delete data from Firebase DB
I am trying to delete specific values from my firebase DB.
I want to delete this entry from firebase:

What I tried so far is my button on how to trigger the delete button:

```<code> <div class="single-bfunctions"
 *ngFor='let bfunc of liste'>
<b> Name: </b>{{bfunc.Name}} <br>
<b> Beschreibung: </b>  {{bfunc.Descr}}<br>
<b> Key: </b>   {{bfunc.$key}}
<button type="button"  ng-click="deleteSth(bfunc.name)">Delete Item </button>
</div>
</code>```

... and my delete-method:

```<code>deleteSth(name){
  firebase.database().ref('/BFunctions/').child(name).remove();
}
</code>```

As I am also pretty new to Angular I don't really what the solution could be.
I appreciate your answers!

答:
Try using the ref object

```<code>    <div class="single-bfunctions"
*ngFor='let bfunc of liste'>
<b> Name: </b>{{bfunc.Name}} <br>
<b> Beschreibung: </b>  {{bfunc.Descr}}<br>
<b> Key: </b>   {{bfunc.$key}}
<button type="button"  ng-click="deleteSth(bfunc.$key)">Delete Item
</button>
</div>
</code>```

and

```<code>deleteSth(key){
    firebase.database().ref('/BFunctions/' + key).remove();
}
</code>```

If that doesnt work check your console it could be related to permissions or something else

Body:
I am trying to delete specific values from my firebase DB.
I want to delete this entry from firebase:

What I tried so far is my button on how to trigger the delete button:

 Name: {{bfunc.Name}}

 Beschreibung:   {{bfunc.Descr}}

 Key:    {{bfunc.$key}}
<button type="button"  ng-click="deleteSth(bfunc.name)">Delete Item </button>

... and my delete-method:

deleteSth(name){
  firebase.database().ref('/BFunctions/').child(name).remove();
}

As I am also pretty new to Angular I don't really what the solution could be.
I appreciate your answers!

Body:
Try using the ref object

    <div class="single-bfunctions"
*ngFor='let bfunc of liste'>
<b> Name: </b>{{bfunc.Name}} <br>
<b> Beschreibung: </b>  {{bfunc.Descr}}<br>
<b> Key: </b>   {{bfunc.$key}}
<button type="button"  ng-click="deleteSth(bfunc.$key)">Delete Item
</button>
</div>

and

deleteSth(key){
    firebase.database().ref('/BFunctions/' + key).remove();
}

If that doesnt work check your console it could be related to permissions or something else


问:
Python: how to sort a list of strings by substring relevance?
I have some list of strings, for example:

```<code>["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]
</code>```

I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order:

```<code>["SOME TEXT",
"foo bar SOME TEXT baz",
"SOME foo TEXT",
"foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT"]
</code>```

The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets.

I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood.

Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how to do this sort there. So idea now is to get query set and next sort it out of the database (yep, I know that might be a bad decision, but for now I want it just work). But if anybody tells me how to do this within any of technologies, I have mentioned here - that will be also super cool. Thank you!

p.s. The length of substring supposed to be 2-10 words in max 20 word string.

答:
See your friendly neighborhood sorting tutorial.  You'll need a sort with a key.  Here's a trivial function to give you the idea; it finds the distance between the two words, returning that as the difference metric.

```<code>sentence = ["foo bar SOME baz TEXT bob",
            "SOME foo bar baz bob TEXT",
            "SOME foo TEXT",
            "foo bar SOME TEXT baz",
            "SOME TEXT"]

def match_score(sentence):
    some_pos = sentence.find("SOME")
    text_pos = sentence.find("TEXT")
    return abs(text_pos - some_pos)

sentence.sort(key = lambda x: match_score(x))

for item in sentence:
    print(item)
</code>```

Output:

```<code>foo bar SOME TEXT baz
SOME TEXT
foo bar SOME baz TEXT bob
SOME foo TEXT
SOME foo bar baz bob TEXT
</code>```

Body:
I have some list of strings, for example:

["foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT",
"SOME foo TEXT",
"foo bar SOME TEXT baz",
"SOME TEXT"]

I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order:

["SOME TEXT",
"foo bar SOME TEXT baz",
"SOME foo TEXT",
"foo bar SOME baz TEXT bob",
"SOME foo bar baz bob TEXT"]

The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets.

I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood.

Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how to do this sort there. So idea now is to get query set and next sort it out of the database (yep, I know that might be a bad decision, but for now I want it just work). But if anybody tells me how to do this within any of technologies, I have mentioned here - that will be also super cool. Thank you!

p.s. The length of substring supposed to be 2-10 words in max 20 word string.

Body:
See your friendly neighborhood sorting tutorial.  You'll need a sort with a key.  Here's a trivial function to give you the idea; it finds the distance between the two words, returning that as the difference metric.

sentence = ["foo bar SOME baz TEXT bob",
            "SOME foo bar baz bob TEXT",
            "SOME foo TEXT",
            "foo bar SOME TEXT baz",
            "SOME TEXT"]

def match_score(sentence):
    some_pos = sentence.find("SOME")
    text_pos = sentence.find("TEXT")
    return abs(text_pos - some_pos)

sentence.sort(key = lambda x: match_score(x))

for item in sentence:
    print(item)

Output:

foo bar SOME TEXT baz
SOME TEXT
foo bar SOME baz TEXT bob
SOME foo TEXT
SOME foo bar baz bob TEXT


问:
apostrophe issue with ajax post to php
i am posting data with jquery ajax to php but if input has ' inside, data wont be posted. I tried encodeURIComponent but wont work.

any idea on this ?

thanks

EDIT:
my code

```<code>var name = $("input#name_add").val();
         name = encodeURIComponent(name);

$.post("function.php", { name: name }, function(data) {

                               //codes
                });

$query = "UPDATE `table` SET name = '" . stripslashes($_POST['name']) . "' WHERE ID = '$id'";
$result = mysql_query($query);
if ($result){
print "ok";

}
</code>```

答:
This is what solved it for me. Since the JavaScript encodeURIComponent() function does not encode apostrophes to %27, I did it myself using my own replaceAll() function.

JS Snippet:

```<code>name = encodeURIComponent(name.replaceAll("'", '%27'));
</code>```

This is the replaceAll() function in my utilities JS file:

```<code>String.prototype.replaceAll = function(f, r, no_escape) {
    var rexp = new RegExp(Util.EscapeRegExp(f), 'g');
    if (no_escape) { rexp = new RegExp(f, 'g'); }
    return this.replace(rexp, r);
};
</code>```

For my purposes, I needed the apostrophe to not be %27 anymore, and the PHP function urldecode() does not do apostrophes either, so I used str_replace() to take care of that.

PHP Snippet:

```<code>$name = str_replace('%27', "'", urldecode($_POST['name'] ) );
</code>```

Title: apostrophe issue with ajax post to php

Body:
i am posting data with jquery ajax to php but if input has ' inside, data wont be posted. I tried encodeURIComponent but wont work.

any idea on this ?

thanks

EDIT:
my code

var name = $("input#name_add").val();
         name = encodeURIComponent(name);

$.post("function.php", { name: name }, function(data) {

                               //codes
                });

$query = "UPDATE `table` SET name = '" . stripslashes($_POST['name']) . "' WHERE ID = '$id'";
$result = mysql_query($query);
if ($result){
print "ok";

}

Body:
This is what solved it for me. Since the JavaScript encodeURIComponent() function does not encode apostrophes to %27, I did it myself using my own replaceAll() function.

JS Snippet:

name = encodeURIComponent(name.replaceAll("'", '%27'));

This is the replaceAll() function in my utilities JS file:

String.prototype.replaceAll = function(f, r, no_escape) {
    var rexp = new RegExp(Util.EscapeRegExp(f), 'g');
    if (no_escape) { rexp = new RegExp(f, 'g'); }
    return this.replace(rexp, r);
};

For my purposes, I needed the apostrophe to not be %27 anymore, and the PHP function urldecode() does not do apostrophes either, so I used str_replace() to take care of that.

PHP Snippet:

$name = str_replace('%27', "'", urldecode($_POST['name'] ) );


答:
You can load the current date info into the DateFormatter:</p>

```<code>let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "MM/dd hh:mm aa"

dateFormatter.defaultDate = Date() // start with the current date

self.dateCompleted = dateFormatter.date(from: self.DeliverBy!)
</code>```

Title: incorrect string to date conversion swift 3.0

Body:
You can load the current date info into the DateFormatter:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "MM/dd hh:mm aa"

dateFormatter.defaultDate = Date() // start with the current date

self.dateCompleted = dateFormatter.date(from: self.DeliverBy!)


问:
Fill in web form from an app and submit
I have a webpage with a simple form with 3 input fields, Name, Email and Course and a submit button. Nothing fancy.

Upon developing an android app, I would like to know how I could fill in that web form from within my android app without using a webview to actually load the webpage.

答:
I have used something like this in the past. However you will have to load a webview (though you dont need to show it.) then do something like below. Keep in mind that if the site changes the id down the road this approach will not work.</p>

```<code>webView.loadUrl("javascript:var
    name=document.getElementById('nameInput').value='" yourNameValue "'");
webView.loadUrl("javascript:document.getElementById('submit').click()");
</code>```

Title: Fill in web form from an app and submit

Body:
I have used something like this in the past. However you will have to load a webview (though you dont need to show it.) then do something like below. Keep in mind that if the site changes the id down the road this approach will not work.

webView.loadUrl("javascript:var
    name=document.getElementById('nameInput').value='" yourNameValue "'");
webView.loadUrl("javascript:document.getElementById('submit').click()");


问:
What is the native application API for iphone and android that is equivalent html5 canvas?
I have developed html5 canvas based animations (non-interacive) which work very well in latest desktop browsers but perform miserably on iphone and android. I want to port these web based html5 canvas application to native iphone and android applications. I am looking for something that will provide the quickest way to port such applications to native iphone and android applications without having to learn something completely different like opengl es. Is there such native API ( something like canvas 2d drawing surface) and if so what is the API?</p>

答: On the iPhone, you should look into Core Animation and Animation Blocks. I have 0 Android experience though, so I can't help you with that. </p>


问:
TypeError: unsupported operand type(s) for -: 'str' and 'str' on line 4 how do i fix
```<code>print("you have chosen black")
gamble = input("how much do you want to gamble")
print("you have gambled",gamble)
money_left = money_left - gamble
print("you have",money_left,"left")
spin = random.randint(1,20)
print("It landed on....")
time.sleep(3)
print(spin)
</code>```

line 4 not working and money_left already a variable

getting a TypeError: unsupported operand type(s) for -: 'str' and 'str'

答:
Cast gamble to a number</p>

```<code>money_left = int(money_left) - int(gamble)
</code>```

Body:
print("you have chosen black")
gamble = input("how much do you want to gamble")
print("you have gambled",gamble)
money_left = money_left - gamble
print("you have",money_left,"left")
spin = random.randint(1,20)
print("It landed on....")
time.sleep(3)
print(spin)

line 4 not working and money_left already a variable

getting a TypeError: unsupported operand type(s) for -: 'str' and 'str'

Body:
Cast gamble to a number

money_left = int(money_left) - int(gamble)