问:
Picking a number from a contact but removing the country code
I am able to get the contact phone number on button click then transfer it to an EditText, but I want only to get the result without the country code. Exemple : +33 xx xx xx xxx becomes xx xx xx xxx

Is there  a way I can achieve this?
The following code I use to get the number and put it in an EditText:

Button click:

```<code>Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                editText.setText(phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
Try to use replaceall. For example:
    String phone = cursor.getString(0);
    phone = phone.replaceAll("+33", "");
    editText.setText(phone);

Body:
I am able to get the contact phone number on button click then transfer it to an EditText, but I want only to get the result without the country code. Exemple : +33 xx xx xx xxx becomes xx xx xx xxx

Is there  a way I can achieve this?
The following code I use to get the number and put it in an EditText:

Button click:

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                editText.setText(phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


来源: stackexchange

问:
Update SQL query is not working in Java Swing
Here i made table called sub_master with column sub_id and name,  insertion and deletion working perfectly fine with this, so put those functions here as well to get reference for update function
and i'm using PostgreSQL for this.
In command line UPDATE query is working fine and query as:
UPDATE school_submaster SET name =''  WHERE sub_id = ;</p>

```<code>private void InsertRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "INSERT INTO school_submaster (sub_id, \"name\") VALUES ("+SidInput.getText()+",'"+SnameInput.getText()+"')";
  executeSQlQuery(query, "Inserted");
}

private void UpdateRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "UPDATE school_submaster SET 'name' ='"+SnameInput.getText()+"'+WHERE sub_id = "+SidInput.getText();
  executeSQlQuery(query, "Updated");
}

private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt)
{
    String query = "DELETE FROM school_submaster WHERE sub_id = "+SidInput.getText();
    executeSQlQuery(query, "Deleted");
}
</code>```

答:
Only use single quotes for string and date constants.  Never use single quotes around column names or table names.

Your update is:

```<code>UPDATE school_submaster
    SET 'name' ='<something>'+WHERE sub_id = "+SidInput.getText();
</code>```

This has the additional issue of a + in the query string.  It should look ore like:

```<code>UPDATE school_submaster
    SET name = '<something>'
    WHERE sub_id = "+SidInput.getText();
</code>```

But even that is not true.  You need to learn to use parameters to pass parameters into queries.  The query should be some variant of:

```<code>UPDATE school_submaster
    SET name = ?
    WHERE sub_id = ?
</code>```

Where the ? is a placeholder for a parameter (it might also be @name or something else).

ContentLicense: CC BY-SA 3.0

Body:
Here i made table called sub_master with column sub_id and name,  insertion and deletion working perfectly fine with this, so put those functions here as well to get reference for update function
and i'm using PostgreSQL for this.
In command line UPDATE query is working fine and query as:
UPDATE school_submaster SET name =''  WHERE sub_id = ;

private void InsertRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "INSERT INTO school_submaster (sub_id, \"name\") VALUES ("+SidInput.getText()+",'"+SnameInput.getText()+"')";
  executeSQlQuery(query, "Inserted");
}

private void UpdateRowActionPerformed(java.awt.event.ActionEvent evt)
{
  String query = "UPDATE school_submaster SET 'name' ='"+SnameInput.getText()+"'+WHERE sub_id = "+SidInput.getText();
  executeSQlQuery(query, "Updated");
}

private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt)
{
    String query = "DELETE FROM school_submaster WHERE sub_id = "+SidInput.getText();
    executeSQlQuery(query, "Deleted");
}

Body:
Only use single quotes for string and date constants.  Never use single quotes around column names or table names.

Your update is:

UPDATE school_submaster
    SET 'name' ='<something>'+WHERE sub_id = "+SidInput.getText();

This has the additional issue of a + in the query string.  It should look ore like:

UPDATE school_submaster
    SET name = '<something>'
    WHERE sub_id = "+SidInput.getText();

But even that is not true.  You need to learn to use parameters to pass parameters into queries.  The query should be some variant of:

UPDATE school_submaster
    SET name = ?
    WHERE sub_id = ?

Where the ? is a placeholder for a parameter (it might also be @name or something else).


问:
TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"
I'm trying to setup a new computer to synchronize with my SVN repository that's hosted with cvsdude.com.

I get this error:

![SVN Error][1] - removed image shack image that had been replaced by an advert

Here's what I did (these have worked in the past):

Downloaded and installed TortoiseSVN

Created a new folder C:\aspwebsite

Right-clicked, chose SVN Checkout...

Entered the following information, clicked OK:

URL of repository: -svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://<reponame>-svn.cvsdude.com/aspwebsite

Checkout directory: C:\aspwebsite

Checkout depth: Fully recursive

Omit externals: Unchecked

Revision: HEAD revision

Got TortoiseSVN error:

OPTIONS of '-svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://<reponame>-svn.cvsdude.com/aspwebsite': could not connect to server (-svn.cvsdude.com" rel="nofollow noreferrer">https://<reponame>-svn.cvsdude.com)

Rather than getting the error, TortoiseSVN should have asked for my username and password and then downloaded about 90MB.

Why can't I checkout from my Subversion repository?

Kent Fredric wrote:

Either their security certificate has
  expired, or their hosting is
  broken/down.

Contact CVSDude and ask them whats up.

It could also be a timeout, because
  for me their site is exhaustively
  slow..

It errors after only a couple seconds. I don't think it's a timeout.

Matt wrote:

Try visiting
  https://[redacted]-svn.cvsdude.com/aspwebsite
  and see what happens. If you can visit
  it in your browser, you ought to be
  able to get the files in your SVN
  client and we can work from there. If
  it fails, then there's your answer.

I can access the site in a web browser.

答:
It sounds like you are almost definitely behind a proxy server.

Where this does not work for me behind my proxy:

```<code>svn checkout http://v8.googlecode.com/svn/trunk/ v8-read-only
</code>```

this does:

```<code>svn --config-option servers:global:http-proxy-host=MY_PROXY_HOST --config-option servers:global:http-proxy-port=MY_PROXY_PORT checkout http://v8.googlecode.com/svn/trunk/ v8-read-only
</code>```

UPDATE I forgot to quote my source :-)

http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.1

OwnerDisplayName: Zack

Body:
I'm trying to setup a new computer to synchronize with my SVN repository that's hosted with cvsdude.com.

I get this error:

![SVN Error][1] - removed image shack image that had been replaced by an advert

Here's what I did (these have worked in the past):

Downloaded and installed TortoiseSVN

Created a new folder C:\aspwebsite

Right-clicked, chose SVN Checkout...

Entered the following information, clicked OK:

URL of repository: <a href="https://<reponame>-svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://<reponame>-svn.cvsdude.com/aspwebsite

Checkout directory: C:\aspwebsite

Checkout depth: Fully recursive

Omit externals: Unchecked

Revision: HEAD revision

Got TortoiseSVN error:

OPTIONS of '<a href="https://<reponame>-svn.cvsdude.com/aspwebsite" rel="nofollow noreferrer">https://<reponame>-svn.cvsdude.com/aspwebsite': could not connect to server (<a href="https://<reponame>-svn.cvsdude.com" rel="nofollow noreferrer">https://<reponame>-svn.cvsdude.com)

Rather than getting the error, TortoiseSVN should have asked for my username and password and then downloaded about 90MB.

Why can't I checkout from my Subversion repository?

Kent Fredric wrote:

Either their security certificate has
  expired, or their hosting is
  broken/down.

Contact CVSDude and ask them whats up.

It could also be a timeout, because
  for me their site is exhaustively
  slow..

It errors after only a couple seconds. I don't think it's a timeout.

Matt wrote:

Try visiting
  https://[redacted]-svn.cvsdude.com/aspwebsite
  and see what happens. If you can visit
  it in your browser, you ought to be
  able to get the files in your SVN
  client and we can work from there. If
  it fails, then there's your answer.

I can access the site in a web browser.

LastEditorDisplayName: Zack

Body:
It sounds like you are almost definitely behind a proxy server.

Where this does not work for me behind my proxy:

svn checkout http://v8.googlecode.com/svn/trunk/ v8-read-only

this does:

svn --config-option servers:global:http-proxy-host=MY_PROXY_HOST --config-option servers:global:http-proxy-port=MY_PROXY_PORT checkout http://v8.googlecode.com/svn/trunk/ v8-read-only

UPDATE I forgot to quote my source :-)

http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.1

ContentLicense: CC BY-SA 2.5


问:
FXML TableView "Class fxmlPerson does not support property "bestellnr"
So I'm currently trying to implement a GUI for an online-shop (assignment for university) and I'm stuck at the table which lists all current orders.
The GUI is based on an FXML-Application.
My TableView is as follows:

```<code><TableView fx:id="tableView" prefHeight="400.0" prefWidth="1250.0" GridPane.columnIndex="0" GridPane.rowIndex="1">
   <columns>
      <TableColumn text="Bestellnr.">
         <cellValueFactory>
            <PropertyValueFactory property="bestellnr" />
         </cellValueFactory>
      </TableColumn>
[7 more columns like that, but with different properties]
   </columns>
   <items>
      <FXCollections fx:factory="observableArrayList">
         <Person bestellnr="0001" kundennr="0000" kundenname="John Smith" summe="1000" lieferstatus="gesendet" bestelldatum="03.12.1291" liefertermin="05.12.1291" bezahlt="yes" />
      </FXCollections>
   </items>
</TableView>
</code>```

The properties of the class "Person" are SimpleStringProperties

```<code>    private final SimpleStringProperty bestellnr = new SimpleStringProperty("");
    private final SimpleStringProperty kundennr = new SimpleStringProperty("");
    private final SimpleStringProperty kundenname = new SimpleStringProperty("");
    private final SimpleStringProperty summe = new SimpleStringProperty("");
    private final SimpleStringProperty lieferstatus = new SimpleStringProperty("");
    private final SimpleStringProperty bestelldatum = new SimpleStringProperty("");
    private final SimpleStringProperty liefertermin = new SimpleStringProperty("");
    private final SimpleStringProperty bezahlt = new SimpleStringProperty("");
</code>```

I also added getter- and setter-methods to these SimpleStringProperties:

```<code>   public String getBestellNr() {
        return bestellnr.get();
    }

    public void setBestellNr(String fName) {
        bestellnr.set(fName);
    }

    public String getKundenNr() {
        return kundennr.get();
    }

    public void setKundenNr(String fName) {
        kundennr.set(fName);
    }

    public String getKundenName() {
        return kundenname.get();
    }

    public void setKundenName(String fName) {
        kundenname.set(fName);
    }

    public String getSumme() {
        return summe.get();
    }

    public void setSumme(String fName) {
        summe.set(fName);
    }

    public String getLieferStatus() {
        return lieferstatus.get();
    }

    public void setLieferStatus(String fName) {
        lieferstatus.set(fName);
    }

    public String getBestellDatum() {
        return bestelldatum.get();
    }

    public void setBestellDatum(String fName) {
        bestelldatum.set(fName);
    }

    public String getLieferTermin() {
        return liefertermin.get();
    }

    public void setLieferTermin(String fName) {
        liefertermin.set(fName);
    }

    public String getBezahlt() {
        return bezahlt.get();
    }

    public void setBezahlt(String fName) {
        bezahlt.set(fName);
    }
</code>```

Now everytime I try to run the project, I get the error "Class fxmlPerson does not support property "bestellnr".

I based this program on this tutorial: http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm and it works. But as soon as I start adding the additional columns I get this error.

Thanks in advance for your help!

答:
The property names being used in your FXML file do not match the method names of your getters and setters.

A property with name bestellnr must correspond to methods with names getBestellnr and setBestellnr.  Your methods have names getBestellNr and setBestellNr.  The capitalisation of the letter N is the difference.

To get from a property name to a getter or setter method name, you capitalise the first letter and put get or set on the front.

Change the property bestellnr in your FXML to bestellNr, or change your getter and setter methods to getBestellnr and setBestellnr.  Repeat this process for other properties where the property names and method names don't match.

Body:
So I'm currently trying to implement a GUI for an online-shop (assignment for university) and I'm stuck at the table which lists all current orders.
The GUI is based on an FXML-Application.
My TableView is as follows:

<TableView fx:id="tableView" prefHeight="400.0" prefWidth="1250.0" GridPane.columnIndex="0" GridPane.rowIndex="1">
   <columns>
      <TableColumn text="Bestellnr.">
         <cellValueFactory>
            <PropertyValueFactory property="bestellnr" />
         </cellValueFactory>
      </TableColumn>
[7 more columns like that, but with different properties]
   </columns>
   <items>
      <FXCollections fx:factory="observableArrayList">
         <Person bestellnr="0001" kundennr="0000" kundenname="John Smith" summe="1000" lieferstatus="gesendet" bestelldatum="03.12.1291" liefertermin="05.12.1291" bezahlt="yes" />
      </FXCollections>
   </items>
</TableView>

The properties of the class "Person" are SimpleStringProperties

    private final SimpleStringProperty bestellnr = new SimpleStringProperty("");
    private final SimpleStringProperty kundennr = new SimpleStringProperty("");
    private final SimpleStringProperty kundenname = new SimpleStringProperty("");
    private final SimpleStringProperty summe = new SimpleStringProperty("");
    private final SimpleStringProperty lieferstatus = new SimpleStringProperty("");
    private final SimpleStringProperty bestelldatum = new SimpleStringProperty("");
    private final SimpleStringProperty liefertermin = new SimpleStringProperty("");
    private final SimpleStringProperty bezahlt = new SimpleStringProperty("");

I also added getter- and setter-methods to these SimpleStringProperties:

   public String getBestellNr() {
        return bestellnr.get();
    }

    public void setBestellNr(String fName) {
        bestellnr.set(fName);
    }

    public String getKundenNr() {
        return kundennr.get();
    }

    public void setKundenNr(String fName) {
        kundennr.set(fName);
    }

    public String getKundenName() {
        return kundenname.get();
    }

    public void setKundenName(String fName) {
        kundenname.set(fName);
    }

    public String getSumme() {
        return summe.get();
    }

    public void setSumme(String fName) {
        summe.set(fName);
    }

    public String getLieferStatus() {
        return lieferstatus.get();
    }

    public void setLieferStatus(String fName) {
        lieferstatus.set(fName);
    }

    public String getBestellDatum() {
        return bestelldatum.get();
    }

    public void setBestellDatum(String fName) {
        bestelldatum.set(fName);
    }

    public String getLieferTermin() {
        return liefertermin.get();
    }

    public void setLieferTermin(String fName) {
        liefertermin.set(fName);
    }

    public String getBezahlt() {
        return bezahlt.get();
    }

    public void setBezahlt(String fName) {
        bezahlt.set(fName);
    }

Now everytime I try to run the project, I get the error "Class fxmlPerson does not support property "bestellnr".

I based this program on this tutorial: http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm and it works. But as soon as I start adding the additional columns I get this error.

Thanks in advance for your help!


问:
VB.net 2010 - IndexOutOfRange from datagridview when refreshing dataset
I have a datagridview on a form that is bound to a table in a dataset from another class.

I use a data adapter to .Fill a table in that dataset and the grid displays the data fine.

Works fine.

On my form I have a textbox the user can type in that will will pass a parameter to the storedprocedure used to fill this table.   So on startup the textbox will have "%" in it.  and then the user can type in "F%" and get everything that starts with an "F"

So when that textbox changes I launch an async refresh (.BeginInvoke) to do my refresh.  The table gets populated with the reduced number of records (I check ds.table(0).rows.count and it is correct)

But the datagridview then starts throwing datagridview.dataerror events.  "System.IndexOutofRangeException : Index # does not have a value"

It looks like the dataset is getting filled correctly and not having any issues, but the datagrid is not liking this update.  The index out of range error is so common that I'm not finding what I need through searches.

Thanks in advance!  :)

答:
I had a similar problem and it was because I wanted to do this:

dg1.CurrentCell = dg1.Rows(dg1.RowCount - 1).Cells(1)

after changing dg1.DataSource.

It seems to be dangerous to use RowCount when AllowUserToAddRows = True.

I switched it to False and it worked.


问:
How to convert PowerPoint (.ppt, .pptx) to several images of each slide?
Do you guys have some .Net libraries which has ability to convert a PowerPoint Presentation file into images?</p>

答:
Using add reference to  Microsoft.Office.Interop.PowerPoint.dll. To convert PowerPoint slides to PNG images:

PowerPoint.Presentation pptPresentation = pptApplication.Presentations.Open2007(FILE);
foreach (PowerPoint.Slide pptSlide in pptPresentation.Slides)
{
   pptSlide.Export(NEWNAME, "PNG", 1024, 768);
}
```


问:
How to send (AJAX) POST data to url and redirect to the same url with data?
```<code>jQuery(".w").click(function() {
    var id =jQuery(this).attr('id');

    var location="http://localhost:8888/Admin/description/description.php";
    $.ajax({
        url: location,
        type:'POST',
        data:{data:id}
    });
});
</code>```

I want to redirect to location along with data, can't use form in my case

答:
    $(".w").click(function(){
           var id =jQuery(this).attr('id');
    var location="http://localhost:8888/Admin/description/description.php";
    $.ajax({
    url: location,
    type:'POST',
    data:{data:id},
    success: function(data){
    alert(data.data);
    }
    });
    });```

add the success attribute of ajax

Body:
jQuery(".w").click(function() {
    var id =jQuery(this).attr('id');

    var location="http://localhost:8888/Admin/description/description.php";
    $.ajax({
        url: location,
        type:'POST',
        data:{data:id}
    });
});

I want to redirect to location along with data, can't use form in my case

Body:
    $(".w").click(function(){
           var id =jQuery(this).attr('id');
    var location="http://localhost:8888/Admin/description/description.php";
    $.ajax({
    url: location,
    type:'POST',
    data:{data:id},
    success: function(data){
    alert(data.data);
    }
    });
    });

add the success attribute of ajax


问:
android widget as async task
sorry for question which was many time answered but for me is still now working :-(

I have following activiy code:

```<code>public class WidgetProvider extends AppWidgetProvider {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int count = appWidgetIds.length;

    for (int i = 0; i < count; i++) {
        int widgetId = appWidgetIds[i];

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.simple_widget);

        Intent intent = new Intent(context, SimpleWidgetProvider.class);
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        new Weather(remoteViews).execute();
        remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
    }
}
</code>```

}

with Async Weather class but this doesn't work. Value is missing in remoteViews.

```<code>class Weather extends AsyncTask<Void, String, String> {

private RemoteViews remoteViews ;

public Weather(RemoteViews remoteViews) {
    this.remoteViews = remoteViews;
}

@Override
protected String doInBackground(Void... arg0) {
  return "COLD";
}

@Override
protected void onPostExecute(String temp) {
    remoteViews.setTextViewText(R.id.textView, temp);
}
</code>```

答:
Whatever RemoteViews that you pass to updateAppWidget() will be used at that time. In your case, your Weather task will not even begin to be executed by the time that the RemoteViews has been used, and so your change to that RemoteViews will be pointless.

Instead:

Switch to Thread, as there is no value in using AsyncTask here, and

Do all the work for a given widget ID, including calling updateAppWidget(), in the Thread

Title: android widget as async task

Body:
sorry for question which was many time answered but for me is still now working :-(

I have following activiy code:

public class WidgetProvider extends AppWidgetProvider {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int count = appWidgetIds.length;

    for (int i = 0; i < count; i++) {
        int widgetId = appWidgetIds[i];

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.simple_widget);

        Intent intent = new Intent(context, SimpleWidgetProvider.class);
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        new Weather(remoteViews).execute();
        remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
    }
}

}

with Async Weather class but this doesn't work. Value is missing in remoteViews.

class Weather extends AsyncTask<Void, String, String> {

private RemoteViews remoteViews ;

public Weather(RemoteViews remoteViews) {
    this.remoteViews = remoteViews;
}

@Override
protected String doInBackground(Void... arg0) {
  return "COLD";
}

@Override
protected void onPostExecute(String temp) {
    remoteViews.setTextViewText(R.id.textView, temp);
}


问:
Reliably jumping to named anchor on dynamically generated page?
I have a web page which is dynamically built by the client.  It generates dozens of list items each with its own named anchor.  The side of the page has a fixed table of contents (TOC) with hyperlinks that point to the named anchors.  This allows the user to click a TOC entry a jump to the item.

The trouble I am encountering is that on the initial page load the page is dynamically generated and so it cannot scroll to the item in the initial hash of the URL using the default behavior of a browser.  Additionally, when the user switches to a different book the page is completely regenerated with new content and a new starting hash.  Same problem: since the hash preexists the content, it doesn't situate itself with the item already in view.

I nearly solved this with JavaScript by awaiting the rendering and then jumping to the hash using scrollIntoView method on the appropriate element.

The next problem is that the stylesheet is not fully applied by the time scrollIntoView is called and so the final position of the item is unknown.  I see the unstyled item scroll into view, but once styling is applied the positioning is lost.  I put a 1 second setTimeout in place to delay the scrollIntoView call.  This works but feels fragile.

Are there reliable techniques for jumping to a named anchor when the content comes after the hash is in place?  If I knew when the CSS was done styling content that might help.  Alternately, it might be useful to trigger an event once the height of the page stabilizes (thus signaling the finalization of CSS styling).

答:
I had a similar problem, although in my case only the table of contents and named anchors were autogenerated in the onload handler - not the rest of the page content. I solved the initial hash problem by adding the following code to my onload handler after generating the anchors:

```<code>if (location.hash)
{
    var requested_hash = location.hash.slice(1);
    location.hash = '';
    location.hash = requested_hash;
}
</code>```

I had to set the hash to '' before setting it back to the requested name to make the browser respond. This seemed to work in all the browsers I tried (Opera, Chrome, Edge, IE, FF).

Body:
I had a similar problem, although in my case only the table of contents and named anchors were autogenerated in the onload handler - not the rest of the page content. I solved the initial hash problem by adding the following code to my onload handler after generating the anchors:

if (location.hash)
{
    var requested_hash = location.hash.slice(1);
    location.hash = '';
    location.hash = requested_hash;
}

I had to set the hash to '' before setting it back to the requested name to make the browser respond. This seemed to work in all the browsers I tried (Opera, Chrome, Edge, IE, FF).


问:
For comma-separated
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

```<code>boy, man,girl, woman,tyrannosaurus rex, lion
</code>```

And these would be invalid tags:

```<code>hat, cat, rat, c3po, @gmail
</code>```

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

答:
Try something like this:

```<code>var re = /^(\w+,? ?)+$/;
var str1 = "boy, man,girl, woman,tyrannosaurus rex, lion";
var str2 = "hat, cat, rat, c3po, @gmail";
alert(str1.test(re));  // true
alert(str2.test(re));  // false
</code>```

Breaking it down... \w matches word characters, \w+ matches 1 or more word characters. ,? ? matches optional comma and space. (Two commas would be rejected.) The ()+ around everything says one or more times. Lastly ^ and $ anchors it to the beginning and end of the string to make sure everything is matched.

Title: For comma-separated

Body:
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

boy, man,girl, woman,tyrannosaurus rex, lion

And these would be invalid tags:

hat, cat, rat, c3po, @gmail

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

Body:
Try something like this:

var re = /^(\w+,? ?)+$/;
var str1 = "boy, man,girl, woman,tyrannosaurus rex, lion";
var str2 = "hat, cat, rat, c3po, @gmail";
alert(str1.test(re));  // true
alert(str2.test(re));  // false

Breaking it down... \w matches word characters, \w+ matches 1 or more word characters. ,? ? matches optional comma and space. (Two commas would be rejected.) The ()+ around everything says one or more times. Lastly ^ and $ anchors it to the beginning and end of the string to make sure everything is matched.


问:
DeepLinkDispatch - incompatible types: List<Object> cannot be converted to List<DeepLinkEntry>
Following the tutorial on the github page I have:

added to my project's parent build.gradle:

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' <---

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
</code>```

added to my app's build.gradle:

```<code>apply plugin: 'com.neenbedankt.android-apt'

...

compile 'com.airbnb:deeplinkdispatch:3.0.0'
apt 'com.airbnb:deeplinkdispatch-processor:3.0.0'
</code>```

Created a module class and annotated it:

```<code>@DeepLinkModule
public class AppDeepLinkModule
{

}
</code>```

Now when I try to build, it displays the above error message:

```<code>Error:(12, 82) error: incompatible types: List<Object> cannot be converted to List<DeepLinkEntry>
</code>```

It then points me towards this class which is autogenerated:

```<code>public final class AppDeepLinkModuleLoader implements Parser {
  public static final List<DeepLinkEntry> REGISTRY = Collections.unmodifiableList(Arrays.asList(
  )); <-- this line here

  @Override
  public DeepLinkEntry parseUri(String uri) {
    for (DeepLinkEntry entry : REGISTRY) {
      if (entry.matches(uri)) {
        return entry;
      }
    }
    return null;
  }
}
</code>```

I've referred to their sample app and mine seems identical. Here is a link to their class which does the same thing.

I completed further steps until I need to use the autogenerated class in case this was the issue but this didn't fix things either. AndroidManifest.xml:

```<code><activity
        android:name=".deeplink.DeepLinkActivity"
        android:theme="@android:style/Theme.NoDisplay">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:host="slackwebsocket"
                android:scheme="http"/>
        </intent-filter>
    </activity>
</code>```

DeepLinkActivity:

```<code>@DeepLinkHandler({AppDeepLinkModule.class})
public class DeepLinkActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }
}
</code>```

How do I fix this?

答:
Have you tried a simple cast?

(List<DeepLinkEntry>)

I mean
public static final List<DeepLinkEntry> REGISTRY = (List<DeepLinkEntry>) Collections.unmodifiableList(Arrays.asList(
  )); <-- this line here

Body:
Following the tutorial on the github page I have:

added to my project's parent build.gradle:

dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' <---

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

added to my app's build.gradle:

apply plugin: 'com.neenbedankt.android-apt'

...

compile 'com.airbnb:deeplinkdispatch:3.0.0'
apt 'com.airbnb:deeplinkdispatch-processor:3.0.0'

Created a module class and annotated it:

@DeepLinkModule
public class AppDeepLinkModule
{

}

Now when I try to build, it displays the above error message:

Error:(12, 82) error: incompatible types: List<Object> cannot be converted to List<DeepLinkEntry>

It then points me towards this class which is autogenerated:

public final class AppDeepLinkModuleLoader implements Parser {
  public static final List<DeepLinkEntry> REGISTRY = Collections.unmodifiableList(Arrays.asList(
  )); <-- this line here

  @Override
  public DeepLinkEntry parseUri(String uri) {
    for (DeepLinkEntry entry : REGISTRY) {
      if (entry.matches(uri)) {
        return entry;
      }
    }
    return null;
  }
}

I've referred to their sample app and mine seems identical. Here is a link to their class which does the same thing.

I completed further steps until I need to use the autogenerated class in case this was the issue but this didn't fix things either. AndroidManifest.xml:

<activity
        android:name=".deeplink.DeepLinkActivity"
        android:theme="@android:style/Theme.NoDisplay">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:host="slackwebsocket"
                android:scheme="http"/>
        </intent-filter>
    </activity>

DeepLinkActivity:

@DeepLinkHandler({AppDeepLinkModule.class})
public class DeepLinkActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }
}

How do I fix this?


问:
using friendly id with includes and where
I was using this query to fetch a property with nested resources

```<code>@property=Property.includes(rooms: [:photos]).where(id: params[:id]).first
</code>```

The above works. But now I want to use friendly_id. So I tried     @property=Property.includes(rooms: [:photos]).friendly.where(id: params[:id]).first which didnt work. All docs for friendly_id uses find instead of where but here how can I make it work?

答:
You can just filter on the column you use for the friendly_id, usually named slug

```<code>Property.includes(roomes: [:photos]).where(slug: params[:id]).first
</code>```

Body:
I was using this query to fetch a property with nested resources

@property=Property.includes(rooms: [:photos]).where(id: params[:id]).first

The above works. But now I want to use friendly_id. So I tried     @property=Property.includes(rooms: [:photos]).friendly.where(id: params[:id]).first which didnt work. All docs for friendly_id uses find instead of where but here how can I make it work?

Body:
You can just filter on the column you use for the friendly_id, usually named slug

Property.includes(roomes: [:photos]).where(slug: params[:id]).first


问:
Need help in URL rewriting sub-domains
I recently registered a domain name kbcsurveyors.com. Then, I created two sub-domains, which created two new folders in the root folder.

My motive is that if I type kbcsurveyors.com/preinspection, it should point to preinspection.kbcsurveyors.com. Same for other sub domains.

In my .htaccess, which I placed inside root of mydomainname.com, I have written following lines:

```<code>RewriteEngine  On
RewriteBase /
RewriteRule ^preinspection/(.*)$          https://kbcsurveyors.com/$1 [L,NC,QSA]    # Handle requests for "Preinspection"
</code>```

But this file structure does not work. How do I write the .htaccess file to achieve what I want?

Regards

EDIT

I have asked a fresh question as this one has been messed up. Here is the link:How to rewrite rules for sub-domains

答:
```<code>RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^sub-domain1.mydomainname.com
RewriteRule ^(.*)$ http://mydomainname.com/$1 [L,NC,QSA]
</code>```

Title: Need help in URL rewriting sub-domains

Body:
I recently registered a domain name kbcsurveyors.com. Then, I created two sub-domains, which created two new folders in the root folder.

My motive is that if I type kbcsurveyors.com/preinspection, it should point to preinspection.kbcsurveyors.com. Same for other sub domains.

In my .htaccess, which I placed inside root of mydomainname.com, I have written following lines:

RewriteEngine  On
RewriteBase /
RewriteRule ^preinspection/(.*)$          https://kbcsurveyors.com/$1 [L,NC,QSA]    # Handle requests for "Preinspection"

But this file structure does not work. How do I write the .htaccess file to achieve what I want?

Regards

EDIT

I have asked a fresh question as this one has been messed up. Here is the link:How to rewrite rules for sub-domains


问:
Sticky an animated navbar once scrolled past a certain point
I am trying to sticky an animated navbar to the top of the page once the user scrolls past a certain part. (there are many examples on here, but I couldn't make any work).

I want to add javascript without using bootstrap, without making it conflict with the existing onscroll animation, and without nesting the entire page in that navbar's own div.

Do I use Javascript or is there a method with CSS?

https://jsfiddle.net/p9xfy79x/2/

```<code>window.onscroll = function() {
  myFunction()
};
function myFunction() {
  var navbar = document.getElementById("myNavbar");
  if (document.body.scrollTop > 85 || document.documentElement.scrollTop > 100) {
    navbar.className = " bar" + " card" + " animate-top" + " white";
  } else {
    navbar.className = navbar.className.replace(" card animate-top white", "");
  }
}
</code>```

答:
Your CSS selector .animate-top is the one causing the problem here. The main issue is that its setting the inner div of your nav to relative. Just change your css selector to the following and it should fix your issue:

```<code>.animate-top {
  position: fixed;
  top:0;
  animation: animatetop 0.4s
}
</code>```

Working example here: https://jsfiddle.net/7ze2fukk/

Hope this helps. Cheers.

Body:
I am trying to sticky an animated navbar to the top of the page once the user scrolls past a certain part. (there are many examples on here, but I couldn't make any work).

I want to add javascript without using bootstrap, without making it conflict with the existing onscroll animation, and without nesting the entire page in that navbar's own div.

Do I use Javascript or is there a method with CSS?

https://jsfiddle.net/p9xfy79x/2/

window.onscroll = function() {
  myFunction()
};
function myFunction() {
  var navbar = document.getElementById("myNavbar");
  if (document.body.scrollTop > 85 || document.documentElement.scrollTop > 100) {
    navbar.className = " bar" + " card" + " animate-top" + " white";
  } else {
    navbar.className = navbar.className.replace(" card animate-top white", "");
  }
}

Body:
Your CSS selector .animate-top is the one causing the problem here. The main issue is that its setting the inner div of your nav to relative. Just change your css selector to the following and it should fix your issue:

.animate-top {
  position: fixed;
  top:0;
  animation: animatetop 0.4s
}

Working example here: https://jsfiddle.net/7ze2fukk/

Hope this helps. Cheers.


问:
CSS: 3 divs - Resizing 2 outer divs automatically based on width of inner div/text
My problem is best outlined with this schematic/image which outlines how I want it to look:

!

I have a background image and 2 divs for text over the top of it (headline, and intro-text). I also have 2 divs on either side of the headline - these are for the white horizontal stripes.

My issue is that the headline is changeable in a CMS, and I want the horizontal white stripes to automatically fill up the space to the left and to the right of it, regardless of the headline's width.

I can't figure out how to make those 2 horizontal white stripes resize automatically.

Here's my HTML:

```<code><div id="masthead">
<div id="headline-container">
    <div id="left-stripe"> </div><div id="headline">{headline}</div><div id="right-stripe"> </div>
</div>
<div class="clear-both"> </div>
<div id="intro-text">{intro_text}</div>
</div>
</code>```

And here's my CSS - ignore the widths specified for the left-stripe and right-stripe - they're just placeholders:

```<code>#masthead {
    height: 260px;
}

div#headline-container {
    width:960px;
    padding:none;
}
div#left-stripe{
    float: left;
    background-color:#fff;
    height: 3px;
    width:500px;
    display: inline;
}
div#right-stripe{
    float: right;
    background-color:#fff;
    height: 3px;
    width:100px;
    display: inline;
}
div#headline {
    text-align:right;
    color: #fff;
    font-size: 200%;
    float: left;
    display: inline;
}
div#intro-text {
    text-align: left;
    float: right;
    width: 300px;
    color: #fff;
}
</code>```

Ideas? Please let me know if I can provide more detail.

答:
You can do this dynamically, with jQuery, for example. You take the full width of the 3 div's, drop the size of the inner div and assign dynamically the widths of the 2 outer div's in which the bar should repeat horizontally.

Basically, you will need:
$("#whole-div").width() - $("#inner-div").width() for the outer div's total width. Then, depending on your positioning of the inner-div, you assign values for the outer div's.
For example: whole div has 1000px, inner div has 200px and inner div is positioned 600px left. You will then assign 600px to the left div ($("#whole-div").width() - $("#inner-div").css('left')) and 200px for the right div ($("#whole-div").width() - $("#inner-div").css('left') - $("#inner-div").width()). Of course, you will then set a background-repeat property on the outer div so that the image repeats.

Hope that helps!

ContentLicense: CC BY-SA 4.0

Body:
My problem is best outlined with this schematic/image which outlines how I want it to look:

!

I have a background image and 2 divs for text over the top of it (headline, and intro-text). I also have 2 divs on either side of the headline - these are for the white horizontal stripes.

My issue is that the headline is changeable in a CMS, and I want the horizontal white stripes to automatically fill up the space to the left and to the right of it, regardless of the headline's width.

I can't figure out how to make those 2 horizontal white stripes resize automatically.

Here's my HTML:

{headline}

{intro_text}

And here's my CSS - ignore the widths specified for the left-stripe and right-stripe - they're just placeholders:

#masthead {
    height: 260px;
}

div#headline-container {
    width:960px;
    padding:none;
}
div#left-stripe{
    float: left;
    background-color:#fff;
    height: 3px;
    width:500px;
    display: inline;
}
div#right-stripe{
    float: right;
    background-color:#fff;
    height: 3px;
    width:100px;
    display: inline;
}
div#headline {
    text-align:right;
    color: #fff;
    font-size: 200%;
    float: left;
    display: inline;
}
div#intro-text {
    text-align: left;
    float: right;
    width: 300px;
    color: #fff;
}

Ideas? Please let me know if I can provide more detail.


问:
How to put Items into DynamoDB table using python?
I'm trying to put an Item into an Amazon DynamoDB table using a python script, but when I run the python script I get following error:

```<code>Traceback (most recent call last):
  File "./table.py", line 32, in <module>
    item.put(None, None)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/item.py", line 183, in put
    return self.table.layer2.put_item(self, expected_value, return_values)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer2.py", line 551, in put_item
    object_hook=self.dynamizer.decode)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer1.py", line 384, in put_item
    object_hook=object_hook)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer1.py", line 119, in make_request
    retry_handler=self._retry_handler)
  File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 954, in _mexe
    status = retry_handler(response, i, next_sleep)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer1.py", line 159, in _retry_handler
    data)
boto.exception.DynamoDBResponseError: DynamoDBResponseError: 400 Bad Request
{u'message': u'Requested resource not found', u'__type': u'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'}
</code>```

My code is:

```<code>#!/usr/bin/python

import boto
import boto.s3
import sys

from boto import dynamodb2
from boto.dynamodb2.table import Table
from boto.s3.key import Key
import boto.dynamodb

conn = boto.dynamodb.connect_to_region('us-west-2', aws_access_key_id=<My_access_key>, aws_secret_access_key=<my_secret_key>)

entity = conn.create_schema(hash_key_name='RPI_ID', hash_key_proto_value=str, range_key_name='PIC_ID', range_key_proto_value=str)
table = conn.create_table(name='tblSensor', schema=entity, read_units=10, write_units=10)

item_data = {
        'Pic_id': 'P100',
        'RId': 'R100',
        'Temperature': '28.50'
    }
item = table.new_item(
        # Our hash key is 'forum'
        hash_key='RPI_ID',
        # Our range key is 'subject'
        range_key='PIC_ID',
        # This has the
        attrs=item_data
    )

item.put() // I got error here.
</code>```

My reference is: Setting/Getting/Deleting CORS Configuration on a Bucket

答: I searched on google and solved my that problem. I have set correct time and date on my raspberry pi board and run that program, it's working fine.

Body:
I'm trying to put an Item into an Amazon DynamoDB table using a python script, but when I run the python script I get following error:

Traceback (most recent call last):
  File "./table.py", line 32, in <module>
    item.put(None, None)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/item.py", line 183, in put
    return self.table.layer2.put_item(self, expected_value, return_values)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer2.py", line 551, in put_item
    object_hook=self.dynamizer.decode)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer1.py", line 384, in put_item
    object_hook=object_hook)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer1.py", line 119, in make_request
    retry_handler=self._retry_handler)
  File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 954, in _mexe
    status = retry_handler(response, i, next_sleep)
  File "/usr/local/lib/python2.7/dist-packages/boto/dynamodb/layer1.py", line 159, in _retry_handler
    data)
boto.exception.DynamoDBResponseError: DynamoDBResponseError: 400 Bad Request
{u'message': u'Requested resource not found', u'__type': u'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException'}

My code is:

#!/usr/bin/python

import boto
import boto.s3
import sys

from boto import dynamodb2
from boto.dynamodb2.table import Table
from boto.s3.key import Key
import boto.dynamodb

conn = boto.dynamodb.connect_to_region('us-west-2', aws_access_key_id=<My_access_key>, aws_secret_access_key=<my_secret_key>)

entity = conn.create_schema(hash_key_name='RPI_ID', hash_key_proto_value=str, range_key_name='PIC_ID', range_key_proto_value=str)
table = conn.create_table(name='tblSensor', schema=entity, read_units=10, write_units=10)

item_data = {
        'Pic_id': 'P100',
        'RId': 'R100',
        'Temperature': '28.50'
    }
item = table.new_item(
        # Our hash key is 'forum'
        hash_key='RPI_ID',
        # Our range key is 'subject'
        range_key='PIC_ID',
        # This has the
        attrs=item_data
    )

item.put() // I got error here.

My reference is: Setting/Getting/Deleting CORS Configuration on a Bucket


问:
Upload a file from the Internet directly to a remote host through WinSCP
Is there a way to directly upload a file (with an Internet address) to a Linux machine using WinSCP? I don't want to download to my local machine, and then upload  to the Linux server - I will like to do download directly: Internet -> Linux machine.

I already tried wget and curl -O, but the downloaded file is complete, so I am trying other methods like WinSCP.

```<code>>  wget https://www.kaggle.com/c/data-science-bowl-2017/download/stage1_labels.csv.zip
> --2017-04-01 17:22:04--  https://www.kaggle.com/c/data-science-bowl-2017/download/stage1_labels.csv.zip
> Resolving www.kaggle.com (www.kaggle.com)... 168.62.224.124 Connecting
> to www.kaggle.com (www.kaggle.com)|168.62.224.124|:443... connected.
> HTTP request sent, awaiting response... 302 Found Location:
> /account/login?ReturnUrl=%2fc%2fdata-science-bowl-2017%2fdownload%2fstage1_labels.csv.zip
> [following]
> --2017-04-01 17:22:05--  https://www.kaggle.com/account/login?ReturnUrl=%2fc%2fdata-science-bowl-2017%2fdownload%2fstage1_labels.csv.zip
> Reusing existing connection to www.kaggle.com:443. HTTP request sent,
> awaiting response... 200 OK Length: 15671 (15K) [text/html] Saving to:
> ‘stage1_labels.csv.zip’
>
> 100%[=================================================================================>] 15,671      --.-K/s   in 0.03s
>
> 2017-04-01 17:22:05 (441 KB/s) - ‘stage1_labels.csv.zip’ saved
> [15671/15671]
</code>```

The target file is 67 GB in size.

答: Connect to the other machine where you want to download the file using ssh and run the wget there. It will get transfered only once using the HTTPS protocol (which is fast). SFTP is generally very slow.

Body:
Is there a way to directly upload a file (with an Internet address) to a Linux machine using WinSCP? I don't want to download to my local machine, and then upload  to the Linux server - I will like to do download directly: Internet -> Linux machine.

I already tried wget and curl -O, but the downloaded file is complete, so I am trying other methods like WinSCP.

>  wget https://www.kaggle.com/c/data-science-bowl-2017/download/stage1_labels.csv.zip
> --2017-04-01 17:22:04--  https://www.kaggle.com/c/data-science-bowl-2017/download/stage1_labels.csv.zip
> Resolving www.kaggle.com (www.kaggle.com)... 168.62.224.124 Connecting
> to www.kaggle.com (www.kaggle.com)|168.62.224.124|:443... connected.
> HTTP request sent, awaiting response... 302 Found Location:
> /account/login?ReturnUrl=%2fc%2fdata-science-bowl-2017%2fdownload%2fstage1_labels.csv.zip
> [following]
> --2017-04-01 17:22:05--  https://www.kaggle.com/account/login?ReturnUrl=%2fc%2fdata-science-bowl-2017%2fdownload%2fstage1_labels.csv.zip
> Reusing existing connection to www.kaggle.com:443. HTTP request sent,
> awaiting response... 200 OK Length: 15671 (15K) [text/html] Saving to:
> ‘stage1_labels.csv.zip’
>
> 100%[=================================================================================>] 15,671      --.-K/s   in 0.03s
>
> 2017-04-01 17:22:05 (441 KB/s) - ‘stage1_labels.csv.zip’ saved
> [15671/15671]

The target file is 67 GB in size.


问:
Why does my original array gets changed when i only change copied array?
here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

```<code>public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    }
}
</code>```

thanks for your time

答: You haven't copied the array, you've only copied a reference to the array. Both variables are referring to the same array. See this question to make a deep copy of the array: How do I do a deep copy of a 2D array in Java?</p>

Body:
here i want to make duplicate array "arr" for my tile array and make some changes to it, the problem is when i make the changes (in method neighbors) it applies to the original array "tiles" too

public class Board {
    private final int [][] tiles;
    // construct a board from an n-by-n array of blocks
    // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks) {
        tiles = blocks;
    }// all neighboring boards
    public Iterable<Board> neighbors() {
        Queue<Board> q = new LinkedList<>();
        int [][] arr = tiles;
        // do stuff
        if (y+1 < n) {
            int t = arr[x][y];
            arr[x][y] = arr[x][y+1];
            arr[x][y+1] = t;
            Board br = new Board(arr);
            if(!this.equals(br)) {
                q.add(new Board(arr));
            }
        }
        return q;
    }
}

thanks for your time


问:
Building an NSstring out of an NSMutableArray
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?</p>

```<code>  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: %@ ", ans);
    }
</code>```

答:
I think you mean

```<code>ans = [ans stringByAppendingString:(NSString *)obj];
</code>```

not just

```<code>[ans stringByAppendingString:(NSString *)obj];
</code>```

NSStrings are immutable -- you can't append to them. -stringByAppendingString: returns a new string (which you could then assign to ans).

Alternatively, you might use an NSMutableString and the -appendString: method.

Body:
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?

  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: %@ ", ans);
    }

Body:
I think you mean

ans = [ans stringByAppendingString:(NSString *)obj];

not just

[ans stringByAppendingString:(NSString *)obj];

NSStrings are immutable -- you can't append to them. -stringByAppendingString: returns a new string (which you could then assign to ans).

Alternatively, you might use an NSMutableString and the -appendString: method.


问:
Error In PHP5 ..Unable to load dynamic library
```<code>root@ip-10-131-9-200:/etc/php5/apache2# php -a
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/curl.so' - /usr/lib/php5/20090626+lfs/curl.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/mcrypt.so' - /usr/lib/php5/20090626+lfs/mcrypt.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/mysql.so' - /usr/lib/php5/20090626+lfs/mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/mysqli.so' - /usr/lib/php5/20090626+lfs/mysqli.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/pdo.so' - /usr/lib/php5/20090626+lfs/pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/pdo_mysql.so' - /usr/lib/php5/20090626+lfs/pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
Interactive shell
</code>```

答:
I had a similar problem, which led me here:

```<code>$ phpunit --version
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20131226/profiler.so' - /usr/lib/php5/20131226/profiler.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
</code>```

Unlike the above, installing the software did not resolve my problem because I already had it.

```<code>$ sudo apt-get install php5-uprofiler
Reading package lists... Done
Building dependency tree
Reading state information... Done
php5-uprofiler is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 52 not upgraded.
</code>```

I found my solution via : Debian Bug report logs

```<code>$ sudo vim /etc/php5/mods-available/uprofiler.ini
</code>```

I edited the ini file, changing extension=profiler.so to extension=uprofiler.so .... the result, happily:

```<code>$ phpunit --version
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
</code>```

i.e. no more warning.

Body:
I had a similar problem, which led me here:

$ phpunit --version
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20131226/profiler.so' - /usr/lib/php5/20131226/profiler.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.

Unlike the above, installing the software did not resolve my problem because I already had it.

$ sudo apt-get install php5-uprofiler
Reading package lists... Done
Building dependency tree
Reading state information... Done
php5-uprofiler is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 52 not upgraded.

I found my solution via : Debian Bug report logs

$ sudo vim /etc/php5/mods-available/uprofiler.ini

I edited the ini file, changing extension=profiler.so to extension=uprofiler.so .... the result, happily:

$ phpunit --version
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.

i.e. no more warning.


问:
Unable to see the Manager External User option, how to enable it in salesforce?
I am new to the salesforce and I am not able to see the "Manage External User" in my window why ?

Like Below why ?

答:
Ensure that Communities is enabled in your org.

Ensure that your profile has Manage External Users permission.

Ensure that Manage External User button is added to contact Layout.

Ensure that the contact is associated with a account.

If the issue happens in a sandbox you must ensure that there are appropriate licenses available. If the sandbox was created before the production org had community license then the "Manage External Button" will not be there in the sandbox. In such case ensure that production org has the required license, then refresh the sandbox.


问:
$.getJSON function with json object
I've the below combination of server-side and client-side json processing code. I'm able to load json data from remote url and from local .js file.
But, somehow I'm unable to figure out how to load data from the serverjson object in the below code snippet.

```<code>    var json ;

    <#list jsons as json>
             serverjson = ${json};
             console.log(serverjson);

          $.getJSON(---have to load data from json object----).done(function (jsonData) {
            var time = 0; var curc = 0; var prec = 0;
            $.each(jsonData.current.timeSeries, function(i,item){
                //console.log(jsonData.current.timeSeries[i].beginTimeSeconds+" : "+jsonData.current.timeSeries[i].endTimeSeconds+" : "+jsonData.current.timeSeries[i].inspectedCount);
                time = jsonData.current.timeSeries[i].beginTimeSeconds;
                curc = jsonData.current.timeSeries[i].inspectedCount;
                //curdata.addRows([curc]);
                curdata.push(curc)
                //data.addRows([[jsonData.current.timeSeries[i].beginTimeSeconds,jsonData.current.timeSeries[i].endTimeSeconds,jsonData.current.timeSeries[i].inspectedCount]]);

           });
</#list>
</code>```

So, to conclude, I'm not passing remote url or .js file in the $.getJSON() function, I need to pass serverjson object.

Please help me how to solve this.

Thanks in advance.

答:
Instead of:

```<code>$.getJSON(---have to load data from json object----).done(function (jsonData) {
     // code
});
</code>```

do:

```<code>var jsonData = JSON.parse(serverjson);
// code
</code>```

Title: $.getJSON function with json object

Body:
I've the below combination of server-side and client-side json processing code. I'm able to load json data from remote url and from local .js file.
But, somehow I'm unable to figure out how to load data from the serverjson object in the below code snippet.

    var json ;

    <#list jsons as json>
             serverjson = ${json};
             console.log(serverjson);

          $.getJSON(---have to load data from json object----).done(function (jsonData) {
            var time = 0; var curc = 0; var prec = 0;
            $.each(jsonData.current.timeSeries, function(i,item){
                //console.log(jsonData.current.timeSeries[i].beginTimeSeconds+" : "+jsonData.current.timeSeries[i].endTimeSeconds+" : "+jsonData.current.timeSeries[i].inspectedCount);
                time = jsonData.current.timeSeries[i].beginTimeSeconds;
                curc = jsonData.current.timeSeries[i].inspectedCount;
                //curdata.addRows([curc]);
                curdata.push(curc)
                //data.addRows([[jsonData.current.timeSeries[i].beginTimeSeconds,jsonData.current.timeSeries[i].endTimeSeconds,jsonData.current.timeSeries[i].inspectedCount]]);

           });
</#list>

So, to conclude, I'm not passing remote url or .js file in the $.getJSON() function, I need to pass serverjson object.

Please help me how to solve this.

Thanks in advance.

Body:
Instead of:

$.getJSON(---have to load data from json object----).done(function (jsonData) {
     // code
});

do:

var jsonData = JSON.parse(serverjson);
// code


问:
@Autowired class members declared with <default> scope instead of private
I keep reading articles and tutorials on the Internet, that involve Spring, and I see that a lot of them have code samples where they declare their @Autowired members with scope default instead of private.

E.g.

```<code>@Autowired
AccountRepository accountRepository;
</code>```

instead of

```<code>@Autowired
private AccountRepository accountRepository;
</code>```

I was wondering why that is. Because from a good encapsulation point of view I think this is wrong. Is there any benefit from doing this in Spring that I do not know of?

答:
It is never a good practice to inject the dependencies directly through fields, rather use the constructor injection (which @JBNizet pointed out as well), you can look here for more details on this.

In short, you should be using @Autowired on the bean constructors which will generally be public.

Body:
I keep reading articles and tutorials on the Internet, that involve Spring, and I see that a lot of them have code samples where they declare their @Autowired members with scope default instead of private.

E.g.

@Autowired
AccountRepository accountRepository;

instead of

@Autowired
private AccountRepository accountRepository;

I was wondering why that is. Because from a good encapsulation point of view I think this is wrong. Is there any benefit from doing this in Spring that I do not know of?


问:
m2eclipse says "Missing artifact" but I can build from cmdline!
I'm trying to use this Sonatype Eclipse plugin for the first time to handle an existing (huge) software that I can build with maven form the command line.

I have configured the plugin to use my maven 2.2.1 installation instead of the built-in Maven 3.

In Eclipse I have 25 projects (loaded through the root pom.xml) and 4 of them have compilation errors; the maven console contains a lot of lines like this one:

Missing artifact commons-logging:commons-logging:jar:1.0.4:compile

I have all the jars in my repository and the M2_REPO classpath variable correctly defined.  Why the plugin doesn't see all the jars?

The .classpath file of those projects simply references "MAVEN2_CLASSPATH_CONTAINER", there isn't a list of the jars.
The pom.xml in Eclipse shows an error on the first line for the missing jars but I can build from the command line!

Any idea?  I need help!  I will try to move to NetBeans if I don't solve this problem.

Thank you.

答: Remove all the artifacts except the jar in maven local repository</p>


问:
How to trigger a Windows and L key Python-hotkey?
I am trying to run this code in Python.

```<code>import pyautogui
pyautogui.hotkey('win', 'l')
</code>```

So that when I run it it will trigger switch user in Windows but all it does is press l when I need it to press Win+l

答:
As said in my comment, it is most likely that this key combination doesn't work because Windows handles it specially.

If you want to simply lock the workstation, you can use this solution which uses ctypes to call Windows' LockWorkstation-Function:

Lock windows workstation using Python

Python code:

```<code>import ctypes
ctypes.windll.user32.LockWorkStation()
</code>```

Body:
I am trying to run this code in Python.

import pyautogui
pyautogui.hotkey('win', 'l')

So that when I run it it will trigger switch user in Windows but all it does is press l when I need it to press Win+l

Body:
As said in my comment, it is most likely that this key combination doesn't work because Windows handles it specially.

If you want to simply lock the workstation, you can use this solution which uses ctypes to call Windows' LockWorkstation-Function:

Lock windows workstation using Python

Python code:

import ctypes
ctypes.windll.user32.LockWorkStation()


问:
Merging records in a table with 2-columns primary key
I have prepared a simple test case for my question -

In a game player ids and names are stored in the table users:

```<code>CREATE TABLE users (
        uid SERIAL PRIMARY KEY,
        name varchar(255) NOT NULL
);
</code>```

And the players can rate each other in the table reviews with 2-columns PK:

```<code>CREATE TABLE reviews (
        uid integer NOT NULL CHECK (uid <> author) REFERENCES users ON DELETE CASCADE,
        author integer NOT NULL REFERENCES users(uid) ON DELETE CASCADE,
        review varchar(255),
        PRIMARY KEY(uid, author)
);
</code>```

Here both tables are filled with sample data:

```<code>INSERT INTO users (uid, name) VALUES (1, 'User 1');
INSERT INTO users (uid, name) VALUES (2, 'User 2');
INSERT INTO users (uid, name) VALUES (3, 'User 3');
INSERT INTO users (uid, name) VALUES (4, 'User 4');

INSERT INTO reviews (uid, author, review) VALUES (1, 2, 'User 2 says: 1 is nice');
INSERT INTO reviews (uid, author, review) VALUES (1, 3, 'User 3 says: 1 is nice');
INSERT INTO reviews (uid, author, review) VALUES (1, 4, 'User 4 says: 1 is nice');

INSERT INTO reviews (uid, author, review) VALUES (2, 1, 'User 1 says: 2 is nice');
INSERT INTO reviews (uid, author, review) VALUES (2, 3, 'User 3 says: 2 is nice');
INSERT INTO reviews (uid, author, review) VALUES (2, 4, 'User 4 says: 2 is ugly');

INSERT INTO reviews (uid, author, review) VALUES (3, 1, 'User 1 says: 3 is nice');
INSERT INTO reviews (uid, author, review) VALUES (3, 2, 'User 2 says: 3 is ugly');
INSERT INTO reviews (uid, author, review) VALUES (3, 4, 'User 4 says: 3 is ugly');

INSERT INTO reviews (uid, author, review) VALUES (4, 1, 'User 1 says: 4 is ugly');
INSERT INTO reviews (uid, author, review) VALUES (4, 2, 'User 2 says: 4 is ugly');
INSERT INTO reviews (uid, author, review) VALUES (4, 3, 'User 3 says: 4 is ugly');
</code>```

When my mobile app notices, that the same player is using several user ids, it merges the records with the custom stored function shown below.

While merging (to the out_uid) the user reviews of himself are deleted and any resulting overlapping reviews should be dropped too.

(To the background of merging records: this is really necessary, because I run another game with player reviews for many years, and users kept pestering me - why their reviews and game stats are different, when they logged in via Facebook, via Google+, via Apple Game Center...)

Since there is no UPDATE ... ON CONFLICT DO NOTHING - I have tried to help myself with the following two INSERT ... SELECT ... ON CONFLICT DO NOTHING in the custom stored function:

```<code>CREATE OR REPLACE FUNCTION merge_users(
                in_uids integer[],
                OUT out_uid integer
        ) RETURNS integer AS
$func$
BEGIN
        SELECT
                MIN(uid)
        INTO STRICT
                out_uid
        FROM users
        WHERE uid = ANY(in_uids);

        -- delete self-reviews
        DELETE FROM reviews
        WHERE uid = out_uid
        AND author = ANY(in_uids);

        DELETE FROM reviews
        WHERE author = out_uid
        AND uid = ANY(in_uids);

        -- try to copy as many reviews OF this user as possible
        INSERT INTO reviews (
                uid,
                author,
                review
        ) SELECT
                out_uid,        -- change to out_uid
                author,
                review
        FROM reviews
        WHERE uid <> out_uid
        AND uid = ANY(in_uids)
        ON CONFLICT DO NOTHING;

        DELETE FROM reviews
        WHERE uid <> out_uid
        AND uid = ANY(in_uids);

        -- try to copy as many reviews BY this user as possible
        INSERT INTO reviews (
                uid,
                author,
                review
        ) SELECT
                uid,
                out_uid,        -- change to out_uid
                review
        FROM reviews
        WHERE author <> out_uid
        AND author = ANY(in_uids)
        ON CONFLICT DO NOTHING;

        DELETE FROM reviews
        WHERE author <> out_uid
        AND author = ANY(in_uids);

        DELETE FROM users
        WHERE uid <> out_uid
        AND uid = ANY(in_uids);
END
$func$ LANGUAGE plpgsql;
</code>```

Unfortunately, there are problems - please run the 2 commands to see them:

```<code>test=> SELECT out_uid FROM merge_users(ARRAY[1,2]);
 out_uid
---------
       1
(1 row)

test=> SELECT out_uid FROM merge_users(ARRAY[1,2,3,4]);
ERROR:  new row for relation "reviews" violates check constraint "reviews_check"
DETAIL:  Failing row contains (1, 1, User 4 says: 3 is ugly).
CONTEXT:  SQL statement "INSERT INTO reviews (
                uid,
                author,
                review
        ) SELECT
                uid,
                out_uid,        -- change to out_uid
                review
        FROM reviews
        WHERE author <> out_uid
        AND author = ANY(in_uids)
        ON CONFLICT DO NOTHING"
PL/pgSQL function merge_users(integer[]) line 38 at SQL statement
</code>```

So deleting self-reviews seems not to work, please help.

Also I wonder if there is a better way to merge the reviews records, than my trick with INSERT ... SELECT ... ON CONFLICT DO NOTHING.

For your convenience I have created an SQL Fiddle.

Also I have asked this question at the very helpful pgsql-general mailing list.

答:
I think I would approach this by:

Deleting any self reviews based on the combined user ids.

Combining the rest together.

I think it is the first part that is failing.  Try this delete:

```<code>DELETE FROM reviews
WHERE uid = ANY(in_uids) AND author = ANY(in_uids);
</code>```

That is, any combination of the old uids is a problem.  I'm not sure if in_uids contains all equivalent uids, but the idea is that the entire equivalent class is used for this purpose.

Body:
I have prepared a simple test case for my question -

In a game player ids and names are stored in the table users:

CREATE TABLE users (
        uid SERIAL PRIMARY KEY,
        name varchar(255) NOT NULL
);

And the players can rate each other in the table reviews with 2-columns PK:

CREATE TABLE reviews (
        uid integer NOT NULL CHECK (uid <> author) REFERENCES users ON DELETE CASCADE,
        author integer NOT NULL REFERENCES users(uid) ON DELETE CASCADE,
        review varchar(255),
        PRIMARY KEY(uid, author)
);

Here both tables are filled with sample data:

INSERT INTO users (uid, name) VALUES (1, 'User 1');
INSERT INTO users (uid, name) VALUES (2, 'User 2');
INSERT INTO users (uid, name) VALUES (3, 'User 3');
INSERT INTO users (uid, name) VALUES (4, 'User 4');

INSERT INTO reviews (uid, author, review) VALUES (1, 2, 'User 2 says: 1 is nice');
INSERT INTO reviews (uid, author, review) VALUES (1, 3, 'User 3 says: 1 is nice');
INSERT INTO reviews (uid, author, review) VALUES (1, 4, 'User 4 says: 1 is nice');

INSERT INTO reviews (uid, author, review) VALUES (2, 1, 'User 1 says: 2 is nice');
INSERT INTO reviews (uid, author, review) VALUES (2, 3, 'User 3 says: 2 is nice');
INSERT INTO reviews (uid, author, review) VALUES (2, 4, 'User 4 says: 2 is ugly');

INSERT INTO reviews (uid, author, review) VALUES (3, 1, 'User 1 says: 3 is nice');
INSERT INTO reviews (uid, author, review) VALUES (3, 2, 'User 2 says: 3 is ugly');
INSERT INTO reviews (uid, author, review) VALUES (3, 4, 'User 4 says: 3 is ugly');

INSERT INTO reviews (uid, author, review) VALUES (4, 1, 'User 1 says: 4 is ugly');
INSERT INTO reviews (uid, author, review) VALUES (4, 2, 'User 2 says: 4 is ugly');
INSERT INTO reviews (uid, author, review) VALUES (4, 3, 'User 3 says: 4 is ugly');

When my mobile app notices, that the same player is using several user ids, it merges the records with the custom stored function shown below.

While merging (to the out_uid) the user reviews of himself are deleted and any resulting overlapping reviews should be dropped too.

(To the background of merging records: this is really necessary, because I run another game with player reviews for many years, and users kept pestering me - why their reviews and game stats are different, when they logged in via Facebook, via Google+, via Apple Game Center...)

Since there is no UPDATE ... ON CONFLICT DO NOTHING - I have tried to help myself with the following two INSERT ... SELECT ... ON CONFLICT DO NOTHING in the custom stored function:

CREATE OR REPLACE FUNCTION merge_users(
                in_uids integer[],
                OUT out_uid integer
        ) RETURNS integer AS
$func$
BEGIN
        SELECT
                MIN(uid)
        INTO STRICT
                out_uid
        FROM users
        WHERE uid = ANY(in_uids);

        -- delete self-reviews
        DELETE FROM reviews
        WHERE uid = out_uid
        AND author = ANY(in_uids);

        DELETE FROM reviews
        WHERE author = out_uid
        AND uid = ANY(in_uids);

        -- try to copy as many reviews OF this user as possible
        INSERT INTO reviews (
                uid,
                author,
                review
        ) SELECT
                out_uid,        -- change to out_uid
                author,
                review
        FROM reviews
        WHERE uid <> out_uid
        AND uid = ANY(in_uids)
        ON CONFLICT DO NOTHING;

        DELETE FROM reviews
        WHERE uid <> out_uid
        AND uid = ANY(in_uids);

        -- try to copy as many reviews BY this user as possible
        INSERT INTO reviews (
                uid,
                author,
                review
        ) SELECT
                uid,
                out_uid,        -- change to out_uid
                review
        FROM reviews
        WHERE author <> out_uid
        AND author = ANY(in_uids)
        ON CONFLICT DO NOTHING;

        DELETE FROM reviews
        WHERE author <> out_uid
        AND author = ANY(in_uids);

        DELETE FROM users
        WHERE uid <> out_uid
        AND uid = ANY(in_uids);
END
$func$ LANGUAGE plpgsql;

Unfortunately, there are problems - please run the 2 commands to see them:

test=> SELECT out_uid FROM merge_users(ARRAY[1,2]);
 out_uid
---------
       1
(1 row)

test=> SELECT out_uid FROM merge_users(ARRAY[1,2,3,4]);
ERROR:  new row for relation "reviews" violates check constraint "reviews_check"
DETAIL:  Failing row contains (1, 1, User 4 says: 3 is ugly).
CONTEXT:  SQL statement "INSERT INTO reviews (
                uid,
                author,
                review
        ) SELECT
                uid,
                out_uid,        -- change to out_uid
                review
        FROM reviews
        WHERE author <> out_uid
        AND author = ANY(in_uids)
        ON CONFLICT DO NOTHING"
PL/pgSQL function merge_users(integer[]) line 38 at SQL statement

So deleting self-reviews seems not to work, please help.

Also I wonder if there is a better way to merge the reviews records, than my trick with INSERT ... SELECT ... ON CONFLICT DO NOTHING.

For your convenience I have created an SQL Fiddle.

Also I have asked this question at the very helpful pgsql-general mailing list.

Body:
I think I would approach this by:

Deleting any self reviews based on the combined user ids.

Combining the rest together.

I think it is the first part that is failing.  Try this delete:

DELETE FROM reviews
WHERE uid = ANY(in_uids) AND author = ANY(in_uids);

That is, any combination of the old uids is a problem.  I'm not sure if in_uids contains all equivalent uids, but the idea is that the entire equivalent class is used for this purpose.


问:
Python equivalent for C#'s generic List<T>
I am creating a simple GUI program to manage priorities.

I have successfully managed to add functionality to add an item to the listbox. Now I want to add the item to the something what is known as List<> in C#. Does such a thing exist in Python?

For instance, in C#, to add an item to the listview I would first create:

```<code>List<Priority> priorities = new List<Priority>();
</code>```

...and then create the following method:

```<code>void Add()
{
    if (listView1.SelectedItems.Count > 0)
    {
        MessageBox.Show("Please make sure you have no priorities selected!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else if (txt_Priority.ReadOnly == true) { MessageBox.Show("Please make sure you refresh fields first!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
    else
    {
        if ((txt_Priority.Text.Trim().Length == 0)) { MessageBox.Show("Please enter the word!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
        else
        {
            Priority p = new Priority();
            p.Subject = txt_Priority.Text;

            if (priorities.Find(x => x.Subject == p.Subject) == null)
            {
                priorities.Add(p);
                listView1.Items.Add(p.Subject);
            }
            else
            {
                MessageBox.Show("That priority already exists in your program!");
            }
            ClearAll();
            Sync();
            Count();
        }
    }
    SaveAll();

}
</code>```

答:
Type hints

Since Python 3.5, it's possible to add type hints. Coupled with dataclasses (Python 3.7+), and generic collections (Python 3.9+), you can write:

```<code>from dataclasses import dataclass

@dataclass
class Priority:
    """Basic example class"""
    name: str
    level: int = 1

foo = Priority("foo")
bar = Priority("bar", 2)

priorities: list[Priority] = [foo, bar]

print(priorities)
# [Priority(name='foo', level=1), Priority(name='bar', level=2)]
print(sorted(priorities, key= lambda p: p.name))
# [Priority(name='bar', level=2), Priority(name='foo', level=1)]

baz = "Not a priority"
priorities.append(baz) # <- Your IDE will probably complain

print(priorities)
# [Priority(name='foo', level=1), Priority(name='bar', level=2), 'Not a priority']
</code>```

In Python 3.5, the code would look like:

```<code>from typing import List

class Priority:
    """Basic example class"""
    def __init__(self, name: str, level: int = 1):
        self.name = name
        self.level = level

    def __str__(self):
        return '%s (%d)' % (self.name, self.level)

    def __repr__(self):
        return str(self)

foo = Priority("foo")
bar = Priority("bar", 2)

priorities: List[Priority] = [foo, bar]

print(priorities)
# [foo (1), bar (2)]
print(sorted(priorities, key=lambda p: p.name))
# [bar (2), foo (1)]

baz = "Not a priority"
priorities.append(baz) # <- Your IDE will probably complain

print(priorities)
# [foo (1), bar (2), 'Not a priority']
</code>```

Note that type hints are optional, and the above code will run fine, even if there's a type mismatch when appending baz.

You can explicitly check for errors with mypy:

```<code>❯ mypy priorities.py
priorities.py:22: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "Priority"
Found 1 error in 1 file (checked 1 source file)
</code>```

Dynamic language

Even if it now has type hints, Python stays dynamic, and type hints are completely optional:

```<code>>>> my_generic_list = []
>>> my_generic_list.append(3)
>>> my_generic_list.append("string")
>>> my_generic_list.append(['another list'])
>>> my_generic_list
[3, 'string', ['another list']]
</code>```

You don't have to define anything before appending any object to an existing list.

Python uses duck-typing. If you iterate on a list and call a method on each one of the elements, you need to make sure that the elements understand the method.

So if you want the equivalent of :

```<code>List<Priority> priorities
</code>```

you just need to initialize a list and make sure you only add Priority instances to it. That's it!

Body:
I am creating a simple GUI program to manage priorities.

I have successfully managed to add functionality to add an item to the listbox. Now I want to add the item to the something what is known as List<> in C#. Does such a thing exist in Python?

For instance, in C#, to add an item to the listview I would first create:

List<Priority> priorities = new List<Priority>();

...and then create the following method:

void Add()
{
    if (listView1.SelectedItems.Count > 0)
    {
        MessageBox.Show("Please make sure you have no priorities selected!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else if (txt_Priority.ReadOnly == true) { MessageBox.Show("Please make sure you refresh fields first!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
    else
    {
        if ((txt_Priority.Text.Trim().Length == 0)) { MessageBox.Show("Please enter the word!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); }
        else
        {
            Priority p = new Priority();
            p.Subject = txt_Priority.Text;

            if (priorities.Find(x => x.Subject == p.Subject) == null)
            {
                priorities.Add(p);
                listView1.Items.Add(p.Subject);
            }
            else
            {
                MessageBox.Show("That priority already exists in your program!");
            }
            ClearAll();
            Sync();
            Count();
        }
    }
    SaveAll();

}

Body:
Type hints

Since Python 3.5, it's possible to add type hints. Coupled with dataclasses (Python 3.7+), and generic collections (Python 3.9+), you can write:

from dataclasses import dataclass

@dataclass
class Priority:
    """Basic example class"""
    name: str
    level: int = 1

foo = Priority("foo")
bar = Priority("bar", 2)

priorities: list[Priority] = [foo, bar]

print(priorities)
# [Priority(name='foo', level=1), Priority(name='bar', level=2)]
print(sorted(priorities, key= lambda p: p.name))
# [Priority(name='bar', level=2), Priority(name='foo', level=1)]

baz = "Not a priority"
priorities.append(baz) # <- Your IDE will probably complain

print(priorities)
# [Priority(name='foo', level=1), Priority(name='bar', level=2), 'Not a priority']

In Python 3.5, the code would look like:

from typing import List

class Priority:
    """Basic example class"""
    def __init__(self, name: str, level: int = 1):
        self.name = name
        self.level = level

    def __str__(self):
        return '%s (%d)' % (self.name, self.level)

    def __repr__(self):
        return str(self)

foo = Priority("foo")
bar = Priority("bar", 2)

priorities: List[Priority] = [foo, bar]

print(priorities)
# [foo (1), bar (2)]
print(sorted(priorities, key=lambda p: p.name))
# [bar (2), foo (1)]

baz = "Not a priority"
priorities.append(baz) # <- Your IDE will probably complain

print(priorities)
# [foo (1), bar (2), 'Not a priority']

Note that type hints are optional, and the above code will run fine, even if there's a type mismatch when appending baz.

You can explicitly check for errors with mypy:

❯ mypy priorities.py
priorities.py:22: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "Priority"
Found 1 error in 1 file (checked 1 source file)

Dynamic language

Even if it now has type hints, Python stays dynamic, and type hints are completely optional:

>>> my_generic_list = []
>>> my_generic_list.append(3)
>>> my_generic_list.append("string")
>>> my_generic_list.append(['another list'])
>>> my_generic_list
[3, 'string', ['another list']]

You don't have to define anything before appending any object to an existing list.

Python uses duck-typing. If you iterate on a list and call a method on each one of the elements, you need to make sure that the elements understand the method.

So if you want the equivalent of :

List<Priority> priorities

you just need to initialize a list and make sure you only add Priority instances to it. That's it!


问:
cc1.exe System Error - libwinpthread-1.dll missing - But it isn't
I recently downloaded MinGW-w64 from Sourceforge onto my external hard drive, where all the files reside in:

E:\mingw-w64\x86_64-4.9.2-posix-seh-rt_v3-rev1\mingw64\bin

When I try compiling my first "Hello World" program using gcc on Windows 8.1, I get a cc1.exe System Error, that tells me

The program can't start because libwinpthread-1.dll is missing.
  Try reinstalling the program to fix the problem.

And yet, libwinpthread-1.dll (all 54,784 bytes of it) is sitting right there in the very same directory as gcc.exe. Do I really need to reinstall everything, or is something else going wrong here?

答:
I know this post is over two years old but I recently had the same problem when using CMake.

I fixed it by adding MinGW to the "Path" Envionment Variable:
I am using Windows 10 Home.

"Windows Key"+ Pause/Break

On the left there is "Advanced System settings"

On the bottom of this window there is a button called "Environment Variables"

Click on the name "Path"

Click on "edit" under System Variables

Add your MinGW directory there. For me that was C:\MinGW\bin

I Hope I could help. If not you, maybe someone else.


问:
I am trying to make a rectangle which takes a user inut to get a size
I am new to java and I  want to make a rectangle which uses a user input with scanner to get a size for the rectangle. The problem is that it takes the user inputs but it doesn't display the rectangle. I believe it is because my y integer is in a static function, but I am not sure how to fix this. I searched google for quite a long time but I couldn't find an answer. Could anyone please help me? Thank you. :)</p>

```<code>    import java.util.Scanner;
    import java.awt.*;
    import java.awt.event.ActionListener;

    import javax.swing.*;

    public class Shape extends JPanel implements ActionListener{

        Timer tm = new Timer(5, this);

        public static void main(String[] args){
             System.out.println("Place in the width of your vaccum cleaner here:");
             Scanner myY = new Scanner(System.in);
             int y = myY.nextInt();

             JFrame jf = new JFrame("Title");
             jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             Shape s = new Shape();
             jf.add(s);
             jf.setSize(600, 400);
             jf.setVisible(true);
        }
        public void paintComponent(Graphics g){
             super.paintComponent(g);
             this.setBackground(Color.PINK);

             g.setColor(Color.BLACK);
             g.fillRect(0, 0, 40, y);

             tm.start();
        }
    }
</code>```

答:
The code you posted doesn't compile, so there is now way it will show the rectangle.

int y is defined in main, and it is not recognized in paintComponent.

make it a class variable : static int y;  and initialize it in main by : y = myY.nextInt();

Body:
I am new to java and I  want to make a rectangle which uses a user input with scanner to get a size for the rectangle. The problem is that it takes the user inputs but it doesn't display the rectangle. I believe it is because my y integer is in a static function, but I am not sure how to fix this. I searched google for quite a long time but I couldn't find an answer. Could anyone please help me? Thank you. :)

    import java.util.Scanner;
    import java.awt.*;
    import java.awt.event.ActionListener;

    import javax.swing.*;

    public class Shape extends JPanel implements ActionListener{

        Timer tm = new Timer(5, this);

        public static void main(String[] args){
             System.out.println("Place in the width of your vaccum cleaner here:");
             Scanner myY = new Scanner(System.in);
             int y = myY.nextInt();

             JFrame jf = new JFrame("Title");
             jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             Shape s = new Shape();
             jf.add(s);
             jf.setSize(600, 400);
             jf.setVisible(true);
        }
        public void paintComponent(Graphics g){
             super.paintComponent(g);
             this.setBackground(Color.PINK);

             g.setColor(Color.BLACK);
             g.fillRect(0, 0, 40, y);

             tm.start();
        }
    }


问:
context to use call and apply in Javascript?
Guys can any one explain context to use call and apply methods in Javascript?

Why to use call and apply instead of calling a function directly ?

答:
If you have experience with Object Oriented Programming then call and apply will make sense if you compare it with inheritance and override the properties or method/functions of parent class from child class. Which is similar with call in javascript as following:

```<code>function foo () {
  this.helloworld = "hello from foo"
}
foo.prototype.print = function () {
  console.log(this.helloworld)
}

foo.prototype.main = function () {
  this.print()
}

function bar() {
  this.helloworld = 'hello from bar'
}
// declaring print function to override the previous print
bar.prototype.print = function () {
  console.log(this.helloworld)
}

var iamfoo = new foo()

iamfoo.main() // prints: hello from foo

iamfoo.main.call(new bar()) // override print and prints: hello from bar
</code>```

Body:
If you have experience with Object Oriented Programming then call and apply will make sense if you compare it with inheritance and override the properties or method/functions of parent class from child class. Which is similar with call in javascript as following:

function foo () {
  this.helloworld = "hello from foo"
}
foo.prototype.print = function () {
  console.log(this.helloworld)
}

foo.prototype.main = function () {
  this.print()
}

function bar() {
  this.helloworld = 'hello from bar'
}
// declaring print function to override the previous print
bar.prototype.print = function () {
  console.log(this.helloworld)
}

var iamfoo = new foo()

iamfoo.main() // prints: hello from foo

iamfoo.main.call(new bar()) // override print and prints: hello from bar


问:
Restarting a Python Interpreter Quietly
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.

I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.

I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).

So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?

Thanks,

Dan

答: If you know in advance the modules, classes, functions, variables, etc... in use, you could pickle them to disk and reload. I'm not sure off the top of my head the best way to tackle the issue if your environment contains many unknowns. Though, it may suffice to pickle globals and locals.</p>

OwnerDisplayName: Dan

Title: Restarting a Python Interpreter Quietly

LastEditorDisplayName: Benoit

OwnerDisplayName: daniel