问:
Delete randomly selected N documents in a collection (MongoDB)
Could anybody please tell me what's the elegant way you would delete N randomly selected documents in a collection in a MongoDB database (through Python ideally)? I would like to use somewhat concise like this  </p>

```<code>db.users.remove({ $sample: { size: N } })
</code>```

<p>But this one doesn't parse and I couldn't find a working alternative anywhere else . Many thanks! </p>

答:
use aggregation to get your sample and store _id values to a list:

```<code>list_of_ids=list(db.users.aggregate([{'$sample': {'size': 10 }}, {'$project' : {'_id' : 1}} ]))
</code>```

use delete_many to drop sample documents

```<code>results = db.users.delete_many({'_id: {'$in': list_of_ids}})
</code>```

(*) make sure to check here for limitations of $sample

Body:
Could anybody please tell me what's the elegant way you would delete N randomly selected documents in a collection in a MongoDB database (through Python ideally)? I would like to use somewhat concise like this

db.users.remove({ $sample: { size: N } })

But this one doesn't parse and I couldn't find a working alternative anywhere else . Many thanks!

Body:
use aggregation to get your sample and store _id values to a list:

list_of_ids=list(db.users.aggregate([{'$sample': {'size': 10 }}, {'$project' : {'_id' : 1}} ]))

use delete_many to drop sample documents

results = db.users.delete_many({'_id: {'$in': list_of_ids}})

(*) make sure to check here for limitations of $sample


来源: stackexchange

问:
Stripe API PHP. Get all payments of subscription by subscription_id
I receive a hook from Clickfunnels that contains a "subscription_id": "sub_AnDOcr3inf0Qfx". How can I get all payments of this subscription using this data? Will be very appreciated for any help.</p>

答: You can list all Invoices for the given Customer and Subscription and each of those will have a charge property that you can then retrieve (or you could just expand it for your 'list Invoices' API call).

ContentLicense: CC BY-SA 3.0


问:
python logger loggin twice
I have a simple flask app which is supposed to log to console. My issue is that it is logging twice to console.

I have following logging config:

```<code>root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s | src="%(name)s" | lvl="%(levelname)s" | msg="%(message)s"')
ch.setFormatter(formatter)
ch.setLevel(logging.INFO)
root.addHandler(ch)
#werkzeug disable werkzeug logs
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.setLevel(logging.ERROR)
</code>```

Console output:

```<code>INFO:auth:Starting oauth flow
2017-06-08 14:16:08,494 | src="auth" | lvl="INFO" | msg="Starting oauth flow"
</code>```

答:
Try to determine how many handlers do root has:

```<code>print(len(root.handlers))
</code>```

I guess you have more then one handlers. To avoid this you can add a handler if there are no other handlers:

```<code>if not root.handlers:
    root.addHandler(...)
</code>```

You can remove all the handlers from a logger:

```<code>for x in root.handlers.copy():
    root.removeHandler(x)
</code>```

Title: python logger loggin twice

Body:
I have a simple flask app which is supposed to log to console. My issue is that it is logging twice to console.

I have following logging config:

root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s | src="%(name)s" | lvl="%(levelname)s" | msg="%(message)s"')
ch.setFormatter(formatter)
ch.setLevel(logging.INFO)
root.addHandler(ch)
#werkzeug disable werkzeug logs
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.setLevel(logging.ERROR)

Console output:

INFO:auth:Starting oauth flow
2017-06-08 14:16:08,494 | src="auth" | lvl="INFO" | msg="Starting oauth flow"

Body:
Try to determine how many handlers do root has:

print(len(root.handlers))

I guess you have more then one handlers. To avoid this you can add a handler if there are no other handlers:

if not root.handlers:
    root.addHandler(...)

You can remove all the handlers from a logger:

for x in root.handlers.copy():
    root.removeHandler(x)


问:
Not Found error for socket.io on the client-side
I am trying to include socket.io on the client-side. I keep getting this error message in the console every 5 seconds:

```<code>GET https://example.com/socket.io/?EIO=3&transport=polling&t=Lo8ssW0 404 (Not Found)
</code>```

My code:

```<code>script(src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.2/socket.io.slim.js')
var socketio = io.connect('https://example.com',{secure: true, port:5089})
</code>```

On the server-side I have:

```<code>const socketio = app.listen(5089)
var io = require('socket.io')(socketio)
</code>```

which works correctly.

What am I doing wrong?

答:
Simply replace

```<code>var socketio = io.connect('https://example.com',{secure: true, port:5089})
</code>```

by:

```<code>var socketio = io.connect()
</code>```

Does this help? If so, the problem is the host or the port in your original function call.

This simplified code should work, at least if you load the client from the server that runs Socket.io as well.

Body:
I am trying to include socket.io on the client-side. I keep getting this error message in the console every 5 seconds:

GET https://example.com/socket.io/?EIO=3&transport=polling&t=Lo8ssW0 404 (Not Found)

My code:

script(src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.2/socket.io.slim.js')
var socketio = io.connect('https://example.com',{secure: true, port:5089})

On the server-side I have:

const socketio = app.listen(5089)
var io = require('socket.io')(socketio)

which works correctly.

What am I doing wrong?

Body:
Simply replace

var socketio = io.connect('https://example.com',{secure: true, port:5089})

by:

var socketio = io.connect()

Does this help? If so, the problem is the host or the port in your original function call.

This simplified code should work, at least if you load the client from the server that runs Socket.io as well.


问:
Why does unordered_map take two values?
I'm just not getting it - why does this initialize a 2 parameter value?

I know there's a key and value...but do I need to specifically give the key every time? Doesn't this have an internal hashing function?

I have a question that's : "Given 2 arrays, find common numbers + different numbers". Simple enough. Though my issue is actually implementing the STL container "unordered_map" because I can't find anything explicitly explaining why it takes two parameters.

What I wanna' do:

```<code>unordered_map<int> hash;
hash.insert(5);

if ( hash.find(5) == true)
{
  cout << "Okay, got it. It's in the hash table." << endl;
}
</code>```

So something like that so you can get the gist. Just not sure why there are two values like:

```<code>unordered_map<int, int> hash;
</code>```

Thanks for the help!

答:
As others have noted, a map isn't really what you're looking for.

What they've advised instead is a set (or unordered_set).

At least IMO, this is somewhat questionable as well. It's clearly a lot better fit, but given the circumstances (you want to take two lists, find what numbers they contain, then find the intersection/difference) you'd probably be better off putting the numbers into vectors, then using sort and unique to remove duplicates. A set or unordered_set will typically work better if you need to do insertions and deletions and maintain uniqueness as you do so. A vector tends to work better when/if you can store all the data, then sort it, then ensure uniqueness--and once you've done that, you don't need to modify that list again.

Finally, you should also take note of std::set_intersection and std::set_difference (or possibly std::set_symmetric_difference). These will take a set of inputs that have been sorted (but not necessarily stored in an std::set) and find (obviously enough) the intersection and difference between the two lists of numbers--exactly what you apparently need as your result.

Title: Why does unordered_map take two values?

Body:
I'm just not getting it - why does this initialize a 2 parameter value?

I know there's a key and value...but do I need to specifically give the key every time? Doesn't this have an internal hashing function?

I have a question that's : "Given 2 arrays, find common numbers + different numbers". Simple enough. Though my issue is actually implementing the STL container "unordered_map" because I can't find anything explicitly explaining why it takes two parameters.

What I wanna' do:

unordered_map<int> hash;
hash.insert(5);

if ( hash.find(5) == true)
{
  cout << "Okay, got it. It's in the hash table." << endl;
}

So something like that so you can get the gist. Just not sure why there are two values like:

unordered_map<int, int> hash;

Thanks for the help!


问:
What is the Default ArrayList size in Java 8

What is the default size for an arraylist in java 8? As far as I remember and searched on google, everywhere I am finding that it is 10 by default but when I am taking output of the below code, it is printing 0. Is there any changes happened in java 8 related to this?

```<code>ArrayList<String> arrList = new ArrayList<String>();
System.out.println("size:"+arrList.size());
</code>```

My second query is: when I add some element to the list, then will the size increase by 1.5 times of previous size or it will increase by only 1?

PS: Is there any way to know the current capacity of the arraylist object?

答:
The initial List has the capacity zero (unless you specify otherwise):

```<code> private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
</code>```

When it has to grow, this is used:

```<code>int newCapacity = oldCapacity + (oldCapacity >> 1)
</code>```

oldCapacity >> 1 is division by two, so it grows by 1.5

The one thing to notice that once you remove elements, the capacity does not change. If you need it to shrink use trimToSize.

The 10 is right actually, but only when you put an element into the ArrayList:

```<code>    ArrayList<String> ar = new ArrayList<>();

    Field f = ar.getClass().getDeclaredField("elementData");
    f.setAccessible(true);
    int l = ((Object[]) f.get(ar)).length;
    System.out.println(l); // 0

    ar.add("1");

    int x = ((Object[]) f.get(ar)).length;
    System.out.println(x); // 10
</code>```

Body:
What is the default size for an arraylist in java 8? As far as I remember and searched on google, everywhere I am finding that it is 10 by default but when I am taking output of the below code, it is printing 0. Is there any changes happened in java 8 related to this?

ArrayList<String> arrList = new ArrayList<String>();
System.out.println("size:"+arrList.size());

My second query is: when I add some element to the list, then will the size increase by 1.5 times of previous size or it will increase by only 1?

PS: Is there any way to know the current capacity of the arraylist object?

Body:
The initial List has the capacity zero (unless you specify otherwise):

 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

When it has to grow, this is used:

int newCapacity = oldCapacity + (oldCapacity >> 1)

oldCapacity >> 1 is division by two, so it grows by 1.5

The one thing to notice that once you remove elements, the capacity does not change. If you need it to shrink use trimToSize.

The 10 is right actually, but only when you put an element into the ArrayList:

    ArrayList<String> ar = new ArrayList<>();

    Field f = ar.getClass().getDeclaredField("elementData");
    f.setAccessible(true);
    int l = ((Object[]) f.get(ar)).length;
    System.out.println(l); // 0

    ar.add("1");

    int x = ((Object[]) f.get(ar)).length;
    System.out.println(x); // 10


问:
Automatically install build dependencies prior to building an RPM package
I am trying to build a .rpm package. I have just followed the steps to do that. Till now all steps were gone fine but now i just stuck with this step. I just ran the following command and got this error:

rpmbuild -ba asterisk.spec

```<code>error: Failed build dependencies:
    gtk2-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
    libsrtp-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
    [... more ...]
    freetds-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
    uw-imap-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
</code>```

I am using fedora-15. How to resolve this error?

How I do install all depencencies during installation of src.rpm package. Is it possible?

答:
yum-builddep doesn't seem to work if the mirror you use doesn't serve source RPMs. This may not handle all cases, but it usually works for me:

```<code>sudo yum install -y $(<rpmbuild> | fgrep 'is needed by' | awk '{print $1}')
</code>```

where <rpmbuild> is your rpmbuild command (e.g., rpmbuild -ba foo.spec).

Body:
I am trying to build a .rpm package. I have just followed the steps to do that. Till now all steps were gone fine but now i just stuck with this step. I just ran the following command and got this error:

rpmbuild -ba asterisk.spec

error: Failed build dependencies:
    gtk2-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
    libsrtp-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
    [... more ...]
    freetds-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64
    uw-imap-devel is needed by asterisk-1.8.12.2-1.fc15.x86_64

I am using fedora-15. How to resolve this error?

How I do install all depencencies during installation of src.rpm package. Is it possible?

Body:
yum-builddep doesn't seem to work if the mirror you use doesn't serve source RPMs. This may not handle all cases, but it usually works for me:

sudo yum install -y $(<rpmbuild> | fgrep 'is needed by' | awk '{print $1}')

where <rpmbuild> is your rpmbuild command (e.g., rpmbuild -ba foo.spec).


问:
Why do some arrays mirror each other in PowerShell?
I am using PowerShell 2.0. When I make a new variable as an array and then set another variable to be equal to the first one, the second variable "mirrors" the first one.  After changing an object in the original array, the exact same change appears in the second array. For instance,

```<code>$array0001 = 6, 7, 3, 4, 0
$array0002 = $array0001
$array0001[3] = 55
$array0002
</code>```

with the output being

```<code>6
7
3
55
0
</code>```

I notice that when you set the second variable to have the same value as the first variable, except this time enclosed within a subexpression operator, modifications to the first array do not affect the second array. For instance,

```<code>$array0001 = 6, 7, 3, 4, 0
$array0002 = $($array0001)
$array0001[3] = 55
$array0002
</code>```

with the output being

```<code>6
7
3
4
0
</code>```

Why does enclosing the value in a subexpression operator change the behavior of the variable? Is there another or better way to avoid making array variables that "mirror" each other?

ETA: I have now found that $array0002 = @($array0001) and $array0002 = &{$array0001} both accomplish the exact same objective.

答:
It's called "pass by reference". Instead of actually assigning a value, you're assigning a reference to another location that holds a value. If the value in the original location changes, the reference you made is pointing to that original location, and will see the updated value.

Most languages have ways to "pass by reference" and "pass by value". That's what you found by doing $array0002=$($array0001). Neither one is better than the other, they just both have different uses.

In PowerShell you can also put .value behind your reference to grab the value, instead of the reference.

ContentLicense: CC BY-SA 4.0

Body:
I am using PowerShell 2.0. When I make a new variable as an array and then set another variable to be equal to the first one, the second variable "mirrors" the first one.  After changing an object in the original array, the exact same change appears in the second array. For instance,

$array0001 = 6, 7, 3, 4, 0
$array0002 = $array0001
$array0001[3] = 55
$array0002

with the output being

6
7
3
55
0

I notice that when you set the second variable to have the same value as the first variable, except this time enclosed within a subexpression operator, modifications to the first array do not affect the second array. For instance,

$array0001 = 6, 7, 3, 4, 0
$array0002 = $($array0001)
$array0001[3] = 55
$array0002

with the output being

6
7
3
4
0

Why does enclosing the value in a subexpression operator change the behavior of the variable? Is there another or better way to avoid making array variables that "mirror" each other?

ETA: I have now found that $array0002 = @($array0001) and $array0002 = &{$array0001} both accomplish the exact same objective.


问:
Enter on a file, modify the rows and overwrite the file. With a .bat file
I am doing some modifications on a text file; however the program is adding lines instead of modifying them.

As i am new to it, can you help or guide me?

Here is my code:

```<code>setlocal enabledelayedexpansion
for /f "delims=" %%a in (economic_changes.txt) do (
   SET s='%%a
   SET s=!s:;= !
   SET s=!s:- =-;;!
   SET s=!s: -=-!
   SET s=!s:-;;-=-;-!
   SET s=!s:-=%!
   SET s=!s:_= %!
   SET s=!s:;=';'%!
   SET s=!s:;'';'=;;%!

   echo !s!
) >>  "%userprofile%\desktop\Economic_Folder\economic_changes.txt"
</code>```

答:
Here's a "dirty" trick:

@echo off
setlocal enabledelayedexpansion

set _FILE="%userprofile%\desktop\Economic_Folder\economic_changes.txt"
for /f %%a in ('type %_FILE% ^&^& echo.^>NUL 2^>%_FILE%') do (
    SET s='%%a
    SET s=!s:;= !
    SET s=!s:- =-;;!
    SET s=!s: -=-!
    SET s=!s:-;;-=-;-!
    SET s=!s:-=%!
    SET s=!s:_= %!
    SET s=!s:;=';'%!
    SET s=!s:;'';'=;;%!

    echo !s!
) >> %_FILE%
```

The "algorithm":

type the file contents to be consumed by the for loop

Empty it (thanks to [SO]: How to create empty text file from a batch file?)

Append everything in (your original code)

Body:
I am doing some modifications on a text file; however the program is adding lines instead of modifying them.

As i am new to it, can you help or guide me?

Here is my code:

setlocal enabledelayedexpansion
for /f "delims=" %%a in (economic_changes.txt) do (
   SET s='%%a
   SET s=!s:;= !
   SET s=!s:- =-;;!
   SET s=!s: -=-!
   SET s=!s:-;;-=-;-!
   SET s=!s:-=%!
   SET s=!s:_= %!
   SET s=!s:;=';'%!
   SET s=!s:;'';'=;;%!

   echo !s!
) >>  "%userprofile%\desktop\Economic_Folder\economic_changes.txt"

Body:
Here's a "dirty" trick:

@echo off
setlocal enabledelayedexpansion

set _FILE="%userprofile%\desktop\Economic_Folder\economic_changes.txt"
for /f %%a in ('type %_FILE% ^&^& echo.^>NUL 2^>%_FILE%') do (
    SET s='%%a
    SET s=!s:;= !
    SET s=!s:- =-;;!
    SET s=!s: -=-!
    SET s=!s:-;;-=-;-!
    SET s=!s:-=%!
    SET s=!s:_= %!
    SET s=!s:;=';'%!
    SET s=!s:;'';'=;;%!

    echo !s!
) >> %_FILE%

The "algorithm":

type the file contents to be consumed by the for loop

Empty it (thanks to [SO]: How to create empty text file from a batch file?)

Append everything in (your original code)


问:
IndexOf: how many vowels there are?
I need to have the code tell the user how many of the five vowels (a,e,i,o,u) are in the first string, as well as the second string. This is what I've worked up so far but I'm stuck in terms of how to print how many vowels there are total.</p>

```<code>Scanner in=new Scanner(System.in);

    System.out.println( "Enter String 1: ");
    String s1=in.next();
    System.out.println( "Enter String 2: ");
    String s2=in.next();

   int a= s1.length();

   int b= s2.length();

   if (a<b)
   System.out.println( s2 + "is longer than " + s1);
   else if (b<a)
   System.out.println( s1 + " is longer than " + s2);
   else
   System.out.println(s1 + " and " + s2 + " are the same length.");

   int c=(s1.indexOf(('a')));
   int d=(s1.indexOf(('e')));
   int e=(s1.indexOf(('o')));
   int f=(s1.indexOf(('i')));
   int g=(s1.indexOf(('u')));

   if (c>=0)
   System.out.println( "AFFIRMATIVE FOR A");
   if (d>=0)
   System.out.println( "AFFIRMATIVE FOR E");
   if (e>=0)
   System.out.println( "AFFIRMAtive fOR O");
   if (f>=0)
   System.out.println( "AFFIRMATIVE for I");
   if (g>=0)
   System.out.println( "AFFIRMATIVE for U");
</code>```

答:
Try out this code snippet. </p>

```<code>int a=0,o=0,i=0,e=0,u=0;
for (int ii = 0;ii<s1.length();ii++)
{
    if (s1.charAt(ii)=='a')a++;
    if (s1.charAt(ii)=='o')o++;
    if (s1.charAt(ii)=='i')i++;
    if (s1.charAt(ii)=='u')u++;
    if (s1.charAt(ii)=='e')e++;
}
for (int ii = 0;ii<s2.length();ii++)
{
    if (s2.charAt(ii)=='a')a++;
    if (s2.charAt(ii)=='o')o++;
    if (s2.charAt(ii)=='i')i++;
    if (s2.charAt(ii)=='u')u++;
    if (s2.charAt(ii)=='e')e++;
}
int total = a+o+i+u+e;
System.out.println (total);
</code>```

Title: IndexOf: how many vowels there are?

Body:
I need to have the code tell the user how many of the five vowels (a,e,i,o,u) are in the first string, as well as the second string. This is what I've worked up so far but I'm stuck in terms of how to print how many vowels there are total.

Scanner in=new Scanner(System.in);

    System.out.println( "Enter String 1: ");
    String s1=in.next();
    System.out.println( "Enter String 2: ");
    String s2=in.next();

   int a= s1.length();

   int b= s2.length();

   if (a<b)
   System.out.println( s2 + "is longer than " + s1);
   else if (b=0)
   System.out.println( "AFFIRMATIVE FOR A");
   if (d>=0)
   System.out.println( "AFFIRMATIVE FOR E");
   if (e>=0)
   System.out.println( "AFFIRMAtive fOR O");
   if (f>=0)
   System.out.println( "AFFIRMATIVE for I");
   if (g>=0)
   System.out.println( "AFFIRMATIVE for U");

Body:
Try out this code snippet.

int a=0,o=0,i=0,e=0,u=0;
for (int ii = 0;ii<s1.length();ii++)
{
    if (s1.charAt(ii)=='a')a++;
    if (s1.charAt(ii)=='o')o++;
    if (s1.charAt(ii)=='i')i++;
    if (s1.charAt(ii)=='u')u++;
    if (s1.charAt(ii)=='e')e++;
}
for (int ii = 0;ii<s2.length();ii++)
{
    if (s2.charAt(ii)=='a')a++;
    if (s2.charAt(ii)=='o')o++;
    if (s2.charAt(ii)=='i')i++;
    if (s2.charAt(ii)=='u')u++;
    if (s2.charAt(ii)=='e')e++;
}
int total = a+o+i+u+e;
System.out.println (total);


问:
combining two scripts into one google sheets
I am working on a spreadsheet for work and i need to use two scripts, but i can only use one when i go to "script editor". I don't know how to merge these two scripts so that they both function simultaneously when a cell is edited. Thank you very much for your help! The two scripts are the following.

****First one****

```<code>/**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 4;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: false } );
  }
}
</code>```

****Second one:*****

```<code>function onEdit(event)
{
  var timezone = "UTC-5";
  var timestamp_format = "mm-dd-yyyy'Time:' hh:mm:ss";
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestampt";
  var sheet = event.source.getSheetByName('Sheet1, Sheet2'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}

}
</code>```

答:
you could combine them as you asked:

/**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 4;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: false } );
  }
  // 2nd script
   var timezone = "UTC-5";
  var timestamp_format = "mm-dd-yyyy'Time:' hh:mm:ss";
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestampt";
  var sheet = event.source.getSheetByName('Sheet1, Sheet2'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}

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

<p>Or you could call the 2nd function from the onedit function:</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>/**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 4;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: false } );
  }
  onEdit2();
}

function onEdit2(event){
   var timezone = "UTC-5";
  var timestamp_format = "mm-dd-yyyy'Time:' hh:mm:ss";
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestampt";
  var sheet = event.source.getSheetByName('Sheet1, Sheet2'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}
  </code>```

Body:
I am working on a spreadsheet for work and i need to use two scripts, but i can only use one when i go to "script editor". I don't know how to merge these two scripts so that they both function simultaneously when a cell is edited. Thank you very much for your help! The two scripts are the following.

****First one****

/**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 4;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: false } );
  }
}

****Second one:*****

function onEdit(event)
{
  var timezone = "UTC-5";
  var timestamp_format = "mm-dd-yyyy'Time:' hh:mm:ss";
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestampt";
  var sheet = event.source.getSheetByName('Sheet1, Sheet2'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}

}

Body:
you could combine them as you asked:

/**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 4;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: false } );
  }
  // 2nd script
   var timezone = "UTC-5";
  var timestamp_format = "mm-dd-yyyy'Time:' hh:mm:ss";
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestampt";
  var sheet = event.source.getSheetByName('Sheet1, Sheet2'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}

}

Or you could call the 2nd function from the onedit function:

/**
 * Automatically sorts the 1st column (not the header row) Ascending.
 */
function onEdit(event){
  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();

  var columnToSortBy = 4;
  var tableRange = "A2:T99"; // What to sort.

  if(editedCell.getColumn() == columnToSortBy){
    var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy, ascending: false } );
  }
  onEdit2();
}

function onEdit2(event){
   var timezone = "UTC-5";
  var timestamp_format = "mm-dd-yyyy'Time:' hh:mm:ss";
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestampt";
  var sheet = event.source.getSheetByName('Sheet1, Sheet2'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}


问:
How can I pass variable parameters into a Javascript Function using Excel VBA (2)
Well based on the post: The same as this one

I've tryed to do this:

```<code>Call mFramePesquisa.parentWindow.execScript("gotoPage(pesquisa.html?re_ligacao)", "JavaScript")
</code>```

As you can see the js function takes one parameter "pesquisa.html?re_licagao" but when executed on the browser it gives an error saying that ":" was expected.

So i've tryed to quote the function parameter without success:

```<code>Call mFramePesquisa.parentWindow.execScript("gotoPage(" & chr(34) & "pesquisa.html?re_ligacao" & chr(34) & ")", "JavaScript")
</code>```

or

```<code>Call mFramePesquisa.parentWindow.execScript("gotoPage('pesquisa.html?re_ligacao')", "JavaScript")
</code>```

Both throw out an "Object expected" error on ie browser.

Any suggestions?

thx

PS: I've tried also to use chr(63) instead of "?" but without success.

Edit: I suspect it had something to do with the string used as parameter, since in the original JS the function is called like this on a onChange evento for a  object:

```<code>onchange=javascript:gotoPage(this.value)
</code>```

答:
This worked for me in a test page:

```<code>IE.document.parentWindow.execScript "RunMe(""hello"")", "jscript"
</code>```

Tim

ContentLicense: CC BY-SA 2.5

Body:
Well based on the post: The same as this one

I've tryed to do this:

Call mFramePesquisa.parentWindow.execScript("gotoPage(pesquisa.html?re_ligacao)", "JavaScript")

As you can see the js function takes one parameter "pesquisa.html?re_licagao" but when executed on the browser it gives an error saying that ":" was expected.

So i've tryed to quote the function parameter without success:

Call mFramePesquisa.parentWindow.execScript("gotoPage(" & chr(34) & "pesquisa.html?re_ligacao" & chr(34) & ")", "JavaScript")

or

Call mFramePesquisa.parentWindow.execScript("gotoPage('pesquisa.html?re_ligacao')", "JavaScript")

Both throw out an "Object expected" error on ie browser.

Any suggestions?

thx

PS: I've tried also to use chr(63) instead of "?" but without success.

Edit: I suspect it had something to do with the string used as parameter, since in the original JS the function is called like this on a onChange evento for a  object:

onchange=javascript:gotoPage(this.value)

Body:
This worked for me in a test page:

IE.document.parentWindow.execScript "RunMe(""hello"")", "jscript"

Tim


问:
What are the rules of converting one markdown title into an HTML anchor?
I need to generate a long README.md file and some links to different sections like a table of contents in the beginning. Markdown translates the section headings into links:

This is a heading and a link in Markdown

In order to generate the link for the table of content, I need the values for the anchor. The text I have. The fragment I need the rules. Probably this will be:

```<code>[This is a heading and a link in Markdown](#thisisaheadingandalinkinmarkdown)
</code>```

Does anyone know the rules how the headings in markdown are converted to anchor/fragment values?

答:
I find that within the markdown header rules, there is an adjustment for these from the previous note.

1.All text is converted to lowercase

2.All non-word text (e.g., punctuation, HTML) is not removed but converted to hyphens

3.All spaces are converted to hyphens

4.Two or more hyphens in a row are converted to one

5.If a header with the same ID has already been generated, a unique incrementing number is appended, starting at 1.

So, SEND EMAIL TO DBA'S - is created like this: * [5. SEND EMAIL TO DBA'S](#5-send-email-to-dba-s).

Hope this helps anyone looking.

Body:
I need to generate a long README.md file and some links to different sections like a table of contents in the beginning. Markdown translates the section headings into links:

This is a heading and a link in Markdown

In order to generate the link for the table of content, I need the values for the anchor. The text I have. The fragment I need the rules. Probably this will be:

[This is a heading and a link in Markdown](#thisisaheadingandalinkinmarkdown)

Does anyone know the rules how the headings in markdown are converted to anchor/fragment values?


问:
Differences between two groups in molecular genetic
Usually I have some variable in 3 conditions in 2 groups. How can I find, is there are any statistic differences between this two groups?

For example short csv:

```<code>genotype,group,gene
5g/5g,1,PAI
5g/5g,1,PAI
4g/5g,1,PAI
4g/5g,1,PAI
4g/5g,1,PAI
4g/5g,1,PAI
5g/5g,1,PAI
4g/4g,1,PAI
4g/4g,1,PAI
4g/4g,2,PAI
4g/5g,2,PAI
4g/4g,2,PAI
4g/4g,2,PAI
4g/4g,2,PAI
4g/5g,2,PAI
5g/5g,2,PAI
4g/4g,2,PAI
5g/5g,2,PAI
5g/5g,2,PAI
5g/5g,2,PAI
4g/5g,2,PAI
</code>```

gene PAI have 3 genotypes: 5g/5g, 4g/5g and 4g/4g.

If present this data in table format:

So, how can I find one p-value like there - picture below?

答:
Might this be what you're looking for?

```<code>## simulating some data
df <- data.frame(genotype=sample(c("5g/5g","4g/5g","4g/4g"),16,replace=T), group=c(rep(1,8), rep(2,8)))

df
##    genotype group
## 1     4g/5g     1
## 2     4g/5g     1
## 3     4g/5g     1
## 4     5g/5g     1
## 5     5g/5g     1
## 6     4g/4g     1
## 7     4g/4g     1
## 8     4g/5g     1
## 9     4g/4g     2
## 10    4g/4g     2
## 11    4g/4g     2
## 12    4g/5g     2
## 13    5g/5g     2
## 14    5g/5g     2
## 15    4g/5g     2
## 16    4g/4g     2

## first a table
with(df, table(group, genotype))
##      genotype
## group 4g/4g 4g/5g 5g/5g
##     1     2     4     2
##     2     4     2     2

## and maybe a chi-squared test is what you want?
with(df, chisq.test(table(group,genotype)))
##    Pearson's Chi-squared test

## data:  table(group, genotype)
## X-squared = 1.3333, df = 2, p-value = 0.5134
</code>```

Note that this isn't with your real data, but you could do the same thing.

Body:
Usually I have some variable in 3 conditions in 2 groups. How can I find, is there are any statistic differences between this two groups?

For example short csv:

genotype,group,gene
5g/5g,1,PAI
5g/5g,1,PAI
4g/5g,1,PAI
4g/5g,1,PAI
4g/5g,1,PAI
4g/5g,1,PAI
5g/5g,1,PAI
4g/4g,1,PAI
4g/4g,1,PAI
4g/4g,2,PAI
4g/5g,2,PAI
4g/4g,2,PAI
4g/4g,2,PAI
4g/4g,2,PAI
4g/5g,2,PAI
5g/5g,2,PAI
4g/4g,2,PAI
5g/5g,2,PAI
5g/5g,2,PAI
5g/5g,2,PAI
4g/5g,2,PAI

gene PAI have 3 genotypes: 5g/5g, 4g/5g and 4g/4g.

If present this data in table format:

So, how can I find one p-value like there - picture below?

Body:
Might this be what you're looking for?

## simulating some data
df <- data.frame(genotype=sample(c("5g/5g","4g/5g","4g/4g"),16,replace=T), group=c(rep(1,8), rep(2,8)))

df
##    genotype group
## 1     4g/5g     1
## 2     4g/5g     1
## 3     4g/5g     1
## 4     5g/5g     1
## 5     5g/5g     1
## 6     4g/4g     1
## 7     4g/4g     1
## 8     4g/5g     1
## 9     4g/4g     2
## 10    4g/4g     2
## 11    4g/4g     2
## 12    4g/5g     2
## 13    5g/5g     2
## 14    5g/5g     2
## 15    4g/5g     2
## 16    4g/4g     2

## first a table
with(df, table(group, genotype))
##      genotype
## group 4g/4g 4g/5g 5g/5g
##     1     2     4     2
##     2     4     2     2

## and maybe a chi-squared test is what you want?
with(df, chisq.test(table(group,genotype)))
##    Pearson's Chi-squared test

## data:  table(group, genotype)
## X-squared = 1.3333, df = 2, p-value = 0.5134

Note that this isn't with your real data, but you could do the same thing.


答:
I think you are confusing size with capacity. Size is the number of elements you have placed into the arrayList while capacity is the max number of elements the arrayList can take. Once you've reached max, the capacity is doubled(if i remember correctly).

So when you add an element into your arrayList, size will always increase by one. If size is equal to capacity, then capacity will increase.

Title: What is the Default ArrayList size in Java 8


Title: pandas dataframe change column value

Body:
I have python dict like this:

keysdict={'date': {20: '201012', 21: '201101', 22: '201102', 23: '201103', 24: '201104', 25: '201105', 26: '201106', 27: '201107', 28: '201108', 29: '201109', 30: '201110', 31: '201111'}}

And I have pandas dataframe like this

A    B
20  0.123
21  2.123
22  4.45
23  3.2
24  3.1
25  3.9
26  4.2

Now I want to add an extra column C which takes the respective value from dict keys that are in Column A . Like below one

A    B      C
20  0.123  201012
21  2.123  201101
22  4.45   201102
23  3.2    201103
24  3.1    201104
25  3.9    201105
26  4.2    201106

I tried this

df.loc[:,'C']=keysdict['date'][df.loc['A']]

But getting below error

KeyError: 'the label [A] is not in the [index]

Body:
You can directly use map without apply

df['C'] = df['A'].map(keysdict['date'])

    A   B       C
0   20  0.123   201012
1   21  2.123   201101
2   22  4.450   201102
3   23  3.200   201103
4   24  3.100   201104
5   25  3.900   201105
6   26  4.200   201106


问:
parent process that calls waitpid() is unable to find its child
I am trying to better understand fork(), waitpid() and child/parent processes, however there are some strange behaviors I have encountered with the following code:

```<code>#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void){ // Main

    int status;
    pid_t wPID, cPID;
    printf("[%i] Hi I am the parent and I am about to create a child...\n", getpid());
    fflush(0);
    pid_t childPID = fork();

    if (childPID >= 0){
        if(childPID == 0){ //child process
            cPID = getpid();
            printf("[%i] %i\n", getpid(), cPID );
            printf("[%i] Hi, I am the child process...\n", getpid() );
            sleep(1);

            for(int i = 0; i<3; i++){
                printf("[%i] %i\n", getpid(), i);
            }
            exit(0);
        }
        else{ //parent
            printf("[%i] %i\n", getpid(), cPID );
            wPID = waitpid(cPID, &status, 0);
            printf("[%i] value returned by waitpid: %i\n", getpid(), wPID);

            if (WIFEXITED(status))
                printf("[%i] child exited, status=%d\n", getpid(), WEXITSTATUS(status));
            else if (WIFSIGNALED(status))
                printf("[%i] child killed (signal %d)\n", getpid(), WTERMSIG(status));
            else if (WIFSTOPPED(status))
                printf("[%i] child stopped (signal %d)\n", getpid(), WSTOPSIG(status));
            else  /* Non-standard case -- may never happen */
                printf("Unexpected status (0x%x)\n", status);
            return 0;
        }
    }
    else{
        printf("\n Fork failed, quitting!\n");
        return 2;  // error
    }
}
</code>```

console output:

```
$ ./waitpidexample
[6103] Hi I am the parent and I am about to create a child...
Error: No child processes
[6103] 1540418008
[6103] value returned by waitpid: -1
[6103] child killed (signal 54)
[6104] 6285
[6104] Hi, I am the child process...
[6104] 0
[6104] 1
[6104] 2
```

I believe my issue is in the cPID variable being used in waitpid()...

there is some sort of scope issue happening here, as it evaluates to different values in the child / parent.

How am I supposed to get the correct child process id for use in waitpid()?

Why is the code after my waitpid() being executed before the code in the child process?

答:
cPID is only changed in the child process. When you call fork, a complete copy is made (functionally, in reality until something is changed, the memory is shared). This means that when cPID is written in the child (first branch) the parent does not see it. Change the references to cPID in the parent (second branch) to childPID (assigned from fork()):

```<code>else{ //parent
    printf("[%i] %i\n", getpid(), childPID );
    wPID = waitpid(childPID, &status, 0);
    printf("[%i] value returned by waitpid: %i\n", getpid(), wPID);
    if (WIFEXITED(status))
        printf("[%i] child exited, status=%d\n", getpid(), WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        printf("[%i] child killed (signal %d)\n", getpid(), WTERMSIG(status));
    else if (WIFSTOPPED(status))
        printf("[%i] child stopped (signal %d)\n", getpid(), WSTOPSIG(status));
    else  /* Non-standard case -- may never happen */
        printf("Unexpected status (0x%x)\n", status);
        return 0;
}
</code>```

Also, I recommend using braces after all your if statements

Run Order

fork() does not define which process gets run first, just that there is now a child process (in which it returns 0) and a parent process (in which it returns the child's PID). The child process will be identical to the parent, except for the return value of fork(). Sometimes, the parent goes first, sometimes the child does. It is non-deterministic.

Body:
I am trying to better understand fork(), waitpid() and child/parent processes, however there are some strange behaviors I have encountered with the following code:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void){ // Main

    int status;
    pid_t wPID, cPID;
    printf("[%i] Hi I am the parent and I am about to create a child...\n", getpid());
    fflush(0);
    pid_t childPID = fork();

    if (childPID >= 0){
        if(childPID == 0){ //child process
            cPID = getpid();
            printf("[%i] %i\n", getpid(), cPID );
            printf("[%i] Hi, I am the child process...\n", getpid() );
            sleep(1);

            for(int i = 0; i<3; i++){
                printf("[%i] %i\n", getpid(), i);
            }
            exit(0);
        }
        else{ //parent
            printf("[%i] %i\n", getpid(), cPID );
            wPID = waitpid(cPID, &status, 0);
            printf("[%i] value returned by waitpid: %i\n", getpid(), wPID);

            if (WIFEXITED(status))
                printf("[%i] child exited, status=%d\n", getpid(), WEXITSTATUS(status));
            else if (WIFSIGNALED(status))
                printf("[%i] child killed (signal %d)\n", getpid(), WTERMSIG(status));
            else if (WIFSTOPPED(status))
                printf("[%i] child stopped (signal %d)\n", getpid(), WSTOPSIG(status));
            else  /* Non-standard case -- may never happen */
                printf("Unexpected status (0x%x)\n", status);
            return 0;
        }
    }
    else{
        printf("\n Fork failed, quitting!\n");
        return 2;  // error
    }
}

console output:

$ ./waitpidexample
[6103] Hi I am the parent and I am about to create a child...
Error: No child processes
[6103] 1540418008
[6103] value returned by waitpid: -1
[6103] child killed (signal 54)
[6104] 6285
[6104] Hi, I am the child process...
[6104] 0
[6104] 1
[6104] 2

I believe my issue is in the cPID variable being used in waitpid()...

there is some sort of scope issue happening here, as it evaluates to different values in the child / parent.

How am I supposed to get the correct child process id for use in waitpid()?

Why is the code after my waitpid() being executed before the code in the child process?

Body:
cPID is only changed in the child process. When you call fork, a complete copy is made (functionally, in reality until something is changed, the memory is shared). This means that when cPID is written in the child (first branch) the parent does not see it. Change the references to cPID in the parent (second branch) to childPID (assigned from fork()):

else{ //parent
    printf("[%i] %i\n", getpid(), childPID );
    wPID = waitpid(childPID, &status, 0);
    printf("[%i] value returned by waitpid: %i\n", getpid(), wPID);
    if (WIFEXITED(status))
        printf("[%i] child exited, status=%d\n", getpid(), WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        printf("[%i] child killed (signal %d)\n", getpid(), WTERMSIG(status));
    else if (WIFSTOPPED(status))
        printf("[%i] child stopped (signal %d)\n", getpid(), WSTOPSIG(status));
    else  /* Non-standard case -- may never happen */
        printf("Unexpected status (0x%x)\n", status);
        return 0;
}

Also, I recommend using braces after all your if statements

Run Order

fork() does not define which process gets run first, just that there is now a child process (in which it returns 0) and a parent process (in which it returns the child's PID). The child process will be identical to the parent, except for the return value of fork(). Sometimes, the parent goes first, sometimes the child does. It is non-deterministic.


问:
IndexError: list index out of range Not getting Solved
```<code>import glob
from bs4 import BeautifulSoup
f = open('csvfile.csv','w')
for file in glob.glob('*.htm'):
    print 'Processing', file
    for y in range(0,3):
        for x in range(0, 6):
            soup = BeautifulSoup(open(file).read())
            all_string=soup.find_all("h2")[x].get_text()
            #stack=[]
            #acct.write(", ".join(stack) + '\n')
            f.write(all_string)
            f.write('\n')
            print(all_string)
    x=0
f.close()
</code>```

Output-

Processing Alkali-Controlled C–H Cleavage or N–C Bond Formation by N2-Derived Iron Nitrides and Imides - Journal of the American Chemical Society (ACS Publications).htm

Abstract

Supporting Information

Vanadium-catalyzed Reduction of Molecular Dinitrogen into Silylamine under Ambient Reaction Conditions

Traceback (most recent call last):

File "", line 1, in
      runfile('/Users/ROXX/Desktop/project/csv1.py', wdir='/Users/ROXX/Desktop/project')

File
  "/Users/ROXX/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py",
  line 880, in runfile
      execfile(filename, namespace)

File
  "/Users/ROXX/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py",
  line 94, in execfile
      builtins.execfile(filename, *where)

File "/Users/ROXX/Desktop/project/csv1.py", line 17, in
      all_string=soup.find_all("h2")[x].get_text()

IndexError: list index out of range

答: The reason for the error probably is that there are less than 7 occurrences of h2 in the file you are processing (in the second loop). Repeating on "all_string" instead of a fixed interval would probably solve the issue.</p>

Body:
import glob
from bs4 import BeautifulSoup
f = open('csvfile.csv','w')
for file in glob.glob('*.htm'):
    print 'Processing', file
    for y in range(0,3):
        for x in range(0, 6):
            soup = BeautifulSoup(open(file).read())
            all_string=soup.find_all("h2")[x].get_text()
            #stack=[]
            #acct.write(", ".join(stack) + '\n')
            f.write(all_string)
            f.write('\n')
            print(all_string)
    x=0
f.close()

Output-

Processing Alkali-Controlled C–H Cleavage or N–C Bond Formation by N2-Derived Iron Nitrides and Imides - Journal of the American Chemical Society (ACS Publications).htm

Abstract

Supporting Information

Vanadium-catalyzed Reduction of Molecular Dinitrogen into Silylamine under Ambient Reaction Conditions

Traceback (most recent call last):

File "", line 1, in
      runfile('/Users/ROXX/Desktop/project/csv1.py', wdir='/Users/ROXX/Desktop/project')

File
  "/Users/ROXX/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py",
  line 880, in runfile
      execfile(filename, namespace)

File
  "/Users/ROXX/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py",
  line 94, in execfile
      builtins.execfile(filename, *where)

File "/Users/ROXX/Desktop/project/csv1.py", line 17, in
      all_string=soup.find_all("h2")[x].get_text()

IndexError: list index out of range


问:
how stopped script while procces id exist? Solaris
I want to stall the execution of my script until a process is closed (I have the PID stored in a variable).

```<code>#!/bin/bash

outputl=$( ps -ef | grep $var4 | awk '{print $2}' )  >> $logfile

while [ "ps -p $outputl" ]  > /dev/null;
do
  sleep 1;
done
echo "Stopped $instance" >> $logfile
//command...
</code>```

It stays in the "while" and not continue whit script.

答:
This line:

```<code>while [ "ps -p $output1" ]
</code>```

does not execute the ps command. It simply tests whether the string "ps -p $output1" is not empty, and it obviously isn't. To test the output of a command, use $():

```<code>while [ "$(ps -p "$output1")" ]
</code>```

But since ps produces a header, this will always be true. The best way to test if a PID exists is to use the kill command with signal 0; this doesn't actually send a signal, it just tests whether it's possible to send a signal. I'm assuming this code is being run either by root or the userid running the application being checked. So you can write:

```<code>while kill -0 "$output1" 2>/dev/null
</code>```

Also, your code for getting the PID into $output1 is wrong. ps -ef will also include the grep command, which matches the name you're looking for, so you need to filter that out. Use:

```<code>output1=$(ps -ef | grep "$var4" | awk '!/grep/ { print $2 }')
</code>```

Redirecting the output to $logfile is not necessary, since variable assignments don't print anything.

Many systems have a pgrep command, which can be used by itself to test if a process with a given name exists; if you have this, you can use it instead of reinventing the wheel (and if not, you should be able to install it).

Body:
I want to stall the execution of my script until a process is closed (I have the PID stored in a variable).

#!/bin/bash

outputl=$( ps -ef | grep $var4 | awk '{print $2}' )  >> $logfile

while [ "ps -p $outputl" ]  > /dev/null;
do
  sleep 1;
done
echo "Stopped $instance" >> $logfile
//command...

It stays in the "while" and not continue whit script.

Body:
This line:

while [ "ps -p $output1" ]

does not execute the ps command. It simply tests whether the string "ps -p $output1" is not empty, and it obviously isn't. To test the output of a command, use $():

while [ "$(ps -p "$output1")" ]

But since ps produces a header, this will always be true. The best way to test if a PID exists is to use the kill command with signal 0; this doesn't actually send a signal, it just tests whether it's possible to send a signal. I'm assuming this code is being run either by root or the userid running the application being checked. So you can write:

while kill -0 "$output1" 2>/dev/null

Also, your code for getting the PID into $output1 is wrong. ps -ef will also include the grep command, which matches the name you're looking for, so you need to filter that out. Use:

output1=$(ps -ef | grep "$var4" | awk '!/grep/ { print $2 }')

Redirecting the output to $logfile is not necessary, since variable assignments don't print anything.

Many systems have a pgrep command, which can be used by itself to test if a process with a given name exists; if you have this, you can use it instead of reinventing the wheel (and if not, you should be able to install it).


问:
How to set up kubernetes NGINX ingress in AWS and SSL termination
I set up a kubernetes cluster in AWS using KOPS; now I want to set up an NGINX ingress controller and terminate TLS with AWS managed certificate. The topology in my understanding is AWS ELB is facing the internet and terminates TLS, forwards unencrypted to ingress service which then does dispatches.

I've deployed ingress controller from https://github.com/kubernetes/ingress/tree/master/examples/aws/nginx

Except I used annotations as described on top of https://github.com/kubernetes/ingress/issues/71 to add the certificate.

I add the route to Route53 and open my browser to https address and get a 400 response from NGINX with message "The plain HTTP request was sent to HTTPS port"

What am I doing wrong?

This is my ingress resource:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
  name: dispatcher
  namespace: test
spec:
  rules:
  - host: REDACTED
    http:
      paths:
      - backend:
          serviceName: REDACTED
          servicePort: 80
        path: /api/v0
</code>```

答: I managed to get this done largely using the ingress here: https://github.com/kubernetes/kops/tree/master/addons/ingress-nginx except for the ingress service I added service.beta.kubernetes.io/aws-load-balancer-ssl-cert annotation pointing to my certificate ARN and set targetPort of both the ports to 80

Body:
I set up a kubernetes cluster in AWS using KOPS; now I want to set up an NGINX ingress controller and terminate TLS with AWS managed certificate. The topology in my understanding is AWS ELB is facing the internet and terminates TLS, forwards unencrypted to ingress service which then does dispatches.

I've deployed ingress controller from https://github.com/kubernetes/ingress/tree/master/examples/aws/nginx

Except I used annotations as described on top of https://github.com/kubernetes/ingress/issues/71 to add the certificate.

I add the route to Route53 and open my browser to https address and get a 400 response from NGINX with message "The plain HTTP request was sent to HTTPS port"

What am I doing wrong?

This is my ingress resource:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
  name: dispatcher
  namespace: test
spec:
  rules:
  - host: REDACTED
    http:
      paths:
      - backend:
          serviceName: REDACTED
          servicePort: 80
        path: /api/v0


问:
AOT (Ahead-Of-Time) Compilation with ES5
Is it possible to do AOT compilation in Angular using only ES5?

More to the point, can I use the NGTools Webpack plugin with ES5?

I know TypeScript is the preferable language of choice for Angular, however my place of employment did not approve using TypeScript for our Angular project.  My hands are a bit tied, and I don't want performance to suffer on the client due to this.

Some relevant info on my project:

Webpack 2 for build/packaging

Written in ES2015 transpiled to ES5 using Babel

I have looked all over and have not been able to find a clear answer on this, I would really appreciate any info anyone can provide.

Thanks in advance!

答:
In you tsconfig.json file set the target to es5.</p>

```<code>    "target": "es5",
</code>```

Body:
In you tsconfig.json file set the target to es5.

    "target": "es5",


问:
How to use --since option with docker logs command
I want to look at last 1 hour of docker container log using docker logs --since option. Which value I should provide for --since parameter?

答:
Please refer to the Docker docs.

```<code>docker logs --since 1h
</code>```

The --since option shows only the container logs generated after a given date. You can specify the date as an RFC 3339 date, a UNIX timestamp, or a Go duration string (e.g. 1m30s, 3h). Besides RFC3339 date format you may also use RFC3339Nano, 2006-01-02T15:04:05, 2006-01-02T15:04:05.999999999, 2006-01-02Z07:00, and 2006-01-02.

Body:
Please refer to the Docker docs.

docker logs --since 1h

The --since option shows only the container logs generated after a given date. You can specify the date as an RFC 3339 date, a UNIX timestamp, or a Go duration string (e.g. 1m30s, 3h). Besides RFC3339 date format you may also use RFC3339Nano, 2006-01-02T15:04:05, 2006-01-02T15:04:05.999999999, 2006-01-02Z07:00, and 2006-01-02.


问:
Firebase database high delay after a long standby
I'm currently testing Firebase on a non-production Firebase app which I am the only one who works on.

When I try to query the database to retrieve the data after there has not been any query during the last 24 hours, the query take about 8 seconds. After a query is done, the next ones would take normal amount of time (about 100ms).

This is not about caching the queries, by "next queries" I mean new queries which are not the same.

To reproduce it:

Create a database node called users, users children are user data (first name, last name, age, gender, etc)

Add 500,000 users to this node

Get a user by its UID and measure the time. (It should take about 100ms)

Wait 24 hours (I don't know the exact time, but I'm sure about 24 hours)

Get any user by its UID and measure the time. (It should take about 8sec)

Get any user by its UID and measure the time. (It should take about 100ms)

I want to know if this is a known issue to Firebase realtime database or not?

答:
Firebase keeps recently used data in its internal cache. This cache is cleared after a few minutes.

But the exact numbers depend on how much data you're loading and how you're loading that data. Without seeing a specific setup that shows how to reproduce these numbers there really isn't much anyone can say.


问:
Java Send Mail Function
Does anybody has a proper java send mail function that works 100 % and can share it with me. I am getting some problem with mine!!!</p>

答: You can also check Email package from Jakarta. It provides higher level and more user friendly API on top of Java mail API.</p>

Title: Java Send Mail Function


答:
In the parent process, cPID is never initialized.  The variables in the parent and child are separate from each other, so a variable change in the child is not visible in the parent and vice versa.

The parent already has the child pid in childPID, so use that instead.

```<code>printf("[%i] %i\n", getpid(), childPID );
wPID = waitpid(childPID, &status, 0);
</code>```

Title: parent process that calls waitpid() is unable to find its child

Body:
In the parent process, cPID is never initialized.  The variables in the parent and child are separate from each other, so a variable change in the child is not visible in the parent and vice versa.

The parent already has the child pid in childPID, so use that instead.

printf("[%i] %i\n", getpid(), childPID );
wPID = waitpid(childPID, &status, 0);


问:
Database Schema for Consignment Inventory
I'm developing a consignment inventory for hospitals,

The infrastructure is this:

```<code>Multiple Suppliers
Multiple Warehouses
Multiple Hospitals
</code>```

I'm stuck on deciding whether to make a separated stock tables for EACH hospitals and warehouses or store them all in one stock table.

My current plan is this:

They are all going to read on a single item table for general item information only, then the stocks, stock movements, consign orders, employees, patients will have separate tables per hospital/warehouses.

Example:

Separated Tables

tbl_items //centralized item information
tbl_suppliers //centralized supplier information
tbl_warehouse1id_stocks
tbl_warehouse1id_stockmovements
tbl_warehouse2id_stocks
tbl_warehouse2id_stockmovements
tbl_hospital1id_stocks
tbl_hospital1id_stockmovements
tbl_hospital1id_employee
tbl_hospital1id_patients
tbl_hospital2id_stocks
tbl_hospital2id_stockmovements
tbl_hospital2id_employee
tbl_hospital2id_patients
```

<p><strong>Merged Tables</strong></p>

<pre class="lang-cs prettyprint-override"><code>tbl_items //centralized item information
tbl_suppliers //centralized supplier information
tbl_warehouse_stocks //where warehouse_ids are primary keys
tbl_warehouse_stockmovements //where warehouse_ids are primary keys
tbl_hospital_stocks //where hospital_ids are primary keys
tbl_hospital_stockmovements //where hospital_ids are primary keys
tbl_hospital_employee //where hospital_ids are primary keys
tbl_hospital_patients //where hospital_ids are primary keys
</code>```

which is better? for maintaining, speed optimization etc.? my current opinion is that the separated approach is better because why should (for example) hospital1 search for their certain stock of items to the pool of stocks of all hospitals? does this affect the speed? if hospital1 tries to query their entire stock record, it will affect the query time of other hospital because hospital1 is currently searching for their records. of course indexing should help but still.

EDIT:

The server resides on a single location and its a web-based system.

答:
I would highly recommend taking the MERGED TABLES approach that you've laid out.

Disadvantages of Separate Tables:

Every time a new warehouse/hospital is built or added to the tracking system, you have to add new tables to your schema

Writing a query to count the stock of a single item across all hospitals or warehouses now because a much more complex query (unions/joins through every table).  Combine this with the fact that a new warehouse may be added to the system (previous point), you now have to update all these queries individually

How will your web back-end layer know which table to query? This sounds like you would be going down the path of dynamic query generation and will be adding yet more complexity to your code base.

Unless you have significant constraints that you haven't laid out (extremely large db with billions of rows or poor hardware that you can't scale up), indexes are designed to exactly help with this scenario.

Body:
I'm developing a consignment inventory for hospitals,

The infrastructure is this:

Multiple Suppliers
Multiple Warehouses
Multiple Hospitals

I'm stuck on deciding whether to make a separated stock tables for EACH hospitals and warehouses or store them all in one stock table.

My current plan is this:

They are all going to read on a single item table for general item information only, then the stocks, stock movements, consign orders, employees, patients will have separate tables per hospital/warehouses.

Example:

Separated Tables

tbl_items //centralized item information
tbl_suppliers //centralized supplier information
tbl_warehouse1id_stocks
tbl_warehouse1id_stockmovements
tbl_warehouse2id_stocks
tbl_warehouse2id_stockmovements
tbl_hospital1id_stocks
tbl_hospital1id_stockmovements
tbl_hospital1id_employee
tbl_hospital1id_patients
tbl_hospital2id_stocks
tbl_hospital2id_stockmovements
tbl_hospital2id_employee
tbl_hospital2id_patients

Merged Tables

tbl_items //centralized item information
tbl_suppliers //centralized supplier information
tbl_warehouse_stocks //where warehouse_ids are primary keys
tbl_warehouse_stockmovements //where warehouse_ids are primary keys
tbl_hospital_stocks //where hospital_ids are primary keys
tbl_hospital_stockmovements //where hospital_ids are primary keys
tbl_hospital_employee //where hospital_ids are primary keys
tbl_hospital_patients //where hospital_ids are primary keys

which is better? for maintaining, speed optimization etc.? my current opinion is that the separated approach is better because why should (for example) hospital1 search for their certain stock of items to the pool of stocks of all hospitals? does this affect the speed? if hospital1 tries to query their entire stock record, it will affect the query time of other hospital because hospital1 is currently searching for their records. of course indexing should help but still.

EDIT:

The server resides on a single location and its a web-based system.


问:
Modulo in JavaScript - large number
I try to calculate with JS' modulo function, but don't get the right result (which should be 1). Here is a hardcoded piece of code.

```<code>var checkSum = 210501700012345678131468;
alert(checkSum % 97);

Result: 66
</code>```

Whats the problem here?

Regards,
Benedikt

答: Silent Matt has developed a Javascript library  for Big Integers. It could solve this issue too.</p>

Title: Modulo in JavaScript - large number

Body:
I try to calculate with JS' modulo function, but don't get the right result (which should be 1). Here is a hardcoded piece of code.

var checkSum = 210501700012345678131468;
alert(checkSum % 97);

Result: 66

Whats the problem here?

Regards,
Benedikt


问:
dataset does not support system nullable in crystal reports
I am using vs2012 asp.net mvc and crystal reports v.13.

i have this error when i am trying to export the crystal report

DataSet does not support System.Nullable<>.

at this line

rd.SetDataSource(cn.Customers.Select(c => new

```<code>    public ActionResult Index()
    {
        ViewBag.listCustomers = cn.Customers.ToList();
        return View();
    }
    public ActionResult Export()
    {
        ReportDocument rd = new ReportDocument();
        rd.Load(Path.Combine(Server.MapPath("~/Reports/CustomerReport.rpt")));
        rd.SetDataSource(cn.Customers.Select(c => new
        {
            CustomerID = c.CustomerID  ,
            CustomerName = c.CustomerName ,
            CustomerEmail = c.CustomerEmail ,
            CustomerZipCode = c.CustomerZipCode ,
            CustomerCountry = c.CustomerCountry ,
            CustomerCity = c.CustomerCity,
        }).ToList());

        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();
        Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);

        return File(stream, "application/pdf", "CustomerList.pdf");
  }
</code>```

this is the view:

        CustomerID
        CustomerName
        CustomerEmail
        CustomerZipCode
        CustomerCountry
        CustomerCity

    @foreach (var cust in ViewBag.listCustomers)
    {

            @cust.CustomerID
            @cust.CustomerName
            @cust.CustomerEmail
            @cust.CustomerZipCode
            @cust.CustomerCountry
            @cust.CustomerCity

    }

    Export report

```

答:
I understand that "cn.Customers.Select" is returning an anonymous type where its attributes have infered types.

Then "rd.SetDataSource" takes that object of that anonymous type and create a DataSet to the ReportDocument.

Once the anonymous type has an infered type that is nullable (because of the attributes of your Customer class), the framework try to create a DataColumn using that nullable type. So you get the error mentioned.

So, you may try to drive the anonymous type to avoid nullable types for its attributes. To do the that, try the following. But since i don't know your Customer class, i will simplify the scenario and assume it has only one property and it is nullable.

```<code>class Customer { public int? CustomerID; }
</code>```

Then you could try this:

```<code>rd.SetDataSource(cn.Customers.Select(c => new
{
    CustomerID = c.CustomerID == null ? 0 : c.CustomerID
}).ToList());
</code>```

Do something like that for all of your nullable attributes.

Body:
I am using vs2012 asp.net mvc and crystal reports v.13.

i have this error when i am trying to export the crystal report

DataSet does not support System.Nullable<>.

at this line

rd.SetDataSource(cn.Customers.Select(c => new

    public ActionResult Index()
    {
        ViewBag.listCustomers = cn.Customers.ToList();
        return View();
    }
    public ActionResult Export()
    {
        ReportDocument rd = new ReportDocument();
        rd.Load(Path.Combine(Server.MapPath("~/Reports/CustomerReport.rpt")));
        rd.SetDataSource(cn.Customers.Select(c => new
        {
            CustomerID = c.CustomerID  ,
            CustomerName = c.CustomerName ,
            CustomerEmail = c.CustomerEmail ,
            CustomerZipCode = c.CustomerZipCode ,
            CustomerCountry = c.CustomerCountry ,
            CustomerCity = c.CustomerCity,
        }).ToList());

        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();
        Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);

        return File(stream, "application/pdf", "CustomerList.pdf");
  }

this is the view:

        CustomerID
        CustomerName
        CustomerEmail
        CustomerZipCode
        CustomerCountry
        CustomerCity

    @foreach (var cust in ViewBag.listCustomers)
    {

            @cust.CustomerID
            @cust.CustomerName
            @cust.CustomerEmail
            @cust.CustomerZipCode
            @cust.CustomerCountry
            @cust.CustomerCity

    }

    Export report

Body:
I understand that "cn.Customers.Select" is returning an anonymous type where its attributes have infered types.

Then "rd.SetDataSource" takes that object of that anonymous type and create a DataSet to the ReportDocument.

Once the anonymous type has an infered type that is nullable (because of the attributes of your Customer class), the framework try to create a DataColumn using that nullable type. So you get the error mentioned.

So, you may try to drive the anonymous type to avoid nullable types for its attributes. To do the that, try the following. But since i don't know your Customer class, i will simplify the scenario and assume it has only one property and it is nullable.

class Customer { public int? CustomerID; }

Then you could try this:

rd.SetDataSource(cn.Customers.Select(c => new
{
    CustomerID = c.CustomerID == null ? 0 : c.CustomerID
}).ToList());

Do something like that for all of your nullable attributes.


问:
SFML 2.4.2 for Visual C++ 2017 using the 2015 build of SFML
So I am trying to write some network related code, specifically a port scanner using SFML.  I am running VS 2017 and have downloaded the SFML build for 2015 however people have said this should work with 2017.

My demo code so far to try and see if the library is working is:

```<code>#include <iostream>
#include <SFML/Network.hpp>
#include <string>

using namespace std;

bool port_is_open(const string& address, int port) {
    sf::TcpSocket socket;
    bool open = (socket.connect(sf::IpAddress(address), port) == sf::Socket::Done);
    socket.disconnect();
    return open;
}

int main() {
    cout << "Enter IP number: ";
    string address;
    cin >> address;

    cout << "Enter Port number: ";
    int port;
    cin >> port;

    if (port_is_open(address, port)) {
        cout << "Port " << port << ": OPEN" << endl;
    }
    else {
        cout << "Port " << port << ": CLOSED" << endl;
    }

    return 0;
}
</code>```

But I wouldn't be here if this was working.

Severity  Code    Description Project File    Line    Suppression State
  Error   LNK2019 unresolved external symbol "public: virtual __thiscall sf::Socket::~Socket(void)" (??1Socket@sf@@UAE@XZ) referenced in function "public: virtual __thiscall sf::TcpSocket::~TcpSocket(void)" (??1TcpSocket@sf@@UAE@XZ)  PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: __thiscall sf::TcpSocket::TcpSocket(void)" (??0TcpSocket@sf@@QAE@XZ) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)   PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: enum sf::Socket::Status __thiscall sf::TcpSocket::connect(class sf::IpAddress const &,unsigned short,class sf::Time)" (?connect@TcpSocket@sf@@QAE?AW4Status@Socket@2@ABVIpAddress@2@GVTime@2@@Z) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)   PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: void __thiscall sf::TcpSocket::disconnect(void)" (?disconnect@TcpSocket@sf@@QAEXXZ) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)    PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: __thiscall sf::IpAddress::IpAddress(class std::basic_string,class std::allocator > const &)" (??0IpAddress@sf@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)    PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2001 unresolved external symbol "public: static class sf::Time const sf::Time::Zero" (?Zero@Time@sf@@2V12@B) PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

  Warning LNK4272 library machine type 'x64' conflicts with target machine type 'X86' PortScannerWin32    D:\SFML-2.4.2\lib\sfml-network-d.lib    1

Error LNK1120 6 unresolved externals  PortScannerWin32    c:\users\james\documents\visual studio 2017\Projects\PortScannerWin32\Debug\PortScannerWin32.exe    1

Those are my errors and if I am honest, I literally have no clue at all.  I have followed the tutorials word by word and typed in the dependencies etc.

Anyone have any idea what is going wrong?  I would say the obvious answer is 2015 being used in VS 2017 but a lot of forums have said that it works with no problems as there was an update in the SFML 2015 that allowed this.

答:
You are not linking against the correct library platform.

Warning LNK4272 library machine type 'x64' conflicts with target machine type 'X86' PortScannerWin32 D:\SFML-2.4.2\lib\sfml-network-d.lib 1

This states that you are linking against a 64bits library while your project is in 32bits. Make sure to take the correct library, or update your project to build it as a 64bits project.

Body:
So I am trying to write some network related code, specifically a port scanner using SFML.  I am running VS 2017 and have downloaded the SFML build for 2015 however people have said this should work with 2017.

My demo code so far to try and see if the library is working is:

#include <iostream>
#include <SFML/Network.hpp>
#include <string>

using namespace std;

bool port_is_open(const string& address, int port) {
    sf::TcpSocket socket;
    bool open = (socket.connect(sf::IpAddress(address), port) == sf::Socket::Done);
    socket.disconnect();
    return open;
}

int main() {
    cout << "Enter IP number: ";
    string address;
    cin >> address;

    cout << "Enter Port number: ";
    int port;
    cin >> port;

    if (port_is_open(address, port)) {
        cout << "Port " << port << ": OPEN" << endl;
    }
    else {
        cout << "Port " << port << ": CLOSED" << endl;
    }

    return 0;
}

But I wouldn't be here if this was working.

Severity  Code    Description Project File    Line    Suppression State
  Error   LNK2019 unresolved external symbol "public: virtual __thiscall sf::Socket::~Socket(void)" (??1Socket@sf@@UAE@XZ) referenced in function "public: virtual __thiscall sf::TcpSocket::~TcpSocket(void)" (??1TcpSocket@sf@@UAE@XZ)  PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: __thiscall sf::TcpSocket::TcpSocket(void)" (??0TcpSocket@sf@@QAE@XZ) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)   PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: enum sf::Socket::Status __thiscall sf::TcpSocket::connect(class sf::IpAddress const &,unsigned short,class sf::Time)" (?connect@TcpSocket@sf@@QAE?AW4Status@Socket@2@ABVIpAddress@2@GVTime@2@@Z) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)   PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: void __thiscall sf::TcpSocket::disconnect(void)" (?disconnect@TcpSocket@sf@@QAEXXZ) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)    PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2019 unresolved external symbol "public: __thiscall sf::IpAddress::IpAddress(class std::basic_string,class std::allocator > const &)" (??0IpAddress@sf@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "bool __cdecl port_is_open(class std::basic_string,class std::allocator > const &,int)" (?port_is_open@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)    PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

Error LNK2001 unresolved external symbol "public: static class sf::Time const sf::Time::Zero" (?Zero@Time@sf@@2V12@B) PortScannerWin32    c:\Users\James\documents\visual studio 2017\Projects\PortScannerWin32\PortScannerWin32\PortScanner.obj  1

  Warning LNK4272 library machine type 'x64' conflicts with target machine type 'X86' PortScannerWin32    D:\SFML-2.4.2\lib\sfml-network-d.lib    1

Error LNK1120 6 unresolved externals  PortScannerWin32    c:\users\james\documents\visual studio 2017\Projects\PortScannerWin32\Debug\PortScannerWin32.exe    1

Those are my errors and if I am honest, I literally have no clue at all.  I have followed the tutorials word by word and typed in the dependencies etc.

Anyone have any idea what is going wrong?  I would say the obvious answer is 2015 being used in VS 2017 but a lot of forums have said that it works with no problems as there was an update in the SFML 2015 that allowed this.


答:
as the help says

--since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes

I would do

docker logs mycontainer_or_id --since 60m

This syntax is correct according to my active container

Title: How to use --since option with docker logs command

Body: I want to look at last 1 hour of docker container log using docker logs --since option. Which value I should provide for --since parameter?


问:
Why does this code only show 1 ID
I am having a problem.
I know I am using deprecated MySQL, but I am working on a website for school and security is not necessary(as long as it works). I am trying to get all the Id's from a table called Reviews. This should be stored in a array. For some reason it only shows the first one. How to get all of them stored in 1 array? This is my code which is not working:</p>

```<code>$sql1 = "SELECT Klanten_id FROM Reviews";
$res1 = mysql_query($sql1);
$r = mysql_fetch_assoc($res1)['Klanten_id'];
</code>```

答:
1.Don't use outdated mysql_* library.Turn to mysqli_* or PDO.

2.mysql_fetch_assoc: Fetch a result row as an associative array. So you need to apply loop to get all data

Like below:-

```<code>$ids = array(); //created an array
while ($row = mysql_fetch_assoc($res1)) {
    $ids[] = $row['Klanten_id']; // assign each id to the array
}
print_r($ids);// print array
</code>```

3.To start working on mysqli/PDO check basic example here:- mysqli/PDO example

Title: Why does this code only show 1 ID

Body:
I am having a problem.
I know I am using deprecated MySQL, but I am working on a website for school and security is not necessary(as long as it works). I am trying to get all the Id's from a table called Reviews. This should be stored in a array. For some reason it only shows the first one. How to get all of them stored in 1 array? This is my code which is not working:

$sql1 = "SELECT Klanten_id FROM Reviews";
$res1 = mysql_query($sql1);
$r = mysql_fetch_assoc($res1)['Klanten_id'];

Body:
1.Don't use outdated mysql_* library.Turn to mysqli_* or PDO.

2.mysql_fetch_assoc: Fetch a result row as an associative array. So you need to apply loop to get all data

Like below:-

$ids = array(); //created an array
while ($row = mysql_fetch_assoc($res1)) {
    $ids[] = $row['Klanten_id']; // assign each id to the array
}
print_r($ids);// print array

3.To start working on mysqli/PDO check basic example here:- mysqli/PDO example


问:
android remove WebView debug logcat
like this one

```<code>WebView  D  evaluateJavascript=blah blah
</code>```

Can this be removed?

I tried use Proguard to remove Log, but only my logs are removed. WebView log still there.

```<code>-assumenosideeffects class android.util.Log {
    public static *** d(...);
    public static *** v(...);
}
</code>```

Edit: It's not about filtering log. I don`t want someone see the log when running my app, which more difficult to hack.

答:
Try this</p>

```<code>webView.setWebChromeClient(new WebChromeClient()
{
   @Override
   public boolean onConsoleMessage(ConsoleMessage cm) {
      //Log.d("TAG", cm.message() + " at " + cm.sourceId() + ":" + cm.lineNumber());
      return true;
   }
});
</code>```

Title: android remove WebView debug logcat

Body:
like this one

WebView  D  evaluateJavascript=blah blah

Can this be removed?

I tried use Proguard to remove Log, but only my logs are removed. WebView log still there.

-assumenosideeffects class android.util.Log {
    public static *** d(...);
    public static *** v(...);
}

Edit: It's not about filtering log. I don`t want someone see the log when running my app, which more difficult to hack.

Body:
Try this

webView.setWebChromeClient(new WebChromeClient()
{
   @Override
   public boolean onConsoleMessage(ConsoleMessage cm) {
      //Log.d("TAG", cm.message() + " at " + cm.sourceId() + ":" + cm.lineNumber());
      return true;
   }
});


答:
I don't have any knowledge of this library, but these seem like pretty standard linker errors. There should be no problem linking VS 2017 (Platform Toolset v141) with libraries compiled with VS 2015 (Plaform Toolset v141). Microsoft have kept binary compatibility between the compilers in VS 2015 and 2017, which allows mixing code compiled with either together in the same executible.

The header file your are including (SFML/Network.hpp) "promises" implementations for the classes you are using. It's the linker's job to match up the "promises" with the actual implementations, contained in a static lib (.lib), and put them together to create your exe.

Note the last warning:

```<code>Warning LNK4272 library machine type 'x64' conflicts with target machine type 'X86' PortScannerWin32 D:\SFML-2.4.2\lib\sfml-network-d.lib 1
</code>```

As a first step, I would change the platform value on your project within Visual Studio to x64, so the "bitness" of the library matches that of your executible. This is native machine code, so the generated code must be for the same architecture.

Note that when changing this, you might need to set project properties such as the include and library paths, as well as linker inputs, so that your code compiles. You can use the project property sheets to set the x64 values to those in the x86 platform.

Title: SFML 2.4.2 for Visual C++ 2017 using the 2015 build of SFML

Body:
I don't have any knowledge of this library, but these seem like pretty standard linker errors. There should be no problem linking VS 2017 (Platform Toolset v141) with libraries compiled with VS 2015 (Plaform Toolset v141). Microsoft have kept binary compatibility between the compilers in VS 2015 and 2017, which allows mixing code compiled with either together in the same executible.

The header file your are including (SFML/Network.hpp) "promises" implementations for the classes you are using. It's the linker's job to match up the "promises" with the actual implementations, contained in a static lib (.lib), and put them together to create your exe.

Note the last warning:

Warning LNK4272 library machine type 'x64' conflicts with target machine type 'X86' PortScannerWin32 D:\SFML-2.4.2\lib\sfml-network-d.lib 1

As a first step, I would change the platform value on your project within Visual Studio to x64, so the "bitness" of the library matches that of your executible. This is native machine code, so the generated code must be for the same architecture.

Note that when changing this, you might need to set project properties such as the include and library paths, as well as linker inputs, so that your code compiles. You can use the project property sheets to set the x64 values to those in the x86 platform.


问:
creating an array inside a while loop(or for loop) then using that array outside
What I am trying to do, which this won't do and probably never will do, is to create an array using a loop and then calling that array in another class. What would be the best way to go about this. I've looked all over for a solution and they won't compile. Thanks for the help.

```<code>import java.util.*;
public class Test{

public static void main(String[] args){

    Grow t = new Grow();
    ArrayList arr = new ArrayList();
    arr = t.Grow();
    System.out.print(arr);

}
}

public class Grow{
    static int row;
    static int column;

public ArrayList<Integer> poli(){
        while(row < 51 ){
            int r = row;
                while(column < 1){
                    ArrayList<Integer> policy = new ArrayList<Integer>();
                    policy.add(r);
                    policy.add(0);

                }

            column-=1;
            row++;
        }

    return policy;

}
</code>```

EDIT:
new problem.
    Getting error Exception in thread "main"java.lang.OutOfMemoryError:Java heap   space
    at java.util.Arrays.copyOf(Arrays.java:3210)
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at Grow.policy(Grow.java:14)
    at Test.main(Test.java:8)

```<code>public class Test{
public static void main(String[] args){

Grow trr = new Grow();
ArrayList arr = trr.policy();
System.out.print(arr);

}
}
</code>```

Here is what I have now. Everything works until I try to make the array in Test class.

```<code>import java.util.*;

public class Grow{
    static int row;
    static int column;

public ArrayList<Integer> policy(){

ArrayList<Integer> policy = new ArrayList<Integer>();
    while(row < 51 ){
          while(column < 1){

                policy.add(row);
                policy.add(0);
                column++; //this addition fixed my problem
            }

        column-=1;
        row++;
    }

return policy;

    }
}

public class Test{

    public static void main(String[] args){
       Grow work= new Grow();
       ArrayList testing= work.policy();
       System.out.print(testing);

    }
}
</code>```

I know it's something simple. I just can't see the solution. Thanks in advance.
EDIT: Update. Found the problem. Column only had a decrease of 1 (really could use column--;) which made it loop forever. Added column++ to the code and now it works. Knew it was something simple.

答:
You should initialize it outside:

```<code>public ArrayList<Integer> poli(){

    ArrayList<Integer> policy = new ArrayList<Integer>();

    while(row < 51 ){
        int r = row;
            while(column < 1){

                policy.add(r);
                policy.add(0);

            }

        column-=1;
        row++;
    }

return policy;

}
</code>```

Also, you don't need a variable to store row. policy.add(row); will work fine too.

Body:
What I am trying to do, which this won't do and probably never will do, is to create an array using a loop and then calling that array in another class. What would be the best way to go about this. I've looked all over for a solution and they won't compile. Thanks for the help.

import java.util.*;
public class Test{

public static void main(String[] args){

    Grow t = new Grow();
    ArrayList arr = new ArrayList();
    arr = t.Grow();
    System.out.print(arr);

}
}

public class Grow{
    static int row;
    static int column;

public ArrayList<Integer> poli(){
        while(row < 51 ){
            int r = row;
                while(column < 1){
                    ArrayList<Integer> policy = new ArrayList<Integer>();
                    policy.add(r);
                    policy.add(0);

                }

            column-=1;
            row++;
        }

    return policy;

}

EDIT:
new problem.
    Getting error Exception in thread "main"java.lang.OutOfMemoryError:Java heap   space
    at java.util.Arrays.copyOf(Arrays.java:3210)
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at Grow.policy(Grow.java:14)
    at Test.main(Test.java:8)

public class Test{
public static void main(String[] args){

Grow trr = new Grow();
ArrayList arr = trr.policy();
System.out.print(arr);

}
}

Here is what I have now. Everything works until I try to make the array in Test class.

import java.util.*;

public class Grow{
    static int row;
    static int column;

public ArrayList<Integer> policy(){

ArrayList<Integer> policy = new ArrayList<Integer>();
    while(row < 51 ){
          while(column < 1){

                policy.add(row);
                policy.add(0);
                column++; //this addition fixed my problem
            }

        column-=1;
        row++;
    }

return policy;

    }
}

public class Test{

    public static void main(String[] args){
       Grow work= new Grow();
       ArrayList testing= work.policy();
       System.out.print(testing);

    }
}

I know it's something simple. I just can't see the solution. Thanks in advance.
EDIT: Update. Found the problem. Column only had a decrease of 1 (really could use column--;) which made it loop forever. Added column++ to the code and now it works. Knew it was something simple.

Body:
You should initialize it outside:

public ArrayList<Integer> poli(){

    ArrayList<Integer> policy = new ArrayList<Integer>();

    while(row < 51 ){
        int r = row;
            while(column < 1){

                policy.add(r);
                policy.add(0);

            }

        column-=1;
        row++;
    }

return policy;

}

Also, you don't need a variable to store row. policy.add(row); will work fine too.