问:
Angular ng-class and bootstraps css
I am using 'table-striped' from bootstrap and 'ng-class' from angularjs to present a table. The idea is to show striped table and when click on one row, it is highlighted.

The following is copied from chrome as a result of 'click' on odd row.

```<code><div class="table-responsive" id="Destination">
    <table class="table table-striped" id="destinationTable">
    <thead>
...
    </thead>
    <tbody>
        <!-- ngRepeat: entity in destinations -->
        <tr ng-repeat="entity in destinations" ng-click="setName()" ng-class="{'highlight' : destinationName == entity.name}" class="ng-scope highlight">

    </tbody>
    </table>
</div>
</code>```

As you can see, "class="ng-scope highlight" is already generated by angularjs on that row, but it just not take effect.

Also it is strange to me the same code works well for even row. I don't see the difference of the html between that from odd row click and that from the even row click.

In the "bootstrap.css", it has,

```<code>.table-striped > tbody > tr:nth-of-type(odd) {background-color: #f9f9f9;}
</code>```

I am wondering this class in applied to overwrite the one I want, the 'highlight'.

Is there anyway to solve it?

答:
I faced the same issue and it seemed to have to do with the css in the table striping.

A workaround would be to do the following:

Either use ng-style directive

Use !important in the css of the class attribute you want to show ( for example  background-color: #dff0d8 !important; for your highlight class )

Item #1 is probably the better way to go here but both should work.

Title: Angular ng-class and bootstraps css

Body:
I am using 'table-striped' from bootstrap and 'ng-class' from angularjs to present a table. The idea is to show striped table and when click on one row, it is highlighted.

The following is copied from chrome as a result of 'click' on odd row.

...

As you can see, "class="ng-scope highlight" is already generated by angularjs on that row, but it just not take effect.

Also it is strange to me the same code works well for even row. I don't see the difference of the html between that from odd row click and that from the even row click.

In the "bootstrap.css", it has,

.table-striped > tbody > tr:nth-of-type(odd) {background-color: #f9f9f9;}

I am wondering this class in applied to overwrite the one I want, the 'highlight'.

Is there anyway to solve it?


来源: stackexchange

问:
SQL Server 2008 and Almost-Progressive Sum and Average?
I have a table with several million rows, with an ID column and a DateTimeOffset column. The table simply tracks elapsed time for some operations.

Without touching a cursor or doing RBAR, how can I get the difference between each row, and then the average time among all rows?

For example, if row 1 is 12:00 and row 2 is 12:01 and row 3 is 12:03 then my result set would have row 1 with 0, row 2 with 1, and row 3 with 2. Then my next result set would have a value of 1.5.

Help?

Thanks.

答:
Assuming each identity value is just 1 greater than the previous, you can do something using a subquery like so:</p>

```<code>select testdate, DATEDIFF(SECOND, TestDate,
     (select TestDate from TestDates tdIn where tdIn.TestId = tdOut.TestId + 1))
from TestDates tdOut
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Assuming each identity value is just 1 greater than the previous, you can do something using a subquery like so:

select testdate, DATEDIFF(SECOND, TestDate,
     (select TestDate from TestDates tdIn where tdIn.TestId = tdOut.TestId + 1))
from TestDates tdOut


问:
conditional guard clauses in elixir
Is there any way to use or or and expressions in function guard clauses:

```<code>defmodule Test do
   def testfn(arg1, arg2) when is_nil(arg1) || is_nil(arg2), do: :nothing

   def testfn2(arg1, arg2) when is_nil(arg1) && is_nil(arg2), do: :nothing
end
</code>```

答:
Guard expressions do not support && and || (which accept any value on the LHS), but only and and or (which accepts only booleans on the LHS). Since is_nil always returns a boolean, you can switch to using and and or:

```<code>defmodule Test do
   def testfn(arg1, arg2) when is_nil(arg1) or is_nil(arg2), do: :nothing

   def testfn2(arg1, arg2) when is_nil(arg1) and is_nil(arg2), do: :nothing
end
</code>```

https://hexdocs.pm/elixir/master/guards.html contains a list of all functions/operators allowed in guards.

ContentLicense: CC BY-SA 3.0

Title: conditional guard clauses in elixir

Body:
Is there any way to use or or and expressions in function guard clauses:

defmodule Test do
   def testfn(arg1, arg2) when is_nil(arg1) || is_nil(arg2), do: :nothing

   def testfn2(arg1, arg2) when is_nil(arg1) && is_nil(arg2), do: :nothing
end

Body:
Guard expressions do not support && and || (which accept any value on the LHS), but only and and or (which accepts only booleans on the LHS). Since is_nil always returns a boolean, you can switch to using and and or:

defmodule Test do
   def testfn(arg1, arg2) when is_nil(arg1) or is_nil(arg2), do: :nothing

   def testfn2(arg1, arg2) when is_nil(arg1) and is_nil(arg2), do: :nothing
end

https://hexdocs.pm/elixir/master/guards.html contains a list of all functions/operators allowed in guards.


问:
Access VBA Public Function - Variable for Control and Field?
I want to set up a public function like the following:

(A)

```<code>Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkControl = -1
ElseIf chkField = "N" Then
    chkControl = 0
Else: chkControl = 0
End If
End Function
</code>```

(B)

```<code>Public Function CheckYNFlipper(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkField = "N"
    chkControl = 0
ElseIf chkField = "N" Then
    chkField = "Y"
    chkControl = -1
Else: chkField = "Y"
    chkControl = -1
End If
End Function
</code>```

The reason for this is, that I have a form, which has an underlying SQL table.  I have no control over the data, but I must represent it, for the ability to maintain it.  I have 10 fields, in the underlying table, which have a Y or N as their values.  The data types are actually nvarchar(10).  At the same time, I have to show these fields as checkbox controls, on the form, for ease of use.

The above code, is an attempt I am making to A - set the checkbox control to align with the current value in the table--> -1 = Y and 0 = N, and to B - update the table value, and switch the check box to checked or unchecked, from what it was, to the opposite, based on the onclick event of that control.

I want to make chkField and chkControl variables to the public function, that would be the table-field, and the form-control.  I can't seem to get the right syntax, and was hoping someone might have clarification on how to do this.

for the form load and current, I tried this:

```<code>CheckYNField Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA
</code>```

for the on click, I tried this:

```<code>CheckYNFlipper Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA
</code>```

I've tried some other methods, but doesn't seem to be working.  I'm doing something wrong, but I can't tell what.  Appreciate any tips!

Edit/Update:
I tried Kostas K.'s solution, abandoning the idea of making a public functions with parameters for the fields and controls.  I put the following, on load and on current:

```<code>With Me
    If .txtfieldboundtablefieldA.Value = "Y" Then
        .unboundchkA.Value = True
    ElseIf .txtfieldboundtablefieldA.Value = "N" Then
        .unboundchkA.Value = False
    Else: .unboundchkA.Value = False
    End If
End With
</code>```

This is on a continuous form, so that it can show like a giant grid.  There are the identifying bound field controls, and then a series of these checkboxes, to display the Y/N true/false status of each of these particular fields.  I can't bound the checkboxes to the fields, because it changes the field value in the table to -1 or 0, and we need it to stay Y or N.  I added a bound text field, to hold the table/field value for each row (hence the call to a text box control in the above revised code).  The checkbox is unbound, and is there to display the field value, and allow the user to check and uncheck, so I can use on-click code to change the table field value between Y and N.

The above code is not seeming to show the correct checkbox value for each bound text field, based on each row.  It shows based on the row that currently has focus.  If I click on a row, where the table field is Y, all rows checkboxes on the form show true.  If I move to a row, where the table field is N, all checkboxes for all rows change to false.  I am struggling to just initially get 1 checkbox to show accurately, on every row of the continuous form, based on every record in the table.  This is a small table, like 30 records.  I really didn't think it would be so difficult to present this the way we need to.

Any ideas, how I could better do this?

答:
Edit:

Set the Control Source of the checkbox to:

```<code>= IIf([YourYesNoField] = "Y", -1, 0)
</code>```

In order to update when clicked:

```<code>Private Sub chkCheckNameA_Click()
    Dim yesNo As String
        yesNo = IIf(Me.chkCheckNameA.Value = 0, "Y", "N") 'reverse value
    CurrentDb.Execute "Update [YourTable] SET [YourYesNoField]='" & yesNo & "' WHERE [ID]=" & Me![ID], dbFailOnError
    Me.Requery
End Sub
</code>```

You could try something this.

Check the Y/N field and assign the function's boolean return value to the checkbox (A).

On the checkbox click event, check its value and update the Y/N field (B).

```<code>'Form Load
Private Sub Form_Load()
    With Me
        .chkCheckNameA.Value = CheckYNField(![FieldA])
    End With
End Sub

'Click
Private Sub chkCheckNameA_Click()
    With Me
        ![FieldA] = IIf(.chkCheckNameA.Value = 0, "N", "Y")
    End With
End Sub

'True returns -1, False returns 0
Private Function CheckYNField(ByVal chkField As String) As Boolean
    CheckYNField = (chkField = "Y")
End Function
</code>```

Body:
I want to set up a public function like the following:

(A)

Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkControl = -1
ElseIf chkField = "N" Then
    chkControl = 0
Else: chkControl = 0
End If
End Function

(B)

Public Function CheckYNFlipper(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkField = "N"
    chkControl = 0
ElseIf chkField = "N" Then
    chkField = "Y"
    chkControl = -1
Else: chkField = "Y"
    chkControl = -1
End If
End Function

The reason for this is, that I have a form, which has an underlying SQL table.  I have no control over the data, but I must represent it, for the ability to maintain it.  I have 10 fields, in the underlying table, which have a Y or N as their values.  The data types are actually nvarchar(10).  At the same time, I have to show these fields as checkbox controls, on the form, for ease of use.

The above code, is an attempt I am making to A - set the checkbox control to align with the current value in the table--> -1 = Y and 0 = N, and to B - update the table value, and switch the check box to checked or unchecked, from what it was, to the opposite, based on the onclick event of that control.

I want to make chkField and chkControl variables to the public function, that would be the table-field, and the form-control.  I can't seem to get the right syntax, and was hoping someone might have clarification on how to do this.

for the form load and current, I tried this:

CheckYNField Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA

for the on click, I tried this:

CheckYNFlipper Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA

I've tried some other methods, but doesn't seem to be working.  I'm doing something wrong, but I can't tell what.  Appreciate any tips!

Edit/Update:
I tried Kostas K.'s solution, abandoning the idea of making a public functions with parameters for the fields and controls.  I put the following, on load and on current:

With Me
    If .txtfieldboundtablefieldA.Value = "Y" Then
        .unboundchkA.Value = True
    ElseIf .txtfieldboundtablefieldA.Value = "N" Then
        .unboundchkA.Value = False
    Else: .unboundchkA.Value = False
    End If
End With

This is on a continuous form, so that it can show like a giant grid.  There are the identifying bound field controls, and then a series of these checkboxes, to display the Y/N true/false status of each of these particular fields.  I can't bound the checkboxes to the fields, because it changes the field value in the table to -1 or 0, and we need it to stay Y or N.  I added a bound text field, to hold the table/field value for each row (hence the call to a text box control in the above revised code).  The checkbox is unbound, and is there to display the field value, and allow the user to check and uncheck, so I can use on-click code to change the table field value between Y and N.

The above code is not seeming to show the correct checkbox value for each bound text field, based on each row.  It shows based on the row that currently has focus.  If I click on a row, where the table field is Y, all rows checkboxes on the form show true.  If I move to a row, where the table field is N, all checkboxes for all rows change to false.  I am struggling to just initially get 1 checkbox to show accurately, on every row of the continuous form, based on every record in the table.  This is a small table, like 30 records.  I really didn't think it would be so difficult to present this the way we need to.

Any ideas, how I could better do this?

Body:
Edit:

Set the Control Source of the checkbox to:

= IIf([YourYesNoField] = "Y", -1, 0)

In order to update when clicked:

Private Sub chkCheckNameA_Click()
    Dim yesNo As String
        yesNo = IIf(Me.chkCheckNameA.Value = 0, "Y", "N") 'reverse value
    CurrentDb.Execute "Update [YourTable] SET [YourYesNoField]='" & yesNo & "' WHERE [ID]=" & Me![ID], dbFailOnError
    Me.Requery
End Sub

You could try something this.

Check the Y/N field and assign the function's boolean return value to the checkbox (A).

On the checkbox click event, check its value and update the Y/N field (B).

'Form Load
Private Sub Form_Load()
    With Me
        .chkCheckNameA.Value = CheckYNField(![FieldA])
    End With
End Sub

'Click
Private Sub chkCheckNameA_Click()
    With Me
        ![FieldA] = IIf(.chkCheckNameA.Value = 0, "N", "Y")
    End With
End Sub

'True returns -1, False returns 0
Private Function CheckYNField(ByVal chkField As String) As Boolean
    CheckYNField = (chkField = "Y")
End Function


问:
Searching and returning results from a database
I am not familiar with databases I have a database file named words_library.db that contains a table named dictionary_lib in which there is two columns one is English_lib and the second is German_lib what I want to achieve is:
When the user types a word in the search box and validates a dialog box appears showing results like the following picture (check fig. 1) here's the code I have so far:

Java

```<code>db =new DataBaseHelper(getContext());
try {

    db.createDataBase();
    db.openDataBase();

}
catch (Exception e)
{
    e.printStackTrace();
}
namelist=new LinkedHashMap<>();
int ii;
SQLiteDatabase sd = db.getReadableDatabase();
Cursor cursor = sd.query("dictionary_lib" ,null, null, null, null, null, null);
ii=cursor.getColumnIndex("English_lib");
eng_list=new ArrayList<String>();
german_list= new ArrayList<String>();
while (cursor.moveToNext()){
    namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("German_lib")));
}
Iterator entries = namelist.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry thisEntry = (Map.Entry) entries.next();
    eng_list.add(String.valueOf(thisEntry.getKey()));
    german_list.add(String.valueOf(thisEntry.getValue()));
}
for (int i = 0; i < eng_list.size(); i++){
    if (eng_list.contains(text)){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        builder.setTitle(text);
        builder.setMessage(
                "\n'word' in german: "+german_list.get(i).toString()
        );
        builder.setNegativeButton("CLOSE", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Stxt.setBackground(getResources().getDrawable(R.drawable.blue_out_line));
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
</code>```

Desired result (fig. 1)

答:
I have a database file named words_library.db

It's not really clear how you have that file, or are loading it, but moving on.

When the user types a word in the search box and validates

Is this on a button click? I'll assume it is.

The problem you seem to be having is breaking the problem into smaller steps.

You need to

Find all german words in a database from an english word

Load those words in some form of List. (Just keep a Cursor, you don't need to extract your columns).

Display this list within a Dialog (see AlertDialog.Builder#setCursor)

Each of these should ideally be written as separate methods

The following code is untested, but I believe should be close to what you are looking for.

```<code>// Get your database reference
final DataBaseHelper db = new DataBaseHelper(getContext());

// Setup the search button
findViewById(R.id.start_search).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final String searchQuery = searchBox.getText().toString();
        Cursor germanWordCursor = getGermanWords(db, searchQuery);
        showDialog(String.format("'%s' in German", searchQuery), germanWordCursor);
    }
});

// Query the database for the german words from a given english word
private Cursor getGermanWords(DataBaseHelper dbHelper, String englishQuery) {
    final SQLiteDatabase db = dbHelper.getReadableDatabase();

    return db.query("dictionary_lib",
           null,
           "English_Lib = ?",
           new String[] { englishQuery },
           null, null, null);
}

// Display a list dialog from a database cursor
private void showDialog(String title, Cursor cursor) {

  final int theme = R.style.AppCompatAlertDialogStyle;
  final Drawable blueOutLine = getResources().getDrawable(R.drawable.blue_out_line, theme);

  AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), theme)
      .setTitle(title)
      .setCursor(cursor, null, "German_lib")
      .setNegativeButton("CLOSE", new DialogInterface.OnClickListener(){
          @Override
          public void onClick(DialogInterface dialog, int id){
              Stxt.setBackground(blueOutLine);
            }
      }).show();
}
</code>```

Note setCursor will require a column named _id in the database table

Body:
I am not familiar with databases I have a database file named words_library.db that contains a table named dictionary_lib in which there is two columns one is English_lib and the second is German_lib what I want to achieve is:
When the user types a word in the search box and validates a dialog box appears showing results like the following picture (check fig. 1) here's the code I have so far:

Java

db =new DataBaseHelper(getContext());
try {

    db.createDataBase();
    db.openDataBase();

}
catch (Exception e)
{
    e.printStackTrace();
}
namelist=new LinkedHashMap<>();
int ii;
SQLiteDatabase sd = db.getReadableDatabase();
Cursor cursor = sd.query("dictionary_lib" ,null, null, null, null, null, null);
ii=cursor.getColumnIndex("English_lib");
eng_list=new ArrayList<String>();
german_list= new ArrayList<String>();
while (cursor.moveToNext()){
    namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("German_lib")));
}
Iterator entries = namelist.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry thisEntry = (Map.Entry) entries.next();
    eng_list.add(String.valueOf(thisEntry.getKey()));
    german_list.add(String.valueOf(thisEntry.getValue()));
}
for (int i = 0; i < eng_list.size(); i++){
    if (eng_list.contains(text)){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        builder.setTitle(text);
        builder.setMessage(
                "\n'word' in german: "+german_list.get(i).toString()
        );
        builder.setNegativeButton("CLOSE", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Stxt.setBackground(getResources().getDrawable(R.drawable.blue_out_line));
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

Desired result (fig. 1)

Body:
I have a database file named words_library.db

It's not really clear how you have that file, or are loading it, but moving on.

When the user types a word in the search box and validates

Is this on a button click? I'll assume it is.

The problem you seem to be having is breaking the problem into smaller steps.

You need to

Find all german words in a database from an english word

Load those words in some form of List. (Just keep a Cursor, you don't need to extract your columns).

Display this list within a Dialog (see AlertDialog.Builder#setCursor)

Each of these should ideally be written as separate methods

The following code is untested, but I believe should be close to what you are looking for.

// Get your database reference
final DataBaseHelper db = new DataBaseHelper(getContext());

// Setup the search button
findViewById(R.id.start_search).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final String searchQuery = searchBox.getText().toString();
        Cursor germanWordCursor = getGermanWords(db, searchQuery);
        showDialog(String.format("'%s' in German", searchQuery), germanWordCursor);
    }
});

// Query the database for the german words from a given english word
private Cursor getGermanWords(DataBaseHelper dbHelper, String englishQuery) {
    final SQLiteDatabase db = dbHelper.getReadableDatabase();

    return db.query("dictionary_lib",
           null,
           "English_Lib = ?",
           new String[] { englishQuery },
           null, null, null);
}

// Display a list dialog from a database cursor
private void showDialog(String title, Cursor cursor) {

  final int theme = R.style.AppCompatAlertDialogStyle;
  final Drawable blueOutLine = getResources().getDrawable(R.drawable.blue_out_line, theme);

  AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), theme)
      .setTitle(title)
      .setCursor(cursor, null, "German_lib")
      .setNegativeButton("CLOSE", new DialogInterface.OnClickListener(){
          @Override
          public void onClick(DialogInterface dialog, int id){
              Stxt.setBackground(blueOutLine);
            }
      }).show();
}

Note setCursor will require a column named _id in the database table


问:
concatenate two lists of string in r
Here is my sample:

```<code>a = c("a","b","c")
b = c("1","2","3")
</code>```

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

```<code>paste(a[1],b[1])
</code>```

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

答:
You can do:

```<code>c(sapply(a, function(x) {paste(x,b)}))
[1] "a 1" "a 2" "a 3" "b 1" "b 2" "b 3" "c 1" "c 2" "c 3"
</code>```

edited paste0 into paste to match OP update

Title: concatenate two lists of string in r

Body:
Here is my sample:

a = c("a","b","c")
b = c("1","2","3")

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

paste(a[1],b[1])

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

Body:
You can do:

c(sapply(a, function(x) {paste(x,b)}))
[1] "a 1" "a 2" "a 3" "b 1" "b 2" "b 3" "c 1" "c 2" "c 3"

edited paste0 into paste to match OP update


问:
How can I remove a chunk of text from a Javascript string?
I am trying to analyze a piece of text via JavaScript and, reading up, have learned that parsing HTML with Regex is quite evil. I'd like to remove a more sinister part of my text before I analyze it.

If I've got a chunk of text like the item below, how might I (1) slice everything from [caption] to [/caption] and (2) store that text in a new var?

```<code>Sed rutrum enim sit amet sem fringilla egestas placerat mauris pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ultricies egestas malesuada. Etiam rhoncus eros a leo imperdiet vitae tincidunt purus laoreet. Mauris ut mauris quam, sed pharetra urna. Etiam eu enim mauris, vitae bibendum orci. Quisque ac sapien massa, at dignissim tellus.

[caption id="blah" align="alignleft" width="123" caption="Lorem ipsum dolor sit, consectetur adipiscing elit."]<a href="http://www.google.com/something"><img title="Lorem ipsum dolor sit, consectetur adipiscing elit." src="http://google.com/something/else.png" alt="Lorem ipsum dolor sit, consectetur adipiscing elit." width="345" /></a>[/caption]

Aenean faucibus mi sit amet leo suscipit nec egestas leo ultrices. Integer tincidunt, urna quis varius accumsan, urna quam congue nulla, ut ornare orci purus in ligula. Suspendisse varius, tellus aliquam tincidunt, ante semper elit, sit amet tincidunt elit augue eget odio. Vivamus sit amet tincidunt massa. Sed nunc ligula, feugiat quis volutpat congue, eleifend in tellus. Curabitur ut dictum felis. Nunc sodales euismod leo, in commodo elit ornare hendrerit. Cras luctus eros id nisl vestibulum elementum. Maecenas ut neque turpis. Donec ornare hendrerit rutrum. Non nibh leo, dictum ullamcorper dui.
</code>```

答:
You can use .split()

```<code>var temp = yourText.split("[caption")
</code>```

This gives you:

temp[0] with everything before "[caption"

temp[1] with everything after "[caption"

You can then continue to split/join the array fragments to eliminate any potion of the string.

Body:
I am trying to analyze a piece of text via JavaScript and, reading up, have learned that parsing HTML with Regex is quite evil. I'd like to remove a more sinister part of my text before I analyze it.

If I've got a chunk of text like the item below, how might I (1) slice everything from [caption] to [/caption] and (2) store that text in a new var?

Sed rutrum enim sit amet sem fringilla egestas placerat mauris pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ultricies egestas malesuada. Etiam rhoncus eros a leo imperdiet vitae tincidunt purus laoreet. Mauris ut mauris quam, sed pharetra urna. Etiam eu enim mauris, vitae bibendum orci. Quisque ac sapien massa, at dignissim tellus.

[caption id="blah" align="alignleft" width="123" caption="Lorem ipsum dolor sit, consectetur adipiscing elit."][/caption]

Aenean faucibus mi sit amet leo suscipit nec egestas leo ultrices. Integer tincidunt, urna quis varius accumsan, urna quam congue nulla, ut ornare orci purus in ligula. Suspendisse varius, tellus aliquam tincidunt, ante semper elit, sit amet tincidunt elit augue eget odio. Vivamus sit amet tincidunt massa. Sed nunc ligula, feugiat quis volutpat congue, eleifend in tellus. Curabitur ut dictum felis. Nunc sodales euismod leo, in commodo elit ornare hendrerit. Cras luctus eros id nisl vestibulum elementum. Maecenas ut neque turpis. Donec ornare hendrerit rutrum. Non nibh leo, dictum ullamcorper dui.

Body:
You can use .split()

var temp = yourText.split("[caption")

This gives you:

temp[0] with everything before "[caption"

temp[1] with everything after "[caption"

You can then continue to split/join the array fragments to eliminate any potion of the string.


问:
set facebook comment using xpath and selenium
I'm trying to post comment automatically using my browser. for that I made this code

```<code>static void Facebook()
    {
        var url = "http://facebook.com";

        var email = "email";
        var password = "password";

        ChromeOptions options = new ChromeOptions();
        options.AddArgument("--disable-notifications");

        driver = new ChromeDriver(options);

        driver.Url = url;

        driver.Manage().Window.Maximize();

        driver.FindElement(By.Id("email")).SendKeys(email);
        driver.FindElement(By.Id("pass")).SendKeys(password + Keys.Enter);

        driver.Url = "https://www.facebook.com/CsharpCorner/photos/a.487296564614322.115393.194086953935286/1572378532772781/?type=3&theater";

        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

        driver.FindElement(By.XPath(@"/html[@id='facebook']/body[@class='hasLeftCol _2yq home composerExpanded _5vb_ fbx _-kb s_v05quun15 chrome webkit win x1 Locale_en_US']/div[@id='photos_snowlift']/div[@class='_n9']/div[@class='_n3']/div[@class='fbPhotoSnowliftContainer snowliftPayloadRoot uiContextualLayerParent']/div[@class='clearfix fbPhotoSnowliftPopup']/div[@class='rhc photoUfiContainer']/div[@id='fbPhotoSnowliftDetails']/form[@id='u_4b_5']/div[@id='fbPhotoSnowliftFeedbackInput']/ul[@id='u_jsonp_3_18']/div[@id='addComment_1572378532772781']/div[@class='UFIMentionsInputWrap UFIStickersEnabledInput clearfix']/div[2]/div[@class='UFIImageBlockContent _42ef _8u']/div[@class='UFICommentContainer']/div[@class='_fmi UFIInputContainer']/div[@class='_2xwx _289c']/div[@id='composer_text_input_box']/div[@class='_5yk2']/div[@class='_5rp7']/div[@class='_5rpb']/div[@class='notranslate _5rpu']/div/div/div[@class='_1mf _1mj']"))
            .SendKeys("123123");

        Thread.Sleep(2000);
        driver.Quit();

    }
</code>```

This workd perfect till driver.findElement I've copied that xpath using xpath helper chrome extension but unfortunatelly I'm getting error that

no such element: Unable to locate element:...

What can I do?

答:
I suspect your XPath is too specific, here's what I would do:

First, when building an XPath, start by looking for an id, then look for "organizational" attributes like class, name, value, etc...

In your case, since you are using a tool to automatically generate an XPath, you should try to simplify it, looking for the same rules described above.

This would make it a little easier to debug, while making your XPath a bit more generic. This may solve cases where your tool is too specific when generating the XPath, for instance if an element's class is dynamically generated by some JavaScript.

Here's my process, using your XPath:

```<code>/html[@id='facebook']/body[@class='hasLeftCol _2yq home composerExpanded _5vb_ fbx _-kb s_v05quun15 chrome webkit win x1 Locale_en_US']/div[@id='photos_snowlift']/div[@class='_n9']/div[@class='_n3']/div[@class='fbPhotoSnowliftContainer snowliftPayloadRoot uiContextualLayerParent']/div[@class='clearfix fbPhotoSnowliftPopup']/div[@class='rhc photoUfiContainer']/div[@id='fbPhotoSnowliftDetails']/form[@id='u_4b_5']/div[@id='fbPhotoSnowliftFeedbackInput']/ul[@id='u_jsonp_3_18']/div[@id='addComment_1572378532772781']/div[@class='UFIMentionsInputWrap UFIStickersEnabledInput clearfix']/div[2]/div[@class='UFIImageBlockContent _42ef _8u']/div[@class='UFICommentContainer']/div[@class='_fmi UFIInputContainer']/div[@class='_2xwx _289c']/div[@id='composer_text_input_box']/div[@class='_5yk2']/div[@class='_5rp7']/div[@class='_5rpb']/div[@class='notranslate _5rpu']/div/div/div[@class='_1mf _1mj']
</code>```

Start from right to left, looking for a node with an id, and removing all nodes to its left:

```<code>/div[@id='composer_text_input_box']/div[@class='_5yk2']/div[@class='_5rp7']/div[@class='_5rpb']/div[@class='notranslate _5rpu']/div/div/div[@class='_1mf _1mj']
</code>```

Start from right to left again, looking for a node with an attribute, and removing all nodes to its left, except for the id node:

```<code>/div[@id='composer_text_input_box']/div[@class='_1mf _1mj']
</code>```

Add a / before both the id node and the attribute node. // signifies matching nodes recursively down the DOM tree.

```<code>//div[@id='composer_text_input_box']//div[@class='_1mf _1mj']
</code>```

Finally, verify correctness in the browser's console (F12) by searching (CTRL+F) for the XPath.

Body:
I'm trying to post comment automatically using my browser. for that I made this code

static void Facebook()
    {
        var url = "http://facebook.com";

        var email = "email";
        var password = "password";

        ChromeOptions options = new ChromeOptions();
        options.AddArgument("--disable-notifications");

        driver = new ChromeDriver(options);

        driver.Url = url;

        driver.Manage().Window.Maximize();

        driver.FindElement(By.Id("email")).SendKeys(email);
        driver.FindElement(By.Id("pass")).SendKeys(password + Keys.Enter);

        driver.Url = "https://www.facebook.com/CsharpCorner/photos/a.487296564614322.115393.194086953935286/1572378532772781/?type=3&theater";

        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

        driver.FindElement(By.XPath(@"/html[@id='facebook']/body[@class='hasLeftCol _2yq home composerExpanded _5vb_ fbx _-kb s_v05quun15 chrome webkit win x1 Locale_en_US']/div[@id='photos_snowlift']/div[@class='_n9']/div[@class='_n3']/div[@class='fbPhotoSnowliftContainer snowliftPayloadRoot uiContextualLayerParent']/div[@class='clearfix fbPhotoSnowliftPopup']/div[@class='rhc photoUfiContainer']/div[@id='fbPhotoSnowliftDetails']/form[@id='u_4b_5']/div[@id='fbPhotoSnowliftFeedbackInput']/ul[@id='u_jsonp_3_18']/div[@id='addComment_1572378532772781']/div[@class='UFIMentionsInputWrap UFIStickersEnabledInput clearfix']/div[2]/div[@class='UFIImageBlockContent _42ef _8u']/div[@class='UFICommentContainer']/div[@class='_fmi UFIInputContainer']/div[@class='_2xwx _289c']/div[@id='composer_text_input_box']/div[@class='_5yk2']/div[@class='_5rp7']/div[@class='_5rpb']/div[@class='notranslate _5rpu']/div/div/div[@class='_1mf _1mj']"))
            .SendKeys("123123");

        Thread.Sleep(2000);
        driver.Quit();

    }

This workd perfect till driver.findElement I've copied that xpath using xpath helper chrome extension but unfortunatelly I'm getting error that

no such element: Unable to locate element:...

What can I do?

Body:
I suspect your XPath is too specific, here's what I would do:

First, when building an XPath, start by looking for an id, then look for "organizational" attributes like class, name, value, etc...

In your case, since you are using a tool to automatically generate an XPath, you should try to simplify it, looking for the same rules described above.

This would make it a little easier to debug, while making your XPath a bit more generic. This may solve cases where your tool is too specific when generating the XPath, for instance if an element's class is dynamically generated by some JavaScript.

Here's my process, using your XPath:

/html[@id='facebook']/body[@class='hasLeftCol _2yq home composerExpanded _5vb_ fbx _-kb s_v05quun15 chrome webkit win x1 Locale_en_US']/div[@id='photos_snowlift']/div[@class='_n9']/div[@class='_n3']/div[@class='fbPhotoSnowliftContainer snowliftPayloadRoot uiContextualLayerParent']/div[@class='clearfix fbPhotoSnowliftPopup']/div[@class='rhc photoUfiContainer']/div[@id='fbPhotoSnowliftDetails']/form[@id='u_4b_5']/div[@id='fbPhotoSnowliftFeedbackInput']/ul[@id='u_jsonp_3_18']/div[@id='addComment_1572378532772781']/div[@class='UFIMentionsInputWrap UFIStickersEnabledInput clearfix']/div[2]/div[@class='UFIImageBlockContent _42ef _8u']/div[@class='UFICommentContainer']/div[@class='_fmi UFIInputContainer']/div[@class='_2xwx _289c']/div[@id='composer_text_input_box']/div[@class='_5yk2']/div[@class='_5rp7']/div[@class='_5rpb']/div[@class='notranslate _5rpu']/div/div/div[@class='_1mf _1mj']

Start from right to left, looking for a node with an id, and removing all nodes to its left:

/div[@id='composer_text_input_box']/div[@class='_5yk2']/div[@class='_5rp7']/div[@class='_5rpb']/div[@class='notranslate _5rpu']/div/div/div[@class='_1mf _1mj']

Start from right to left again, looking for a node with an attribute, and removing all nodes to its left, except for the id node:

/div[@id='composer_text_input_box']/div[@class='_1mf _1mj']

Add a / before both the id node and the attribute node. // signifies matching nodes recursively down the DOM tree.

//div[@id='composer_text_input_box']//div[@class='_1mf _1mj']

Finally, verify correctness in the browser's console (F12) by searching (CTRL+F) for the XPath.


问:
Find the same string in mysql table between certain column values
I have a table in MySQL database let's call it products:

```<code>id_product | id_lang | name
-----------+---------+-----
       654 |       1 | abc
       654 |       2 | xyz
       654 |       3 | abc
       456 |       1 | qwe
       456 |       2 | rty
       456 |       3 | zxc
       123 |       1 | bnm
       123 |       2 | bnm
       123 |       3 | jkl
       789 |       1 | ert
       789 |       2 | tyu
       789 |       3 | ert
       333 |       1 | ddd
       333 |       2 | o
       333 |       3 | bbb
       222 |       1 | xxx
       222 |       2 | zzz
       222 |       3 | o
</code>```

I would like to find all id_product which have the same name in id_lang 1 and 3. So result in this case should be id_product: 654 and 789. It would be great if in this query could find also all id_product where id_lang is 3 and name is "o". So result should be id_product: 654, 789 and 222. But if it is too complicated I can have two queries and merge two array's in PHP.

答:
You can use the following solution using GROUP BY and HAVING. With UNION you can merge two querys to get one result:

```<code>SELECT id_product
FROM products
WHERE id_lang IN (1, 3)
GROUP BY id_product, name
HAVING COUNT(name) > 1
UNION
SELECT id_product
FROM products
WHERE id_lang = 3 AND name = 'o'
</code>```

demo on dbfiddle.uk

To get your first expected result you can use the following query:

```<code>-- result of this query: 654 and 789
SELECT id_product
FROM table_name
WHERE id_lang IN (1, 3)
GROUP BY id_product, name
HAVING COUNT(name) > 1
</code>```

To get your second result you can use the following query:

```<code>-- result of this query: 222
SELECT id_product
FROM table_name
WHERE id_lang = 3 AND name = 'o'
</code>```

To join these two results you can merge the querys by using UNION (see solution at the beginning).

ContentLicense: CC BY-SA 4.0

Body:
I have a table in MySQL database let's call it products:

id_product | id_lang | name
-----------+---------+-----
       654 |       1 | abc
       654 |       2 | xyz
       654 |       3 | abc
       456 |       1 | qwe
       456 |       2 | rty
       456 |       3 | zxc
       123 |       1 | bnm
       123 |       2 | bnm
       123 |       3 | jkl
       789 |       1 | ert
       789 |       2 | tyu
       789 |       3 | ert
       333 |       1 | ddd
       333 |       2 | o
       333 |       3 | bbb
       222 |       1 | xxx
       222 |       2 | zzz
       222 |       3 | o

I would like to find all id_product which have the same name in id_lang 1 and 3. So result in this case should be id_product: 654 and 789. It would be great if in this query could find also all id_product where id_lang is 3 and name is "o". So result should be id_product: 654, 789 and 222. But if it is too complicated I can have two queries and merge two array's in PHP.

Body:
You can use the following solution using GROUP BY and HAVING. With UNION you can merge two querys to get one result:

SELECT id_product
FROM products
WHERE id_lang IN (1, 3)
GROUP BY id_product, name
HAVING COUNT(name) > 1
UNION
SELECT id_product
FROM products
WHERE id_lang = 3 AND name = 'o'

demo on dbfiddle.uk

To get your first expected result you can use the following query:

-- result of this query: 654 and 789
SELECT id_product
FROM table_name
WHERE id_lang IN (1, 3)
GROUP BY id_product, name
HAVING COUNT(name) > 1

To get your second result you can use the following query:

-- result of this query: 222
SELECT id_product
FROM table_name
WHERE id_lang = 3 AND name = 'o'

To join these two results you can merge the querys by using UNION (see solution at the beginning).


问:
How to get Javascript variable value into CSS?
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}
```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}
</code>```

答:
I'm not sure wether that's the best way to achieve what you want to do, as you could also use a container element and change its content directly:

const screenContentElement = document.getElementById('screen__content');

function pad(value) {
  const str = value + '';

  return str.length === 2 ? str : '0' + str;
}

function clock(){
  var d = new Date();

  return pad(d.getHours())
    + ':' + pad(d.getMinutes())
    + ':' + pad(d.getSeconds());
}

setInterval(() => {
  screenContentElement.innerText = clock();
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#screen {
  font-family: Arial, sans-serif;
  position: relative;
  height: 100%;
  width: 100%;
  background: #98E8EE;
  text-align: center;
  padding: 2rem 0;
}

#screen__content {
  color: #F9F5F4;
  font-size: 40px;
}</code>```

```
</div>
</div>
</p>

<p>However, regarding the code you provided, to dynamically change the value of a <code>content</code> property in a <code>CSS</code> pseudo-element you can use the <code>attr()</code> CSS function together with a <code>data-*</code> attribute:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const screenElement = document.getElementById('screen');

function pad(value) {
  const str = value + '';

  return str.length === 2 ? str : '0' + str;
}

function clock(){
  var d = new Date();

  return pad(d.getHours())
    + ':' + pad(d.getMinutes())
    + ':' + pad(d.getSeconds());
}

setInterval(() => {
  screenElement.dataset.time = clock();
}, 1000);</code>```

#screen {
  font-family: Arial, sans-serif;
  position: relative;
  height: 100%;
  width: 100%;
  background: #98E8EE;
  text-align: center;
  padding: 2rem 0;
}

#screen::before {
  color: #F9F5F4;
  font-size: 40px;
  content: attr(data-time);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="screen"></div></code>```

Body:
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}

CSS:

.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}

Body:
I'm not sure wether that's the best way to achieve what you want to do, as you could also use a container element and change its content directly:

const screenContentElement = document.getElementById('screen__content');

function pad(value) {
  const str = value + '';

  return str.length === 2 ? str : '0' + str;
}

function clock(){
  var d = new Date();

  return pad(d.getHours())
    + ':' + pad(d.getMinutes())
    + ':' + pad(d.getSeconds());
}

setInterval(() => {
  screenContentElement.innerText = clock();
}, 1000);

#screen {
  font-family: Arial, sans-serif;
  position: relative;
  height: 100%;
  width: 100%;
  background: #98E8EE;
  text-align: center;
  padding: 2rem 0;
}

#screen__content {
  color: #F9F5F4;
  font-size: 40px;
}

<div id="screen" class="screen">
  <span id="screen__content"></span>
</div>

However, regarding the code you provided, to dynamically change the value of a content property in a CSS pseudo-element you can use the attr() CSS function together with a data-* attribute:

const screenElement = document.getElementById('screen');

function pad(value) {
  const str = value + '';

  return str.length === 2 ? str : '0' + str;
}

function clock(){
  var d = new Date();

  return pad(d.getHours())
    + ':' + pad(d.getMinutes())
    + ':' + pad(d.getSeconds());
}

setInterval(() => {
  screenElement.dataset.time = clock();
}, 1000);

#screen {
  font-family: Arial, sans-serif;
  position: relative;
  height: 100%;
  width: 100%;
  background: #98E8EE;
  text-align: center;
  padding: 2rem 0;
}

#screen::before {
  color: #F9F5F4;
  font-size: 40px;
  content: attr(data-time);
}

<div id="screen"></div>


问:
WPF BitmapSource ImageSource
I am binding an Image.Source property to the result of the property shown below.

```<code>public BitmapSource MyImageSource
{
    get
    {
        BitmapSource source = null;

        PngBitmapDecoder decoder;
        using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                source = decoder.Frames[0];
        }

        return source;
    }
}
</code>```

For some reason this is failing during the rendering of the image (Deep in the PresentationCore assembly). I am certain the image is not corrupt as I can successfully show the same image w/o the binding

```<code><Image Name="FooImage" Source="/logo.png" />
</code>```

I have to bind the image source in code because I will eventually be creating the image stream from a base64 string.

Anyone know if this is a bug w/ WPF? or am I doing something incorrectly?

答:
Are you positive it's a PNG and not just a renamed Bitmap or Jpeg? If you create a new Bitmap image and then just rename it and change the file extension, this error is reproducible.

If I use a known PNG with your code, I don't get your issue, but a COM exception is thrown:

The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))

Can you try it out with a random PNG off the web and see if you get the same result?

Title: WPF BitmapSource ImageSource

Body:
I am binding an Image.Source property to the result of the property shown below.

public BitmapSource MyImageSource
{
    get
    {
        BitmapSource source = null;

        PngBitmapDecoder decoder;
        using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                source = decoder.Frames[0];
        }

        return source;
    }
}

For some reason this is failing during the rendering of the image (Deep in the PresentationCore assembly). I am certain the image is not corrupt as I can successfully show the same image w/o the binding

<Image Name="FooImage" Source="/logo.png" />

I have to bind the image source in code because I will eventually be creating the image stream from a base64 string.

Anyone know if this is a bug w/ WPF? or am I doing something incorrectly?

OwnerDisplayName: KP Adrian


问:
Replace backward slashes with forwards slashes or double backward slashes in C++
So I have a string:

```<code>string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";
</code>```

I want to replace all backward slashes in it with forward ones so it looks like:

```<code>C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug
</code>```

This does not work:

```<code>string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");
</code>```

Obviously, \ is an escape character so that is probably causing the problem.

答:
Is the "string path = ..." in your source file as shown?  If so, then there are no backslashes to replace.

The following program:

```<code>#include <iostream>
#include <string>

using namespace std;

int main()
{
    string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

    cout << path;
}
</code>```

Outputs:

```<code>C:UsersRichardDocumentsVisual Studio 2010ProjectsClientDebug
</code>```

Note: the above program compiles (with a bunch of warnings) in MSVC (through VS2010), but with GCC 4.5.1 I get an error:

```<code>C:\temp\test.cpp:8:19: error: incomplete universal character name \U
</code>```

The behavior of MSVC for this error (or GCC for that matter) might be configurable with appropriate options.

Body:
So I have a string:

string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

I want to replace all backward slashes in it with forward ones so it looks like:

C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug

This does not work:

string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");

Obviously, \ is an escape character so that is probably causing the problem.

Body:
Is the "string path = ..." in your source file as shown?  If so, then there are no backslashes to replace.

The following program:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

    cout << path;
}

Outputs:

C:UsersRichardDocumentsVisual Studio 2010ProjectsClientDebug

Note: the above program compiles (with a bunch of warnings) in MSVC (through VS2010), but with GCC 4.5.1 I get an error:

C:\temp\test.cpp:8:19: error: incomplete universal character name \U

The behavior of MSVC for this error (or GCC for that matter) might be configurable with appropriate options.


问:
Google Home - how to detect user name
How to detect username/email associated with google account from Google home?
i would like to use this name/email in greetings.

for example,
If user say, "OK google, Good Morning"
expecting below reply from  Google home,
"Good Morning user , how I can help you?" (user replaced with actual name )

Also tried to create intent in api.ai but need to provide name first and then GH will use that name in reply.  GH shouldn't speak user's name from its associated google account.

答:
For names, you can use the permissions documented here. Also take a look at this sample.

Emails are currently not supported without using account linking.

Title: Google Home - how to detect user name


问:
Get a piece of string and replace with other one?
I'm looking for a way to replace from HTML file the "href" and "src" content of each line with other string. So, I need to replace this:

```<code><img src="images/file.png" alt="">
</code>```

With this:

```<code><img src="data:image/png;base64,PD94bWwgdmVyc2lvbj0i..." alt="">
</code>```

Actually I write a function that can convert files to base64. I need to search for href/src, take his file path content and replace it with the base64 version of the file, but I don't know how to.

Here the function to convert files to base64:

```<code>def filetoB64 (fpath=None,raw=False):
    fstring = None
    fmime = None
    freturn = None

    if fpath is not None:
        if os.path.isfile(fpath):
            fmime = mimetypes.MimeTypes().guess_type(fpath)[0]

            if fmime in (filemimes['text'] + filemimes['image'] + filemimes['audio'] + filemimes['video']):
                with open(fpath,'rb') as f:
                    fcontent = f.read()
                    fstring = base64.encodestring(fcontent).replace('\n','')

                    if raw:
                        freturn = fstring
                    else:
                        freturn = ''.join(['data:',fmime,';base64,',fstring])
            else:
                freturn = fpath
        else:
            freturn = fpath

    return freturn
</code>```

答:
I'm assuming that your function to convert a file to base64 is fully working.

If you want to replace some tags in your HTML code, you can use regex like this example:

```<code>import re

string = '<img src="images/file.png" href="http://wwww.linktoreplace.com", alt="">'

to_replace = re.findall('(\w+)="(.*?)"', string)

for k, v in to_replace:
    if k == 'src':
        string = re.sub(v, "src_replaced_by_this_string", string)
    if k == 'href':
        string = re.sub(v, "href_replaced_by_this_string", string)

print(string)
</code>```

Output:

```<code><img src="src_replaced_by_this_string" href="href_replaced_by_this_string", alt="">
</code>```

Otherwise, you can use BeautifulSoup which is a Python library for pulling data out of HTML and XML files.

Body:
I'm looking for a way to replace from HTML file the "href" and "src" content of each line with other string. So, I need to replace this:

With this:

Actually I write a function that can convert files to base64. I need to search for href/src, take his file path content and replace it with the base64 version of the file, but I don't know how to.

Here the function to convert files to base64:

def filetoB64 (fpath=None,raw=False):
    fstring = None
    fmime = None
    freturn = None

    if fpath is not None:
        if os.path.isfile(fpath):
            fmime = mimetypes.MimeTypes().guess_type(fpath)[0]

            if fmime in (filemimes['text'] + filemimes['image'] + filemimes['audio'] + filemimes['video']):
                with open(fpath,'rb') as f:
                    fcontent = f.read()
                    fstring = base64.encodestring(fcontent).replace('\n','')

                    if raw:
                        freturn = fstring
                    else:
                        freturn = ''.join(['data:',fmime,';base64,',fstring])
            else:
                freturn = fpath
        else:
            freturn = fpath

    return freturn

Body:
I'm assuming that your function to convert a file to base64 is fully working.

If you want to replace some tags in your HTML code, you can use regex like this example:

import re

string = '<img src="images/file.png" href="http://wwww.linktoreplace.com", alt="">'

to_replace = re.findall('(\w+)="(.*?)"', string)

for k, v in to_replace:
    if k == 'src':
        string = re.sub(v, "src_replaced_by_this_string", string)
    if k == 'href':
        string = re.sub(v, "href_replaced_by_this_string", string)

print(string)

Output:

<img src="src_replaced_by_this_string" href="href_replaced_by_this_string", alt="">

Otherwise, you can use BeautifulSoup which is a Python library for pulling data out of HTML and XML files.


问:
How do I parse a java simple date format in R?
The extra T and Z are throwing me off:

```<code>strptime("2017-06-08T11:55:53.179000Z", "%Y-%m-%dT%H:%M:%SZ")
</code>```

Returns NA

答:
According to ?strptime, you can parse it with %OS parameter by setting the digits.secs option:

Specific to R is %OSn, which for output gives the seconds truncated to
  0 <= n <= 6 decimal places (and if %OS is not followed by a digit, it
  uses the setting of getOption("digits.secs"), or if that is unset, n =
  0). Further, for strptime %OS will input seconds including fractional
  seconds. Note that %S does not read fractional parts on output.

```<code>options(digits.secs = 6)
strptime("2017-06-08T11:55:53.179000Z", "%Y-%m-%dT%H:%M:%OSZ")
# [1] "2017-06-08 11:55:53.179 EDT"
</code>```

Body:
The extra T and Z are throwing me off:

strptime("2017-06-08T11:55:53.179000Z", "%Y-%m-%dT%H:%M:%SZ")

Returns NA

Body:
According to ?strptime, you can parse it with %OS parameter by setting the digits.secs option:

Specific to R is %OSn, which for output gives the seconds truncated to
  0 <= n <= 6 decimal places (and if %OS is not followed by a digit, it
  uses the setting of getOption("digits.secs"), or if that is unset, n =
  0). Further, for strptime %OS will input seconds including fractional
  seconds. Note that %S does not read fractional parts on output.

options(digits.secs = 6)
strptime("2017-06-08T11:55:53.179000Z", "%Y-%m-%dT%H:%M:%OSZ")
# [1] "2017-06-08 11:55:53.179 EDT"


问:
Google Analytics reports stopped updating but real time view still shows activity
I recently started using Google Analytics and everything seemed to be working for the first few days. Then a few days ago the overview stopped working but the real time view seems fine.

I'm using some custom code to send measurement protocol requests via HTTP and that code hasn't changed since it was released. Google Analytics also reports "no data received in the last 48 hours" even though I can see events coming in in real time.

When I called Google's support line they seemed to think it was a problem with how the events are generated. I don't see how that could be the case, since the code hasn't changed, but maybe someone else has an idea?

Here's the code that's sending the event:

```<code>BOOL SendGoogleAnalytics(char* action, char* category)
{
   if (!IsGoogleAnalyticsEnabled())
   {
      return FALSE;
   }

   CStringA strAction = CStringA(action);
   CStringA strCategory = CStringA(category);

   HttpRequest req;
   Http http;

   CStringA strClientID = "0";

   req.UsePost();
   req.put_Path("www.google-analytics.com");

   req.AddHeader("HOST", m_GAHost);
   req.AddHeader("Accept", "*/*");
   req.put_ContentType("text/html");

   req.AddParam("v",   "1");
   req.AddParam("t",   "event");
   req.AddParam("tid", "UA-xxxxxxxx-xx");
   req.AddParam("cid", strClientID);
   req.AddParam("ni",  "1");
   req.AddParam("an",  "My App");
   req.AddParam("av",  x.x.x.x);
   req.AddParam("ec",  strCategory);
   req.AddParam("ea",  strAction);
   req.AddParam("el",  "dist code 1");
   req.AddParam("ds",  "this code");

   return SendPost(m_GAHost, false, &req);
}
</code>```

答: It turns out that Google Analytics will only accept a certain number of hits from each client ID in a given time frame. Replacing strClientID above with a per-user GUID string solved the problem.</p>

Body:
I recently started using Google Analytics and everything seemed to be working for the first few days. Then a few days ago the overview stopped working but the real time view seems fine.

I'm using some custom code to send measurement protocol requests via HTTP and that code hasn't changed since it was released. Google Analytics also reports "no data received in the last 48 hours" even though I can see events coming in in real time.

When I called Google's support line they seemed to think it was a problem with how the events are generated. I don't see how that could be the case, since the code hasn't changed, but maybe someone else has an idea?

Here's the code that's sending the event:

BOOL SendGoogleAnalytics(char* action, char* category)
{
   if (!IsGoogleAnalyticsEnabled())
   {
      return FALSE;
   }

   CStringA strAction = CStringA(action);
   CStringA strCategory = CStringA(category);

   HttpRequest req;
   Http http;

   CStringA strClientID = "0";

   req.UsePost();
   req.put_Path("www.google-analytics.com");

   req.AddHeader("HOST", m_GAHost);
   req.AddHeader("Accept", "*/*");
   req.put_ContentType("text/html");

   req.AddParam("v",   "1");
   req.AddParam("t",   "event");
   req.AddParam("tid", "UA-xxxxxxxx-xx");
   req.AddParam("cid", strClientID);
   req.AddParam("ni",  "1");
   req.AddParam("an",  "My App");
   req.AddParam("av",  x.x.x.x);
   req.AddParam("ec",  strCategory);
   req.AddParam("ea",  strAction);
   req.AddParam("el",  "dist code 1");
   req.AddParam("ds",  "this code");

   return SendPost(m_GAHost, false, &req);
}


问:
Log all warnings with futile.logger
Trying to log all errors and warnings with futile.logger.

Somewhat satisfied with this for dealing with errors:

```<code>library(futile.logger)
options(error = function() { flog.error(geterrmessage()) ; traceback() ; stop() })
log("a")
# Error in log("a") : argument non numérique pour une fonction mathématique
# ERROR [2016-12-01 21:12:07] Error in log("a") : argument non numérique pour une fonction mathématique
#
# No traceback available
# Erreur pendant l'emballage (wrapup) :
</code>```

There is redundancy, but I can easily separate between stderr, stdout and log file, so it's not a problem. It's certainly not pretty, there is an additional "wrapup" error message somehow caused by the final stop() that I don't understand, so I'm open to suggestions.

I cannot find a similar solution for warnings. What I tried:

```<code>options(warn = 1L)
options(warning.expression = expression(flog.warn(last.warning)))
log(- 1)
# [1] NaN
</code>```

But to no avail.

Follow-up question: Are there best practices that I am unknowingly ignoring?

答:
In can contribute two options to log R conditions like warnings with futile.logger and catch all warnings no matter how deep the function call stack is:

Wrap your code with withCallingHandlers for a basic solution

Use my package tryCatchLog for an advanced solution (for compliance reason: I am the author)

To explain the solutions I have created a simple R script that produces warnings and errors:

```<code># Store this using the file name "your_code_file.R"
# This could be your code...

f1 <- function(value) {
  print("f1() called")
  f2(value)                 # call another function to show what happens
  print("f1() returns")
}

f2 <- function(value) {
  print("f2() called")
  a <- log(-1)           # This throws a warning: "NaNs produced"
  print(paste("log(-1) =", a))
  b <- log(value)        # This throws an error if you pass a string as value
  print("f2() returns")
}

f1(1)  # produces a warning
f1("not a number") # produces a warning and an error
</code>```

Executed "as is" (without logging) this code produces this output:

```<code>[1] "f1() called"
[1] "f2() called"
[1] "log(-1) = NaN"
[1] "f2() returns"
[1] "f1() returns"
[1] "f1() called"
[1] "f2() called"
[1] "log(-1) = NaN"
Error in log(value) : non-numeric argument to mathematical function
Calls: source -> withVisible -> eval -> eval -> f1 -> f2
In addition: Warning messages:
1: In log(-1) : NaNs produced
2: In log(-1) : NaNs produced
</code>```

Solution 1 (withCallingHandlers)

Create a new R file that is called by R and sources your unchanged (!) original R script:

```<code># Store this using the file name "logging_injector_withCallingHandlers.R"
# Main function to inject logging of warnings without changing your original source code

library(futile.logger)

flog.threshold(INFO)

# Injecting the logging of errors and warnings:
tryCatch(withCallingHandlers({
  source("your_code_file.R")     # call your unchanged code by sourcing it!
}, error = function(e) {
     call.stack <- sys.calls()   # "sys.calls" within "withCallingHandlers" is like a traceback!
     log.message <- e$message
     flog.error(log.message)     # let's ignore the call.stack for now since it blows-up the output
}, warning = function(w) {
     call.stack <- sys.calls()   # "sys.calls" within "withCallingHandlers" is like a traceback!
     log.message <- w$message
     flog.warn(log.message)      # let's ignore the call.stack for now since it blows-up the output
     invokeRestart("muffleWarning")  # avoid warnings to "bubble up" to being printed at the end by the R runtime
})
 , error = function(e) {
  flog.info("Logging injector: The called user code had errors...")
})
</code>```

If you execute this wrapper code the R output is:

```<code>$ Rscript logging_injector_withCallingHandlers.R
NULL
[1] "f1() called"
[1] "f2() called"
WARN [2017-06-08 22:35:53] NaNs produced
[1] "log(-1) = NaN"
[1] "f2() returns"
[1] "f1() returns"
[1] "f1() called"
[1] "f2() called"
WARN [2017-06-08 22:35:53] NaNs produced
[1] "log(-1) = NaN"
ERROR [2017-06-08 22:35:53] non-numeric argument to mathematical function
INFO [2017-06-08 22:35:53] Logging injector: The called user code had errors...
</code>```

As you can see

warnings are logged now

the call stack could be output too (I have disabled this to avoid flooding this answer)

References: https://stackoverflow.com/a/19446931/4468078

Solution 2 - package tryCatchLog (I am the author)

Solution 1 has some drawbacks, mainly:

The stack trace ("traceback") does not contain file names and line numbers

The stack trace is flooded with internal function calls you don't want to see (believe me or try it with your non-trival R scripts ;-)

Instead of copying&pasting the above code snippet again and again I have developed a package that encapsulates the above withCallingHandlers logic in a function and adds additional features like

logging of errors, warnings and messages

identifying the origin of errors and warnings by logging a stack trace with a reference to the source file name and line number

support post-mortem analysis after errors by creating a dump file with all variables of the global environment (workspace) and each function called (via dump.frames) - very helpful for batch jobs that you cannot debug on the server directly to reproduce the error!

To wrap the above R script file using tryCatchLog create a wrapper file

```<code># Store this using the file name "logging_injector_tryCatchLog.R"
# Main function to inject logging of warnings without changing your original source code

# install.packages("devtools")
# library(devtools)
# install_github("aryoda/tryCatchLog")
library(tryCatchLog)
library(futile.logger)

flog.threshold(INFO)

tryCatchLog({
  source("your_code_file.R")     # call your unchanged code by sourcing it!
  #, dump.errors.to.file = TRUE  # Saves a dump of the workspace and the call stack named dump_<YYYYMMDD_HHMMSS>.rda
})
</code>```

and execute it via Rscript to get this (shortened!) result:

```<code># $ Rscript -e "options(keep.source = TRUE); source('logging_injector_tryCatchLog.R')" > log.txt
[1] "f1() called"
[1] "f2() called"
WARN [2017-06-08 23:13:31] NaNs produced
Compact call stack:
  1 source("logging_injector_tryCatchLog.R")
  2 logging_injector_tryCatchLog.R#12: tryCatchLog({
  3 logging_injector_tryCatchLog.R#13: source("your_code_file.R")
  4 your_code_file.R#18: f1(1)
  5 your_code_file.R#6: f2(value)
  6 your_code_file.R#12: .signalSimpleWarning("NaNs produced", quote(log(-1)))
Full call stack:
  1 source("logging_injector_tryCatchLog.R")
  2 withVisible(eval(ei, envir))

  ...
<a lot of logging output omitted here...>
</code>```

As you can see clearly at the call stack level 6 the source code file name and line number (#12) is logged as the source of the warning together with the source code snippet throwing the warning:

6  your_code_file.R#12 .signalSimpleWarning("NaNs produced", quote(log(-1)))

Title: Log all warnings with futile.logger

Body:
Trying to log all errors and warnings with futile.logger.

Somewhat satisfied with this for dealing with errors:

library(futile.logger)
options(error = function() { flog.error(geterrmessage()) ; traceback() ; stop() })
log("a")
# Error in log("a") : argument non numérique pour une fonction mathématique
# ERROR [2016-12-01 21:12:07] Error in log("a") : argument non numérique pour une fonction mathématique
#
# No traceback available
# Erreur pendant l'emballage (wrapup) :

There is redundancy, but I can easily separate between stderr, stdout and log file, so it's not a problem. It's certainly not pretty, there is an additional "wrapup" error message somehow caused by the final stop() that I don't understand, so I'm open to suggestions.

I cannot find a similar solution for warnings. What I tried:

options(warn = 1L)
options(warning.expression = expression(flog.warn(last.warning)))
log(- 1)
# [1] NaN

But to no avail.

Follow-up question: Are there best practices that I am unknowingly ignoring?

Body:
In can contribute two options to log R conditions like warnings with futile.logger and catch all warnings no matter how deep the function call stack is:

Wrap your code with withCallingHandlers for a basic solution

Use my package tryCatchLog for an advanced solution (for compliance reason: I am the author)

To explain the solutions I have created a simple R script that produces warnings and errors:

# Store this using the file name "your_code_file.R"
# This could be your code...

f1 <- function(value) {
  print("f1() called")
  f2(value)                 # call another function to show what happens
  print("f1() returns")
}

f2 <- function(value) {
  print("f2() called")
  a <- log(-1)           # This throws a warning: "NaNs produced"
  print(paste("log(-1) =", a))
  b <- log(value)        # This throws an error if you pass a string as value
  print("f2() returns")
}

f1(1)  # produces a warning
f1("not a number") # produces a warning and an error

Executed "as is" (without logging) this code produces this output:

[1] "f1() called"
[1] "f2() called"
[1] "log(-1) = NaN"
[1] "f2() returns"
[1] "f1() returns"
[1] "f1() called"
[1] "f2() called"
[1] "log(-1) = NaN"
Error in log(value) : non-numeric argument to mathematical function
Calls: source -> withVisible -> eval -> eval -> f1 -> f2
In addition: Warning messages:
1: In log(-1) : NaNs produced
2: In log(-1) : NaNs produced

Solution 1 (withCallingHandlers)

Create a new R file that is called by R and sources your unchanged (!) original R script:

# Store this using the file name "logging_injector_withCallingHandlers.R"
# Main function to inject logging of warnings without changing your original source code

library(futile.logger)

flog.threshold(INFO)

# Injecting the logging of errors and warnings:
tryCatch(withCallingHandlers({
  source("your_code_file.R")     # call your unchanged code by sourcing it!
}, error = function(e) {
     call.stack <- sys.calls()   # "sys.calls" within "withCallingHandlers" is like a traceback!
     log.message <- e$message
     flog.error(log.message)     # let's ignore the call.stack for now since it blows-up the output
}, warning = function(w) {
     call.stack <- sys.calls()   # "sys.calls" within "withCallingHandlers" is like a traceback!
     log.message <- w$message
     flog.warn(log.message)      # let's ignore the call.stack for now since it blows-up the output
     invokeRestart("muffleWarning")  # avoid warnings to "bubble up" to being printed at the end by the R runtime
})
 , error = function(e) {
  flog.info("Logging injector: The called user code had errors...")
})

If you execute this wrapper code the R output is:

$ Rscript logging_injector_withCallingHandlers.R
NULL
[1] "f1() called"
[1] "f2() called"
WARN [2017-06-08 22:35:53] NaNs produced
[1] "log(-1) = NaN"
[1] "f2() returns"
[1] "f1() returns"
[1] "f1() called"
[1] "f2() called"
WARN [2017-06-08 22:35:53] NaNs produced
[1] "log(-1) = NaN"
ERROR [2017-06-08 22:35:53] non-numeric argument to mathematical function
INFO [2017-06-08 22:35:53] Logging injector: The called user code had errors...

As you can see

warnings are logged now

the call stack could be output too (I have disabled this to avoid flooding this answer)

References: https://stackoverflow.com/a/19446931/4468078

Solution 2 - package tryCatchLog (I am the author)

Solution 1 has some drawbacks, mainly:

The stack trace ("traceback") does not contain file names and line numbers

The stack trace is flooded with internal function calls you don't want to see (believe me or try it with your non-trival R scripts ;-)

Instead of copying&pasting the above code snippet again and again I have developed a package that encapsulates the above withCallingHandlers logic in a function and adds additional features like

logging of errors, warnings and messages

identifying the origin of errors and warnings by logging a stack trace with a reference to the source file name and line number

support post-mortem analysis after errors by creating a dump file with all variables of the global environment (workspace) and each function called (via dump.frames) - very helpful for batch jobs that you cannot debug on the server directly to reproduce the error!

To wrap the above R script file using tryCatchLog create a wrapper file

# Store this using the file name "logging_injector_tryCatchLog.R"
# Main function to inject logging of warnings without changing your original source code

# install.packages("devtools")
# library(devtools)
# install_github("aryoda/tryCatchLog")
library(tryCatchLog)
library(futile.logger)

flog.threshold(INFO)

tryCatchLog({
  source("your_code_file.R")     # call your unchanged code by sourcing it!
  #, dump.errors.to.file = TRUE  # Saves a dump of the workspace and the call stack named dump_<YYYYMMDD_HHMMSS>.rda
})

and execute it via Rscript to get this (shortened!) result:

# $ Rscript -e "options(keep.source = TRUE); source('logging_injector_tryCatchLog.R')" > log.txt
[1] "f1() called"
[1] "f2() called"
WARN [2017-06-08 23:13:31] NaNs produced
Compact call stack:
  1 source("logging_injector_tryCatchLog.R")
  2 logging_injector_tryCatchLog.R#12: tryCatchLog({
  3 logging_injector_tryCatchLog.R#13: source("your_code_file.R")
  4 your_code_file.R#18: f1(1)
  5 your_code_file.R#6: f2(value)
  6 your_code_file.R#12: .signalSimpleWarning("NaNs produced", quote(log(-1)))
Full call stack:
  1 source("logging_injector_tryCatchLog.R")
  2 withVisible(eval(ei, envir))

  ...
<a lot of logging output omitted here...>

As you can see clearly at the call stack level 6 the source code file name and line number (#12) is logged as the source of the warning together with the source code snippet throwing the warning:

6  your_code_file.R#12 .signalSimpleWarning("NaNs produced", quote(log(-1)))


问:
Disable checkboxes based on status of one checkbox
if 'choose not to answer' is checked, i need to disable the other checkboxes, here is my code and html, any help as to why it's not working?

code

```<code>function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
    $('#living :input').attr('disabled', true);
} else {
    $('#living :input').removeAttr('disabled');
}
</code>```

html

```<code><p>With whom do you live? Choose all that apply<br/>
    <input type="checkbox" name="living" value="alone" id="living">
    Live alone <br>
    <input type="checkbox" name="living" value="husband" id="living">
    Husband <br>
    <input type="checkbox" name="living" value="partner" id="living">
    Partner <br>
    <input type="checkbox" name="living" value="children" id="living">
    Children <br>
    <input type="checkbox" name="living" value="parents" id="living">
    Parents <br>
    <input type="checkbox" name="living" value="other_relatives" id="living">
    Other relatives <br>
    <input type="checkbox" name="living" value="religion" id="living">
    Religious order <br>
    <input type="checkbox" name="living" value="no_answer"
                id="toggleElement">
    Choose not to answer <br>
</p>
</code>```

答:
I don't see your function being called anywhere, you can rig it up inside a document.ready handler though, and simplify it too, like this:

```<code>$(function() {
  $("#toggleElement").change(function() {
    $('input[name=living]').not(this).attr('disabled', this.checked);
  });
});
</code>```

Also note that your selector was incorrect, it should be just based on the name...and that ID should be left out, since it's duplicated.

Body:
if 'choose not to answer' is checked, i need to disable the other checkboxes, here is my code and html, any help as to why it's not working?

code

function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
    $('#living :input').attr('disabled', true);
} else {
    $('#living :input').removeAttr('disabled');
}

html

With whom do you live? Choose all that apply

    <input type="checkbox" name="living" value="alone" id="living">
    Live alone

    <input type="checkbox" name="living" value="husband" id="living">
    Husband

    <input type="checkbox" name="living" value="partner" id="living">
    Partner

    <input type="checkbox" name="living" value="children" id="living">
    Children

    <input type="checkbox" name="living" value="parents" id="living">
    Parents

    <input type="checkbox" name="living" value="other_relatives" id="living">
    Other relatives

    <input type="checkbox" name="living" value="religion" id="living">
    Religious order

    <input type="checkbox" name="living" value="no_answer"
                id="toggleElement">
    Choose not to answer

Body:
I don't see your function being called anywhere, you can rig it up inside a document.ready handler though, and simplify it too, like this:

$(function() {
  $("#toggleElement").change(function() {
    $('input[name=living]').not(this).attr('disabled', this.checked);
  });
});

Also note that your selector was incorrect, it should be just based on the name...and that ID should be left out, since it's duplicated.


问:
Creating a 2d numpy array to hold characters
I have the following numpy array and previous set up that has a word queue and a temporary variable 'temp' to store a word. This word needs to be "put", letter by letter, into the numpy 2d array:

```<code>from collections import deque
import numpy as np
message=input("Write a message:")
wordqueue=message.split()
queue=deque(wordqueue)
print(wordqueue)

for i in range(1):
  temp=wordqueue.pop(0) #store the removed item in the temporary variable 'temp'
print(wordqueue)
print(temp)
display = np.zeros((4,10)) #create a 2d array that is to store the words from the queue
print(display)
display[0, 0] = temp #add the word from the temp variable to fill the array (each character in each sequential position in the array)
print(display)
</code>```

Unfortunately, the output is as follows:

```<code>Write a message: This is a message for the display array
['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
['is', 'a', 'message', 'for', 'the', 'display', 'array']
This
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
Traceback (most recent call last):
  File "python", line 20, in <module>
ValueError: could not convert string to float: 'This'
</code>```

I did try to define the 2d array and define the data type, but that too wasn't very obvious and I kept getting various errors.

What I would like help with is the following:
1. Ideally, I would like the numpy array to be set up with "*"s instead of zeros/ones (the documentation didn't help with this setup).
2. Replace the *s in the array with the temp variable. One letter for each *

EXAMPLE:

Display array:
 (4 x 20)

```<code>* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
</code>```

Enter Message: This is a test message
temp: This

Updated display would show:

```<code>t h i s * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
</code>```

for subsequent words, it would then populate the array (truncating if the word was too big and going to the next line if necessary)

So far:
https://repl.it/IcJ3/7

I tried this, for instance, to create the char array:

```<code>display = np.chararray((4,10)) #create a 2d array that is to store the letters in the words from the queue
display[:]="*"
</code>```

but it produced this, with the erroneous "b" inserted. Cannot see why ...

```<code>[[b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']]
</code>```

Updated (working on )repl.it here:
https://repl.it/IcJ3/8

答:
Going from a string to a list to an array containing one word per element:

```<code>In [402]: astr = "This is a message for the display array"
In [403]: alist = astr.split()
In [404]: alist
Out[404]: ['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
In [405]: arr = np.array(alist)
In [406]: arr
Out[406]:
array(['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array'],
      dtype='<U7')
In [407]: arr.shape
Out[407]: (8,)
</code>```

I'm using PY3, so the dtype is U7, chosen automatically by np.array to be big enough to hold the largest string in the list.

For an array to hold single characters:

```<code>In [408]: carr = np.zeros((4,10), 'U1')
In [409]: carr
Out[409]:
array([['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', '']],
      dtype='<U1')
In [410]: carr.fill('*')
In [411]: carr
Out[411]:
array([['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')
</code>```

Make an array of single characters from the string:

```<code>In [430]: np.array(list(astr))
Out[430]:
array(['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'm', 'e', 's',
       's', 'a', 'g', 'e', ' ', 'f', 'o', 'r', ' ', 't', 'h', 'e', ' ',
       'd', 'i', 's', 'p', 'l', 'a', 'y', ' ', 'a', 'r', 'r', 'a', 'y'],
      dtype='<U1')
</code>```

Mapping the list of words on to single character array is a bit more tedious.  This goes into the arr[0,0:4], etc.

Here's a way of mapping a list of words onto an array:

```<code>In [462]: alist
Out[462]: ['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
In [463]: ''.join(alist)                     # back to one string
Out[463]: 'Thisisamessageforthedisplayarray'
In [464]: np.array(list(''.join(alist)))     # a flat array of char
Out[464]:
array(['T', 'h', 'i', 's', 'i', 's', 'a', 'm', 'e', 's', 's', 'a', 'g',
       'e', 'f', 'o', 'r', 't', 'h', 'e', 'd', 'i', 's', 'p', 'l', 'a',
       'y', 'a', 'r', 'r', 'a', 'y'],
      dtype='<U1')
In [465]: _.shape
Out[465]: (32,)
</code>```

or I could copy the list of characters onto an existing array (using flat to treat it as 1d):

```<code>In [466]: arr = np.zeros((4,10), 'U1')
In [467]: arr.flat[:32] = list(''.join(alist))
In [468]: arr
Out[468]:
array([['T', 'h', 'i', 's', 'i', 's', 'a', 'm', 'e', 's'],
       ['s', 'a', 'g', 'e', 'f', 'o', 'r', 't', 'h', 'e'],
       ['d', 'i', 's', 'p', 'l', 'a', 'y', 'a', 'r', 'r'],
       ['a', 'y', '', '', '', '', '', '', '', '']],
      dtype='<U1')
</code>```

and if I throw in blanks between words:

```<code>In [471]: arr.flat[:39] = list(' '.join(alist))
In [472]: arr
Out[472]:
array([['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' '],
       ['m', 'e', 's', 's', 'a', 'g', 'e', ' ', 'f', 'o'],
       ['r', ' ', 't', 'h', 'e', ' ', 'd', 'i', 's', 'p'],
       ['l', 'a', 'y', ' ', 'a', 'r', 'r', 'a', 'y', '']],
      dtype='<U1')
</code>```

Body:
I have the following numpy array and previous set up that has a word queue and a temporary variable 'temp' to store a word. This word needs to be "put", letter by letter, into the numpy 2d array:

from collections import deque
import numpy as np
message=input("Write a message:")
wordqueue=message.split()
queue=deque(wordqueue)
print(wordqueue)

for i in range(1):
  temp=wordqueue.pop(0) #store the removed item in the temporary variable 'temp'
print(wordqueue)
print(temp)
display = np.zeros((4,10)) #create a 2d array that is to store the words from the queue
print(display)
display[0, 0] = temp #add the word from the temp variable to fill the array (each character in each sequential position in the array)
print(display)

Unfortunately, the output is as follows:

Write a message: This is a message for the display array
['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
['is', 'a', 'message', 'for', 'the', 'display', 'array']
This
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
Traceback (most recent call last):
  File "python", line 20, in <module>
ValueError: could not convert string to float: 'This'

I did try to define the 2d array and define the data type, but that too wasn't very obvious and I kept getting various errors.

What I would like help with is the following:
1. Ideally, I would like the numpy array to be set up with "*"s instead of zeros/ones (the documentation didn't help with this setup).
2. Replace the *s in the array with the temp variable. One letter for each *

EXAMPLE:

Display array:
 (4 x 20)

* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *

Enter Message: This is a test message
temp: This

Updated display would show:

t h i s * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *

for subsequent words, it would then populate the array (truncating if the word was too big and going to the next line if necessary)

So far:
https://repl.it/IcJ3/7

I tried this, for instance, to create the char array:

display = np.chararray((4,10)) #create a 2d array that is to store the letters in the words from the queue
display[:]="*"

but it produced this, with the erroneous "b" inserted. Cannot see why ...

[[b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']
 [b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*' b'*']]

Updated (working on )repl.it here:
https://repl.it/IcJ3/8

Body:
Going from a string to a list to an array containing one word per element:

In [402]: astr = "This is a message for the display array"
In [403]: alist = astr.split()
In [404]: alist
Out[404]: ['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
In [405]: arr = np.array(alist)
In [406]: arr
Out[406]:
array(['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array'],
      dtype='<U7')
In [407]: arr.shape
Out[407]: (8,)

I'm using PY3, so the dtype is U7, chosen automatically by np.array to be big enough to hold the largest string in the list.

For an array to hold single characters:

In [408]: carr = np.zeros((4,10), 'U1')
In [409]: carr
Out[409]:
array([['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', ''],
       ['', '', '', '', '', '', '', '', '', '']],
      dtype='<U1')
In [410]: carr.fill('*')
In [411]: carr
Out[411]:
array([['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']],
      dtype='<U1')

Make an array of single characters from the string:

In [430]: np.array(list(astr))
Out[430]:
array(['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'm', 'e', 's',
       's', 'a', 'g', 'e', ' ', 'f', 'o', 'r', ' ', 't', 'h', 'e', ' ',
       'd', 'i', 's', 'p', 'l', 'a', 'y', ' ', 'a', 'r', 'r', 'a', 'y'],
      dtype='<U1')

Mapping the list of words on to single character array is a bit more tedious.  This goes into the arr[0,0:4], etc.

Here's a way of mapping a list of words onto an array:

In [462]: alist
Out[462]: ['This', 'is', 'a', 'message', 'for', 'the', 'display', 'array']
In [463]: ''.join(alist)                     # back to one string
Out[463]: 'Thisisamessageforthedisplayarray'
In [464]: np.array(list(''.join(alist)))     # a flat array of char
Out[464]:
array(['T', 'h', 'i', 's', 'i', 's', 'a', 'm', 'e', 's', 's', 'a', 'g',
       'e', 'f', 'o', 'r', 't', 'h', 'e', 'd', 'i', 's', 'p', 'l', 'a',
       'y', 'a', 'r', 'r', 'a', 'y'],
      dtype='<U1')
In [465]: _.shape
Out[465]: (32,)

or I could copy the list of characters onto an existing array (using flat to treat it as 1d):

In [466]: arr = np.zeros((4,10), 'U1')
In [467]: arr.flat[:32] = list(''.join(alist))
In [468]: arr
Out[468]:
array([['T', 'h', 'i', 's', 'i', 's', 'a', 'm', 'e', 's'],
       ['s', 'a', 'g', 'e', 'f', 'o', 'r', 't', 'h', 'e'],
       ['d', 'i', 's', 'p', 'l', 'a', 'y', 'a', 'r', 'r'],
       ['a', 'y', '', '', '', '', '', '', '', '']],
      dtype='<U1')

and if I throw in blanks between words:

In [471]: arr.flat[:39] = list(' '.join(alist))
In [472]: arr
Out[472]:
array([['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' '],
       ['m', 'e', 's', 's', 'a', 'g', 'e', ' ', 'f', 'o'],
       ['r', ' ', 't', 'h', 'e', ' ', 'd', 'i', 's', 'p'],
       ['l', 'a', 'y', ' ', 'a', 'r', 'r', 'a', 'y', '']],
      dtype='<U1')


答:
If you want to use the value of time in some css property then you can simple do that using javascript/jquery : </p>

```<code>$("#SomeId or .SomeCLass").css("PropertyName",time);
</code>```

Title: How to get Javascript variable value into CSS?

Body:
If you want to use the value of time in some css property then you can simple do that using javascript/jquery :

$("#SomeId or .SomeCLass").css("PropertyName",time);


问:
sudo: command not found when I ssh into server
I am a newbie with server handling and Linux. I am trying to install composer on my server so that i can host my Laravel project onto it as mentioned in the tutorial in Ultimate Guide: Deploy Laravel 5.3 App on LEMP Stack. I ssh into the server and after installation of composer when I run sudo mv composer.phar /usr/local/bin/composer I am getting a message in the terminal:

```<code>-bash: sudo: command not found
</code>```

I desperately need some deliberate help

答:
As suggested in this post, you may have to install sudo in your server.

To do that, log in as root with the following command: su -. Then install sudo with your package manager (if you're in Ubuntu: apt-get install sudo).

Then add your user to the sudo group: usermod -aG sudo <username>.

Finally type exit to log out of the root account and go back to your user.

Body:
I am a newbie with server handling and Linux. I am trying to install composer on my server so that i can host my Laravel project onto it as mentioned in the tutorial in Ultimate Guide: Deploy Laravel 5.3 App on LEMP Stack. I ssh into the server and after installation of composer when I run sudo mv composer.phar /usr/local/bin/composer I am getting a message in the terminal:

-bash: sudo: command not found

I desperately need some deliberate help


问:
Java object, interface
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class</p>

```<code>import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};
</code>```

答:
You can't have multiple public classes/interfaces in a single Java file.  Remove the public keyword and nest them inside the CalcModel class if you want to keep them all in the same file, otherwise it needs to be in its own file.

Also, you misspelled the interface declaration "Oparation" (which you refer to as Operation elsewhere).

The code seems to have quite a few other issues as well ...

Title: Java object, interface

Body:
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};


问:
Javascript append to url if not null
I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?     </p>

```<code>    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;
</code>```

答:
I would put all your potential values into an object, iterate the object pushing the querystring part to an array if the object value exists and is valid, then join the parts into a real querystring which you can then attach to your url:</p>

```<code>var obj = {
  "age": $('#age').val(),
  "fn": $('#fn').val(),
  "ln": $('#ln').val(),
  "city": $('#city').val(),
  "country": $('#country').val()
};

var arr = [];
for (var k in obj) {
  if (obj[k] || obj[k] === 0)
    arr.push(k + "=" + encodeURIComponent(obj[k]));
}

var url = "https://penisurl";

if (arr.length) {
  url += "?" + arr.join("&");
}
</code>```

Title: Javascript append to url if not null

Body:
I want to append the values if they are not null to the link. It doesn't allow the if in the string, so what should i do instead?

    var age = $('#age').val();
    var fn = $('#fn').val();
    var ln = $('#ln').val();
    var city = $('#city').val();
    var country = $('#country').val();

    var link = "https://mysre.com/articles/index.php?title=man-sets-biggest-pizza-record" if(age !=null){ "&age=" + age + } "&fn=" + fn + "&ln=" + ln + "&city=" + city + "&country=" + country;

Body:
I would put all your potential values into an object, iterate the object pushing the querystring part to an array if the object value exists and is valid, then join the parts into a real querystring which you can then attach to your url:

var obj = {
  "age": $('#age').val(),
  "fn": $('#fn').val(),
  "ln": $('#ln').val(),
  "city": $('#city').val(),
  "country": $('#country').val()
};

var arr = [];
for (var k in obj) {
  if (obj[k] || obj[k] === 0)
    arr.push(k + "=" + encodeURIComponent(obj[k]));
}

var url = "https://penisurl";

if (arr.length) {
  url += "?" + arr.join("&");
}