问:
GWT Grid is not appearing with uiBinder
I have a 2 by 2 Grid in a project which is initialised using uiBuilder, however, the grid never appears on the page. The title and subheading appear fine. I've been struggling with this for days. Any advice is very much appreciated (this is my first gwt project). Thank you!

There are 3 files: Test.java, TaskSelect.java and TaskSelect.ui.xml

*Test.java***

```<code>package org.client;
    import com.google.gwt.core.client.*;
    import com.google.gwt.user.client.ui.*;

    public class Test extends DeckPanel implements EntryPoint
    {

    public void onModuleLoad()
    {
        Test t = new Test();
    TaskSelect taskselect = new TaskSelect();
    t.add(taskselect);
    t.showWidget(0);
        RootPanel.get().clear();
        RootPanel.get().add(t);
    }
}
</code>```

*TaskSelect.java**

```<code>package org.client;

    import com.google.gwt.user.client.ui.*;
    import com.google.gwt.core.client.GWT;
    import com.google.gwt.uibinder.client.*;

    public class TaskSelect extends Composite {
    interface Binder extends UiBinder<Widget, TaskSelect> { }
    private static final Binder binder = GWT.create(Binder.class);
    @UiField Button buttonA;
    @UiField Button buttonB;
    @UiField Button buttonC;
    @UiField Button buttonD;
    @UiField Grid mygrid;

    public TaskSelect() {
        initWidget(binder.createAndBindUi(this));
    }
}
</code>```

*TaskSelect.ui.xml**

```<code><ui:UiBinder
  xmlns:ui='urn:ui:com.google.gwt.uibinder'
  xmlns:g='urn:import:com.google.gwt.user.client.ui'>

  <ui:style>
    .bigbutton {
    font-size: 24pt;
    width: 300px;
    height: 95px;
    }

    .h1 {
    font-size: 36pt;
    font-weight: bold;
    text-align: center;
    margin: auto;
    }

    .subheading {
    font-size: 24pt;
    text-align: center;
    margin: auto;
    }

    .panel {
    margin: auto;
    }
    </ui:style>
      <g:DockLayoutPanel unit='EM' addStyleNames='{style.panel}'>
    <g:north size='10'>
      <g:VerticalPanel addStyleNames='{style.panel}'>
        <g:Label addStyleNames='{style.h1}'>Title is here</g:Label>
        <g:Label addStyleNames='{style.subheading}'>Sub heading</g:Label>
      </g:VerticalPanel>
    </g:north>
    <g:center size='10'>
      <g:Grid ui:field='mygrid' addStyleNames='{style.panel}' cellSpacing='50'>
        <g:row>
          <g:customCell>
            <g:Button ui:field='buttonA'>Button A</g:Button>
          </g:customCell>
          <g:customCell>
            <g:Button addStyleNames='{style.bigbutton}' text='Button B' ui:field='buttonB' />
          </g:customCell>
        </g:row>
        <g:row>
          <g:customCell>
            <g:Button addStyleNames='{style.bigbutton}' text='Button C' ui:field='buttonC' />
          </g:customCell>
          <g:customCell>
            <g:Button addStyleNames='{style.bigbutton}' text='Button D' ui:field='buttonD' />
          </g:customCell>
        </g:row>
      </g:Grid>
    </g:center>
  </g:DockLayoutPanel>
</ui:UiBinder>
</code>```

答:
The height/width of the grid is set by the DockLayoutPanel as DockLayoutPanel automatically scales to fill the whole area. Check the documentation on the Layout widgets and see if you need DockLayoutPanel or DockPanel.

Anyway adding this to the .panel style should make it work:

```<code>height:100%;
</code>```

Yes, it doesn't sound logical...

-edit-

And use RootLayoutPanel.get() instead of RootPanel.get(). This because you use a LayoutPanel.

ContentLicense: CC BY-SA 2.5

Title: GWT Grid is not appearing with uiBinder

Body:
I have a 2 by 2 Grid in a project which is initialised using uiBuilder, however, the grid never appears on the page. The title and subheading appear fine. I've been struggling with this for days. Any advice is very much appreciated (this is my first gwt project). Thank you!

There are 3 files: Test.java, TaskSelect.java and TaskSelect.ui.xml

*Test.java***

package org.client;
    import com.google.gwt.core.client.*;
    import com.google.gwt.user.client.ui.*;

    public class Test extends DeckPanel implements EntryPoint
    {

    public void onModuleLoad()
    {
        Test t = new Test();
    TaskSelect taskselect = new TaskSelect();
    t.add(taskselect);
    t.showWidget(0);
        RootPanel.get().clear();
        RootPanel.get().add(t);
    }
}

*TaskSelect.java**

package org.client;

    import com.google.gwt.user.client.ui.*;
    import com.google.gwt.core.client.GWT;
    import com.google.gwt.uibinder.client.*;

    public class TaskSelect extends Composite {
    interface Binder extends UiBinder<Widget, TaskSelect> { }
    private static final Binder binder = GWT.create(Binder.class);
    @UiField Button buttonA;
    @UiField Button buttonB;
    @UiField Button buttonC;
    @UiField Button buttonD;
    @UiField Grid mygrid;

    public TaskSelect() {
        initWidget(binder.createAndBindUi(this));
    }
}

*TaskSelect.ui.xml**

<ui:UiBinder
  xmlns:ui='urn:ui:com.google.gwt.uibinder'
  xmlns:g='urn:import:com.google.gwt.user.client.ui'>

  <ui:style>
    .bigbutton {
    font-size: 24pt;
    width: 300px;
    height: 95px;
    }

    .h1 {
    font-size: 36pt;
    font-weight: bold;
    text-align: center;
    margin: auto;
    }

    .subheading {
    font-size: 24pt;
    text-align: center;
    margin: auto;
    }

    .panel {
    margin: auto;
    }
    </ui:style>
      <g:DockLayoutPanel unit='EM' addStyleNames='{style.panel}'>
    <g:north size='10'>
      <g:VerticalPanel addStyleNames='{style.panel}'>
        <g:Label addStyleNames='{style.h1}'>Title is here</g:Label>
        <g:Label addStyleNames='{style.subheading}'>Sub heading</g:Label>
      </g:VerticalPanel>
    </g:north>
    <g:center size='10'>
      <g:Grid ui:field='mygrid' addStyleNames='{style.panel}' cellSpacing='50'>
        <g:row>
          <g:customCell>
            <g:Button ui:field='buttonA'>Button A</g:Button>
          </g:customCell>
          <g:customCell>
            <g:Button addStyleNames='{style.bigbutton}' text='Button B' ui:field='buttonB' />
          </g:customCell>
        </g:row>
        <g:row>
          <g:customCell>
            <g:Button addStyleNames='{style.bigbutton}' text='Button C' ui:field='buttonC' />
          </g:customCell>
          <g:customCell>
            <g:Button addStyleNames='{style.bigbutton}' text='Button D' ui:field='buttonD' />
          </g:customCell>
        </g:row>
      </g:Grid>
    </g:center>
  </g:DockLayoutPanel>
</ui:UiBinder>

Body:
The height/width of the grid is set by the DockLayoutPanel as DockLayoutPanel automatically scales to fill the whole area. Check the documentation on the Layout widgets and see if you need DockLayoutPanel or DockPanel.

Anyway adding this to the .panel style should make it work:

height:100%;

Yes, it doesn't sound logical...

-edit-

And use RootLayoutPanel.get() instead of RootPanel.get(). This because you use a LayoutPanel.


来源: stackexchange

问:
Most efficient way to select point with the most surrounding points
N.B: there's a major edit at the bottom of the question - check it out

Question

Say I have a set of points:

I want to find the point with the most points surrounding it, within radius  (ie a circle) or within  (ie a square) of the point for 2 dimensions. I'll refer to it as the densest point function.

For the diagrams in this question, I'll represent the surrounding region as circles. In the image above, the middle point's surrounding region is shown in green. This middle point has the most surrounding points of all the points within radius  and would be returned by the densest point function.

What I've tried

A viable way to solve this problem would be to use a range searching solution; this answer explains further and that it has " worst-case time". Using this, I could get the number of points surrounding each point and choose the point with largest surrounding point count.

However, if the points were extremely densely packed (in the order of a million), as such:

then each of these million points () would need to have a range search performed. The worst-case time , where  is the number of points returned in the range, is true for the following point tree types:

kd-trees of two dimensions (which are actually slightly worse, at ),

2d-range trees,

Quadtrees, which have a worst-case time of

So, for a group of  points within radius  of all points within the group, it gives complexity of  for each point. This yields over a trillion operations!

Any ideas on a more efficient, precise way of achieving this, so that I could find the point with the most surrounding points for a group of points, and in a reasonable time (preferably  or less)?

EDIT

Turns out that the method above is correct! I just need help implementing it.

(Semi-)Solution

If I use a 2d-range tree:

A range reporting query costs , for  returned points,

For a range tree with fractional cascading (also known as layered range trees) the complexity is ,

For 2 dimensions, that is ,

Furthermore, if I perform a range counting query (i.e., I do not report each point), then it costs .

I'd perform this on every point - yielding the  complexity I desired!

Problem

However, I cannot figure out how to write the code for a counting query for a 2d layered range tree.

I've found a great resource (from page 113 onwards) about range trees, including 2d-range tree psuedocode. But I can't figure out how to introduce fractional cascading, nor how to correctly implement the counting query so that it is of O(log n) complexity.

I've also found two range tree implementations here and here in Java, and one in C++ here, although I'm not sure this uses fractional cascading as it states above the countInRange method that

It returns the number of such points in worst case
      * O(log(n)^d) time. It can also return the points that are in the rectangle in worst case
      * O(log(n)^d + k) time where k is the number of points that lie in the rectangle.

which suggests to me it does not apply fractional cascading.

Refined question

To answer the question above therefore, all I need to know is if there are any libraries with 2d-range trees with fractional cascading that have a range counting query of complexity  so I don't go reinventing any wheels, or can you help me to write/modify the resources above to perform a query of that complexity?

Also not complaining if you can provide me with any other methods to achieve a range counting query of 2d points in  in any other way!

答:
You can speed up whatever algorithm you use by preprocessing your data in O(n) time to estimate the number of neighbouring points.

For a circle of radius R, create a grid whose cells have dimension R in both the x- and y-directions. For each point, determine to which cell it belongs. For a given cell c this test is easy:

```<code>c.x<=p.x && p.x<=c.x+R && c.y<=p.y && p.y<=c.y+R
</code>```

(You may want to think deeply about whether a closed or half-open interval is correct.)

If you have relatively dense/homogeneous coverage, then you can use an array to store the values. If coverage is sparse/heterogeneous, you may wish to use a hashmap.

Now, consider a point on the grid. The extremal locations of a point within a cell are as indicated:

Points at the corners of the cell can only be neighbours with points in four cells. Points along an edge can be neighbours with points in six cells. Points not on an edge are neighbours with points in 7-9 cells. Since it's rare for a point to fall exactly on a corner or edge, we assume that any point in the focal cell is neighbours with the points in all 8 surrounding cells.

So, if a point p is in a cell (x,y), N[p] identifies the number of neighbours of p within radius R, and Np[y][x] denotes the number of points in cell (x,y), then N[p] is given by:

```<code>N[p] = Np[y][x]+
       Np[y][x-1]+
       Np[y-1][x-1]+
       Np[y-1][x]+
       Np[y-1][x+1]+
       Np[y][x+1]+
       Np[y+1][x+1]+
       Np[y+1][x]+
       Np[y+1][x-1]
</code>```

Once we have the number of neighbours estimated for each point, we can heapify that data structure into a maxheap in O(n) time (with, e.g. make_heap). The structure is now a priority-queue and we can pull points off in O(log n) time per query ordered by their estimated number of neighbours.

Do this for the first point and use a O(log n + k) circle search (or some more clever algorithm) to determine the actual number of neighbours the point has. Make a note of this point in a variable best_found and update its N[p] value.

Peek at the top of the heap. If the estimated number of neighbours is less than N[best_found] then we are done. Otherwise, repeat the above operation.

To improve estimates you could use a finer grid, like so:

along with some clever sliding window techniques to reduce the amount of processing required (see, for instance, this answer for rectangular cases - for circular windows you should probably use a collection of FIFO queues). To increase security you can randomize the origin of the grid.

Considering again the example you posed:

It's clear that this heuristic has the potential to save considerable time: with the above grid, only a single expensive check would need to be performed in order to prove that the middle point has the most neighbours. Again, a higher-resolution grid will improve the estimates and decrease the number of expensive checks which need to be made.

You could, and should, use a similar bounding technique in conjunction with mcdowella's answers; however, his answer does not provide a good place to start looking, so it is possible to spend a lot of time exploring low-value points.

ContentLicense: CC BY-SA 3.0

Body:
You can speed up whatever algorithm you use by preprocessing your data in O(n) time to estimate the number of neighbouring points.

For a circle of radius R, create a grid whose cells have dimension R in both the x- and y-directions. For each point, determine to which cell it belongs. For a given cell c this test is easy:

c.x<=p.x && p.x<=c.x+R && c.y<=p.y && p.y<=c.y+R

(You may want to think deeply about whether a closed or half-open interval is correct.)

If you have relatively dense/homogeneous coverage, then you can use an array to store the values. If coverage is sparse/heterogeneous, you may wish to use a hashmap.

Now, consider a point on the grid. The extremal locations of a point within a cell are as indicated:

Points at the corners of the cell can only be neighbours with points in four cells. Points along an edge can be neighbours with points in six cells. Points not on an edge are neighbours with points in 7-9 cells. Since it's rare for a point to fall exactly on a corner or edge, we assume that any point in the focal cell is neighbours with the points in all 8 surrounding cells.

So, if a point p is in a cell (x,y), N[p] identifies the number of neighbours of p within radius R, and Np[y][x] denotes the number of points in cell (x,y), then N[p] is given by:

N[p] = Np[y][x]+
       Np[y][x-1]+
       Np[y-1][x-1]+
       Np[y-1][x]+
       Np[y-1][x+1]+
       Np[y][x+1]+
       Np[y+1][x+1]+
       Np[y+1][x]+
       Np[y+1][x-1]

Once we have the number of neighbours estimated for each point, we can heapify that data structure into a maxheap in O(n) time (with, e.g. make_heap). The structure is now a priority-queue and we can pull points off in O(log n) time per query ordered by their estimated number of neighbours.

Do this for the first point and use a O(log n + k) circle search (or some more clever algorithm) to determine the actual number of neighbours the point has. Make a note of this point in a variable best_found and update its N[p] value.

Peek at the top of the heap. If the estimated number of neighbours is less than N[best_found] then we are done. Otherwise, repeat the above operation.

To improve estimates you could use a finer grid, like so:

along with some clever sliding window techniques to reduce the amount of processing required (see, for instance, this answer for rectangular cases - for circular windows you should probably use a collection of FIFO queues). To increase security you can randomize the origin of the grid.

Considering again the example you posed:

It's clear that this heuristic has the potential to save considerable time: with the above grid, only a single expensive check would need to be performed in order to prove that the middle point has the most neighbours. Again, a higher-resolution grid will improve the estimates and decrease the number of expensive checks which need to be made.

You could, and should, use a similar bounding technique in conjunction with mcdowella's answers; however, his answer does not provide a good place to start looking, so it is possible to spend a lot of time exploring low-value points.


问:
appending many variables to MySQL with python
```<code>insert_basic = '""' + '"INSERT INTO info VALUES (' + "'" + testid + "','" + username + "','" + fullname + "','" + firstnumber + "','" + secondnumber + "','" + floatnumber + "','" + posts + "','" + country + '","' + bio + '","' + link + '");'
cur.execute(insert_basic)
try:
    db.commit()
except:
    db.rollback()
cur.execute("""SELECT * FROM basic;""")
print cur.fetchall()
</code>```

<p>Hello, I have done a lot of research and I cannot seem to get the syntax right for submitting to SQL. Some of the variables are integers and some are strings with one being a float. </p>

答:
This is what parameterized queries are for:

```<code>parameters = (testid, username, fullname, firstnumber, secondnumber, floatnumber, posts, country, bio, link)
query = """
    INSERT INTO
        info
    VALUES
        (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cur.execute(query, parameters)
</code>```

When you do it this way, you are letting your MySQL database driver to handle the type conversions between Python and MySQL automatically.

And, you are also protecting yourself from SQL injection attacks that would be easy to apply to your initial code where you string concatenate your query.

I would also specify the table column names in this case explicitly:

```<code>INSERT INTO
    info
    (column_name1, column_name2, ...)
VALUES
    (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
</code>```

Body:
insert_basic = '""' + '"INSERT INTO info VALUES (' + "'" + testid + "','" + username + "','" + fullname + "','" + firstnumber + "','" + secondnumber + "','" + floatnumber + "','" + posts + "','" + country + '","' + bio + '","' + link + '");'
cur.execute(insert_basic)
try:
    db.commit()
except:
    db.rollback()
cur.execute("""SELECT * FROM basic;""")
print cur.fetchall()

Hello, I have done a lot of research and I cannot seem to get the syntax right for submitting to SQL. Some of the variables are integers and some are strings with one being a float.

Body:
This is what parameterized queries are for:

parameters = (testid, username, fullname, firstnumber, secondnumber, floatnumber, posts, country, bio, link)
query = """
    INSERT INTO
        info
    VALUES
        (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cur.execute(query, parameters)

When you do it this way, you are letting your MySQL database driver to handle the type conversions between Python and MySQL automatically.

And, you are also protecting yourself from SQL injection attacks that would be easy to apply to your initial code where you string concatenate your query.

I would also specify the table column names in this case explicitly:

INSERT INTO
    info
    (column_name1, column_name2, ...)
VALUES
    (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)


问:
How to change font color of specific date in jQuery calendar?
I want to change the font color of a particular date of a calendar using jQuery in WordPress.</p>

```<code>var d= new date("February 21, 2017");
d.css('color','black');
</code>```

答:
Loop through each td in your table, check its contents, and apply the css as needed.</p>

```<code>$('#your-table-id-here').find('td').each (function() {
      if(this.text() === "February 21, 2017"){
         this.css('color','black');
    }
});
</code>```

Body:
I want to change the font color of a particular date of a calendar using jQuery in WordPress.

var d= new date("February 21, 2017");
d.css('color','black');

Body:
Loop through each td in your table, check its contents, and apply the css as needed.

$('#your-table-id-here').find('td').each (function() {
      if(this.text() === "February 21, 2017"){
         this.css('color','black');
    }
});


问:
Custom navigation fails upon opening an individual record in Microsoft Access project
I'm having issues with my Microsoft Access project.

The project comprises of two forms called, InfoForm and SearchBox.

InfoForm form

The InfoForm form is the primary-form, and has the following:

Custom navigation buttons, which are; Next and Prev

A custom Search button, which opens up the SearchBox form.

SearchBox form

The SearchBox form is used to browse and open individual records, and has the following:

List of available individual records

Open button

Individual records

The individual records open into the InfoForm form.

I use this code on the Open' button of theSearchBox` form, as follows:

```<code>Private Sub Command1_Click()

Dim strLN As String
strLN = Me.SearchResults.Column(0)

Dim strGN As String
strGN = Me.SearchResults.Column(1)

Dim strMN As String
strMN = Me.SearchResults.Column(2)

DoCmd.OpenForm "InfoForm", acNormal, , _
              "[Last Name] = '" & strLN & "' And " & _
              "[Given Name] = '" & strGN & "' And " & _
              "[Middle Name] = '" & strMN & "'"

DoCmd.Close acForm, "SearchBox"

End Sub
</code>```

This code works perfectly when the InfoForm form is first opened, right up until an individual record is opened.

At this point, the navigation buttons "Next" and "Prev" on the 'InfoForm' form stop working.

Please help. Thank you.

答:
As @Andre noted, if the form is filtered to a single record then there are no succeeding or previous records to navigate to. Does your filter criteria result in a single record dataset?

An alternative is to open the form unfiltered (or with a filter that returns a restricted dataset but will usually still have multiple records) and 'go to' the desired record, then there will be succeeding and preceding records to navigate. Example from my code:

To open form:
DoCmd.OpenForm "Samples", , , , , acDialog, strLabNum

Then code behind the opened form:

```<code>Private Sub Form_Open(Cancel As Integer)
Me.RecordsetClone.FindFirst "LabNum='" & Me.OpenArgs & "'"
Me.Bookmark = Me.RecordsetClone.Bookmark
End Sub
</code>```

Body:
I'm having issues with my Microsoft Access project.

The project comprises of two forms called, InfoForm and SearchBox.

InfoForm form

The InfoForm form is the primary-form, and has the following:

Custom navigation buttons, which are; Next and Prev

A custom Search button, which opens up the SearchBox form.

SearchBox form

The SearchBox form is used to browse and open individual records, and has the following:

List of available individual records

Open button

Individual records

The individual records open into the InfoForm form.

I use this code on the Open' button of theSearchBox` form, as follows:

Private Sub Command1_Click()

Dim strLN As String
strLN = Me.SearchResults.Column(0)

Dim strGN As String
strGN = Me.SearchResults.Column(1)

Dim strMN As String
strMN = Me.SearchResults.Column(2)

DoCmd.OpenForm "InfoForm", acNormal, , _
              "[Last Name] = '" & strLN & "' And " & _
              "[Given Name] = '" & strGN & "' And " & _
              "[Middle Name] = '" & strMN & "'"

DoCmd.Close acForm, "SearchBox"

End Sub

This code works perfectly when the InfoForm form is first opened, right up until an individual record is opened.

At this point, the navigation buttons "Next" and "Prev" on the 'InfoForm' form stop working.

Please help. Thank you.

Body:
As @Andre noted, if the form is filtered to a single record then there are no succeeding or previous records to navigate to. Does your filter criteria result in a single record dataset?

An alternative is to open the form unfiltered (or with a filter that returns a restricted dataset but will usually still have multiple records) and 'go to' the desired record, then there will be succeeding and preceding records to navigate. Example from my code:

To open form:
DoCmd.OpenForm "Samples", , , , , acDialog, strLabNum

Then code behind the opened form:

Private Sub Form_Open(Cancel As Integer)
Me.RecordsetClone.FindFirst "LabNum='" & Me.OpenArgs & "'"
Me.Bookmark = Me.RecordsetClone.Bookmark
End Sub


问:
why I can't set locale in Laravel?
I'm using the following simple codes to change the language in my laravel application, But it doesn't change anything. the language still the default 'en'

Route

```<code>Route::get('lang/{local}','LanguageController@setlanguage');
</code>```

Controller

```<code>public function setlanguage(Request $request)
    {
        \App::setLocale($request->local);

        return back()->withInput();
    }
</code>```

View

```<code> @if(App::getLocale() == 'en')
    <a href="{{url('/lang/ar')}}">العربية</a>
 @elseif(App::getLocale() == 'ar')
    <a href="{{url('/lang/en')}}">English</a>
 @endif
</code>```

Am I missing anything?

答:
Change your controller function to</p>

```<code>public function setlanguage($local)
{
    \App::setLocale($local);

    return back()->withInput();
}
</code>```

Title: why I can't set locale in Laravel?

Body:
I'm using the following simple codes to change the language in my laravel application, But it doesn't change anything. the language still the default 'en'

Route

Route::get('lang/{local}','LanguageController@setlanguage');

Controller

public function setlanguage(Request $request)
    {
        \App::setLocale($request->local);

        return back()->withInput();
    }

View

 @if(App::getLocale() == 'en')
    العربية
 @elseif(App::getLocale() == 'ar')
    English
 @endif

Am I missing anything?

Body:
Change your controller function to

public function setlanguage($local)
{
    \App::setLocale($local);

    return back()->withInput();
}


问:
Mysql Python, filter row and delete previus row
I'm stuck doing a script in Python.
I have a table in MySql like this:

I want to filter the type of category (B, for example) and delete the previous row from above. I'm using mysqldb in Python, and practicing with selects and other operators, but I don't know how to do it.

Can someone help me?

答:
```<code>delete from Table where id=  ( Select id from(select  id from Table where CATEGORY = 'B'  and SALARY < ( Select SALARY from Table where CATEGORY = 'B' order by SALARY desc LIMIT 1) LIMIT 1) as x );
</code>```


问:
Hibernate missing column when dropping a column
I have a entity class like this:

```<code>@Entity
@Table (name="CART_ITEM")
public class CartItem {

@Id
@GeneratedValue (strategy=GenerationType.AUTO)
@Column (name="ID")
private int id;

@Column (name="AMOUNT")
private int amount;
...
</code>```

It works fine with the database. But when I drop the column AMOUNT and remove the corresponding field above (with getters and setters) and restart the application, I get this:

```<code> Exception sending context initialized event to listener instance of    class com.retailstore.AppContextListener
javax.persistence.PersistenceException: [PersistenceUnit: manager] Unable to build Hibernate SessionFactory
at   org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at com.retailstore.AppContextListener.createEntityManagerFactory(AppContextListener.java:76)
at com.retailstore.AppContextListener.contextInitialized(AppContextListener.java:66)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at    org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
 Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [AMOUNT] in table [CART_ITEM]
at     org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:85)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50)
at     org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:473)
at     org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at     org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 14 more
</code>```

I have done this many times before and have never encountered this problem. Does someone have any suggestions?

UPDATE:

I think the problem is solved. There where still old classes under WEB-INF/classes.

答: I recognized that WEB-INF/classes contained old classes conflicting with this entity. I deleted those and the application worked.</p>

Body:
I have a entity class like this:

@Entity
@Table (name="CART_ITEM")
public class CartItem {

@Id
@GeneratedValue (strategy=GenerationType.AUTO)
@Column (name="ID")
private int id;

@Column (name="AMOUNT")
private int amount;
...

It works fine with the database. But when I drop the column AMOUNT and remove the corresponding field above (with getters and setters) and restart the application, I get this:

 Exception sending context initialized event to listener instance of    class com.retailstore.AppContextListener
javax.persistence.PersistenceException: [PersistenceUnit: manager] Unable to build Hibernate SessionFactory
at   org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at com.retailstore.AppContextListener.createEntityManagerFactory(AppContextListener.java:76)
at com.retailstore.AppContextListener.contextInitialized(AppContextListener.java:66)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4842)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at    org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
 Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [AMOUNT] in table [CART_ITEM]
at     org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:85)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50)
at     org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:473)
at     org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at     org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 14 more

I have done this many times before and have never encountered this problem. Does someone have any suggestions?

UPDATE:

I think the problem is solved. There where still old classes under WEB-INF/classes.


问:
EXCEL 2016 - Cannot Use TEXT criteria in Conditional Formatting Rules
I have 3 columns. in the 1st i have ascending numbering, in the 2nd dates & 3rd text

I am trying fill in green color into a cell (of 1st column) which meets the following criteria:
the date is older than TODAY() and
contains specific text "text criteria"

in the conditional formatting rules window i tried the following:

```<code>=AND($M$6:$M$827<TODAY(); $O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())*($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())+($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())&($O$6:$O$827="text criteria")
</code>```

All occasions were received without error, however never got the highlight i need.
Because i was sure that the AND function is correct and should have worked i copied it into a 4th column and indeed it worked correctly in all 827 inputs.

On the other hand, i also used only the$M$6:$M$827<TODAY() part into the conditional formatting window and it work. But it also highlighted some entries should not have because it did not have the second criteria.

Is there a problem by using text criteria in conditional formatting?
If yes how should i work around it? (I was thinking to use the newly 4th column; which works correctly; i need the entries that have the value "TRUE")

Thanks in advance for any help

答:
Assuming ; is your delimiter and the column with ascending numbers is K and you wish to format K6:K827 when the value in the corresponding row for ColumnM is before today (but not blank) and the value in the corresponding row ColumnO is text criteria, please select K6:K827 clear any conditional formatting from those cells and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

```<code>=AND(M6<>"";M6<TODAY();O6="text criteria")
</code>```

with green fill and Done.

Body:
I have 3 columns. in the 1st i have ascending numbering, in the 2nd dates & 3rd text

I am trying fill in green color into a cell (of 1st column) which meets the following criteria:
the date is older than TODAY() and
contains specific text "text criteria"

in the conditional formatting rules window i tried the following:

=AND($M$6:$M$827<TODAY(); $O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())*($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())+($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())&($O$6:$O$827="text criteria")

All occasions were received without error, however never got the highlight i need.
Because i was sure that the AND function is correct and should have worked i copied it into a 4th column and indeed it worked correctly in all 827 inputs.

On the other hand, i also used only the$M$6:$M$827<TODAY() part into the conditional formatting window and it work. But it also highlighted some entries should not have because it did not have the second criteria.

Is there a problem by using text criteria in conditional formatting?
If yes how should i work around it? (I was thinking to use the newly 4th column; which works correctly; i need the entries that have the value "TRUE")

Thanks in advance for any help

Body:
Assuming ; is your delimiter and the column with ascending numbers is K and you wish to format K6:K827 when the value in the corresponding row for ColumnM is before today (but not blank) and the value in the corresponding row ColumnO is text criteria, please select K6:K827 clear any conditional formatting from those cells and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=AND(M6<>"";M6<TODAY();O6="text criteria")

with green fill and Done.


问:
php return inside switch case is working but return after switch is not working
Can anyone help me with the following function, why return inside switch case is working (return correct converted price/quantity):

```<code>function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
    switch ($unit_id) {
        case 8: // A Bushel
            $outQ = $quantity / $lbs_in_a_bu;
            $outP = $price * $lbs_in_a_bu;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 10: // Pounds
            $outQ = $quantity;
            $outP = $price;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 11: // CWT
            $outQ = $quantity / LBS_IN_CWT;
            $outP = $price * LBS_IN_CWT;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 12: // Metric Tonne
            $outQ = $quantity / LBS_IN_TON;
            $outP = $price * LBS_IN_TON;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 136: // W Bushel
            $outQ = $quantity / $lbs_in_w_bu;
            $outP = $price * $lbs_in_w_bu;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
    }
}
</code>```

But this one is not? (return only case 136 converted price/quantity) (return after switch is not working) How can I improve from the above one, I want to use less code to do the above function, thanks!

```<code>function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
    switch ($unit_id) {
        case 8: // A Bushel
            $outQ = $quantity / $lbs_in_a_bu;
            $outP = $price * $lbs_in_a_bu;
        case 10: // Pounds
            $outQ = $quantity;
            $outP = $price;
        case 11: // CWT
            $outQ = $quantity / LBS_IN_CWT;
            $outP = $price * LBS_IN_CWT;
        case 12: // Metric Tonne
            $outQ = $quantity / LBS_IN_TON;
            $outP = $price * LBS_IN_TON;
        case 136: // W Bushel
            $outQ = $quantity / $lbs_in_w_bu;
            $outP = $price * $lbs_in_w_bu;
    }
    return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}
</code>```

答:
Add the break; statement at the end of each case. Otherwise the code of the next cases of the switch statement will be executed too.
Your return statement uses variables that are defined in the switch statement. If somehow $unit_id is not in the list of cases, the return will fail in error. To prevent the return from failing, you could add this at the bottom of the case list:

```<code>default:  // $unit_id not found
  return ['quantity' => '0.000', 'price' => '0.000'];  // whatever you like
</code>```

Or you could throw an Exception.

Body:
Can anyone help me with the following function, why return inside switch case is working (return correct converted price/quantity):

function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
    switch ($unit_id) {
        case 8: // A Bushel
            $outQ = $quantity / $lbs_in_a_bu;
            $outP = $price * $lbs_in_a_bu;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 10: // Pounds
            $outQ = $quantity;
            $outP = $price;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 11: // CWT
            $outQ = $quantity / LBS_IN_CWT;
            $outP = $price * LBS_IN_CWT;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 12: // Metric Tonne
            $outQ = $quantity / LBS_IN_TON;
            $outP = $price * LBS_IN_TON;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 136: // W Bushel
            $outQ = $quantity / $lbs_in_w_bu;
            $outP = $price * $lbs_in_w_bu;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
    }
}

But this one is not? (return only case 136 converted price/quantity) (return after switch is not working) How can I improve from the above one, I want to use less code to do the above function, thanks!

function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
    switch ($unit_id) {
        case 8: // A Bushel
            $outQ = $quantity / $lbs_in_a_bu;
            $outP = $price * $lbs_in_a_bu;
        case 10: // Pounds
            $outQ = $quantity;
            $outP = $price;
        case 11: // CWT
            $outQ = $quantity / LBS_IN_CWT;
            $outP = $price * LBS_IN_CWT;
        case 12: // Metric Tonne
            $outQ = $quantity / LBS_IN_TON;
            $outP = $price * LBS_IN_TON;
        case 136: // W Bushel
            $outQ = $quantity / $lbs_in_w_bu;
            $outP = $price * $lbs_in_w_bu;
    }
    return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}

Body:
Add the break; statement at the end of each case. Otherwise the code of the next cases of the switch statement will be executed too.
Your return statement uses variables that are defined in the switch statement. If somehow $unit_id is not in the list of cases, the return will fail in error. To prevent the return from failing, you could add this at the bottom of the case list:

default:  // $unit_id not found
  return ['quantity' => '0.000', 'price' => '0.000'];  // whatever you like

Or you could throw an Exception.


问:
Referencing images in Ruby on Rails
I have a script in a page (below) that calls a jQuery plugin and passes in the path to a number of images. The images are stored in app/assets/img/bg as opposed to app/assets/images.

```<code><script>
    $(".forms-wrapper").backstretch([
        "assets/img/bg/6.jpg",
        "assets/img/bg/5.jpg",
        "assets/img/bg/7.jpg",
        ], {
            fade: 1000,
            duration: 7000
        });
</script>
</code>```

The JavaScript function is in a file located in app/assets/plugins/backstretch.

I can get the functionality working by changing the path to the images and moving the images:-

```<code><script>
    $(".forms-wrapper").backstretch([
        "../assets/7.jpg",
        "../assets/16.jpg",
        "../assets/19.jpg",
        ], {
            fade: 1000,
            duration: 7000
        });
</script>
</code>```

I would rather not move the images as they are referenced from lots of different places. I have tried changing the path in the script to ./assets/img/bg/7.jpg and this doesn’t work.

I seem to be having all sorts of problems with relative paths in rails because it seems to apply it’s own rules.

As another example there is a script that changes theme colors and images but this script is referencing the img folder too. I would need to reference the images folder here with a relative path (../assets/img) but relative paths don't appear to behave themselves properly.

```<code>var setColor = function (color, data_header) {
    jQuery('#style_color').attr("href", "assets/css/theme-colors/" + color + ".css");
    if(data_header == 'light'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
        jQuery('.navbar-brand img').attr("src", "assets/img/themes/logo1-" + color + ".png");
    } else if(data_header == 'dark'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
    }
}
</code>```

How can I reliably address a subdirectory of assets to reference images? This issue manifests itself in different ways in different parts of the application.

Thanks

答:
Please try this.</p>

```<code><script>
  $(".forms-wrapper").backstretch([
    "../assets/img/bg/6.jpg",
    "../assets/img/bg/5.jpg",
    "../assets/img/bg/7.jpg",
    ], {
      fade: 1000,
      duration: 7000
    });
</script>
</code>```

Title: Referencing images in Ruby on Rails

Body:
I have a script in a page (below) that calls a jQuery plugin and passes in the path to a number of images. The images are stored in app/assets/img/bg as opposed to app/assets/images.

The JavaScript function is in a file located in app/assets/plugins/backstretch.

I can get the functionality working by changing the path to the images and moving the images:-

I would rather not move the images as they are referenced from lots of different places. I have tried changing the path in the script to ./assets/img/bg/7.jpg and this doesn’t work.

I seem to be having all sorts of problems with relative paths in rails because it seems to apply it’s own rules.

As another example there is a script that changes theme colors and images but this script is referencing the img folder too. I would need to reference the images folder here with a relative path (../assets/img) but relative paths don't appear to behave themselves properly.

var setColor = function (color, data_header) {
    jQuery('#style_color').attr("href", "assets/css/theme-colors/" + color + ".css");
    if(data_header == 'light'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
        jQuery('.navbar-brand img').attr("src", "assets/img/themes/logo1-" + color + ".png");
    } else if(data_header == 'dark'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
    }
}

How can I reliably address a subdirectory of assets to reference images? This issue manifests itself in different ways in different parts of the application.

Thanks

Body:
Please try this.

<script>
  $(".forms-wrapper").backstretch([
    "../assets/img/bg/6.jpg",
    "../assets/img/bg/5.jpg",
    "../assets/img/bg/7.jpg",
    ], {
      fade: 1000,
      duration: 7000
    });
</script>


问:
Can't get picture veritcally centered in a div
Yet again, I can't get an image to center inside a specific div. The answers I've come across only center it horizontally, but not vertically

#wrap {
width: auto;
margin: 0 auto;
overflow: hidden;
float: left;
}
/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
width: 50%;
height: 500px;
background: #000;
float: left;
}

#leftBlock img {
display: block;
margin: auto;
transition: transform 4s;
}

#leftBlock img:hover {
transform: scale(1.8);
}

#rightBlock {
width: 50%;
height: 500px;
background: #8ab78f;
float: left;
}

#rightBlock img {
display: block;
margin: auto;
}

/*ignore footer*/
#footerBlock {
height: 200px;
background:  #29342a ;
clear: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
<div id="headerBlock">
    <div class="headerText">blah blah blah so neat</div>
    <div class="headerImg"><img src="/yupyup.jpg" height="70" width="70">
    </div>
</div>

<div id="leftBlock">
    <img src="/leftside.jpg" height="250" width="250">
</div>

<div id="rightBlock"></div>
     <img src="/rightside.jpg" height="250" width="250">
<div id="footerBlock"></div>

</div></code>```

The issue I'm coming across is, it only likes to center it horizontally. The only solution i found was doing the following below, but all that's really doing is moving it all over the screen and me having to pin point where it goes (which should be inside that leftBlock div..) :

```<code>#leftBlock img {
position: absolute;
top: 50%;
margin-top: 305px;
left: 50%;
margin-left: -450px;
transition: transform 4s;
}
</code>```

答:
Here is a quick example that I put together that I hope helps you out:

```<code><!DOCTYPE html>
<html>

<head></head>

<body>
  <div style="height: 500px; width: 500px; background: yellow;">
    <div style="background: black; height: 200px; width:
       200px;position: relative;top: 50%; left: 50%;transform:
       translate(-50%,-50%);">
       this is a div yo
    </div>
  </div>
</body>

</html>
</code>```

So basically just do position: relative;top: 50%; left: 50%;transform:translate(-50%,-50%);" on what you want to be centered inside

Body:
Yet again, I can't get an image to center inside a specific div. The answers I've come across only center it horizontally, but not vertically

#wrap {
width: auto;
margin: 0 auto;
overflow: hidden;
float: left;
}
/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
width: 50%;
height: 500px;
background: #000;
float: left;
}

#leftBlock img {
display: block;
margin: auto;
transition: transform 4s;
}

#leftBlock img:hover {
transform: scale(1.8);
}

#rightBlock {
width: 50%;
height: 500px;
background: #8ab78f;
float: left;
}

#rightBlock img {
display: block;
margin: auto;
}

/*ignore footer*/
#footerBlock {
height: 200px;
background:  #29342a ;
clear: left;
}

blah blah blah so neat

The issue I'm coming across is, it only likes to center it horizontally. The only solution i found was doing the following below, but all that's really doing is moving it all over the screen and me having to pin point where it goes (which should be inside that leftBlock div..) :

#leftBlock img {
position: absolute;
top: 50%;
margin-top: 305px;
left: 50%;
margin-left: -450px;
transition: transform 4s;
}

Body:
Here is a quick example that I put together that I hope helps you out:

<!DOCTYPE html>
<html>

<head></head>

<body>
  <div style="height: 500px; width: 500px; background: yellow;">
    <div style="background: black; height: 200px; width:
       200px;position: relative;top: 50%; left: 50%;transform:
       translate(-50%,-50%);">
       this is a div yo
    </div>
  </div>
</body>

</html>

So basically just do position: relative;top: 50%; left: 50%;transform:translate(-50%,-50%);" on what you want to be centered inside


问:
Search and replace with sed does not work with html tags
i have two questions:

1) I try to replace one couple  of html tags and value between them:
i try to replace this gmail	 on this skype

When i tried to do this:
sed -i -e "s/gmail	/skype	/g" test.txt

,i received error:

sed: -e expression #1, char 18: unknown option tos'`

I understand, that i should use string, ok, let's do use this pattern:

sed -i -e "s/'"gmail	"'/"'skype	'"/g" test3.txt

in this case, i have other error:

-su: td: No such file or directory

Where i have error, Please help.

2) I want to make replace only on special line. For example, i have:

```<code><tr>
    <td>click</td>
    <td>gmail</td>
    <td>message-type</td>
</tr>
</code>```

I want to replace only third line. How can i do it ?

答:
Ad 1) Slash is a special character for sed s command. So, this is how your command is interpreted:

```<code>s/<td>gmail</td>/<td>skype</td>/g
  ^        ^ ^ ^ ^
  |        | | | +- options start here
  |        | | +- replacement string stops here
  |        | +- replacement string starts here
  |        +- search pattern stops here
  +- search pattern starts here
</code>```

If you want it to behave as a normal character, quote it with backslash. As given in this answer.

Ad 2) sed -e '3 s/..../'.

PS. man sed is your friend.

Body:
i have two questions:

1) I try to replace one couple  of html tags and value between them:
i try to replace this gmail	 on this skype

When i tried to do this:
sed -i -e "s/gmail	/skype	/g" test.txt

,i received error:

sed: -e expression #1, char 18: unknown option tos'`

I understand, that i should use string, ok, let's do use this pattern:

sed -i -e "s/'"gmail	"'/"'skype	'"/g" test3.txt

in this case, i have other error:

-su: td: No such file or directory

Where i have error, Please help.

2) I want to make replace only on special line. For example, i have:

    click
    gmail
    message-type

I want to replace only third line. How can i do it ?

Body:
Ad 1) Slash is a special character for sed s command. So, this is how your command is interpreted:

s/<td>gmail</td>/<td>skype</td>/g
  ^        ^ ^ ^ ^
  |        | | | +- options start here
  |        | | +- replacement string stops here
  |        | +- replacement string starts here
  |        +- search pattern stops here
  +- search pattern starts here

If you want it to behave as a normal character, quote it with backslash. As given in this answer.

Ad 2) sed -e '3 s/..../'.

PS. man sed is your friend.


问:
OWASP ZAP python API error running script
i want to use python-owasp-zap api. I downloaded and installed all the repositories required for python-owasp-zap . when i run a sample code which was given in the web site https://github.com/zaproxy/zaproxy/wiki/ApiPython I am getting the below error, please help me .

```<code>Traceback (most recent call last):
  File "zap2.py", line 34, in <module>
    while (int(zap.spider.status()) < 100):
ValueError: invalid literal for int() with base 10: 'Does Not Exist'
</code>```

Then, i tried removing paranthesis from status method:

```<code>while (int(zap.spider.status) < 100):
     print 'Spider progress %: ' + zap.spider.status
     time.sleep(2)
</code>```

And i get the following error:

```<code>TypeError: Int argument must be an Int or string not an InstanceMethod
</code>```

Help on rectifying the error is most appreciated.

答:
Spider.status() takes a parameter, scanid. This is to keep track of different scans. You need to specify which scan this is and can be done as shown below.</p>

```<code>target = 'some decimal base address'
scanid = zap.spider.scan(target)
while (int(zap.spider.status(scanid)) < 100):
    print 'Spider progress %: ' + zap.spider.status(scanid)
    time.sleep(5)
</code>```

Body:
i want to use python-owasp-zap api. I downloaded and installed all the repositories required for python-owasp-zap . when i run a sample code which was given in the web site https://github.com/zaproxy/zaproxy/wiki/ApiPython I am getting the below error, please help me .

Traceback (most recent call last):
  File "zap2.py", line 34, in <module>
    while (int(zap.spider.status()) < 100):
ValueError: invalid literal for int() with base 10: 'Does Not Exist'

Then, i tried removing paranthesis from status method:

while (int(zap.spider.status) < 100):
     print 'Spider progress %: ' + zap.spider.status
     time.sleep(2)

And i get the following error:

TypeError: Int argument must be an Int or string not an InstanceMethod

Help on rectifying the error is most appreciated.

Body:
Spider.status() takes a parameter, scanid. This is to keep track of different scans. You need to specify which scan this is and can be done as shown below.

target = 'some decimal base address'
scanid = zap.spider.scan(target)
while (int(zap.spider.status(scanid)) < 100):
    print 'Spider progress %: ' + zap.spider.status(scanid)
    time.sleep(5)


问:
Webpack bundled file not generated
I am just new to webpack and react , just going through the docs and created a example to work. Unfortunately i got stuck and not able to proceed . Th problem is the bundled file is not generated.
 The files i created is

package.json

```<code>{
  "name": "rohith",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  }
}
</code>```

webpack.config.js

```<code>module.export = {
    entry : './main.js',
    output : {
        path : './',
        filename : 'index.js'
    },
    devServer : {
        inline : true,
        port : 3333
    },
    module : {
        loaders : [
            {
                test : /\.js$/,
                exclude : /node_modules/,
                loader : 'babel',
                query : {
                    presets : ['es2015','react']
                }
            }
        ]
    }
}
</code>```

App.js

```<code>import React from 'react';
class App extends React.Component {
    render(){
        return <div>Hello</div>
    }
}

export default App
</code>```

main.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,document.getElementById('app'));
</code>```

index.html

```<code><!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <title>Setup</title>
</head>
<body>
    <div id = "app"></div>
    <script src ="index.js"></script>
</body>
</html>
</code>```

I am getting that bundle is valid, but no index.js is generated.
can't run in localhost 3333

Thanks,

答:
For me the problem was with package.json under that "scripts"

Here is the fix:

Inside your package.json file, under script add the following:

"scripts": {

     "start": "webpack-dev-server",

     "build": "webpack -p"
   }

First I ran the build then start.

yarn build

if you first build then your bundle.js file will be created and after that you can use this command:

yarn start

Title: Webpack bundled file not generated

Body:
I am just new to webpack and react , just going through the docs and created a example to work. Unfortunately i got stuck and not able to proceed . Th problem is the bundled file is not generated.
 The files i created is

package.json

{
  "name": "rohith",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  }
}

webpack.config.js

module.export = {
    entry : './main.js',
    output : {
        path : './',
        filename : 'index.js'
    },
    devServer : {
        inline : true,
        port : 3333
    },
    module : {
        loaders : [
            {
                test : /\.js$/,
                exclude : /node_modules/,
                loader : 'babel',
                query : {
                    presets : ['es2015','react']
                }
            }
        ]
    }
}

App.js

import React from 'react';
class App extends React.Component {
    render(){
        return
Hello

    }
}

export default App

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,document.getElementById('app'));

index.html

<!DOCTYPE html>

    <meta charset = "UTF-8">
    <title>Setup</title>

I am getting that bundle is valid, but no index.js is generated.
can't run in localhost 3333

Thanks,


答: Return exits the function so in your case acts as a break, that is why it works in the first case.</p>

Title: php return inside switch case is working but return after switch is not working


问:
bash assign default value

${parameter:=word}
                Assign Default Values.  If parameter is unset or null, the
  expansion of word is assigned to
  parameter.  The value of parameter is
  then  substituted.   Positional
  parameters  and  special
                parameters may not be assigned to in this way.

I thought I could use this feature to write ${LONG_VARIABLE_NAME:=hello} instead of the longer LONG_VARIABLE_NAME=${LONG_VARIABLE_NAME:-hello}, but now bash also tries to execute 'hello' and that gives a command not found. Any way to avoid that? Or will I have to stick to the latter? Can someone give an example where the assign default is actually useful?

答:
The default value parameter expansion is often useful in build scripts like the example one below.  If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL to a value other than "no" to have it built in.

```<code>$ cat defvar.sh
#!/bin/bash

WITH_PERL=${WITH_PERL:-no}

if [[ "$WITH_PERL" != no ]]; then
    echo "building with perl"
    # ./configure --enable=perl
else
    echo "not building with perl"
    # ./configure
fi
</code>```

Build without Perl

```<code>$ ./defvar.sh
not building with perl
</code>```

Build with Perl

```<code>$ WITH_PERL=yes ./defvar.sh
building with perl
</code>```

Title: bash assign default value

Body:
The default value parameter expansion is often useful in build scripts like the example one below.  If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL to a value other than "no" to have it built in.

$ cat defvar.sh
#!/bin/bash

WITH_PERL=${WITH_PERL:-no}

if [[ "$WITH_PERL" != no ]]; then
    echo "building with perl"
    # ./configure --enable=perl
else
    echo "not building with perl"
    # ./configure
fi

Build without Perl

$ ./defvar.sh
not building with perl

Build with Perl

$ WITH_PERL=yes ./defvar.sh
building with perl


问:
Can I "rename" the methods 'then' and 'catch' when I'm returning a promise?
I would like to change the name and write "exito" (success in spanish) instead of .then() and "error" instead of catch().

Here is my code.

How can I manage with this?

var url = 'http://devmsadasds';
                var object = null;

```<code>            var dataServicio = new dataService(url, object, $scope, $routeParams, $controller, $timeout, $http, $q);
                dataServicio.ajaxPeticion(url, object, $scope, $routeParams, $controller, $timeout, $http, $q)
                 .then( function(response){
                     $scope.datosVista = response;
                 })
                 .catch( function(err){
                     alert(err);
                 });

            }

          function dataService(url, object, $scope, $routeParams, $controller, $timeout, $http, $q) {
                return {
                        ajaxPeticion : ajaxPeticion
                    }

                function ajaxPeticion(url, object, $scope, $routeParams, $controller, $timeout, $http, $q) {
                    if(object === null || object === undefined) {
                        var metodo = 'GET';
                }
                else {
                        var metodo = 'POST';
                }

                    var deferred = $q.defer();
                    var promise = deferred.promise;

                    $http({
                            method: metodo,
                            url: url,
                            data: object,
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    })
                    .then(function(response) {
                        if(response.data.jsonMC.resultado === false || response.status != 200 || response.data.jsonMC.respuesta === null) {
                            deferred.reject(response.data.jsonMC.error);
                        }
                        else {
                            deferred.resolve(response.data.jsonMC.respuesta);
                        }
                    }, function errorCallback(response) {
                        deferred.rejected(response.data.jsonMC.error);
                    });

                    return promise;
                }

            }
</code>```

答:
You could, but to be honest I cannot really see the utility. You are going to create a way that all the developers (or you) will get used to a method which actually doesn't exist, your code will never be understood from outside people who don't know about this "convention".
At the same moment, every library of whatever uses "normal promises", will use the then and not your method.

By the way, this should simply do what you want for simple JavaScript, you can do the same for AngularJS with the $q service:

```<code>Promise.prototype.exito = Promise.prototype.then;
</code>```

Promise.prototype.exito = Promise.prototype.then;
new Promise((resolve, reject) => {
  setTimeout(function() {console.log('finished'); resolve('resolved');}, 2500);
}).exito(function(data){ console.log(data); });```

Again. I strongly recommend you to not do this.

Body:
I would like to change the name and write "exito" (success in spanish) instead of .then() and "error" instead of catch().

Here is my code.

How can I manage with this?

var url = 'http://devmsadasds';
                var object = null;

            var dataServicio = new dataService(url, object, $scope, $routeParams, $controller, $timeout, $http, $q);
                dataServicio.ajaxPeticion(url, object, $scope, $routeParams, $controller, $timeout, $http, $q)
                 .then( function(response){
                     $scope.datosVista = response;
                 })
                 .catch( function(err){
                     alert(err);
                 });

            }

          function dataService(url, object, $scope, $routeParams, $controller, $timeout, $http, $q) {
                return {
                        ajaxPeticion : ajaxPeticion
                    }

                function ajaxPeticion(url, object, $scope, $routeParams, $controller, $timeout, $http, $q) {
                    if(object === null || object === undefined) {
                        var metodo = 'GET';
                }
                else {
                        var metodo = 'POST';
                }

                    var deferred = $q.defer();
                    var promise = deferred.promise;

                    $http({
                            method: metodo,
                            url: url,
                            data: object,
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    })
                    .then(function(response) {
                        if(response.data.jsonMC.resultado === false || response.status != 200 || response.data.jsonMC.respuesta === null) {
                            deferred.reject(response.data.jsonMC.error);
                        }
                        else {
                            deferred.resolve(response.data.jsonMC.respuesta);
                        }
                    }, function errorCallback(response) {
                        deferred.rejected(response.data.jsonMC.error);
                    });

                    return promise;
                }

            }

Body:
You could, but to be honest I cannot really see the utility. You are going to create a way that all the developers (or you) will get used to a method which actually doesn't exist, your code will never be understood from outside people who don't know about this "convention".
At the same moment, every library of whatever uses "normal promises", will use the then and not your method.

By the way, this should simply do what you want for simple JavaScript, you can do the same for AngularJS with the $q service:

Promise.prototype.exito = Promise.prototype.then;

Promise.prototype.exito = Promise.prototype.then;
new Promise((resolve, reject) => {
  setTimeout(function() {console.log('finished'); resolve('resolved');}, 2500);
}).exito(function(data){ console.log(data); });

Again. I strongly recommend you to not do this.


问:
Get JSON data from API with Angular 2
I am trying to get some JSON data by API that I have created, but it does not receive it. I have used the following Angular code:

```<code>getBook(id: string){
    return this._http.get(this.url + 'books/' + id)
               .map(res => {
                   console.log(res.json());         //It does not show anything
                   return res.json();
               })
</code>```

However the getBooks() method has no problems getting the data. There are no errors in the browser console.
This is the whole service code:

```<code>import { Injectable } from '@angular/core';

import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";

@Injectable()
export class LibrosService {

url: string = "http://localhost/API/public/index.php/api/";

constructor(private _http: Http) { }

getBooks(){
    return this._http.get(this.url + 'books')
                .map(res => res.json());        //it works
}

getBook(id: string){
    return this._http.get(this.url + 'books/' + id)
               .map(res => {
                   console.log(res.json());     //it does not work
                   return res.json();
               })
}
</code>```

Sorry for my English if it is not very good and thank you for your help.

答:
In Service </p>

```<code>getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
</code>```

<p>In Component </p>

```<code>getHeroes() {
    this.heroService.getHeroes()
                     .subscribe(
                       heroes => this.heroes = heroes,
                       error =>  this.errorMessage = <any>error);
  }
</code>```

Title: Get JSON data from API with Angular 2

Body:
I am trying to get some JSON data by API that I have created, but it does not receive it. I have used the following Angular code:

getBook(id: string){
    return this._http.get(this.url + 'books/' + id)
               .map(res => {
                   console.log(res.json());         //It does not show anything
                   return res.json();
               })

However the getBooks() method has no problems getting the data. There are no errors in the browser console.
This is the whole service code:

import { Injectable } from '@angular/core';

import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";

@Injectable()
export class LibrosService {

url: string = "http://localhost/API/public/index.php/api/";

constructor(private _http: Http) { }

getBooks(){
    return this._http.get(this.url + 'books')
                .map(res => res.json());        //it works
}

getBook(id: string){
    return this._http.get(this.url + 'books/' + id)
               .map(res => {
                   console.log(res.json());     //it does not work
                   return res.json();
               })
}

Sorry for my English if it is not very good and thank you for your help.

Body:
In Service

getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

In Component

getHeroes() {
    this.heroService.getHeroes()
                     .subscribe(
                       heroes => this.heroes = heroes,
                       error =>  this.errorMessage = <any>error);
  }


问:
NSAutolayoutConstraint - Apply constant before multiplier
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)
</code>```

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)
</code>```

Because I end up losing the constraint.constant that comes from the storyboard.

答:
You could try next:</p>

```<code>class MyConstraint: NSLayoutConstraint {

    fileprivate var storyboardConstant: CGFloat!

    override func awakeFromNib() {
        super.awakeFromNib()
        storyboardConstant = constant
    }

    func copy(with newMultiplier: CGFloat) -> MyConstraint? {
        guard let viewWidth = constraint.secondItem?.bounds?.width,
              let _ = storyboardConstant else {
            return nil
        }
        let newConstraint = MyConstraint(
            item: constraint.firstItem,
            attribute: constraint.firstAttribute,
            relatedBy: constraint.relation,
            toItem: constraint.secondItem,
            attribute: constraint.secondAttribute,
            multiplier: newMultiplier,
            constant: storyboardConstant * newMultiplier
        )
        return newConstraint
    }
}
</code>```

Body:
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)

Because I end up losing the constraint.constant that comes from the storyboard.

Body:
You could try next:

class MyConstraint: NSLayoutConstraint {

    fileprivate var storyboardConstant: CGFloat!

    override func awakeFromNib() {
        super.awakeFromNib()
        storyboardConstant = constant
    }

    func copy(with newMultiplier: CGFloat) -> MyConstraint? {
        guard let viewWidth = constraint.secondItem?.bounds?.width,
              let _ = storyboardConstant else {
            return nil
        }
        let newConstraint = MyConstraint(
            item: constraint.firstItem,
            attribute: constraint.firstAttribute,
            relatedBy: constraint.relation,
            toItem: constraint.secondItem,
            attribute: constraint.secondAttribute,
            multiplier: newMultiplier,
            constant: storyboardConstant * newMultiplier
        )
        return newConstraint
    }
}


问:
Why does it take sooo long to load my solution in Visual Studio?
We have a really big solution with more than 200 projects and thousands of files. Despite of that the solution used to load pretty quickly in Visual Studio 2010 as well as 2012. However, after copying the whole SVN repository to another location, loading and closing the solution suddenly took extreeeemly long. (I am talking about 30-60 minutes here!)</p>

答:
None of the other answers worked for me.  CI compile times were fine, but loading my solution in Visual Studio was taking almost two minutes.  VS would then operate just fine until I closed and opened the solution the next time.  Different versions of VS all showed the same problem and both safe mode and deleting the suo didn't help.

I ended up following the advice in http://geekswithblogs.net/akraus1/archive/2014/04/30/156156.aspx to use Windows Performance Recorder to instrument VS and find the problem.  By looking in Windows Performance Analyzer under the "CPU Usage (Sampled)" section and adding the "Stack (Frame Tags)" column, I was able to dig into the usage of devenv.exe.

Turns out the hot path by count had Microsoft.VisualStudio.Platform.WindowManagement.ni.dll 23 calls down, and below that eventually Microsoft.VisualStudio.ServerExplorer.dll and Microsoft.VisualStudio.Data.Package.dll.  That pointed me to look in Server Explorer in the UI and open the Data Connections tab.  There I found hundreds of mistakenly added connections that came from the debug web.config's ConnectionString section.  Removing those from web.config reduced the load of that individual project from 90+ seconds to almost instant.


问:
What's the proper way to disable ajax cache on select2?
I'm using select2 to load remote data to an html select

The issue with it is that if user selects an option -> clears the input -> data changes in server -> user search for the data again. If I ask for data selected it returns the old (previusly selected) values.

Example:

```<code>//User search for an option and selects it
$('#someSelect').select2('data').Limit
//Here the limit is 0
//Server data changes on server. Now limit is 10
//User searchs again for the same option and selects it
$('#someSelect').select2('data').Limit
//The value returned in the line above is 0 again
//Somehow the data previously selected is cached
//and returned instead of the refreshed data
</code>```

Setting cache:false doesn't do anything.

答:
After hours I figured out the solution.

On the event select2:unselect I had to clear all the options of the select because the plugin has added the selected option to the DOM.

```<code>$('#someSelect').on('select2:unselect',function(){
    $('#someSelect').html(null);
});
</code>```

Body:
I'm using select2 to load remote data to an html select

The issue with it is that if user selects an option -> clears the input -> data changes in server -> user search for the data again. If I ask for data selected it returns the old (previusly selected) values.

Example:

//User search for an option and selects it
$('#someSelect').select2('data').Limit
//Here the limit is 0
//Server data changes on server. Now limit is 10
//User searchs again for the same option and selects it
$('#someSelect').select2('data').Limit
//The value returned in the line above is 0 again
//Somehow the data previously selected is cached
//and returned instead of the refreshed data

Setting cache:false doesn't do anything.

Body:
After hours I figured out the solution.

On the event select2:unselect I had to clear all the options of the select because the plugin has added the selected option to the DOM.

$('#someSelect').on('select2:unselect',function(){
    $('#someSelect').html(null);
});


答:
It is considered bad practice to mask methods with other names.
If you are still considering it, please note "error" also has meaning in English, and it may lead to confusion. </p>

Title: Can I "rename" the methods 'then' and 'catch' when I'm returning a promise?


问:
Button disabled but looks active
So I have a button that is currently set to disabled, and in IE it is greyed out, but in Firefox, Chrome and Safari, it is disabled but still looks active.

Button code

```<code><tr valign="middle">
    <td colspan="2" style="width: 100%">
        <asp:Button ID="DownloadButton" runat="server" Text="Download" Width="85px" CssClass="ESTableHeaderL" OnClick="DownloadButton_Click" />
    </td>
  </tr>
</code>```

And my code behind

```<code>protected void DownloadButton_Click(object sender, EventArgs e)
{
    if (ddBusinessMonth.Items.Count == 0)
    {
        DownloadButton.Enabled = false;
        ShowClientMessageBox("No Data found for downloading");
    }
....

}
</code>```

Is there anything I can do to make it look the same as in IE?

Thanks

答:
A quick way without using a custom CSS class (nothing against style sheets) that can be completed in the code behind.  The following will set the background color of your download button to green (I think it's green, I'm colorblind :-| ):</p>

```<code>DownloadButton.Attributes.Add("style", "background-color:#28C523");
</code>```

Title: Button disabled but looks active

Body:
So I have a button that is currently set to disabled, and in IE it is greyed out, but in Firefox, Chrome and Safari, it is disabled but still looks active.

Button code

        <asp:Button ID="DownloadButton" runat="server" Text="Download" Width="85px" CssClass="ESTableHeaderL" OnClick="DownloadButton_Click" />

And my code behind

protected void DownloadButton_Click(object sender, EventArgs e)
{
    if (ddBusinessMonth.Items.Count == 0)
    {
        DownloadButton.Enabled = false;
        ShowClientMessageBox("No Data found for downloading");
    }
....

}

Is there anything I can do to make it look the same as in IE?

Thanks

Body:
A quick way without using a custom CSS class (nothing against style sheets) that can be completed in the code behind.  The following will set the background color of your download button to green (I think it's green, I'm colorblind :-| ):

DownloadButton.Attributes.Add("style", "background-color:#28C523");


问:
C# Can´t get value from Registry
I´m trying to get the R install path over C# but unfortunatly the Registry.LocalMachine.OpenSubKey(keyName) method returns null.

This is my code:

```<code>var keyName = @"SOFTWARE\R-core\R";

using (var key = Registry.LocalMachine.OpenSubKey(keyName))
{
   if (key != null)
   {
      var value = key.GetValue("InstallPath", 0);
      Console.WriteLine(value);
   }
   else
   {
      Console.WriteLine("No key found!");
   }

}
</code>```

I manually checked if the key exists and it does.

答:
Try to use

```<code>Registry.GetValue (String, String, Object)
</code>```

after that you shoul cast object to your type.
More information you can find on MSDN
GetValue Description

Title: C# Can´t get value from Registry

Body:
I´m trying to get the R install path over C# but unfortunatly the Registry.LocalMachine.OpenSubKey(keyName) method returns null.

This is my code:

var keyName = @"SOFTWARE\R-core\R";

using (var key = Registry.LocalMachine.OpenSubKey(keyName))
{
   if (key != null)
   {
      var value = key.GetValue("InstallPath", 0);
      Console.WriteLine(value);
   }
   else
   {
      Console.WriteLine("No key found!");
   }

}

I manually checked if the key exists and it does.

Body:
Try to use

Registry.GetValue (String, String, Object)

after that you shoul cast object to your type.
More information you can find on MSDN
GetValue Description


问:
How to get fake contacts in iOS Simulator?
How can I get fake contacts in iOS Simulator? Is there a shell script I can use or an editor for my contacts?

Edit: I use React Native so I can't just throw some Swift project in there - is there a command line tool or way to connect the iOS Simulator to my Contacts application on my Mac?

答:
You can download this generated VCF file, and then drag/drop it to your Simulator to import (1000) fake contacts.  I created this test data using the mock data generation website Mockaroo.

This was created using a small Node.js script that takes a CSV and converts it into one single VCF file - which you can then drag and drop to the iOS Simulator.  This is the simplest way to import contacts, no code required or installation of apps needed off GitHub (as the other answers imply). This CSV parser assumes you have three columns at the top of the file (First Name, Last Name, and Phone Number. If you want to add more columns/variables for importing, simply modify your CSV and the parser below based off the vCard spec.

Save the below script as "mock.js" and run it with node mock (here's a GitHub gist of it). This assumes the script below, along with your CSV file (e.g. "MOCK_DATA.csv") is in the same directory. The output of running this script will be a file named "vcards.vcf".

```<code>const fs = require('fs');
const csv = fs.readFileSync('./MOCK_DATA.csv', 'utf8');
const records = csv.split('\n').slice(1);
const VCARDS = [];
records.forEach(function(record, i) {
  const data = record.split(',');
  const VCARD = [
    'BEGIN:VCARD',
    'VERSION:4.0',
    `N:${data[1]};${data[0]};;;`,
    `FN:${data[0]} ${data[1]}`,
    `TEL;type=HOME:${data[2]}`,
    'END:VCARD'
  ].join('\n');
  VCARDS.push(VCARD);
});
fs.writeFileSync(`./vcards.vcf`, VCARDS.join('\n'));
</code>```

Body:
You can download this generated VCF file, and then drag/drop it to your Simulator to import (1000) fake contacts.  I created this test data using the mock data generation website Mockaroo.

This was created using a small Node.js script that takes a CSV and converts it into one single VCF file - which you can then drag and drop to the iOS Simulator.  This is the simplest way to import contacts, no code required or installation of apps needed off GitHub (as the other answers imply). This CSV parser assumes you have three columns at the top of the file (First Name, Last Name, and Phone Number. If you want to add more columns/variables for importing, simply modify your CSV and the parser below based off the vCard spec.

Save the below script as "mock.js" and run it with node mock (here's a GitHub gist of it). This assumes the script below, along with your CSV file (e.g. "MOCK_DATA.csv") is in the same directory. The output of running this script will be a file named "vcards.vcf".

const fs = require('fs');
const csv = fs.readFileSync('./MOCK_DATA.csv', 'utf8');
const records = csv.split('\n').slice(1);
const VCARDS = [];
records.forEach(function(record, i) {
  const data = record.split(',');
  const VCARD = [
    'BEGIN:VCARD',
    'VERSION:4.0',
    `N:${data[1]};${data[0]};;;`,
    `FN:${data[0]} ${data[1]}`,
    `TEL;type=HOME:${data[2]}`,
    'END:VCARD'
  ].join('\n');
  VCARDS.push(VCARD);
});
fs.writeFileSync(`./vcards.vcf`, VCARDS.join('\n'));


问:
Can an interrupted Java thread really skip a finally clause?
I was checking into the oft repeated rumour that daemon threads on the JVM treat finally blocks in some special way (they don't, ok?), when I read this, from the Oracle Java tutorial:

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

(Emphasis is mine.) And the bit about interrupted caught my eye!

My belief is that if a thread is in try/catch code and is interrupted, then either we're in (or eventually enter) a state (eg sleep, wait) where we end up throwing an InterruptedException, or we aren't and we drop out normally or abnormally, but in all cases we will hit the finally clause.

What have I missed? Is there really a way for a Thread to be interrupted and then skip a finally, whilst the application continues?

答:
Since you specifically ask about daemon threads: remember daemon threads go away when the jvm's last nondaemon thread terminates,  so in that case a daemon thread can die without having executed finally blocks (or whatever other code it was about to execute, there's nothing special about finally blocks). Don't use a daemon thread for anything that you don't mind being dropped on the floor when the jvm terminates.

Otherwise, interruption doesn't do anything to shortcut finally blocks. The point of interruption is that the interrupted thread is in control and can finish its execution, including closing resources, however it needs to.

The tutorials can be very helpful but they are not authoritative. The wording in this case uses the word interrupted, it seems reasonable in this context to assume it is referring specifically to thread interruption, which is incorrect.


问:
How to add fields in NEST elastic search nest Attribute mapping?
```<code> "properties": {
          "data": {
            "type": "text",
            "boost": 2,
            "fields": {
              "raw": {
                "type": "text"
              }
}
</code>```

<p>I need to add fields pragmatically, in above code i need to add data.raw. Please help. Thanks in Advance. </p>

答:
There's no way to add multi_fields with attribute mapping; For this, you'll need to use fluent mapping</p>

```<code>void Main()
{
    var client = new ElasticClient();

    client.CreateIndex("index-name", c => c
        .Mappings(m => m
            .Map<Test>(mm => mm
                .AutoMap()
                .Properties(p => p
                    .Text(t => t
                        .Name(n => n.Data)
                        .Boost(2)
                        .Fields(ff => ff
                            .Text(tt => tt
                                .Name("raw")
                            )
                        )
                    )
                )
            )
        )
    );
}

public class Test
{
    public string Data { get; set; }
}
</code>```

Body:
 "properties": {
          "data": {
            "type": "text",
            "boost": 2,
            "fields": {
              "raw": {
                "type": "text"
              }
}

I need to add fields pragmatically, in above code i need to add data.raw. Please help. Thanks in Advance.

Body:
There's no way to add multi_fields with attribute mapping; For this, you'll need to use fluent mapping

void Main()
{
    var client = new ElasticClient();

    client.CreateIndex("index-name", c => c
        .Mappings(m => m
            .Map<Test>(mm => mm
                .AutoMap()
                .Properties(p => p
                    .Text(t => t
                        .Name(n => n.Data)
                        .Boost(2)
                        .Fields(ff => ff
                            .Text(tt => tt
                                .Name("raw")
                            )
                        )
                    )
                )
            )
        )
    );
}

public class Test
{
    public string Data { get; set; }
}


问:
Break and Continue (C)

"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares the two strings starting from index 0. For each match, add one point to userScore. Upon a mismatch, exit the loop using a break statement.

Ex: The following patterns yield a userScore of 4:

simonPattern: R, R, G, B, R, Y, Y, B, G, Y

userPattern:  R, R, G, B, B, R, Y, B, G, Y

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

int main(void) {
   char simonPattern[50] = "";
   char userPattern[50] = "";
   int userScore = 0;
   int i = 0;

   userScore = 0;
   strcpy(simonPattern, "RRGBRYYBGY");
   strcpy(userPattern, "RRGBBRYBGY");

   while (userPattern[i] = simonPattern[i]) {
      userScore = userScore + 1;
      ++i;
      if (userPattern[i] != simonPattern[i]) {
         break;
      }
   }

   printf("userScore: %d\n", userScore);

   return 0;
}
</code>```

I tried running the code, but I got this

http://i.imgur.com/T7srTbb.png

Does anyone know what's causing the extra 1?

Thanks.

答:
```<code>while (simonPattern.at(i) == userPattern.at(i))
{
++i;
++userScore;
}
</code>```

Title: Break and Continue (C)

Body:
"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares the two strings starting from index 0. For each match, add one point to userScore. Upon a mismatch, exit the loop using a break statement.

Ex: The following patterns yield a userScore of 4:

simonPattern: R, R, G, B, R, Y, Y, B, G, Y

userPattern:  R, R, G, B, B, R, Y, B, G, Y

#include <stdio.h>
#include <string.h>

int main(void) {
   char simonPattern[50] = "";
   char userPattern[50] = "";
   int userScore = 0;
   int i = 0;

   userScore = 0;
   strcpy(simonPattern, "RRGBRYYBGY");
   strcpy(userPattern, "RRGBBRYBGY");

   while (userPattern[i] = simonPattern[i]) {
      userScore = userScore + 1;
      ++i;
      if (userPattern[i] != simonPattern[i]) {
         break;
      }
   }

   printf("userScore: %d\n", userScore);

   return 0;
}

I tried running the code, but I got this

http://i.imgur.com/T7srTbb.png

Does anyone know what's causing the extra 1?

Thanks.


问:
QML show window on specified screen
I have hybrid QML/QWidget application and I want to show QML window on the specified screen. Here's the code defining a screen number

```<code>int activeScreenIndex = QApplication::desktop()->screenNumber(QApplication::activeWindow());
</code>```

Now I want to show QML component Window on the screen I've defined this way. Another problem is that I create QML windows unisng Instantiator.

答:
Window::screen was introduced in Qt 5.9.

```<code>Window {
    screen: Qt.application.screens[activeScreenIndex]
}
</code>```

Title: QML show window on specified screen

Body:
I have hybrid QML/QWidget application and I want to show QML window on the specified screen. Here's the code defining a screen number

int activeScreenIndex = QApplication::desktop()->screenNumber(QApplication::activeWindow());

Now I want to show QML component Window on the screen I've defined this way. Another problem is that I create QML windows unisng Instantiator.

Body:
Window::screen was introduced in Qt 5.9.

Window {
    screen: Qt.application.screens[activeScreenIndex]
}


问:
Pass session variable from controller to view in express js
In express controller after log in to application using this code to redirect to main page:

```<code> req.session.user = user.userLogin;
 if (req.session.user=='Admin') {
    global.loggedAdmin = user.userLogin;
 }
 else {
    global.loggedUser = user.userLogin;
 }
 res.redirect('/');
</code>```

And in main menu check if user is logged:

```<code>nav#menu.panel(role='navigation')
    ul
        li
        if loggedUser
            li
                span.setting Welcome #{loggedUser}
                    a(href='/account')
                        i.fa.fa-cog
            li
                hr
            li
                a(href='/logout') Logout
            li
        else if loggedAdmin
            li
                span.setting Welcome #{loggedAdmin}
                    a(href='/account')
                        i.fa.fa-cog
            li
                hr
            li
                a(href='/articles') Articles
            li
                hr
            li
                a(href='/files') Files
            li
                hr
            li
                a(href='/users') Users
            li
                hr
            li
                a(href='/logout') Logout
        else
            li
                a(href='/login') Log in
            li
                hr
            li
                a(href='/register') Register
</code>```

And in app.js:

```<code>app.use(session({
    secret: 'sdfghjkl2345678tyu',
    unset:'destroy',
    resave: false,
    saveUninitialized: false
}));
</code>```

But when first log in as Admin and open website from another device menu catch user login as Admin. Can I pass session variable to pug template without using global in controller and if yes, how to do that?

答:
First it is very important to use app.use() middleware before the app.router() middleware.

You can try this way in app middleware

```<code>app.use((req, res, next) => {
    res.locals.myVar = 'sample value';
    next();
});
</code>```

To get the value of myVar, in the jade file use

index.jade

```<code>extends layout
block content
    value of myVar is #{myVar}
</code>```

voila!!!

But you might want too change the procedure, you are using right now. This is not a promising and secure way. Try to render the page with appropriate JSON value.

Body:
In express controller after log in to application using this code to redirect to main page:

 req.session.user = user.userLogin;
 if (req.session.user=='Admin') {
    global.loggedAdmin = user.userLogin;
 }
 else {
    global.loggedUser = user.userLogin;
 }
 res.redirect('/');

And in main menu check if user is logged:

nav#menu.panel(role='navigation')
    ul
        li
        if loggedUser
            li
                span.setting Welcome #{loggedUser}
                    a(href='/account')
                        i.fa.fa-cog
            li
                hr
            li
                a(href='/logout') Logout
            li
        else if loggedAdmin
            li
                span.setting Welcome #{loggedAdmin}
                    a(href='/account')
                        i.fa.fa-cog
            li
                hr
            li
                a(href='/articles') Articles
            li
                hr
            li
                a(href='/files') Files
            li
                hr
            li
                a(href='/users') Users
            li
                hr
            li
                a(href='/logout') Logout
        else
            li
                a(href='/login') Log in
            li
                hr
            li
                a(href='/register') Register

And in app.js:

app.use(session({
    secret: 'sdfghjkl2345678tyu',
    unset:'destroy',
    resave: false,
    saveUninitialized: false
}));

But when first log in as Admin and open website from another device menu catch user login as Admin. Can I pass session variable to pug template without using global in controller and if yes, how to do that?

Body:
First it is very important to use app.use() middleware before the app.router() middleware.

You can try this way in app middleware

app.use((req, res, next) => {
    res.locals.myVar = 'sample value';
    next();
});

To get the value of myVar, in the jade file use

index.jade

extends layout
block content
    value of myVar is #{myVar}

voila!!!

But you might want too change the procedure, you are using right now. This is not a promising and secure way. Try to render the page with appropriate JSON value.