问:
Does an additional "AND `columnname` LIKE '%'" hurt performance?

simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

```<code>AND `name` LIKE '%'
</code>```

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?

答: Yes.  LIKE's are very expensive.  But as with most things, it depends on the size of your DB.</p>

Body:
simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

AND `name` LIKE '%'

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?


来源: stackexchange

问:
OpenRecordset not recognisng query criteria
I have developed an Access Database query which references an object on a form in order to dynamically filter the data. The criteria upon which the query is filtered is as follows:

```<code>[Forms]![frmMain]![NavigationSubform].[Form]![Frame64]
</code>```

Where [frame64] is where the user chooses one of two options on a form.

Whilst this query runs fine in Access, I want to use this query in a piece of VBA code, but the problem is, when I try to open the record set, VBA won't allow me.

```<code>Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("qryMergeEzineCompleteMerges", dbOpenDynamic, dbSeeChanges)
</code>```

Through my research, I have discovered that it is because VBA doesn't recognise the query criteria I have defined as it refers to a form.

Can anyone please show me how I can reference this recordset in VBA so that it filters by the criteria I have stipulated in the query itself?

Many thanks

答:
You need to open the Recordset through a QueryDef.</p>

```<code>Sub Whatever()
    Dim db As Database
    Dim qdf As QueryDef
    Dim rs As Recordset

    Set db = CurrentDb()
    Set qdf = db.QueryDefs("qryMergeEzineCompleteMerges")

   'add any parameters here
    With qdf
        .Parameters("[parameter1]").Value = value1
        .Parameters("[parameter2]").Value = value2
    End With

    Set rs = qdf.OpenRecordset(dbOpenDynaset)

    '...

    rs.Close
    Set rs = Nothing
    qdf.Close
    Set qdf = Nothing
    Set db = Nothing
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have developed an Access Database query which references an object on a form in order to dynamically filter the data. The criteria upon which the query is filtered is as follows:

[Forms]![frmMain]![NavigationSubform].[Form]![Frame64]

Where [frame64] is where the user chooses one of two options on a form.

Whilst this query runs fine in Access, I want to use this query in a piece of VBA code, but the problem is, when I try to open the record set, VBA won't allow me.

Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("qryMergeEzineCompleteMerges", dbOpenDynamic, dbSeeChanges)

Through my research, I have discovered that it is because VBA doesn't recognise the query criteria I have defined as it refers to a form.

Can anyone please show me how I can reference this recordset in VBA so that it filters by the criteria I have stipulated in the query itself?

Many thanks

Body:
You need to open the Recordset through a QueryDef.

Sub Whatever()
    Dim db As Database
    Dim qdf As QueryDef
    Dim rs As Recordset

    Set db = CurrentDb()
    Set qdf = db.QueryDefs("qryMergeEzineCompleteMerges")

   'add any parameters here
    With qdf
        .Parameters("[parameter1]").Value = value1
        .Parameters("[parameter2]").Value = value2
    End With

    Set rs = qdf.OpenRecordset(dbOpenDynaset)

    '...

    rs.Close
    Set rs = Nothing
    qdf.Close
    Set qdf = Nothing
    Set db = Nothing
End Sub


问:
How to check what the current users role is
How do I check in C# what the current users role is, and print it to the screen.

Thanks!

答:
Roles.GetRolesForUser(); gave me the error The Role Manager feature has not been enabled.

If you are using ASP.NET Identity UserManager you can get it like this:

```<code>var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

var roles = userManager.GetRoles(User.Identity.GetUserId());
</code>```

If you have changed key for user from Guid to Int for example use this code:

```<code>var roles = userManager.GetRoles(User.Identity.GetUserId<int>());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Roles.GetRolesForUser(); gave me the error The Role Manager feature has not been enabled.

If you are using ASP.NET Identity UserManager you can get it like this:

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

var roles = userManager.GetRoles(User.Identity.GetUserId());

If you have changed key for user from Guid to Int for example use this code:

var roles = userManager.GetRoles(User.Identity.GetUserId<int>());


问:
How to quickly build a two dimensional array from two arrays using FP or 3rd party library
I have two double arrays x[], y[] with equal dimension, how to quickly build a double array without loops

Double xy[][] from x, y with the second dimension be 2.

I am OK with using any third part libraries

code using loops

```<code> double xy[][] = new double[x.length][2];
 for (int i = 0; i< x.length; i++) {
            xy[i][0] = x[i];
            xy[i][1] = y[i];
 }
</code>```

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

答:
Here you go. If you look for an online tutorial on working with arrays and matrices in Java you will probably find it helpful for whatever you've got coming next.

```<code>public class JavaTest {

    public static void main(String[] args) {

        double x[] = {0.0, 1.0, 2.0};
        double y[] = {3.0, 4.0, 5.0};

        double xy[][]= new double[2][];
        xy[0] = new double[x.length];
        xy[1] = new double[y.length];

        for (int i=0 ; i < x.length ;i++)
            xy[0][i] = x[i];
        for (int j=0 ; j < y.length ;j++)
            xy[1][j] = y[j];

        for (int i=0 ; i < xy.length ;i++) {
            for (int j=0 ; j < xy[i].length ;j++) {
                System.out.print(xy[i][j] + " ");
            }
            System.out.print("\n");
        }
    }
}
</code>```

Output:

```<code>0.0 1.0 2.0
3.0 4.0 5.0
</code>```

Body:
I have two double arrays x[], y[] with equal dimension, how to quickly build a double array without loops

Double xy[][] from x, y with the second dimension be 2.

I am OK with using any third part libraries

code using loops

 double xy[][] = new double[x.length][2];
 for (int i = 0; i< x.length; i++) {
            xy[i][0] = x[i];
            xy[i][1] = y[i];
 }

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

Body:
Here you go. If you look for an online tutorial on working with arrays and matrices in Java you will probably find it helpful for whatever you've got coming next.

public class JavaTest {

    public static void main(String[] args) {

        double x[] = {0.0, 1.0, 2.0};
        double y[] = {3.0, 4.0, 5.0};

        double xy[][]= new double[2][];
        xy[0] = new double[x.length];
        xy[1] = new double[y.length];

        for (int i=0 ; i < x.length ;i++)
            xy[0][i] = x[i];
        for (int j=0 ; j < y.length ;j++)
            xy[1][j] = y[j];

        for (int i=0 ; i < xy.length ;i++) {
            for (int j=0 ; j < xy[i].length ;j++) {
                System.out.print(xy[i][j] + " ");
            }
            System.out.print("\n");
        }
    }
}

Output:

0.0 1.0 2.0
3.0 4.0 5.0


问:
Launch external program with multiple commands via Powershell
I am currently attempting to launch a different console (.exe) and pass multiple commands; while starting and entering a command works just fine, I haven't been able to find out how multiple ones can be entered via powershell.

```<code>& "C:\Program Files\Docker Toolbox\start.sh" docker-compose up -d --build
</code>```

The given command works fine, but as mentioned I need to pass more than one command - I tried using arrays, ScriptBlocks and different sequences, though to no avail.

Edit:

Noticed that the docker build has a -f tag which allows me to specify a file; however, the issue now seems to be that the executed cmd removes all backslashes & special characters, rendering the path given useless.

Example:

```<code>&"C:\Program Files\Docker Toolbox\start.sh" 'docker-compose build -f
path\to\dockerfile'
</code>```

will result in an error stating that "pathtodockerfile" is an invalid path.

答: Your start.sh needs to be able to handle multiple arguments.  This doesn't look like a PowerShell question

Body:
I am currently attempting to launch a different console (.exe) and pass multiple commands; while starting and entering a command works just fine, I haven't been able to find out how multiple ones can be entered via powershell.

& "C:\Program Files\Docker Toolbox\start.sh" docker-compose up -d --build

The given command works fine, but as mentioned I need to pass more than one command - I tried using arrays, ScriptBlocks and different sequences, though to no avail.

Edit:

Noticed that the docker build has a -f tag which allows me to specify a file; however, the issue now seems to be that the executed cmd removes all backslashes & special characters, rendering the path given useless.

Example:

&"C:\Program Files\Docker Toolbox\start.sh" 'docker-compose build -f
path\to\dockerfile'

will result in an error stating that "pathtodockerfile" is an invalid path.


问:
how to get innerHTML value in javascript code
I want to change table  data by using innerHTML property. But after applying innerHTML property those values set in  are not accessible in Javascript code.

So is there any alternative to innerHTML property so that value can be set in  and it can also be accessed in Javascript Code.

Javascript code

```<code><script>
    var row=0,col=0,i=1;//can be used in loop

    document.getElementById("tableID").rows[row].cells[col].innerHTML=i;
</script>
</code>```

答:
Look at this small sample, innerHTML works. Walk with cursor keys through the Table. Show us more Code

  <!doctype html>

    <meta charset="UTF-8">
    <title>Table key´s</title>

  ```

Body:
Look at this small sample, innerHTML works. Walk with cursor keys through the Table. Show us more Code

  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Table key´s</title>
    <style>
      td{width:40px;height:40px;background:#ddd;}
    </style>
  </head>
  <body>
    <div id="tableContainer">
    </div>
    <script>
      var aktRow=aktCol=4,max=9;
      tableContainer.innerHTML = '<table id="mt">'+('<tr>'+'<td></td>'.repeat(max+1)+'</tr>').repeat(max+1)+'</table>';
      mt.rows[aktRow].cells[aktCol].style.background='#f00';
      window.addEventListener("keyup", function(e){
        var colDiff, rowDiff;
        var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
        if (keyMap.has(e.keyCode)){
          mt.rows[aktRow].cells[aktCol].style.background='#ddd';
          mt.rows[aktRow].cells[aktCol].innerHTML=aktRow+'-'+aktCol;
          console.log(mt.rows[aktRow].cells[aktCol].innerHTML);
          [colDiff,rowDiff]=keyMap.get(e.keyCode);
          aktRow+=rowDiff;
          aktCol+=colDiff;
          aktRow = (aktRow>max) ? max : (aktRow < 0) ? 0 : aktRow;
          aktCol = (aktCol>max) ? max : (aktCol < 0) ? 0 : aktCol;
          mt.rows[aktRow].cells[aktCol].style.background='#f00';
        }
      })
    </script>
  </body>
  </html>


问:
Reading between certain lines
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!</p>

```<code># DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789
</code>```

答:
I think this achieves what you want

```<code>/(.+)\nStats1(?:\n.+){3})/g
</code>```

It matches the following two dates: Dec 8 20:00:00 and Dec 8 21:00:00

Title: Reading between certain lines

Body:
I have a large file that I need to pull out only certain pieces of information. I have found a lot of examples on the web, but I cannot get any to work for my particular instance. I have the file data.log (below), and need to pull out all of the Stats1 counters, including the data above. There are multiple instances of these stats. I cannot seem to get a regular expression to match the date AND Stats1, and then read everything up until the three /n/n/n's.... Any help much appreciated!!!

# DATA FILE

Dec 8 20:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Dec 8 21:00:00
Stats1
  counter1:     123
  counter2:     456
  counter3:     789

Dec 8 21:00:00
Stats2
  counter4:     123
  counter5:     456
  counter6:     789

Body:
I think this achieves what you want

/(.+)\nStats1(?:\n.+){3})/g

It matches the following two dates: Dec 8 20:00:00 and Dec 8 21:00:00


问:
JFreechart program running, but window not displayed
I am running code based on the example shown here using Eclipse on OS X, and I am using the JFreeChart and JCommon libraries.

As i said in the title, the program is running but not displaying anything.
As check I have tried to print the data using the method printData() and it's working perfectly.
It correctly takes the data from a yahoo csv file.

I have even tried using a small bunch of data (20 rows), but it keeps not showing.

The problem may be just in displaying the JFrame window.

The code I have inserted trying to fix it is between //BEGIN and //END comments.

Waiting for a reply,

Thank you.

SEMI-SOLVED:
The code is fine, the problem is related to the JFreeChart Library.

I tried to "Build Path> Add my JFreeChart lib" in another previously working JFrame class.

When i insert the JFreeChart library, it inhibits the window display. Even if i don't import anything; just by adding the library to the building path.

As default system library i'm using "JRE System Library [JavaSE-1.7]".

Code:

```<code>package marketAnalyzer;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.MovingAverage;
import org.jfree.data.xy.*;

import javax.swing.*;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.*;
import java.util.*;
import java.util.List;

public class CandlestickDemo extends JFrame {

    public CandlestickDemo(String stockSymbol) {
        super("CandlestickDemo");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateAxis    domainAxis       = new DateAxis("Date");
        NumberAxis  rangeAxis        = new NumberAxis("Price");
        CandlestickRenderer renderer = new CandlestickRenderer();
        XYDataset   dataset          = getDataSet(stockSymbol);

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        final long ONE_DAY = 24 * 60 * 60 * 1000;
        XYLineAndShapeRenderer maRenderer = new XYLineAndShapeRenderer(true, false);
        XYDataset              maSataset  = MovingAverage.createMovingAverage(dataset, "MA", 30 * ONE_DAY, 0);
        mainPlot.setRenderer(1, maRenderer);
        mainPlot.setDataset (1, maSataset);

        //Do some setting up, see the API Doc
        renderer.setSeriesPaint(0, Color.BLACK);
        renderer.setDrawVolume(false);
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setTimeline( SegmentedTimeline.newMondayThroughFridayTimeline() );

        //Now create the chart and chart panel
        JFreeChart chart = new JFreeChart(stockSymbol, null, mainPlot, false);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(600, 300));

        this.add(chartPanel);
        this.pack();

        //BEGIN

        //TRYING TO DISPLAY THE WINDOW

        chartPanel.setLayout(new java.awt.BorderLayout());
        chartPanel.validate();
        this.setLayout(new java.awt.BorderLayout());
        this.validate();
        chartPanel.repaint();
        this.repaint();

        //END
    }
    protected AbstractXYDataset getDataSet(String stockSymbol) {
        //This is the dataset we are going to create
        DefaultOHLCDataset result = null;
        //This is the data needed for the dataset
        OHLCDataItem[] data;

        //This is where we go get the data, replace with your own data source
        data = getData(stockSymbol);

        //Create a dataset, an Open, High, Low, Close dataset
        result = new DefaultOHLCDataset(stockSymbol, data);

        return result;
    }
    //This method uses yahoo finance to get the OHLC data
    protected OHLCDataItem[] getData(String stockSymbol) {
        List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            //INTERNET DATA
            //              String strUrl= "http://ichart.finance.yahoo.com/table.csv?s="+stockSymbol+"&a=0&b=1&c=2008&d=3&e=30&f=2008&ignore=.csv";
            //              URL url = new URL(strUrl);
            //              BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            //              DateFormat df = new SimpleDateFormat("y-M-d");

            //BEGIN
            FileReader r;
            BufferedReader in;

            r = new FileReader("nasdaqSmall.csv");

            in = new BufferedReader(r);
            DateFormat df = new SimpleDateFormat("y-M-d");

            //END

            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(inputLine, ",");

                Date date       = df.parse( st.nextToken() );
                double open     = Double.parseDouble( st.nextToken() );
                double high     = Double.parseDouble( st.nextToken() );
                double low      = Double.parseDouble( st.nextToken() );
                double close    = Double.parseDouble( st.nextToken() );
                double volume   = Double.parseDouble( st.nextToken() );
                double adjClose = Double.parseDouble( st.nextToken() );

                OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
                dataItems.add(item);
            }
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
        Collections.reverse(dataItems);

        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);

        //BEGIN
        //DEBUG
        printData(data);
        //END

        return data;
    }

    public static void main(String[] args) {
        new CandlestickDemo("MSFT").setVisible(true);

    }

    //PRINT DATA
    public static void printData(OHLCDataItem[] data){
        for(OHLCDataItem el: data){
            System.out.println(""+el.getDate()+" "+el.getOpen()+" "+el.getHigh()+" "+el.getLow()+" "+el.getClose()+
                    " "+el.getVolume());

        }
    }

}
</code>```

答: I was having this issue as well. It comes from adding all of the jars in the JFreeChart lib to the build path. By removing the unnecessary and adding only the jfreechart-1.0.19 and jcommon-1.0.23 jars, my applications started running with the window and chart displayed.

Body:
I am running code based on the example shown here using Eclipse on OS X, and I am using the JFreeChart and JCommon libraries.

As i said in the title, the program is running but not displaying anything.
As check I have tried to print the data using the method printData() and it's working perfectly.
It correctly takes the data from a yahoo csv file.

I have even tried using a small bunch of data (20 rows), but it keeps not showing.

The problem may be just in displaying the JFrame window.

The code I have inserted trying to fix it is between //BEGIN and //END comments.

Waiting for a reply,

Thank you.

SEMI-SOLVED:
The code is fine, the problem is related to the JFreeChart Library.

I tried to "Build Path> Add my JFreeChart lib" in another previously working JFrame class.

When i insert the JFreeChart library, it inhibits the window display. Even if i don't import anything; just by adding the library to the building path.

As default system library i'm using "JRE System Library [JavaSE-1.7]".

Code:

package marketAnalyzer;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.MovingAverage;
import org.jfree.data.xy.*;

import javax.swing.*;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.*;
import java.util.*;
import java.util.List;

public class CandlestickDemo extends JFrame {

    public CandlestickDemo(String stockSymbol) {
        super("CandlestickDemo");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateAxis    domainAxis       = new DateAxis("Date");
        NumberAxis  rangeAxis        = new NumberAxis("Price");
        CandlestickRenderer renderer = new CandlestickRenderer();
        XYDataset   dataset          = getDataSet(stockSymbol);

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        final long ONE_DAY = 24 * 60 * 60 * 1000;
        XYLineAndShapeRenderer maRenderer = new XYLineAndShapeRenderer(true, false);
        XYDataset              maSataset  = MovingAverage.createMovingAverage(dataset, "MA", 30 * ONE_DAY, 0);
        mainPlot.setRenderer(1, maRenderer);
        mainPlot.setDataset (1, maSataset);

        //Do some setting up, see the API Doc
        renderer.setSeriesPaint(0, Color.BLACK);
        renderer.setDrawVolume(false);
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setTimeline( SegmentedTimeline.newMondayThroughFridayTimeline() );

        //Now create the chart and chart panel
        JFreeChart chart = new JFreeChart(stockSymbol, null, mainPlot, false);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(600, 300));

        this.add(chartPanel);
        this.pack();

        //BEGIN

        //TRYING TO DISPLAY THE WINDOW

        chartPanel.setLayout(new java.awt.BorderLayout());
        chartPanel.validate();
        this.setLayout(new java.awt.BorderLayout());
        this.validate();
        chartPanel.repaint();
        this.repaint();

        //END
    }
    protected AbstractXYDataset getDataSet(String stockSymbol) {
        //This is the dataset we are going to create
        DefaultOHLCDataset result = null;
        //This is the data needed for the dataset
        OHLCDataItem[] data;

        //This is where we go get the data, replace with your own data source
        data = getData(stockSymbol);

        //Create a dataset, an Open, High, Low, Close dataset
        result = new DefaultOHLCDataset(stockSymbol, data);

        return result;
    }
    //This method uses yahoo finance to get the OHLC data
    protected OHLCDataItem[] getData(String stockSymbol) {
        List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            //INTERNET DATA
            //              String strUrl= "http://ichart.finance.yahoo.com/table.csv?s="+stockSymbol+"&a=0&b=1&c=2008&d=3&e=30&f=2008&ignore=.csv";
            //              URL url = new URL(strUrl);
            //              BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            //              DateFormat df = new SimpleDateFormat("y-M-d");

            //BEGIN
            FileReader r;
            BufferedReader in;

            r = new FileReader("nasdaqSmall.csv");

            in = new BufferedReader(r);
            DateFormat df = new SimpleDateFormat("y-M-d");

            //END

            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(inputLine, ",");

                Date date       = df.parse( st.nextToken() );
                double open     = Double.parseDouble( st.nextToken() );
                double high     = Double.parseDouble( st.nextToken() );
                double low      = Double.parseDouble( st.nextToken() );
                double close    = Double.parseDouble( st.nextToken() );
                double volume   = Double.parseDouble( st.nextToken() );
                double adjClose = Double.parseDouble( st.nextToken() );

                OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
                dataItems.add(item);
            }
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
        Collections.reverse(dataItems);

        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);

        //BEGIN
        //DEBUG
        printData(data);
        //END

        return data;
    }

    public static void main(String[] args) {
        new CandlestickDemo("MSFT").setVisible(true);

    }

    //PRINT DATA
    public static void printData(OHLCDataItem[] data){
        for(OHLCDataItem el: data){
            System.out.println(""+el.getDate()+" "+el.getOpen()+" "+el.getHigh()+" "+el.getLow()+" "+el.getClose()+
                    " "+el.getVolume());

        }
    }

}


问:
why use Google V8
I don't get it. I'm a C/C++ programmer, what's the possible use of V8 for me? There are few examples and tutorials out there, and they all lack substance - I don't want to use another library to just add a couple of numbers or print something in a console window.
My question is: is there a real use for this technology, and if yes, then would be the scenario?
Also, can I do any part of GUI this way?

Help is appreciated.

答:
Google V8 is a JavaScript engine.

I don't really think it is what you are looking for.

Title: why use Google V8


问:
Why does printing the __repr__ of an integer require parenthesis?
For a string literal, say foo, if I'd want to get it's repr by calling __repr__ of this string, all I'd do is:

```<code>>>> 'foo'.__repr__()
"'foo'"
</code>```

This also works:

```<code>>>> ('foo').__repr__()
"'foo'"
</code>```

It's the same case for floats:

```<code>>>> 1.0.__repr__()
'1.0'
>>> (1.0).__repr__()
'1.0'
</code>```

But when it comes to integers, it isn't quite the same. Trying to call __repr__ without first applying parenthesis throws an error

```<code>>>> 1.__repr__()
  File "<stdin>", line 1
    1.__repr__()
             ^
SyntaxError: invalid syntax
</code>```

However, when I apply parenthesis, it works:

```<code>>>> (1).__repr__()
'1'
</code>```

So, why does an integer require the parenthesis?

答:
Alternatively, you can

```<code>1 .__repr__()
</code>```

The problem is that 1. is a floating-point number. So you have to have something between the 1 and the ., either a space or a parenthesis.

Body:
For a string literal, say foo, if I'd want to get it's repr by calling __repr__ of this string, all I'd do is:

>>> 'foo'.__repr__()
"'foo'"

This also works:

>>> ('foo').__repr__()
"'foo'"

It's the same case for floats:

>>> 1.0.__repr__()
'1.0'
>>> (1.0).__repr__()
'1.0'

But when it comes to integers, it isn't quite the same. Trying to call __repr__ without first applying parenthesis throws an error

>>> 1.__repr__()
  File "<stdin>", line 1
    1.__repr__()
             ^
SyntaxError: invalid syntax

However, when I apply parenthesis, it works:

>>> (1).__repr__()
'1'

So, why does an integer require the parenthesis?

Body:
Alternatively, you can

1 .__repr__()

The problem is that 1. is a floating-point number. So you have to have something between the 1 and the ., either a space or a parenthesis.


问:
Simplifiying JQuery
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <span id="first">Blah blah blah, please <span id="span1">click here</span>.</span>
    <span id="second" style="display:none;">Cancel</span>
    <div id="third" style="display:none;">Test</div></code>```

This code is taken from accepted answer from original post.

答:
One improvement I could suggest is to cache the selectors in a variable and use those. Like so:</p>

```<code>$first = $("#first");
$second = $("#second");
$secondThird = $("#second, #third");
$span1 = $("#span1");

$span1.on('click', function() {
   $secondThird.fadeIn();
   $first.hide();
});

$second.on('click', function() {
   $first.fadeIn();
   $secondThird.hide();
});
</code>```

Title: Simplifiying JQuery

Body:
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });

    Blah blah blah, please click here.
    Cancel

Test

This code is taken from accepted answer from original post.

Body:
One improvement I could suggest is to cache the selectors in a variable and use those. Like so:

$first = $("#first");
$second = $("#second");
$secondThird = $("#second, #third");
$span1 = $("#span1");

$span1.on('click', function() {
   $secondThird.fadeIn();
   $first.hide();
});

$second.on('click', function() {
   $first.fadeIn();
   $secondThird.hide();
});


问:
What is the best practise for providing a method/class/component that supports cancellation?
How do you design a method/class that should support cancellation of the operation?

I realized that I never do that in a consistent manner and I want to change that.

Some of the things I have used:

a boolean property on the class IsCancelled that I synchronize internally. sometimes I have a CanCancel property if the operation cannot be canceled at any given time

pass a Func< bool > delegate that I repeatedly call to see if the operation has been canceled.

terminate the thread manually - although this is definitely bad practise

How do you normally do that?

答: I'd prefer to use the IsCancelled property idea. Your background thread method can check it at the appropriate times, do any cleanup as needed, and terminate the operation. If you're using a callback method when the thread finishes, it's easy to check the property and see if it's valid or not. I've used framework worker thread classes that used this strategy in the past, and it's worked well.

OwnerDisplayName: Patrick Klug

OwnerDisplayName: Marc Charbonneau


答:
Just put a space before the dot:

```<code>>>> 1 .__repr__()
'1'
</code>```

to disambiguate the literal int 1 from a literal "partial" float 1..

Title: Why does printing the __repr__ of an integer require parenthesis?

Body:
Just put a space before the dot:

>>> 1 .__repr__()
'1'

to disambiguate the literal int 1 from a literal "partial" float 1..


问:
How to post a facebook status message using java and selenium webdriver
I logged into Facebook. Now from home page or News Feed page I want to type some message in "Share an Update" text area and click on Post.
Tried below locator. Didn't work.

driver.findElement(By.name("xhpc_message_text")).sendkeys("Hello World");
WebDriverWait wait = new WebDriverWait(driver, 5);

答:
I have found a solution for your question. Please try the below code:

Code:

```<code>    url = "http://facebook.com";
    String email = "email";
    String password = "password";
    System.setProperty("webdriver.chrome.driver", "src/chromedriver 3");
    WebDriver driver = new ChromeDriver();
    driver.get(url);
    driver.manage().window().maximize();
    driver.findElement(By.id("email")).sendKeys("your email id");
    driver.findElement(By.id("pass")).sendKeys("Your password" + Keys.ENTER);
    WebDriverWait wait = new WebDriverWait(driver, 500);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//textarea[contains(@title,'Share an update')]")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//textarea[contains(@title,'Share an update')]")));
     driver.findElement(By.xpath("//textarea[contains(@title,'Share an update')]")).click();

     wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@contenteditable='true']")));
     wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@contenteditable='true']")));
   driver.findElement(By.xpath("//div[@contenteditable='true']")).sendKeys("Hello World");
</code>```

Explanation:

First you have to click on the Share an update text box and then send keys on the div element for which content-editable is set as true.

Body:
I have found a solution for your question. Please try the below code:

Code:

    url = "http://facebook.com";
    String email = "email";
    String password = "password";
    System.setProperty("webdriver.chrome.driver", "src/chromedriver 3");
    WebDriver driver = new ChromeDriver();
    driver.get(url);
    driver.manage().window().maximize();
    driver.findElement(By.id("email")).sendKeys("your email id");
    driver.findElement(By.id("pass")).sendKeys("Your password" + Keys.ENTER);
    WebDriverWait wait = new WebDriverWait(driver, 500);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//textarea[contains(@title,'Share an update')]")));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//textarea[contains(@title,'Share an update')]")));
     driver.findElement(By.xpath("//textarea[contains(@title,'Share an update')]")).click();

     wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@contenteditable='true']")));
     wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@contenteditable='true']")));
   driver.findElement(By.xpath("//div[@contenteditable='true']")).sendKeys("Hello World");

Explanation:

First you have to click on the Share an update text box and then send keys on the div element for which content-editable is set as true.


问:
How to know if textarea cursor reach to the last of the field?
In this example i want to add margin when cursor reach or touch send button and when touched the send button needed to add margin top. As same like current facebook comment field, when cursor touched sticker or emoji icon the icons are shifted to the bottom of fields.

autosize($('textarea'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea { width:99%;min-height:15px }
div { position:relative }
button { position:absolute;right:10px;bottom:8px }</code>```

<textarea class="textarea"></textarea>
<button>
Send
</button>

```

答:
Hard wrap your text area to maximum</p>

```<code><textarea NAME="myTextArea"  ROWS="5" WRAP="HARD"></textarea>
<script>
var numCols = document.getElementById('myTextArea').cols;
document.getElementById('myTextArea').cols=numCols-7;
</script>
</code>```

Body:
In this example i want to add margin when cursor reach or touch send button and when touched the send button needed to add margin top. As same like current facebook comment field, when cursor touched sticker or emoji icon the icons are shifted to the bottom of fields.

autosize($('textarea'));

textarea { width:99%;min-height:15px }
div { position:relative }
button { position:absolute;right:10px;bottom:8px }

<textarea class="textarea"></textarea>
<button>
Send
</button>

Body:
Hard wrap your text area to maximum

<textarea NAME="myTextArea"  ROWS="5" WRAP="HARD"></textarea>
<script>
var numCols = document.getElementById('myTextArea').cols;
document.getElementById('myTextArea').cols=numCols-7;
</script>


问:
Contract throws Invalid address when using send() function in solidity 0.4.6
This is the solidity code that I am trying. Compiling of the code works fine. However, when I call the function send() via javascript it throws exception : throw new Error('invalid address');

```<code>pragma solidity ^0.4.6;
contract Agreement {
   address owner;
   address seller;
   uint amount;

   function Agreement(address _seller,uint _amount) {
     owner = msg.sender; seller=_seller; amount=_amount;
   }

   function send(){
    if (owner.balance < amount) throw;
    if (seller.balance + amount < seller.balance) throw;
    if(!seller.send(amount))throw;
    }
}
</code>```

This is the javascript code

```<code>var compiled = web3.eth.compile.solidity(contractRaw);
var contract = web3.eth.contract(compiled.info.abiDefinition);
var nContract = contract.new('0x61e323dcf5e116597d96558a91601f94b1f80396',web3.toWei(10, "ether"),{from:this.web3.eth.coinbase, data: compiled.code, gas: 380000}, function(e, contractDetails){
        if(!e) {

            if(!contractDetails.address) {
                console.log("Contract transaction send: TransactionHash: " + contractDetails.transactionHash + " waiting to be mined...");

            } else {
                console.log("Contract mined! Address: " + contractDetails.address);
                console.log(contractDetails.send())

            }

        }
    });
</code>```

Whenever the code runs, it throws invalid address error and crashes.

Body:
This is the solidity code that I am trying. Compiling of the code works fine. However, when I call the function send() via javascript it throws exception : throw new Error('invalid address');

pragma solidity ^0.4.6;
contract Agreement {
   address owner;
   address seller;
   uint amount;

   function Agreement(address _seller,uint _amount) {
     owner = msg.sender; seller=_seller; amount=_amount;
   }

   function send(){
    if (owner.balance < amount) throw;
    if (seller.balance + amount < seller.balance) throw;
    if(!seller.send(amount))throw;
    }
}

This is the javascript code

var compiled = web3.eth.compile.solidity(contractRaw);
var contract = web3.eth.contract(compiled.info.abiDefinition);
var nContract = contract.new('0x61e323dcf5e116597d96558a91601f94b1f80396',web3.toWei(10, "ether"),{from:this.web3.eth.coinbase, data: compiled.code, gas: 380000}, function(e, contractDetails){
        if(!e) {

            if(!contractDetails.address) {
                console.log("Contract transaction send: TransactionHash: " + contractDetails.transactionHash + " waiting to be mined...");

            } else {
                console.log("Contract mined! Address: " + contractDetails.address);
                console.log(contractDetails.send())

            }

        }
    });

Whenever the code runs, it throws invalid address error and crashes.

Body: Try 61e323dcf5e116597d96558a91601f94b1f80396, without the 0x


问:
Bizarre behavior of a query
I found this query from a developer:

```<code>DELETE FROM [MYDB].[dbo].[MYSIGN] where USERID in
(select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi');
</code>```

This query deletes every record in table MYSIGN.

The field USERID does not exists in table MYUSER. If I run only the subquery:

```<code>select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi'
</code>```

It throws the right error, because the missing column.

We corrected the query using the right column, but we didn't figure out:

Why the first query works?

Why it deletes every record?

Specs: database is on a SQL SERVER 2016 SP1, CU3.

答:
The problem is the scoping rules of subqueries.  If the column is not found in the subquery tables, then the SQL engine starts looking at the next level out -- and so on (in the case of SQL Server).

Whenever you have multiple tables in a query, always qualify the column names.  This means, put the table name (or alias) with the column alias.  Then you have no ambiguity:

```<code>DELETE
    FROM [MYDB].[dbo].[MYSIGN] m
    WHERE m.USERID IN (SELECT u.USERID FROM [MYDB].[dbo].[MYUSER] u WHERE u.Surname = 'Rossi');
</code>```

A simple rule to follow that makes your code more readable and less prone to error.

Title: Bizarre behavior of a query

Body:
I found this query from a developer:

DELETE FROM [MYDB].[dbo].[MYSIGN] where USERID in
(select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi');

This query deletes every record in table MYSIGN.

The field USERID does not exists in table MYUSER. If I run only the subquery:

select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi'

It throws the right error, because the missing column.

We corrected the query using the right column, but we didn't figure out:

Why the first query works?

Why it deletes every record?

Specs: database is on a SQL SERVER 2016 SP1, CU3.

Body:
The problem is the scoping rules of subqueries.  If the column is not found in the subquery tables, then the SQL engine starts looking at the next level out -- and so on (in the case of SQL Server).

Whenever you have multiple tables in a query, always qualify the column names.  This means, put the table name (or alias) with the column alias.  Then you have no ambiguity:

DELETE
    FROM [MYDB].[dbo].[MYSIGN] m
    WHERE m.USERID IN (SELECT u.USERID FROM [MYDB].[dbo].[MYUSER] u WHERE u.Surname = 'Rossi');

A simple rule to follow that makes your code more readable and less prone to error.


问:
Sort ng-repeat tags by custom list?
My ng-repeat show big data , and after groupBy it divides in 5 divs

```<code><div ng-repeat=" (key, value) in gamesList | groupBy: 'id' ">...</div>
</code>```

ID value is

```<code>{ '1' , '2' , '3' , '4' , '5' }
</code>```

and in result it orders from min to max .

How can I order it with my custom rule, like this:

```<code>{'5' , '2' , '4' , '1' , '3' }
</code>```

答:
You Can sort your data using sort() function instead of using filter.
You have to define your rule like this :

```<code>var myRule = {'5':1,'2':2,'4':3,'1':4,'3':5}
</code>```

And then you have to apply your custom rule over your data.

```<code>scope.gameList=scope.gameList.sort(function(a,b){
  return myRule[a.id]>myRule[b.id];
});
</code>```

You can do this by using custom filter as follows :

```<code>myApp.filter('myFilter', function() {
 return function(input) {
   var output;
   var myRule = {'5':1,'2':2,'4':3,'1':4,'3':5};

   output = input.sort(function(a, b) {
    return myRule[a.id]>myRule[b.id];
   });

   return output;
  }
});
</code>```

And You can apply your custom filter like this :

```<code><div ng-repeat="d in data | myFilter">
</code>```

Here is an example on plunker.
Hope this would help you!

Title: Sort ng-repeat tags by custom list?

Body:
My ng-repeat show big data , and after groupBy it divides in 5 divs

...

ID value is

{ '1' , '2' , '3' , '4' , '5' }

and in result it orders from min to max .

How can I order it with my custom rule, like this:

{'5' , '2' , '4' , '1' , '3' }

Body:
You Can sort your data using sort() function instead of using filter.
You have to define your rule like this :

var myRule = {'5':1,'2':2,'4':3,'1':4,'3':5}

And then you have to apply your custom rule over your data.

scope.gameList=scope.gameList.sort(function(a,b){
  return myRule[a.id]>myRule[b.id];
});

You can do this by using custom filter as follows :

myApp.filter('myFilter', function() {
 return function(input) {
   var output;
   var myRule = {'5':1,'2':2,'4':3,'1':4,'3':5};

   output = input.sort(function(a, b) {
    return myRule[a.id]>myRule[b.id];
   });

   return output;
  }
});

And You can apply your custom filter like this :

<div ng-repeat="d in data | myFilter">

Here is an example on plunker.
Hope this would help you!


问:
Binary Tree with negative values
I was solving a data structure problem and I came across a Binary Tree problem:

Find the maximum node in a binary tree, return the node.
Given the following BST

```<code>    1
   /   \
 -5     2
 / \   /  \
0   3 -4  -5
</code>```

I thought that in a Binary Tree, every node's key is greater than all keys in its left sub-tree, and less than all keys in its right sub-tree.

Can a Binary Tree be unsorted ?

答:
A binary search tree is supposed to be sorted and ordered.

But a binary tree can be unsorted like the one you have shown. Binary search tree is a type of binary tree which happened to be sorted.

Title: Binary Tree with negative values

Body:
I was solving a data structure problem and I came across a Binary Tree problem:

Find the maximum node in a binary tree, return the node.
Given the following BST

    1
   /   \
 -5     2
 / \   /  \
0   3 -4  -5

I thought that in a Binary Tree, every node's key is greater than all keys in its left sub-tree, and less than all keys in its right sub-tree.

Can a Binary Tree be unsorted ?


问:
How to create middlawere for mongoose queries
I have the legacy backend. This backend use mongoose. There is collection "Users". This collection has "email" field.

I was faced with the bug - email is case sensitive. I want to save all new emails in lower case. For this I've modified "Users" schema with this:

```<code>email: {
    type: String,
    lowercase: true
}
</code>```

But also backend has a lot of places with things like:

```<code>user.find({email: some_case_unnormalized_email})
</code>```

or this:

```<code>user.findOne({email: some_case_unnormalized_email})
</code>```

I don't want to modify that places to:

```<code>user.find({email: some_case_unnormalized_email.toLowerCase()})
</code>```

Instead, I want to create some middleware for "Users" schema like:

```<code>UsersSchema.middleware('any_query', queryObject => {
    if (queryObject.email) {
        queryObject.email = queryObject.email.toLowerCase();
    }
});
</code>```

How to do that?

答:
Use pre save hook to modify any property

```<code>UserSchema.pre('find', function(next){
    var query = this;
    // console.log(JSON.stringify(query, null, 2));
    // update your query here
    next();
})

UserSchema.pre('findOne', function(next){
    var query = this;
    // console.log(JSON.stringify(query, null, 2));
    // update your query here
    next();
})
</code>```

Body:
I have the legacy backend. This backend use mongoose. There is collection "Users". This collection has "email" field.

I was faced with the bug - email is case sensitive. I want to save all new emails in lower case. For this I've modified "Users" schema with this:

email: {
    type: String,
    lowercase: true
}

But also backend has a lot of places with things like:

user.find({email: some_case_unnormalized_email})

or this:

user.findOne({email: some_case_unnormalized_email})

I don't want to modify that places to:

user.find({email: some_case_unnormalized_email.toLowerCase()})

Instead, I want to create some middleware for "Users" schema like:

UsersSchema.middleware('any_query', queryObject => {
    if (queryObject.email) {
        queryObject.email = queryObject.email.toLowerCase();
    }
});

How to do that?

Body:
Use pre save hook to modify any property

UserSchema.pre('find', function(next){
    var query = this;
    // console.log(JSON.stringify(query, null, 2));
    // update your query here
    next();
})

UserSchema.pre('findOne', function(next){
    var query = this;
    // console.log(JSON.stringify(query, null, 2));
    // update your query here
    next();
})


问:
Updating multiple entries in a unique column at once with "pure" Hibernate/JPA
I have a table that stores tasks, and a table that stores ordered steps for that task. Steps belong to a task parent (so a task has a one-to-many relationship with a step) and each step has an "ordinal" - which step number it is. I would like the ordinal and the parent task ID to be a combined unique constraint, so for example a single Task can't ever wind up with two different steps set as "step 1", but different tasks can each have their own "step 1".

I would like to be able to update the ordinal of every step belonging to a task at the same time, so that I don't violate the unique constraint. So if I had "Step 1," "Step 2" and "Step 3" I could insert a new step at "Step 2" and shift the existing steps along to become "Step 3" and "Step 4." I'm aware that certain databases allow you to delay checking the constraints until the transaction is committed, but I would highly prefer if I could avoid anything that would require a certain database type, and do this wholly within JPA/Hibernate.

Here's a simplified version of my entities:

Task:

```<code>@Table
@Entity
public class Task {

    @Version
    private Long version;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Step> steps;
}
</code>```

Step:

```<code>@Entity
@Table(
    uniqueConstraints = {
        @UniqueConstraint(
            name = "UX_Step_Parent_Ordinal",
            columnNames = {"parent_id", "ordinal"})
    }
)
public class Step {

    @Version
    private Long version;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, name = "ordinal")
    private Long ordinal;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "parent_id")
    private Task parent;
}
</code>```

So far the only way I've come up with is to first insert the new step at the end, and then dynamically generate an HQL query that looks like the following, which updates every single step in a particular task at once using a CASE:

```<code>UPDATE Step s
SET s.ordinal = CASE
 WHEN (s.id = 55) THEN 1
 WHEN (s.id = 58) THEN 2
 WHEN (s.id = 47) THEN 3
 WHEN (s.id = 33) THEN 4
 ... etc
 ELSE 0 END
WHERE s.parent.id = 5
</code>```

However I'm pretty sure this requires the engine to process the query anew every single time it happens and therefore can't take advantage of things like query caching or other speedups. Is there another way to do this with Hibernate/JPA?

答:
not sure if it really solves the problem, but I think you should model the collection as a map:

```<code>@OneToMany
@MapKeyJoinColumn(Name="ordinal")
private Map<Long,Step> steps;
</code>```

when you add a Step somewhere in between, it's your duty to update the entire Map.

If you still need the ordinal in the step, then you must make it readOnly:

```<code>@Column(nullable = false, name = "ordinal", insertable=false, updateable=false)
private Long ordinal;
</code>```

Body:
I have a table that stores tasks, and a table that stores ordered steps for that task. Steps belong to a task parent (so a task has a one-to-many relationship with a step) and each step has an "ordinal" - which step number it is. I would like the ordinal and the parent task ID to be a combined unique constraint, so for example a single Task can't ever wind up with two different steps set as "step 1", but different tasks can each have their own "step 1".

I would like to be able to update the ordinal of every step belonging to a task at the same time, so that I don't violate the unique constraint. So if I had "Step 1," "Step 2" and "Step 3" I could insert a new step at "Step 2" and shift the existing steps along to become "Step 3" and "Step 4." I'm aware that certain databases allow you to delay checking the constraints until the transaction is committed, but I would highly prefer if I could avoid anything that would require a certain database type, and do this wholly within JPA/Hibernate.

Here's a simplified version of my entities:

Task:

@Table
@Entity
public class Task {

    @Version
    private Long version;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Step> steps;
}

Step:

@Entity
@Table(
    uniqueConstraints = {
        @UniqueConstraint(
            name = "UX_Step_Parent_Ordinal",
            columnNames = {"parent_id", "ordinal"})
    }
)
public class Step {

    @Version
    private Long version;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, name = "ordinal")
    private Long ordinal;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "parent_id")
    private Task parent;
}

So far the only way I've come up with is to first insert the new step at the end, and then dynamically generate an HQL query that looks like the following, which updates every single step in a particular task at once using a CASE:

UPDATE Step s
SET s.ordinal = CASE
 WHEN (s.id = 55) THEN 1
 WHEN (s.id = 58) THEN 2
 WHEN (s.id = 47) THEN 3
 WHEN (s.id = 33) THEN 4
 ... etc
 ELSE 0 END
WHERE s.parent.id = 5

However I'm pretty sure this requires the engine to process the query anew every single time it happens and therefore can't take advantage of things like query caching or other speedups. Is there another way to do this with Hibernate/JPA?

Body:
not sure if it really solves the problem, but I think you should model the collection as a map:

@OneToMany
@MapKeyJoinColumn(Name="ordinal")
private Map<Long,Step> steps;

when you add a Step somewhere in between, it's your duty to update the entire Map.

If you still need the ordinal in the step, then you must make it readOnly:

@Column(nullable = false, name = "ordinal", insertable=false, updateable=false)
private Long ordinal;


问:
AngularJS - Switch between Templates
Currently, I have my directives being switched out in this fashion.

In my directive:

```<code>(function(){
    'use strict';
    var controller = ['$scope', function ($scope) {

      }];

    angular
        .module('moduleName', ['myDependency'])
        .directive('dirName', function($compile, $window){
            return{
                restrict: 'E',
                replace: true,
                require: [ '^?myDependency'],
                scope: false,
                controller: controller ,
                template:
                `<div ng-switch="templateConfig.type">
                   <div ng-switch-when='con1'>
                     <p> Config 1 </p>
                   </div>
                   <div ng-switch-when='con2'>
                     <p> Config 2 </p>
                   </div>
                   <div ng-switch-when='con3'>
                     <p> Config 3 </p>
                   </div>
                 </div>`
</code>```

And in the PHP file, I have the following:

```<code>function pageController($scope, $http, $filter, $cleo, $timeout, $compile) {
    $scope.templateConfig= {type: 'Con2'};
}
        <div class="row-fluid">
            <div class="span1" id="title" > name </div>
            <div class="span11">
                <dirName>
                </dirName>
                <br/>
            </div>
        </div>
        <div class="row-fluid">
            <div class="span1" id="title" > name2 </div>
            <div class="span11">
                <dirName>
                </dirName>
                <br/>
            </div>
        </div>
</code>```

So how it works is that when I can switch between templates using  {type: 'Con2'}. However, this will affect both <dirName></dirName> tags. What I want is for me to have the ability to define them independently of each other.

What I want would be something like <dirName templateConfig=Con1></dirName>. I not entirely sure how to achieve this though but I don't think it should be too difficult to make the switch.

Also, I did leave out a lot of code from the PHP file and changed the original names in the code but none of that should be relevant.

答:
Use the function form of the template property:

```<code>app.directive('dirName', function($compile, $window){
    return{
        restrict: 'E',
        template: function (elem, attrs) {
            switch(attrs.templateConfig) {
                case 'con1':
                  return `<p> Config 1 </p>`;
                case 'con2':
                  return `<p> Config 2 </p>`;
                case 'con3':
                  return `<p> Config 3 </p>`;
             };
         }
     };
})
</code>```

Example usage:

```<code><dir-name template-config="con2">
</dir-name>
</code>```

Update

From the Docs:

template

Value may be:

A function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value.

— AngularJS Comprehensive Directive API Reference - template

Title: AngularJS - Switch between Templates

Body:
Currently, I have my directives being switched out in this fashion.

In my directive:

(function(){
    'use strict';
    var controller = ['$scope', function ($scope) {

      }];

    angular
        .module('moduleName', ['myDependency'])
        .directive('dirName', function($compile, $window){
            return{
                restrict: 'E',
                replace: true,
                require: [ '^?myDependency'],
                scope: false,
                controller: controller ,
                template:
                `

 Config 1

 Config 2

 Config 3

`

And in the PHP file, I have the following:

function pageController($scope, $http, $filter, $cleo, $timeout, $compile) {
    $scope.templateConfig= {type: 'Con2'};
}

 name

                <dirName>
                </dirName>

 name2

                <dirName>
                </dirName>

So how it works is that when I can switch between templates using  {type: 'Con2'}. However, this will affect both <dirName></dirName> tags. What I want is for me to have the ability to define them independently of each other.

What I want would be something like <dirName templateConfig=Con1></dirName>. I not entirely sure how to achieve this though but I don't think it should be too difficult to make the switch.

Also, I did leave out a lot of code from the PHP file and changed the original names in the code but none of that should be relevant.

Body:
Use the function form of the template property:

app.directive('dirName', function($compile, $window){
    return{
        restrict: 'E',
        template: function (elem, attrs) {
            switch(attrs.templateConfig) {
                case 'con1':
                  return `<p> Config 1 </p>`;
                case 'con2':
                  return `<p> Config 2 </p>`;
                case 'con3':
                  return `<p> Config 3 </p>`;
             };
         }
     };
})

Example usage:

<dir-name template-config="con2">
</dir-name>

Update

From the Docs:

template

Value may be:

A function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value.

— AngularJS Comprehensive Directive API Reference - template


问:
How to construct a numpy array with its each element be the minimum value of all possible values?
I want to construct a 1d numpy array a, and I know each a[i] has several possible values. Of course, the numbers of the possible values of any two elements of a can be different. For each a[i], I want to set it be the minimum value of all the possible values.

For example, I have two array:

```<code>idx = np.array([0, 1, 0, 2, 3, 3, 3])
val = np.array([0.1, 0.5, 0.2, 0.6, 0.2, 0.1, 0.3])
</code>```

The array I want to construct is following:

```<code>a = np.array([0.1, 0.5, 0.6, 0.1])
</code>```

So does there exist any function in numpy can finish this work?

答:
Here's one approach -

```<code>def groupby_minimum(idx, val):
    sidx = idx.argsort()
    sorted_idx = idx[sidx]
    cut_idx = np.r_[0,np.flatnonzero(sorted_idx[1:] != sorted_idx[:-1])+1]
    return np.minimum.reduceat(val[sidx], cut_idx)
</code>```

Sample run -

```<code>In [36]: idx = np.array([0, 1, 0, 2, 3, 3, 3])
    ...: val = np.array([0.1, 0.5, 0.2, 0.6, 0.2, 0.1, 0.3])
    ...:

In [37]: groupby_minimum(idx, val)
Out[37]: array([ 0.1,  0.5,  0.6,  0.1])
</code>```

Here's another using pandas -

```<code>import pandas as pd

def pandas_groupby_minimum(idx, val):
    df = pd.DataFrame({'ID' : idx, 'val' : val})
    return df.groupby('ID')['val'].min().values
</code>```

Sample run -

```<code>In [66]: pandas_groupby_minimum(idx, val)
Out[66]: array([ 0.1,  0.5,  0.6,  0.1])
</code>```

Body:
I want to construct a 1d numpy array a, and I know each a[i] has several possible values. Of course, the numbers of the possible values of any two elements of a can be different. For each a[i], I want to set it be the minimum value of all the possible values.

For example, I have two array:

idx = np.array([0, 1, 0, 2, 3, 3, 3])
val = np.array([0.1, 0.5, 0.2, 0.6, 0.2, 0.1, 0.3])

The array I want to construct is following:

a = np.array([0.1, 0.5, 0.6, 0.1])

So does there exist any function in numpy can finish this work?

Body:
Here's one approach -

def groupby_minimum(idx, val):
    sidx = idx.argsort()
    sorted_idx = idx[sidx]
    cut_idx = np.r_[0,np.flatnonzero(sorted_idx[1:] != sorted_idx[:-1])+1]
    return np.minimum.reduceat(val[sidx], cut_idx)

Sample run -

In [36]: idx = np.array([0, 1, 0, 2, 3, 3, 3])
    ...: val = np.array([0.1, 0.5, 0.2, 0.6, 0.2, 0.1, 0.3])
    ...:

In [37]: groupby_minimum(idx, val)
Out[37]: array([ 0.1,  0.5,  0.6,  0.1])

Here's another using pandas -

import pandas as pd

def pandas_groupby_minimum(idx, val):
    df = pd.DataFrame({'ID' : idx, 'val' : val})
    return df.groupby('ID')['val'].min().values

Sample run -

In [66]: pandas_groupby_minimum(idx, val)
Out[66]: array([ 0.1,  0.5,  0.6,  0.1])


问:
C#: Properties that may require a network call?
I know that in C#, properties are supposed to be quick operations (not reading data from a network or file system, etc.) However, I am building a Silverlight app and I need to bind a XAML element to some network data on a ViewModel. As far as I am aware, binding can only be done to properties, not methods. Should I break the guideline here, or is there another way around this that's not occurring to me?</p>

```<code><ListBox ItemsSource="{Binding Users}" />

public IEnumerable<User> Users
{
    get
    {
        // may be cached
        return expensiveNetworkCall();
    }
}
</code>```

答: Actually, although I haven't used it yet, you can bind to methods with the ObjectDataProvider. See here: http://www.thomasclaudiushuber.com/blog/2008/01/10/bind-to-methods-with-objectdataprovider/

Body:
I know that in C#, properties are supposed to be quick operations (not reading data from a network or file system, etc.) However, I am building a Silverlight app and I need to bind a XAML element to some network data on a ViewModel. As far as I am aware, binding can only be done to properties, not methods. Should I break the guideline here, or is there another way around this that's not occurring to me?

<ListBox ItemsSource="{Binding Users}" />

public IEnumerable<User> Users
{
    get
    {
        // may be cached
        return expensiveNetworkCall();
    }
}


问:
Divide a float in any of the st registers by an integer constant in assembly
I need to divide a float in let's say st0 by an integer (in this example 2):
So know that i can achieve this by simply:

```<code>mov rax, 2
fild rax
fdivp st1
</code>```

but is there a more elegant and less bulky version like (and I know the following doesn't work):

```<code>fidiv 2
</code>```

:S please let me know too if it's impossible :) thanks in advance

答:
None of the x87 instructions support immediate values. What you need to do is store the constant you want to divide by in some memory location and then load it implicitly using a memory operand:

```<code>    fdiv DWORD PTR two      ; st0 = st0 / 2
    ...

two REAL4 2.0
</code>```

Note that division by constants can be sped up massively by multiplying with the reciprocal instead:

```<code>    fmul DWORD PTR two     ; st0 = st0 * 0.5 = st0 / 2
    ...

two REAL4 0.5
</code>```

Body:
I need to divide a float in let's say st0 by an integer (in this example 2):
So know that i can achieve this by simply:

mov rax, 2
fild rax
fdivp st1

but is there a more elegant and less bulky version like (and I know the following doesn't work):

fidiv 2

:S please let me know too if it's impossible :) thanks in advance

Body:
None of the x87 instructions support immediate values. What you need to do is store the constant you want to divide by in some memory location and then load it implicitly using a memory operand:

    fdiv DWORD PTR two      ; st0 = st0 / 2
    ...

two REAL4 2.0

Note that division by constants can be sped up massively by multiplying with the reciprocal instead:

    fmul DWORD PTR two     ; st0 = st0 * 0.5 = st0 / 2
    ...

two REAL4 0.5


问:
use addEventListener to replace each onClick
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

```<code><ul>
   <li><button class="bb" value="apple" onClick="aJax(value)">Apple</button></li>
   <li>Banana
      <ul>
         <li><button class="bb" value="green_banana" onClick="aJax(value)">Green_banana</button></li>
         <li><button class="bb" value="yellow_banana" onClick="aJax(value)">Yellow Banana</button></li>
      </ul>
   </li>
   <li><button class="bb" value="cherry" onClick="aJax(value)">Cherry</button></li>
   <li><button class="bb" value="cow..................and more....
</ul>
</code>```

If clicked, I want to pass value to Ajax to return data from mySql:

```<code>  <script>
  function aJax(value)
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET","some_page.php?q="+value,true);
      xmlhttp.send();
      xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       document.getElementById("some_id").innerHTML = xmlhttp.responseText;}
                                                }
                 }
  </script>
</code>```

Is it possible to use addEventListener in my case above to replace each onClick? How to do it if I want to put the JS code on the header? Pls help, I need it in native JS. Thanks.

答:
try that :</p>

```<code>window.addEventListener( 'load' , function () {

    var list = document.querySelectorAll( 'ul > li > button' );

    for ( var i = 0 , l = list.length ; i < l ; i++ ) {

        list[ i ].addEventListener( 'click' , function () {
            aJax( this.value );
        } );

    }

} );
</code>```

Body:
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

<button class="bb" value="apple" onClick="aJax(value)">Apple</button>

Banana

<button class="bb" value="green_banana" onClick="aJax(value)">Green_banana</button>

<button class="bb" value="yellow_banana" onClick="aJax(value)">Yellow Banana</button>

<button class="bb" value="cherry" onClick="aJax(value)">Cherry</button>

<button class="bb" value="cow..................and more....

If clicked, I want to pass value to Ajax to return data from mySql:

Is it possible to use addEventListener in my case above to replace each onClick? How to do it if I want to put the JS code on the header? Pls help, I need it in native JS. Thanks.

Body:
try that :

window.addEventListener( 'load' , function () {

    var list = document.querySelectorAll( 'ul > li > button' );

    for ( var i = 0 , l = list.length ; i < l ; i++ ) {

        list[ i ].addEventListener( 'click' , function () {
            aJax( this.value );
        } );

    }

} );


问:
Use of sizeof operator in C
I wrote a code to print size of different data types in C .

```<code>#include<stdio.h>
int main()
{
     printf("%d", sizeof(int));//size of integer
     printf("%d", sizeof(float));
     printf("%d", sizeof(double));
     printf("%d", sizeof(char));
}
</code>```

This does not work , but if I replace %d with %ld, it works. I did not understand why I have to take long int to print a small range number.

答:
I did not understand why I have to take long int to print a small range number.

Because size_t may represent values much larger than what an int can support; on my particular implementation, the max size value is 18446744073709551615, which definitely won't fit in an int.

Remember that the operand of sizeof may be a parenthesized type name or an object expression:

```<code>static long double really_big_array[100000000];
...
printf( "sizeof really_big_array = %zu\n", sizeof really_big_array );
</code>```

size_t must be able to represent the size of the largest object the implementation allows.

Title: Use of sizeof operator in C

Body:
I wrote a code to print size of different data types in C .

#include<stdio.h>
int main()
{
     printf("%d", sizeof(int));//size of integer
     printf("%d", sizeof(float));
     printf("%d", sizeof(double));
     printf("%d", sizeof(char));
}

This does not work , but if I replace %d with %ld, it works. I did not understand why I have to take long int to print a small range number.

Body:
I did not understand why I have to take long int to print a small range number.

Because size_t may represent values much larger than what an int can support; on my particular implementation, the max size value is 18446744073709551615, which definitely won't fit in an int.

Remember that the operand of sizeof may be a parenthesized type name or an object expression:

static long double really_big_array[100000000];
...
printf( "sizeof really_big_array = %zu\n", sizeof really_big_array );

size_t must be able to represent the size of the largest object the implementation allows.


答:
I thought that in a Binary Tree, every node's key is greater than all
  keys in its left sub-tree, and less than all keys in its right
  sub-tree.

That's property of Binary Search Tree.

Binary tree can be unsorted, but it isn't suitable for lookup (it doesn't have log(n) complexity).

Title: Binary Tree with negative values


答:
Yes, you can do it :

var bbs = document.getElementsByClassName("bb");
for(var i =0; i< bbs.length; i++){
  bbs[i].addEventListener('click', function(){
    var attr = this.value;
    console.log(attr);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
   <li><button class="bb" value="apple" >Apple</button></li>
   <li><button class="bb" value="banana">Banana</button></li>
   <li><button class="bb" value="cherry">Cherry</button></li>
</ul></code>```

Instead of console.log(attr); you can call your custom function

Title: use addEventListener to replace each onClick

Body:
Yes, you can do it :

var bbs = document.getElementsByClassName("bb");
for(var i =0; i< bbs.length; i++){
  bbs[i].addEventListener('click', function(){
    var attr = this.value;
    console.log(attr);
  });
}

<ul>
   <li><button class="bb" value="apple" >Apple</button></li>
   <li><button class="bb" value="banana">Banana</button></li>
   <li><button class="bb" value="cherry">Cherry</button></li>
</ul>

Instead of console.log(attr); you can call your custom function


问:
Does an additional "AND `columnname` LIKE '%'" hurt performance?

simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

```<code>AND `name` LIKE '%'
</code>```

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?

答:
LIKE can definately hurt performance.  The most important thing to check is that you have the proper indexes.  What indexes do you have on the tables being queried?

I suspect that since your LIKE isn't actually doing anything it would just be optimized out but you will need to test to confirm this.

Body:
simple question: Does adding something like this to a query hurt performance in mysql or does it quickly get optimized away?

AND `name` LIKE '%'

I've got no big database here that I could test it on.

By the way, I want this because I want users to be able to send some parameters to my server-side script that then grabs the prepared statement specified by the user and inserts the parameters. I want users to be able to omit parameters when searching without hurting the performance, and LIKE normally is relatively slow, right?


问:
Update text box value only on button click
I How can I display the text box value only on the click of a button? Below in the code snippet..

HTML:

```<code><input type="text" [(ngModel)]="serverName">
<button class="btn btn-primary" (click)="onAddClk">Add</button>
</code>```

TS File:

```<code>onAddClk(){

}
</code>```

How do I access my ngModel from TS file, so that on button click i can see the content of my text box?

答:
As simple as that. If its a component property then you have to access it using this operator.

```<code>onAddClk() {
    console.log(this.serverName);
}
</code>```

By the way Welcome to Angular2!!

 https://angular.io/tutorial

Body:
I How can I display the text box value only on the click of a button? Below in the code snippet..

HTML:

<input type="text" [(ngModel)]="serverName">
<button class="btn btn-primary" (click)="onAddClk">Add</button>

TS File:

onAddClk(){

}

How do I access my ngModel from TS file, so that on button click i can see the content of my text box?

Body:
As simple as that. If its a component property then you have to access it using this operator.

onAddClk() {
    console.log(this.serverName);
}

By the way Welcome to Angular2!!

 https://angular.io/tutorial


问:
Two return statements for one method? Python
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

```<code>count = 80
a = 20
if a > count:
    return xyz
else:
    return abc
</code>```

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

```<code>            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }
</code>```

答:
I saw your last commend so this is how you should compare dates.

Odoo dates are not comparable until you convert them to datetime objects, so to convert odoo date to datetime object use:

```<code>a = datetime.strptime(self.date_field1, "%Y-%m-%d")
b = datetime.strptime(self.date_field1, "%Y-%m-%d")
# where date_field1 and date_field2 are something like this 2017-01-01
# now you can compare a and b
if a < b:
    drink beer
else:
    drink more beer
</code>```

Body:
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

count = 80
a = 20
if a > count:
    return xyz
else:
    return abc

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }

Body:
I saw your last commend so this is how you should compare dates.

Odoo dates are not comparable until you convert them to datetime objects, so to convert odoo date to datetime object use:

a = datetime.strptime(self.date_field1, "%Y-%m-%d")
b = datetime.strptime(self.date_field1, "%Y-%m-%d")
# where date_field1 and date_field2 are something like this 2017-01-01
# now you can compare a and b
if a < b:
    drink beer
else:
    drink more beer


问:
RandomForest incorrect cutoff specified
I am trying to change the default cutoff of randomForest in R. I'm using the form cutoff=c(0.7,0.3) and get an "Incorrect cutoff specified" error for any value used. What is the proper way to change the cutoff?</p>

答:
If it's R RandomForest I know the correct format i this:

```<code>cutoff=c(k,1-k)
cutoff=c(0.7,0.3)
</code>```

EDIT

The cutoff vector should have length equal to the number of classes. SO if you have 3 classes you must have

```<code>cutoff=c(a,b,c)
</code>```

where a+b+c=1

Title: RandomForest incorrect cutoff specified

Body:
If it's R RandomForest I know the correct format i this:

cutoff=c(k,1-k)
cutoff=c(0.7,0.3)

EDIT

The cutoff vector should have length equal to the number of classes. SO if you have 3 classes you must have

cutoff=c(a,b,c)

where a+b+c=1


问:
unsupported operand type(s) for /: ‘map’ and 'int’
```<code>##models.py
    from django.db import models
    from django.contrib.auth.models import User
    import numpy as np

    class Wine(models.Model):
        name=models.CharField(max_length=200)
        def average_rating(self):
            all_ratings = map(lambda x: x.rating, self.review_set.all())
            return np.mean(all_ratings)
        def __unicode__(self):
            return self.name
</code>```

Why is this error showing?What is wrong at line 7?

答:
Not sure why you want to use numpy for this. You could easily calculate the mean yourself, but why not let the database do it via its aggregation features?</p>

```<code>from django.db.models import Avg
...
def average_rating(self):
    return self.review_set.aggregate(Avg('rating'))['rating__avg']
</code>```

Body:
##models.py
    from django.db import models
    from django.contrib.auth.models import User
    import numpy as np

    class Wine(models.Model):
        name=models.CharField(max_length=200)
        def average_rating(self):
            all_ratings = map(lambda x: x.rating, self.review_set.all())
            return np.mean(all_ratings)
        def __unicode__(self):
            return self.name

Why is this error showing?What is wrong at line 7?

Body:
Not sure why you want to use numpy for this. You could easily calculate the mean yourself, but why not let the database do it via its aggregation features?

from django.db.models import Avg
...
def average_rating(self):
    return self.review_set.aggregate(Avg('rating'))['rating__avg']


问:
Regex exercise in R
I want to parse a string using R, and I'd like to get out a list of objects. Brackets, spaces and commas in the string dictate the structure of the final list:

each pair of brackets is separated by a space and the words in each pair of brackets has to form a new object of the list;

words in brackets are separated by comma and should form different elements in each listed object;

the mentioned structure can also be found nested within a pair of brackets.

Here is an example of the string:

```<code>x <- "(K01596,K01610) (K01689) (K01834,K15633,K15634,K15635) (K00927) (K00134,K00150) (K01803) ((K01623,K01624,K11645) (K03841,K02446,K11532,K01086,K04041),K01622)"
</code>```

The desired output should like this:

```<code>list(c("K01596","K01610"), "K01689", c("K01834","K15633","K15634","K15635"), "K00927", c("K00134","K00150"), "K01803", list(list(c("K01623","K01624","K11645"), c("K03841","K02446","K11532","K01086","K04041")), "K01622"))
</code>```

I manage to solve how to do the parsing for case 1)

```<code>match <- gregexpr("\\((?>[^()]|(?R))*\\)", x, perl = T)
x2 <- as.list(substring(x, match[[1]], match[[1]] + attr(match[[1]], "match.length") - 1))
</code>```

and case 2) is also easy, I can just remove the brackets with gsub and split the words using strsplit.
The problem is how to parse case 3), when I have a nested level like:

```<code>((K01623,K01624,K11645) (K03841,K02446,K11532,K01086,K04041),K01622)
</code>```

and I have to get out a listed object that is a list itself:

```<code>list(list(c("K01623","K01624","K11645"), c("K03841","K02446","K11532","K01086","K04041")), "K01622")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Regex exercise in R

Body:
I want to parse a string using R, and I'd like to get out a list of objects. Brackets, spaces and commas in the string dictate the structure of the final list:

each pair of brackets is separated by a space and the words in each pair of brackets has to form a new object of the list;

words in brackets are separated by comma and should form different elements in each listed object;

the mentioned structure can also be found nested within a pair of brackets.

Here is an example of the string:

x <- "(K01596,K01610) (K01689) (K01834,K15633,K15634,K15635) (K00927) (K00134,K00150) (K01803) ((K01623,K01624,K11645) (K03841,K02446,K11532,K01086,K04041),K01622)"

The desired output should like this:

list(c("K01596","K01610"), "K01689", c("K01834","K15633","K15634","K15635"), "K00927", c("K00134","K00150"), "K01803", list(list(c("K01623","K01624","K11645"), c("K03841","K02446","K11532","K01086","K04041")), "K01622"))

I manage to solve how to do the parsing for case 1)

match <- gregexpr("\\((?>[^()]|(?R))*\\)", x, perl = T)
x2 <- as.list(substring(x, match[[1]], match[[1]] + attr(match[[1]], "match.length") - 1))

and case 2) is also easy, I can just remove the brackets with gsub and split the words using strsplit.
The problem is how to parse case 3), when I have a nested level like:

((K01623,K01624,K11645) (K03841,K02446,K11532,K01086,K04041),K01622)

and I have to get out a listed object that is a list itself:

list(list(c("K01623","K01624","K11645"), c("K03841","K02446","K11532","K01086","K04041")), "K01622")

Body:
You can convert to JSON, and then use jsonlite to convert to a list. Once you have this, you can simplify, collapse, or reorganize your list however you like.

library(jsonlite)
library(stringr)

add_paren <- function(x){
  x <- str_sub(x, end = -2) #remove comma
  paste0("(", x, "), ") #add enclosing paren and return comma
}
x <- str_replace_all(x, "\\(\\(.*\\)\\,", add_paren)

x <- gsub("\\(", "\\[", x)
x <- gsub("\\)", "\\]", x)
x <- gsub("\\] \\[", "\\], \\[", x)

add_quote <- function(x) paste0('"', x, '"')

x <- str_replace_all(x, "K[0-9]*", add_quote)
x <- paste0("[", x, "]")

x2 <- fromJSON(x)

Resulting in:

dput(x2)

list(c("K01596", "K01610"), "K01689", c("K01834", "K15633", "K15634",
"K15635"), "K00927", c("K00134", "K00150"), "K01803", list(list(
    c("K01623", "K01624", "K11645"), c("K03841", "K02446", "K11532",
    "K01086", "K04041")), "K01622"))

str(x2)

List of 7
 $ : chr [1:2] "K01596" "K01610"
 $ : chr "K01689"
 $ : chr [1:4] "K01834" "K15633" "K15634" "K15635"
 $ : chr "K00927"
 $ : chr [1:2] "K00134" "K00150"
 $ : chr "K01803"
 $ :List of 2
  ..$ :List of 2
  .. ..$ : chr [1:3] "K01623" "K01624" "K11645"
  .. ..$ : chr [1:5] "K03841" "K02446" "K11532" "K01086" ...
  ..$ : chr "K01622"


问:
Accessing rapidjson::Document array by index
I have this code:

```<code>Document dataDoc;
dataDoc.SetArray();
Document::AllocatorType &allocator = dataDoc.GetAllocator();

for (size_t i = 0; i < 10; ++i)
{
    ostringstream ss;
    ss << "set_" << i + 1 << "_data";

    Document doc;
    doc.Parse<0>(UserDefault::getInstance()->getStringForKey(ss.str().c_str()).c_str());
    dataDoc.PushBack(doc, allocator);
}
</code>```

There's a rapidjson::Document "dataDoc" and I convert it to an array. Then I fill the array with Document objects that contain JSON objects that are fetched from cocos2d::UserDefault and parsed appropriately.

This is the JSON object that is added to the dataDoc:

```<code>{
  "people": [
    {
      "name": "Peter",
      "phone": "123",
      "address": "Address 456"
    },
    {
      "name": "Helen",
      "phone": "123",
      "address": "Address 456"
    },
    {
      "name": "John",
      "phone": "123",
      "address": "Address 456"
    }
  ]
}
</code>```

Now the dataDoc array contains 10 of these objects.

I know that I can handle one object like this:

```<code>Document doc;
rapidjson::Value &people = doc["people"];
string name = people[0]["name"].GetString();
</code>```

But how can I access, for example, the first object in the dataDoc array by index and get the name value as above?

Edit

Tried also with this code:

```<code>vector<string> jsons;
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");

Document dataDoc;
dataDoc.SetArray();
Document::AllocatorType &allocator = dataDoc.GetAllocator();

for (size_t i = 0; i < 3; ++i)
{
    Document doc;
    doc.Parse<0>(jsons.at(i).c_str());
    dataDoc.PushBack(doc, allocator);
}

auto &people = dataDoc[0]["people"];
</code>```

But it gave me the same error. It points to line 1688 in "document.h" located at ...\cocos2d\external\json\.

答:
First, there seems to be an issue in your code the way you create doc - You need to provide the allocator of dataDoc:

```<code>Document doc(&allocator);
</code>```

Then, rapidjson::Document inherits from rapidjson::Value, so you can simply treat it as a value and use the [] operator:

```<code>auto &people = dataDoc[0]["people"];
</code>```

You can also iterate through the whole document:

```<code>for (auto &doc: dataDoc.getArray()) {
    auto &people = doc["people"];
}
</code>```

Prior to C++11:

```<code>for (Value::ConstValueIterator itr = dataDoc.Begin();
     itr != dataDoc.End(); ++itr) {
    auto &people = (*itr)["people"];
}
</code>```

Body:
I have this code:

Document dataDoc;
dataDoc.SetArray();
Document::AllocatorType &allocator = dataDoc.GetAllocator();

for (size_t i = 0; i < 10; ++i)
{
    ostringstream ss;
    ss << "set_" << i + 1 << "_data";

    Document doc;
    doc.Parse<0>(UserDefault::getInstance()->getStringForKey(ss.str().c_str()).c_str());
    dataDoc.PushBack(doc, allocator);
}

There's a rapidjson::Document "dataDoc" and I convert it to an array. Then I fill the array with Document objects that contain JSON objects that are fetched from cocos2d::UserDefault and parsed appropriately.

This is the JSON object that is added to the dataDoc:

{
  "people": [
    {
      "name": "Peter",
      "phone": "123",
      "address": "Address 456"
    },
    {
      "name": "Helen",
      "phone": "123",
      "address": "Address 456"
    },
    {
      "name": "John",
      "phone": "123",
      "address": "Address 456"
    }
  ]
}

Now the dataDoc array contains 10 of these objects.

I know that I can handle one object like this:

Document doc;
rapidjson::Value &people = doc["people"];
string name = people[0]["name"].GetString();

But how can I access, for example, the first object in the dataDoc array by index and get the name value as above?

Edit

Tried also with this code:

vector<string> jsons;
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");

Document dataDoc;
dataDoc.SetArray();
Document::AllocatorType &allocator = dataDoc.GetAllocator();

for (size_t i = 0; i < 3; ++i)
{
    Document doc;
    doc.Parse<0>(jsons.at(i).c_str());
    dataDoc.PushBack(doc, allocator);
}

auto &people = dataDoc[0]["people"];

But it gave me the same error. It points to line 1688 in "document.h" located at ...\cocos2d\external\json\.

Body:
First, there seems to be an issue in your code the way you create doc - You need to provide the allocator of dataDoc:

Document doc(&allocator);

Then, rapidjson::Document inherits from rapidjson::Value, so you can simply treat it as a value and use the [] operator:

auto &people = dataDoc[0]["people"];

You can also iterate through the whole document:

for (auto &doc: dataDoc.getArray()) {
    auto &people = doc["people"];
}

Prior to C++11:

for (Value::ConstValueIterator itr = dataDoc.Begin();
     itr != dataDoc.End(); ++itr) {
    auto &people = (*itr)["people"];
}


问:
How to convert string to byte arrays?
How can I convert a string to its byte value? I have a string "hello" and I want to change is to something like "/x68...".

Title: How to convert string to byte arrays?

Body:
Perhaps you want this (Python 2):

>>> map(ord,'hello')
[104, 101, 108, 108, 111]

For a Unicode string this would return Unicode code points:

>>> map(ord,u'Hello, 马克')
[72, 101, 108, 108, 111, 44, 32, 39532, 20811]

But encode it to get byte values for the encoding:

>>> map(ord,u'Hello, 马克'.encode('chinese'))
[72, 101, 108, 108, 111, 44, 32, 194, 237, 191, 203]
>>> map(ord,u'Hello, 马克'.encode('utf8'))
[72, 101, 108, 108, 111, 44, 32, 233, 169, 172, 229, 133, 139]


问:
Execution of R program from CMD Windows
I am trying to run R program from Windows command line interface. I have seen earlier posts but it couldn't helped me to pass multiple arguments at a same time. Secondly, what changes i need to do in the programso that it can run from command line. </p>

```<code> Statement on CMD look like this;
      C:\Program Files\R\R-3.3.3\bin\i386> Rscript
      C:\Users\Public\Command_Line.R "2017-07-04 14:13:25", "2017-07-04 15:36:40", "0000-0000-0000-0000","1","0"
</code>```

<p>I have executed it but its giving me an error. </p>

```<code> C:\Program Files\R\R-3.3.3\bin\i386> Rscript C:\Users\Public\Command_Line.R   "2017-07-04 14:13:25", "2017-07-04
  15:36:40", '0000-0000-0000-0000', 1, 0

 Loading required package: methods
 Error in args[1] : object of type 'closure' is not subsettable
 Calls: subset -> subset.data.frame -> eval -> eval
 Execution halted

 Actual program is mentioned below;
 args<-commandArgs(FALSE)
 xsub <- subset(d, d$properties$appuserid ==  args[3]  &
                d$properties$devicedate >= args[1]     &
                d$properties$devicedate <= args[2]     &
                d$properties$location$building == args[4]  &
                d$properties$location$floor == args[5]);
</code>```

答: Commandline arguments are not automatically available as args. You need to assign them e.g. with args <- commandArgs(). In your case you are trying to subset the function args() which of course fails.

Title: Execution of R program from CMD Windows

Body:
I am trying to run R program from Windows command line interface. I have seen earlier posts but it couldn't helped me to pass multiple arguments at a same time. Secondly, what changes i need to do in the programso that it can run from command line.

 Statement on CMD look like this;
      C:\Program Files\R\R-3.3.3\bin\i386> Rscript
      C:\Users\Public\Command_Line.R "2017-07-04 14:13:25", "2017-07-04 15:36:40", "0000-0000-0000-0000","1","0"

I have executed it but its giving me an error.

 C:\Program Files\R\R-3.3.3\bin\i386> Rscript C:\Users\Public\Command_Line.R   "2017-07-04 14:13:25", "2017-07-04
  15:36:40", '0000-0000-0000-0000', 1, 0

 Loading required package: methods
 Error in args[1] : object of type 'closure' is not subsettable
 Calls: subset -> subset.data.frame -> eval -> eval
 Execution halted

 Actual program is mentioned below;
 args<-commandArgs(FALSE)
 xsub <- subset(d, d$properties$appuserid ==  args[3]  &
                d$properties$devicedate >= args[1]     &
                d$properties$devicedate <= args[2]     &
                d$properties$location$building == args[4]  &
                d$properties$location$floor == args[5]);


问:
SSRS - Using multiple data sources
Using 2 DataSources and 2 DataSets in SSRS I am trying to do the following...

List the tasks, with a Boolean variable = true on the project list.

Projects & Tasks are 2 separate DataSources.

Projects are made up of tasks, therefore the tasks DataSource has a Related_Project field.

I would like to show all the tasks that are associated to the projects with that variable - true.

Any help on this? Tried Lookups but to no success.

答:
Obviously, your table is limited to use one dataset.

You can achieve your goal using the LOOKUPSET function. It works similar to LOOKUP but returns an array of ALL matches. You can then output this to a cell. Format the textbox as HTML (in the properties tab) and you can output the data with
 to make a list.

You won't be able to take advantage of groups, sorting and having each value in a cell. If possible, I would recommend writing a query to join your datasets so you can achieve the desired result.

Title: SSRS - Using multiple data sources