问:
Data is not getting shown in select tag
I have a select tag of chapters , I am loading a result from query in it. But its not showing in a select tag, the chapter names are displayed like echo statements.

```<code>     <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>

</head>
<body>

<?php
session_start();

$dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman');

    $type = $_POST['type'];
    $question = $_POST["question"];
    $optionA = $_POST["opt1"];
    $optionB = $_POST["opt2"];
    $optionC = $_POST["opt3"];
    $optionD = $_POST["opt4"];
    $ans = $_POST["ans"];
    $chapter = $_POST["chapter"];
?>

<form method="post" action="mcq.php" enctype="multipart/form-data">

<?php if(isset($_POST['question']))
{
?>

Enter the question: <input name="question" type="text" value = "<?php echo $question?>"</input> <br><br>
<?php
}
else
{
?>
    <p> Enter the question :</p> <input name="question" type="text"></input> <br><br>

<?php
}
?>

Select rank :

<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{ ?>
<option value="1"  <?php echo($type==1?"selected":"");?>>SSgt</option>

<option value="2"  <?php echo($type==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($type==3?"selected":"");?>>MSgt</option>
</select>
<?php
}
    else
    {
    ?>
    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>
    <?php
    }
    ?>

<br><br>
<?php if(isset($_POST['opt1']))
{ ?>
<p> Enter options :</p>
Enter option A : <input name="opt1" type="text" value = "<?php echo $optionA?>"</input> <br><br>

<?php
}
else{
?>
<p> Enter options :</p>
Enter option A : <input name="opt1" type="text"> <br><br>
<?php
}
?>
<?php if(isset($_POST['opt2']))
{ ?>

Enter option B : <input name="opt2" value = "<?php echo $optionB?>"</input> <br><br>

<?php
}
else{
?>
Enter option B : <input name="opt2" type="text"> <br><br>
<?php
}
?>

<?php if(isset($_POST['opt3']))
{ ?>
Enter option C : <input name="opt3" value = "<?php echo $optionC?>"</input> <br><br>

<?php
}
else{
?>

Enter option C : <input name="opt3" type="text"> <br><br>

<?php
}
?>

<?php if(isset($_POST['opt4']))
{ ?>
Enter option D : <input name="opt4" value = "<?php echo $optionD?>"</input> <br><br>
<?php
}
else{
?>

Enter option D : <input name="opt4" type="text"> <br><br>

<?php
}
?>

Select correct answer :

<select name="ans" id="type">

<?php if(isset($_POST['ans']))
{
?>
<option value="A"  <?php echo($ans==A?"selected":"");?>>A</option>

<option value="B"  <?php echo($ans==B?"selected":"");?>>B</option>

<option value="C" <?php echo($ans==C?"selected":"");?>>C</option>

<option value="D" <?php echo($ans==D?"selected":"");?>>D</option
</select>

<br><br>
<?php
}
else
{
?>

<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<?php
}
?>
<br><br>

Select Chapter :
<select name="chapters" id="chapters">

<?php

if(isset($_POST['type']))
{
    $stmt = $dbh->prepare("SELECT * FROM chapters where type = :type");
    $stmt->bindParam("type", $type);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);

if(count($results > 0)){
foreach($results as $row):?>
<option value="<?php echo $row['id'];?>"><?php echo $row['title'];?></option>
<?php
endforeach;
}else{?>

<option value="0">No data found</option>
<?php
}

}

else{

$stmt = $dbh->prepare("SELECT * FROM chapters where type = 1");

$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);

if(count($results > 0)){
foreach($results as $row):?>
<option value="<?php echo $row['id'];?>"><?php echo $row['title'];?></option>
<?php
endforeach;
}else{?>

<option value="0">No data found</option>
<?php
}
}
?>

</select> <br><br>

<input type="Submit" value = "Submit" name="b1">

<?php

if(isset($_POST['b1']))
{

ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);

$type = $_POST['type'];
$question = $_POST['question'];
$optionA = $_POST['opt1'];
$optionB = $_POST['opt2'];
$optionC = $_POST['opt3'];
$optionD = $_POST['opt4'];
$ans = $_POST['ans'];
$chapter = $_POST['chapters'];

    $stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer,type,chapterId) VALUES (?, ?, ?, ?, ?, ?, ?,?)");
$stmt->execute(array($question, $optionA, $optionB, $optionC, $optionD, $ans,$type,$chapter));

if ($dbh->lastInsertId())
{
    echo 'Question submitted.';

    echo '<a href="mcq.php">Upload another question.</a>';
    session_destroy();
}
else
{
    echo 'Question could not submit.';
}
}
?>

</form>
</body>
</html>
</code>```

It loads the data in select tag 1st time if type is not set, but if the type is set it shows chapters like echo statements.

What is wrong here? Please help thank you.

答:
I build my options in php then echo the whole string like this
in php

```<code>IF ($row[$i]['abc'] == 'A'){
$a[$i]='<option value="A" selected="selected">A</option>';
$b[$i]='<option value="B" >B</option>';
}
IF ($row[$i]['abc'] == 'B'){
$a[$i]='<option value="A" >A</option>';
$b[$i]='<option value="B" selected="selected" B</option>';
}
</code>```

in my html

```<code> <select>
    <php? echo $a[$i]; ?>
    <php? echo $b[$i]; ?>
 </select>
</code>```

always work and sets it on right data

for practice and learning create a file called try1.php

```<code><?php

$1='<option value="1">1</option>';
$2='<option value="2">2</option>';
//name of your selection
if(isset($_POST['1']){
echo 'you selected : '.$_post['1'];

}
?>
<html>
<body>
<select name="1">
<?php echo $1; ?>
<?php echo $2; ?>
</select>
<input type="submit" name="1" value="1">
</body>
</html>
</code>```

this is code from a file i made for my wife and it has worked for 2 years but it very old and doesnt have function to get what is selected

```<code><?php
session_start();
include_once("../staffpage/getstaff.php");
include_once("../staffpage/staffheader.php");
include_once("../cert/dbc.php");
?>
<html>
   <head>
   </head>
      <body>
        <h1>会员注册</h1>

       <form action="direct to you php file handling your indput.php" method="post">
          <tr>
             <td>
                <table width="60%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                 <tr>
                    <td colspan="3"><strong>会员注册</strong></td>
                 </tr>
                  <tr>
             <td width="78">卡号</td>
         <td width="6">:</td>

         <td width="294"><input type="text" name="cno" required/></td>
         </tr>
         <td width="78"> 收据号</td>
         <td width="6">:
         </td>

         <td width="294"><input type="text" name="rno" required/></td>

         </td>
         </tr>
         <td width="78"> 姓名</td>
         <td width="6">:</td>
         <td width="294"><input type="text" name="fname" required/></td>
         </tr>

         <td width="78">电话</td>
         <td width="6">:</td>
         <td width="294"><input type="text" name="ctel" required/></td>
         </tr>

         <td width="78"> cardname </td>
         <td width="6">:</td>
         <td width="294">
         <select name="cardnameno" >
            <?php
                //my query in this file
                include_once("../sec/cards.php");
                $i=0;
                while($row = mysql_fetch_array($result)) {
                $z2=$row['cardname'];
                $z1=$row['cardnameno'];
                ?>

            <option value="<?php echo $row['cardnameno']; ?>" ><?php echo $row['name']; ?></option>
            <?php
            $i++;
            }
            ?>
        </select>

        </tr>
        <tr>
            <td> </td>
            <td> </td>
            <td><input type="submit" /></td>
        </tr>
    </table>
</form></p>
  </div>
</form>
</body>
</html>
</html>
</code>```

i include this file in another but should not stop it from working

Title: Data is not getting shown in select tag

Body:
I have a select tag of chapters , I am loading a result from query in it. But its not showing in a select tag, the chapter names are displayed like echo statements.

     <!doctype html>

<meta charset="utf-8">
<title>MCQ Questions</title>

<?php
session_start();

$dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman');

    $type = $_POST['type'];
    $question = $_POST["question"];
    $optionA = $_POST["opt1"];
    $optionB = $_POST["opt2"];
    $optionC = $_POST["opt3"];
    $optionD = $_POST["opt4"];
    $ans = $_POST["ans"];
    $chapter = $_POST["chapter"];
?>

<form method="post" action="mcq.php" enctype="multipart/form-data">

<?php if(isset($_POST['question']))
{
?>

Enter the question: <input name="question" type="text" value = "<?php echo $question?>"</input>

<?php
}
else
{
?>

 Enter the question :
 <input name="question" type="text"></input>

<?php
}
?>

Select rank :

<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{ ?>
<option value="1"  <?php echo($type==1?"selected":"");?>>SSgt</option>

<option value="2"  <?php echo($type==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($type==3?"selected":"");?>>MSgt</option>
</select>
<?php
}
    else
    {
    ?>
    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>
    <?php
    }
    ?>

<?php if(isset($_POST['opt1']))
{ ?>

 Enter options :

Enter option A : <input name="opt1" type="text" value = "<?php echo $optionA?>"</input>

<?php
}
else{
?>

 Enter options :

Enter option A : <input name="opt1" type="text">

<?php
}
?>
<?php if(isset($_POST['opt2']))
{ ?>

Enter option B : <input name="opt2" value = "<?php echo $optionB?>"</input>

<?php
}
else{
?>
Enter option B : <input name="opt2" type="text">

<?php
}
?>

<?php if(isset($_POST['opt3']))
{ ?>
Enter option C : <input name="opt3" value = "<?php echo $optionC?>"</input>

<?php
}
else{
?>

Enter option C : <input name="opt3" type="text">

<?php
}
?>

<?php if(isset($_POST['opt4']))
{ ?>
Enter option D : <input name="opt4" value = "<?php echo $optionD?>"</input>

<?php
}
else{
?>

Enter option D : <input name="opt4" type="text">

<?php
}
?>

Select correct answer :

<select name="ans" id="type">

<?php if(isset($_POST['ans']))
{
?>
<option value="A"  <?php echo($ans==A?"selected":"");?>>A</option>

<option value="B"  <?php echo($ans==B?"selected":"");?>>B</option>

<option value="C" <?php echo($ans==C?"selected":"");?>>C</option>

<option value="D" <?php echo($ans==D?"selected":"");?>>D</option
</select>

<?php
}
else
{
?>

<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<?php
}
?>

Select Chapter :
<select name="chapters" id="chapters">

<?php

if(isset($_POST['type']))
{
    $stmt = $dbh->prepare("SELECT * FROM chapters where type = :type");
    $stmt->bindParam("type", $type);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);

if(count($results > 0)){
foreach($results as $row):?>
<option value="<?php echo $row['id'];?>"><?php echo $row['title'];?></option>
<?php
endforeach;
}else{?>

<option value="0">No data found</option>
<?php
}

}

else{

$stmt = $dbh->prepare("SELECT * FROM chapters where type = 1");

$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);

if(count($results > 0)){
foreach($results as $row):?>
<option value="<?php echo $row['id'];?>"><?php echo $row['title'];?></option>
<?php
endforeach;
}else{?>

<option value="0">No data found</option>
<?php
}
}
?>

</select>

<input type="Submit" value = "Submit" name="b1">

<?php

if(isset($_POST['b1']))
{

ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);

$type = $_POST['type'];
$question = $_POST['question'];
$optionA = $_POST['opt1'];
$optionB = $_POST['opt2'];
$optionC = $_POST['opt3'];
$optionD = $_POST['opt4'];
$ans = $_POST['ans'];
$chapter = $_POST['chapters'];

    $stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer,type,chapterId) VALUES (?, ?, ?, ?, ?, ?, ?,?)");
$stmt->execute(array($question, $optionA, $optionB, $optionC, $optionD, $ans,$type,$chapter));

if ($dbh->lastInsertId())
{
    echo 'Question submitted.';

    echo 'Upload another question.';
    session_destroy();
}
else
{
    echo 'Question could not submit.';
}
}
?>

</form>

It loads the data in select tag 1st time if type is not set, but if the type is set it shows chapters like echo statements.

What is wrong here? Please help thank you.

Body:
I build my options in php then echo the whole string like this
in php

IF ($row[$i]['abc'] == 'A'){
$a[$i]='<option value="A" selected="selected">A</option>';
$b[$i]='<option value="B" >B</option>';
}
IF ($row[$i]['abc'] == 'B'){
$a[$i]='<option value="A" >A</option>';
$b[$i]='<option value="B" selected="selected" B</option>';
}

in my html

 <select>
    <php? echo $a[$i]; ?>
    <php? echo $b[$i]; ?>
 </select>

always work and sets it on right data

for practice and learning create a file called try1.php

<?php

$1='<option value="1">1</option>';
$2='<option value="2">2</option>';
//name of your selection
if(isset($_POST['1']){
echo 'you selected : '.$_post['1'];

}
?>
<html>
<body>
<select name="1">
<?php echo $1; ?>
<?php echo $2; ?>
</select>
<input type="submit" name="1" value="1">
</body>
</html>

this is code from a file i made for my wife and it has worked for 2 years but it very old and doesnt have function to get what is selected

<?php
session_start();
include_once("../staffpage/getstaff.php");
include_once("../staffpage/staffheader.php");
include_once("../cert/dbc.php");
?>
<html>
   <head>
   </head>
      <body>
        <h1>&#20250;&#21592;&#27880;&#20876;</h1>

       <form action="direct to you php file handling your indput.php" method="post">
          <tr>
             <td>
                <table width="60%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                 <tr>
                    <td colspan="3"><strong>&#20250;&#21592;&#27880;&#20876;</strong></td>
                 </tr>
                  <tr>
             <td width="78">&#21345;&#21495;</td>
         <td width="6">:</td>

         <td width="294"><input type="text" name="cno" required/></td>
         </tr>
         <td width="78"> &#25910;&#25454;&#21495;</td>
         <td width="6">:
         </td>

         <td width="294"><input type="text" name="rno" required/></td>

         </td>
         </tr>
         <td width="78"> &#22995;&#21517;</td>
         <td width="6">:</td>
         <td width="294"><input type="text" name="fname" required/></td>
         </tr>

         <td width="78">&#30005;&#35805;</td>
         <td width="6">:</td>
         <td width="294"><input type="text" name="ctel" required/></td>
         </tr>

         <td width="78"> cardname </td>
         <td width="6">:</td>
         <td width="294">
         <select name="cardnameno" >
            <?php
                //my query in this file
                include_once("../sec/cards.php");
                $i=0;
                while($row = mysql_fetch_array($result)) {
                $z2=$row['cardname'];
                $z1=$row['cardnameno'];
                ?>

            <option value="<?php echo $row['cardnameno']; ?>" ><?php echo $row['name']; ?></option>
            <?php
            $i++;
            }
            ?>
        </select>

        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td><input type="submit" /></td>
        </tr>
    </table>
</form></p>
  </div>
</form>
</body>
</html>
</html>

i include this file in another but should not stop it from working


来源: stackexchange

问:
How to create a library
I have some code which I want to organize into a class or library for other developers to use more easily on their website.

The way I use the class now is to instantiate an instance of it and start calling the functions I need as I need them.

```<code>$class_object = new MyClass();
$class_object->myFunction();
</code>```

Is this basically all I need to make a library, or do I need to make further changes to turn this into a library?

答:
PHP doesn't have any concept of a library other than what you're already doing. If you want to abstract it (make sure it works outside of your application) and move it into a separate file/directory, you can, but that doesn't qualify it as a library any more than usual!

I will note though, there are some frameworks that use the term library as something specific, but you'll have to look into the individual framework's documentation for that, I'm afraid.

ContentLicense: CC BY-SA 2.5

Title: How to create a library

Body:
I have some code which I want to organize into a class or library for other developers to use more easily on their website.

The way I use the class now is to instantiate an instance of it and start calling the functions I need as I need them.

$class_object = new MyClass();
$class_object->myFunction();

Is this basically all I need to make a library, or do I need to make further changes to turn this into a library?


问:
What is the simplest way to pipe from a Read to a Write
I've got two objects.  One implements the std::io::Read trait and the other implements the std::io::Write trait (e.g., two std::fs::File instances).  I'm trying to figure out a simple and efficient way to pipe the data from the Read instance into the Write instance.

Let me add that I'm fully aware of std::fs::copy, but that only applies to files on a file system...these are not that.  I also looked at std::io::copy, but it doesn't work with Read and Write instances.

I know that I can read the contents of the Read into a Vec<u8> with something like this:

```<code>let mut data = Vec::new();
file.read_to_end(&mut data);
</code>```

But read_to_end fills a Vec<u8> but the corresponding function on Write, write_all, takes a &[u8] and I don't see any method on Vec<u8> that allows me to create a new array, only a slice of some pre-specified size.

I can imagine several different ways to do this (read/write one byte at a time, read/write chunks).  But I am hoping that there is some function in std that does all this (with all the requisite error handling, chunk size management, etc) but if it is there, I haven't been able to find it.

Any suggestions on a simple way to do this?  I am admittedly relatively new to Rust, but believe me when I say I spent quite a bit of time looking for such a thing and couldn't find it.  Yes, I realize in that time I could have implemented but I wanted something that would be efficient and I'm concerned that what I would write wouldn't be optimal.

Thanks for any assistance.

答:
I also looked at std::io::copy, but it doesn't work with Read and Write instances.

It does. Look at the where clause in its signature:

```<code>pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
where R: Read, W: Write
</code>```

For instance, here I redirect stdin to stdout:

```<code>use std::io;

fn main() {
  let mut stdin = io::stdin();
  let mut stdout = io::stdout();
  io::copy(&mut stdin,&mut stdout);
}
</code>```

If you are looking for a buffer to write into and read out of, BufStream from the bufstream crate should be of use.

I can imagine several different ways to do this (read/write one byte at a time, read/write chunks). But I am hoping that there is some function in std that does all this (with all the requisite error handling, chunk size management, etc) but if it is there, I haven't been able to find it.

That is exactly what std::io::copy does - it allocates a buffer and then loops between reading into that buffer and writing out from that buffer until there is nothing left to read.

ContentLicense: CC BY-SA 3.0

Body:
I've got two objects.  One implements the std::io::Read trait and the other implements the std::io::Write trait (e.g., two std::fs::File instances).  I'm trying to figure out a simple and efficient way to pipe the data from the Read instance into the Write instance.

Let me add that I'm fully aware of std::fs::copy, but that only applies to files on a file system...these are not that.  I also looked at std::io::copy, but it doesn't work with Read and Write instances.

I know that I can read the contents of the Read into a Vec<u8> with something like this:

let mut data = Vec::new();
file.read_to_end(&mut data);

But read_to_end fills a Vec<u8> but the corresponding function on Write, write_all, takes a &[u8] and I don't see any method on Vec<u8> that allows me to create a new array, only a slice of some pre-specified size.

I can imagine several different ways to do this (read/write one byte at a time, read/write chunks).  But I am hoping that there is some function in std that does all this (with all the requisite error handling, chunk size management, etc) but if it is there, I haven't been able to find it.

Any suggestions on a simple way to do this?  I am admittedly relatively new to Rust, but believe me when I say I spent quite a bit of time looking for such a thing and couldn't find it.  Yes, I realize in that time I could have implemented but I wanted something that would be efficient and I'm concerned that what I would write wouldn't be optimal.

Thanks for any assistance.

Body:
I also looked at std::io::copy, but it doesn't work with Read and Write instances.

It does. Look at the where clause in its signature:

pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
where R: Read, W: Write

For instance, here I redirect stdin to stdout:

use std::io;

fn main() {
  let mut stdin = io::stdin();
  let mut stdout = io::stdout();
  io::copy(&mut stdin,&mut stdout);
}

If you are looking for a buffer to write into and read out of, BufStream from the bufstream crate should be of use.

I can imagine several different ways to do this (read/write one byte at a time, read/write chunks). But I am hoping that there is some function in std that does all this (with all the requisite error handling, chunk size management, etc) but if it is there, I haven't been able to find it.

That is exactly what std::io::copy does - it allocates a buffer and then loops between reading into that buffer and writing out from that buffer until there is nothing left to read.

ContentLicense: CC BY-SA 4.0


问:
multiple web cams in AMCap
I built the AMCap sample under direct show in SDK. It is able to handle 2 or more web cam, how do I modify the program for me to use them simultaneously… like press one button that says ‘start capture’ and make sure that all the cameras start capturing and one button that says ‘stop capture’ to stop all the cameras. i want the frames from different cameras to be save in different files. I am new to C++ and any kind of help is appreciated ! Thanks for your time!</p>

答:
If you're just starting out with DirectShow programming, this might be a bit of a hill climb, but I hope it's of some help, or points you in the right direction.

M$DN has a page describing how to select a capture device.  It's a little thin on examples, so I've provided a simple implementation below.

The theory is that you need to enumerate all devices in the CLSID_VideoInputDeviceCategory, and attempt to create a render graph for each valid item in the category.

First I'll show you the code to iterate the names of the devices in the category.  Below are 3 static functions you can use to iterate the devices in a category.  Once you've added these functions to your project, you can list the devices in the Video Input Device category by calling the following function:

```<code>ListDevicesInCategory(CLSID_VideoInputDeviceCategory);
</code>```

Okay, here are the three functions.  ListDevicesInCategory() is where the work happens.  It depends on other two functions, FindDeviceInCategory() and CountDevicesInCategory()

```<code>#define RFAIL(x) { HRESULT hr = x; if(FAILED(hr)) {return hr;} }

static HRESULT FindDeviceInCategory(IBaseFilter** pSrc, const IID& cls, wstring& wFilterName,int devNum)
{
    CComPtr<ICreateDevEnum> spDevEnum;
    CComPtr<IEnumMoniker>   spEnum;
    int                     i;

    RFAIL( spDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum) );
    RFAIL( spDevEnum->CreateClassEnumerator(cls, &spEnum, 0) );

    if(spEnum == 0)
        return E_FAIL;

    for(i = 0; i >= 0; i++)
    {
        CComPtr<IMoniker> spiMoniker;

        if( spEnum->Next(1, &spiMoniker, 0) != S_OK )
            return E_FAIL;

        if( devNum == i)
        {
            CComVariant varName;
            CComPtr<IPropertyBag> spiPropBag;
            RFAIL(spiMoniker->BindToStorage(0, 0, IID_IPropertyBag,reinterpret_cast<void**>(&spiPropBag)));
            RFAIL(spiPropBag->Read(L"FriendlyName", &varName, 0));
            RFAIL(spiMoniker->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(pSrc)));
            wFilterName = V_BSTR(&varName);

            varName.Clear();
            return S_OK;
        }
    }

    return E_FAIL;
}

static HRESULT CountDevicesInCategory( int *pCount, const IID& categoryClass )
{
    // pass in a category class like CLSID_VideoInputDeviceCategory, writes the count of the number of filters in that category
    // available on the local machine
    HRESULT hr = S_OK;

    CComPtr<ICreateDevEnum> spIDevEnum;
    CComPtr<IEnumMoniker>   spIEnum;
    CComPtr<IMoniker>       spIMoniker;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, 0, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>(&spIDevEnum));
    if( ! SUCCEEDED(hr) || hr == S_FALSE )
    {
        *pCount = 0;
        return hr;
    }

    hr = spIDevEnum->CreateClassEnumerator( categoryClass, &spIEnum, 0 );
    if( ! SUCCEEDED(hr) || hr == S_FALSE )
    {
        *pCount = 0;
        return hr;
    }

    if( spIEnum )
    {
        while( spIEnum->Next(1, &spIMoniker, 0) == S_OK )
        {
            (*pCount) ++;
            spIMoniker.Detach();
        }
    }

    return S_OK;
}

static HRESULT ListDevicesInCategory( const GUID & cls )
{
    CComPtr<IBaseFilter>    spSource;
    wstring *               psNextFilter        = NULL;
    int                     nDeviceNum          = 0;
    int                     nTotalNumDevices    = 0;
    HRESULT                 hr                  = S_OK;
    bool                    bComplete           = false;
    DeviceNames             CaptureDeviceNames;

    if( FAILED(CountDevicesInCategory( &nTotalNumDevices, (IID)cls )) )
        bComplete = TRUE;

    if( nTotalNumDevices == 0 )
        bComplete = TRUE;

    while( ! bComplete )
    {
        psNextFilter = new std::wstring;

        hr = FindDeviceInCategory( &spSource, (IID)cls, *psNextFilter, nDeviceNum++ );

        if( SUCCEEDED(hr) && spSource  )
        {
            if ( *psNextFilter )
            {
                wcout << *psNextFilter << endl;
                delete *psNextFilter;
                psNextFilter = NULL;
            }

            spSource.Release();
            spSource = NULL;
        }
        else
            bComplete = TRUE;
    }

    return S_OK;
}
</code>```

Once you've identified an item in a category that you're interested in, you can add it to a graph with the IGraphBuilder::AddFilter call.

To add a filter to your graph, you'll first need to get an IBaseFilter* to that filter.  I've got one more function for you to do this with.

Define an IBaseFilter smart pointer:

```<code>CComPtr<IBaseFilter> spSource;
</code>```

Attach to the filter:

```<code>m_spSource.Attach(
                GetFilter(CLSID_VideoInputDeviceCategory, CComBSTR(L"Osprey-450e Video Device 1A"))
          );
</code>```

Here's that last function - GetFilter:

```<code>static IBaseFilter * GetFilter( REFCLSID clsidDeviceClass, CComBSTR & sName )
{
    HRESULT             hr;
    IBaseFilter *       pRetFilter      = NULL;
    ICreateDevEnum *    pSysDevEnum     = NULL;
    IEnumMoniker *      pEnum           = NULL;
    IMoniker *          pMoniker        = NULL;
    int                 nSameSrcCounter = 0;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pSysDevEnum);

    if( pSysDevEnum )
        hr = pSysDevEnum->CreateClassEnumerator(clsidDeviceClass, &pEnum, 0);

    if (hr != S_OK)
        return NULL;

    USES_CONVERSION;

    while ( pEnum->Next(1, &pMoniker, NULL) == S_OK )
    {
        IPropertyBag *pPropBag = NULL;
        VARIANT var;
        VariantInit(&var);

        pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pPropBag);

        hr = pPropBag->Read(L"FriendlyName", &var, 0);
        if (SUCCEEDED(hr))
        {
            if(sName == OLE2T(var.bstrVal))
            {
                hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pRetFilter);
                if (FAILED(hr))
                    pRetFilter = NULL;

                VariantClear(&var);
                pPropBag->Release();
                pMoniker->Release();
                break;
            }
        }

        VariantClear(&var);
        pPropBag->Release();
        pMoniker->Release();
    }

    pSysDevEnum->Release();
    pEnum->Release();

    return pRetFilter;
}
</code>```

Title: multiple web cams in AMCap

Body:
If you're just starting out with DirectShow programming, this might be a bit of a hill climb, but I hope it's of some help, or points you in the right direction.

M$DN has a page describing how to select a capture device.  It's a little thin on examples, so I've provided a simple implementation below.

The theory is that you need to enumerate all devices in the CLSID_VideoInputDeviceCategory, and attempt to create a render graph for each valid item in the category.

First I'll show you the code to iterate the names of the devices in the category.  Below are 3 static functions you can use to iterate the devices in a category.  Once you've added these functions to your project, you can list the devices in the Video Input Device category by calling the following function:

ListDevicesInCategory(CLSID_VideoInputDeviceCategory);

Okay, here are the three functions.  ListDevicesInCategory() is where the work happens.  It depends on other two functions, FindDeviceInCategory() and CountDevicesInCategory()

#define RFAIL(x) { HRESULT hr = x; if(FAILED(hr)) {return hr;} }

static HRESULT FindDeviceInCategory(IBaseFilter** pSrc, const IID& cls, wstring& wFilterName,int devNum)
{
    CComPtr<ICreateDevEnum> spDevEnum;
    CComPtr<IEnumMoniker>   spEnum;
    int                     i;

    RFAIL( spDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum) );
    RFAIL( spDevEnum->CreateClassEnumerator(cls, &spEnum, 0) );

    if(spEnum == 0)
        return E_FAIL;

    for(i = 0; i >= 0; i++)
    {
        CComPtr<IMoniker> spiMoniker;

        if( spEnum->Next(1, &spiMoniker, 0) != S_OK )
            return E_FAIL;

        if( devNum == i)
        {
            CComVariant varName;
            CComPtr<IPropertyBag> spiPropBag;
            RFAIL(spiMoniker->BindToStorage(0, 0, IID_IPropertyBag,reinterpret_cast<void**>(&spiPropBag)));
            RFAIL(spiPropBag->Read(L"FriendlyName", &varName, 0));
            RFAIL(spiMoniker->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(pSrc)));
            wFilterName = V_BSTR(&varName);

            varName.Clear();
            return S_OK;
        }
    }

    return E_FAIL;
}

static HRESULT CountDevicesInCategory( int *pCount, const IID& categoryClass )
{
    // pass in a category class like CLSID_VideoInputDeviceCategory, writes the count of the number of filters in that category
    // available on the local machine
    HRESULT hr = S_OK;

    CComPtr<ICreateDevEnum> spIDevEnum;
    CComPtr<IEnumMoniker>   spIEnum;
    CComPtr<IMoniker>       spIMoniker;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, 0, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>(&spIDevEnum));
    if( ! SUCCEEDED(hr) || hr == S_FALSE )
    {
        *pCount = 0;
        return hr;
    }

    hr = spIDevEnum->CreateClassEnumerator( categoryClass, &spIEnum, 0 );
    if( ! SUCCEEDED(hr) || hr == S_FALSE )
    {
        *pCount = 0;
        return hr;
    }

    if( spIEnum )
    {
        while( spIEnum->Next(1, &spIMoniker, 0) == S_OK )
        {
            (*pCount) ++;
            spIMoniker.Detach();
        }
    }

    return S_OK;
}

static HRESULT ListDevicesInCategory( const GUID & cls )
{
    CComPtr<IBaseFilter>    spSource;
    wstring *               psNextFilter        = NULL;
    int                     nDeviceNum          = 0;
    int                     nTotalNumDevices    = 0;
    HRESULT                 hr                  = S_OK;
    bool                    bComplete           = false;
    DeviceNames             CaptureDeviceNames;

    if( FAILED(CountDevicesInCategory( &nTotalNumDevices, (IID)cls )) )
        bComplete = TRUE;

    if( nTotalNumDevices == 0 )
        bComplete = TRUE;

    while( ! bComplete )
    {
        psNextFilter = new std::wstring;

        hr = FindDeviceInCategory( &spSource, (IID)cls, *psNextFilter, nDeviceNum++ );

        if( SUCCEEDED(hr) && spSource  )
        {
            if ( *psNextFilter )
            {
                wcout << *psNextFilter << endl;
                delete *psNextFilter;
                psNextFilter = NULL;
            }

            spSource.Release();
            spSource = NULL;
        }
        else
            bComplete = TRUE;
    }

    return S_OK;
}

Once you've identified an item in a category that you're interested in, you can add it to a graph with the IGraphBuilder::AddFilter call.

To add a filter to your graph, you'll first need to get an IBaseFilter* to that filter.  I've got one more function for you to do this with.

Define an IBaseFilter smart pointer:

CComPtr<IBaseFilter> spSource;

Attach to the filter:

m_spSource.Attach(
                GetFilter(CLSID_VideoInputDeviceCategory, CComBSTR(L"Osprey-450e Video Device 1A"))
          );

Here's that last function - GetFilter:

static IBaseFilter * GetFilter( REFCLSID clsidDeviceClass, CComBSTR & sName )
{
    HRESULT             hr;
    IBaseFilter *       pRetFilter      = NULL;
    ICreateDevEnum *    pSysDevEnum     = NULL;
    IEnumMoniker *      pEnum           = NULL;
    IMoniker *          pMoniker        = NULL;
    int                 nSameSrcCounter = 0;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pSysDevEnum);

    if( pSysDevEnum )
        hr = pSysDevEnum->CreateClassEnumerator(clsidDeviceClass, &pEnum, 0);

    if (hr != S_OK)
        return NULL;

    USES_CONVERSION;

    while ( pEnum->Next(1, &pMoniker, NULL) == S_OK )
    {
        IPropertyBag *pPropBag = NULL;
        VARIANT var;
        VariantInit(&var);

        pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pPropBag);

        hr = pPropBag->Read(L"FriendlyName", &var, 0);
        if (SUCCEEDED(hr))
        {
            if(sName == OLE2T(var.bstrVal))
            {
                hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pRetFilter);
                if (FAILED(hr))
                    pRetFilter = NULL;

                VariantClear(&var);
                pPropBag->Release();
                pMoniker->Release();
                break;
            }
        }

        VariantClear(&var);
        pPropBag->Release();
        pMoniker->Release();
    }

    pSysDevEnum->Release();
    pEnum->Release();

    return pRetFilter;
}


问:
javascript use await in my function call
Lets say I have a functin like:

```<code>function some(){
    console.log("wow")
    return "some"
}

var some_test = await some()
console.log(some_test)
</code>```

I know it works without await but I want to test await . Here it gives unexpected token error.

Why I am unable to use await here ?

答:
Async functions are supported in the latest versions of Chrome and FF already, and according to caniuse, in the upcoming Edge 15. The await keyword can only be used inside a function marked with async. A couple of good tutorials on the subject:

Async Function Documentation from Mozilla

Introduction to Async Functions

Body:
Lets say I have a functin like:

function some(){
    console.log("wow")
    return "some"
}

var some_test = await some()
console.log(some_test)

I know it works without await but I want to test await . Here it gives unexpected token error.

Why I am unable to use await here ?


问:
Not receiving document _id as an argument in AutoForm method-update
I have an AutoForm with this options:

```<code>{{
    #autoForm
    collection=articulosColecction
    id="articulos_modificar"
    doc=articuloToModificar
    type="method-update"
    meteormethod="areas.update"
    singleMethodArgument=true // Recommended here
}}
</code>```

singleMethodArgument=true is Recommended here

And my method is this:

```<code>export const update = new ValidatedMethod({
    name: 'areas.update',
    validate: null,
    run(doc) {
    console.log(doc._id);
    Areas.update({ _id: doc._id }, doc.modifier)
  }
});
</code>```

The documentation says:

If you set singleMethodArgument=true as a form attribute, your method will be called with a single object argument with _id and modifier properties. You should do this if using the mdg:validated-method package.

But console.log(doc._id); is outputting undefined and I've tried `console.log(doc)' and it outputs only the modifier object.

What is going? Is it something wrong with my AutoForm?

答:
meteormethod argument should call a Meteor.Method.

you should have define:

```<code>Meteor.methods({
  areas.update(updateData){
    check(updateData._id, String);
    check(updateData.modifier, Object);
    //do other stuff here
  }
});
</code>```

inside the method you can use the data._id and modifier.

Body:
I have an AutoForm with this options:

{{
    #autoForm
    collection=articulosColecction
    id="articulos_modificar"
    doc=articuloToModificar
    type="method-update"
    meteormethod="areas.update"
    singleMethodArgument=true // Recommended here
}}

singleMethodArgument=true is Recommended here

And my method is this:

export const update = new ValidatedMethod({
    name: 'areas.update',
    validate: null,
    run(doc) {
    console.log(doc._id);
    Areas.update({ _id: doc._id }, doc.modifier)
  }
});

The documentation says:

If you set singleMethodArgument=true as a form attribute, your method will be called with a single object argument with _id and modifier properties. You should do this if using the mdg:validated-method package.

But console.log(doc._id); is outputting undefined and I've tried `console.log(doc)' and it outputs only the modifier object.

What is going? Is it something wrong with my AutoForm?

Body:
meteormethod argument should call a Meteor.Method.

you should have define:

Meteor.methods({
  areas.update(updateData){
    check(updateData._id, String);
    check(updateData.modifier, Object);
    //do other stuff here
  }
});

inside the method you can use the data._id and modifier.


问:
R - Trying to avoid a loop here
First post ever here, but I've been reading a lot so thanks!

I have a huge dataframes with many columns, but only 4 matter here:

```<code>dates/classes/names/grades.
</code>```

For each date, i have several classes (with students), each with several people (names - always the same people in their respective classes), each one having ONE grade per date.

On the first date, I retrieve the best student per class considering his grade, using max[].

However, for the next dates, I want to do the following:

If the previous best student is still in the top 3 of his class, then we consider him to still be the best one.

Else, we consider the new 1st student to be the best one.

Hence, every date depends on the previous one.

Is it possible to do this without a loop?

I can't find out how, as every iteration depends on the previous one.

This is my code below.
Apologies if it's not optimized!

Thanks a lot :)

```<code>for (i in (1:(length(horizon)-1))) #horizon is the vector of dates
{
    uni3 <- dataaf[dataaf[,1] == as.numeric(horizon[i]),]     #dataaf contains all the data, we only keep the date for the considered date i

    if (i == 1)                             #we take the best student per class
    {
        selecdate <- data.frame()                             #selecdate is the dataframe containing the best people for this date

        for (z in (1:15)    #15 classes
        {
            selecsec <- na.omit(uni3[uni3[,14] == z,])                 #classes are column 14
            ligneselec <- max(selecsec[,13])                          #grades are column 13
            selecsec <- data.frame(uni3[match(ligneselec,uni3[,13]),])
            selecdate <- rbind(selecdate,selecsec)
        }
    }
    else {              #we keep a student if he was in the previous top 3, else we take the best one
        selecdate <- data.frame()

        for (z in (1:15))
        {
            lastsec <- na.omit(lastdate[lastdate[,14] == z,])         #last results

            #retrieving the top 3 people this date
            selecsec <- na.omit(uni3[uni3[,14] == z,])
            newligneselec <- tail(sort(selecsec[,13]),3)
            selecsec <- data.frame(selecsec[rev(match(newligneselec,selecsec[,13])),])

            if((length(match(selecsec[,3],lastsec[,3])[!is.na(match(selecsec[,3],lastsec[,3]))]) == 0))
            {
                ligneselec <- max(selecsec[,13])
                selecsec <- data.frame(uni3[match(ligneselec,uni3[,13]),])
            }
            else
            {
                selecsec <- lastsec
            }

            selecdate <- rbind(selecdate,selecsec)
        }
    }

    lastdate <- selecdate #recording the last results
}
</code>```

EDIT : Here is an example.

In date 1, John and Audrey are both selected in class 1 and 2.

On date 2, John is still among the best 3, so he remains selected,
while Audrey is only 4th so Jim (ranked 1st for the date 2) replaces
her.

On date 3, John is still among the best 3, so he remains selected (no ties issues in the data I work on). Jim is now 4th, so Sandra takes his place.

structure(list(Dates = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("12/02", "13/02", "14/02"
), class = "factor"), Classes = c(1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2
), Names = structure(c(6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L,
6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L, 6L, 3L, 9L, 7L, 1L,
8L, 4L, 10L, 5L, 2L), .Label = c("Ashley", "Audrey", "Bob", "Denis",
"Jim", "John", "Kim", "Sandra", "Terry", "Tim"), class = "factor"),
    Grades = c(10, 5, 3, 2, 1, 3, 4, 5, 6, 7, 8, 2, 10, 9, 1,
    7, 5, 1, 8, 2, 5, 1, 4, 8, 8, 7, 6, 5, 4, 3)), .Names = c("Dates",
"Classes", "Names", "Grades"), row.names = c(NA, -30L), class = "data.frame")

答:
Edited to reflect clarified request in the comments.

```<code>###---------- CREATING THE DATA (may be different from what you had in mind)
# Classes and Students
Classes <- c("U.S. History", "English", "NonLinear Optimization")
Students <- c("James", "Jamie", "John", "Jim", "Jane", "Jordan", "Jose")
df.1 <- expand.grid(Classes = Classes, Students = Students, stringsAsFactors = T)
# Generate Dates
Dates.seq <- seq(as.Date("2017/2/10"), as.Date("2017/3/27"), "days")
df.2 <- merge(Dates.seq, df.1)
# Generate Grades
grading <- c(4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7)
Grades <- sample(grading, size = dim(df.2)[1], replace = T, prob = grading/sum(grading)) # smart students
df <- data.frame(df.2, Grades)
colnames(df) <- c("Dates","Classes","Students","Grades")

# Works assuming your df has the following labeled and formatted columns
str(df)
#'data.frame':  966 obs. of  4 variables:
#  $ Dates   : Date, format: "2017-02-10" "2017-02-11" "2017-02-12" ...
#  $ Classes : Factor w/ 3 levels "U.S. History",..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ Students: Factor w/ 7 levels "James","Jamie",..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ Grades  : num  2.3 3.3 2.3 3.3 2.7 4 4 1.7 2.3 4 ...

# No aggregateion, just splitting by classes
df.split1 <- split(df, df[,"Classes"])
# Then splitting each of those lists by Dates
df.split2 <- lapply(df.split1, function(x) split(x, x[,"Dates"]))
# double the lapply becuase now we have lists within lists
top1 <- lapply(df.split2, function(i) lapply(i, function(j) j[order(-j[,"Grades"])[1], "Students"]))
top3 <- lapply(df.split2, function(i) lapply(i, function(j) j[order(-j[,"Grades"])[1:3], "Students"]))

# Easier to read
AllClasses <- levels(df[,"Classes"])
AllDates <- unique(df[,"Dates"])

# Initialize a matrix to keep track of changes in the Top1 and Top3
superstar <- matrix(NA, nrow = length(AllDates), ncol = length(AllClasses),
                    dimnames = list(as.character(AllDates), AllClasses))

# Looping
for(date in 1:length(AllDates)){
  for(class in AllClasses){
    if(date == 1){
      # First NewTop1 = First Top1
      superstar[date, class] <- unlist(top1[[class]][date])
    } else {
      # If superstar in date-1 is in the Top3 of date now,
      if(superstar[date-1, class] %in% as.numeric(unlist(top3[[class]][date]))){
        # still superstar
        superstar[date,class] <- superstar[date-1, class]
      } else{
        # new superstar is highest scorer of date now
        superstar[date,class] <- unlist(top1[[class]][date])
      }
    }
  }
}
# painful for me trying to figure out how to convert superstar numbers to names but this worked
superstar.char <- as.data.frame(matrix(levels(df[,"Students"])[superstar], ncol = length(AllClasses)))
dimnames(superstar.char) <- dimnames(superstar)
superstar.char # superstar with Students as characters
</code>```

Let me know if you have any difficulties!

Title: R - Trying to avoid a loop here

Body:
First post ever here, but I've been reading a lot so thanks!

I have a huge dataframes with many columns, but only 4 matter here:

dates/classes/names/grades.

For each date, i have several classes (with students), each with several people (names - always the same people in their respective classes), each one having ONE grade per date.

On the first date, I retrieve the best student per class considering his grade, using max[].

However, for the next dates, I want to do the following:

If the previous best student is still in the top 3 of his class, then we consider him to still be the best one.

Else, we consider the new 1st student to be the best one.

Hence, every date depends on the previous one.

Is it possible to do this without a loop?

I can't find out how, as every iteration depends on the previous one.

This is my code below.
Apologies if it's not optimized!

Thanks a lot :)

for (i in (1:(length(horizon)-1))) #horizon is the vector of dates
{
    uni3 <- dataaf[dataaf[,1] == as.numeric(horizon[i]),]     #dataaf contains all the data, we only keep the date for the considered date i

    if (i == 1)                             #we take the best student per class
    {
        selecdate <- data.frame()                             #selecdate is the dataframe containing the best people for this date

        for (z in (1:15)    #15 classes
        {
            selecsec <- na.omit(uni3[uni3[,14] == z,])                 #classes are column 14
            ligneselec <- max(selecsec[,13])                          #grades are column 13
            selecsec <- data.frame(uni3[match(ligneselec,uni3[,13]),])
            selecdate <- rbind(selecdate,selecsec)
        }
    }
    else {              #we keep a student if he was in the previous top 3, else we take the best one
        selecdate <- data.frame()

        for (z in (1:15))
        {
            lastsec <- na.omit(lastdate[lastdate[,14] == z,])         #last results

            #retrieving the top 3 people this date
            selecsec <- na.omit(uni3[uni3[,14] == z,])
            newligneselec <- tail(sort(selecsec[,13]),3)
            selecsec <- data.frame(selecsec[rev(match(newligneselec,selecsec[,13])),])

            if((length(match(selecsec[,3],lastsec[,3])[!is.na(match(selecsec[,3],lastsec[,3]))]) == 0))
            {
                ligneselec <- max(selecsec[,13])
                selecsec <- data.frame(uni3[match(ligneselec,uni3[,13]),])
            }
            else
            {
                selecsec <- lastsec
            }

            selecdate <- rbind(selecdate,selecsec)
        }
    }

    lastdate <- selecdate #recording the last results
}

EDIT : Here is an example.

In date 1, John and Audrey are both selected in class 1 and 2.

On date 2, John is still among the best 3, so he remains selected,
while Audrey is only 4th so Jim (ranked 1st for the date 2) replaces
her.

On date 3, John is still among the best 3, so he remains selected (no ties issues in the data I work on). Jim is now 4th, so Sandra takes his place.

structure(list(Dates = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("12/02", "13/02", "14/02"
), class = "factor"), Classes = c(1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2
), Names = structure(c(6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L,
6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L, 6L, 3L, 9L, 7L, 1L,
8L, 4L, 10L, 5L, 2L), .Label = c("Ashley", "Audrey", "Bob", "Denis",
"Jim", "John", "Kim", "Sandra", "Terry", "Tim"), class = "factor"),
    Grades = c(10, 5, 3, 2, 1, 3, 4, 5, 6, 7, 8, 2, 10, 9, 1,
    7, 5, 1, 8, 2, 5, 1, 4, 8, 8, 7, 6, 5, 4, 3)), .Names = c("Dates",
"Classes", "Names", "Grades"), row.names = c(NA, -30L), class = "data.frame")

Body:
Edited to reflect clarified request in the comments.

###---------- CREATING THE DATA (may be different from what you had in mind)
# Classes and Students
Classes <- c("U.S. History", "English", "NonLinear Optimization")
Students <- c("James", "Jamie", "John", "Jim", "Jane", "Jordan", "Jose")
df.1 <- expand.grid(Classes = Classes, Students = Students, stringsAsFactors = T)
# Generate Dates
Dates.seq <- seq(as.Date("2017/2/10"), as.Date("2017/3/27"), "days")
df.2 <- merge(Dates.seq, df.1)
# Generate Grades
grading <- c(4.0, 3.7, 3.3, 3.0, 2.7, 2.3, 2.0, 1.7)
Grades <- sample(grading, size = dim(df.2)[1], replace = T, prob = grading/sum(grading)) # smart students
df <- data.frame(df.2, Grades)
colnames(df) <- c("Dates","Classes","Students","Grades")

# Works assuming your df has the following labeled and formatted columns
str(df)
#'data.frame':  966 obs. of  4 variables:
#  $ Dates   : Date, format: "2017-02-10" "2017-02-11" "2017-02-12" ...
#  $ Classes : Factor w/ 3 levels "U.S. History",..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ Students: Factor w/ 7 levels "James","Jamie",..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ Grades  : num  2.3 3.3 2.3 3.3 2.7 4 4 1.7 2.3 4 ...

# No aggregateion, just splitting by classes
df.split1 <- split(df, df[,"Classes"])
# Then splitting each of those lists by Dates
df.split2 <- lapply(df.split1, function(x) split(x, x[,"Dates"]))
# double the lapply becuase now we have lists within lists
top1 <- lapply(df.split2, function(i) lapply(i, function(j) j[order(-j[,"Grades"])[1], "Students"]))
top3 <- lapply(df.split2, function(i) lapply(i, function(j) j[order(-j[,"Grades"])[1:3], "Students"]))

# Easier to read
AllClasses <- levels(df[,"Classes"])
AllDates <- unique(df[,"Dates"])

# Initialize a matrix to keep track of changes in the Top1 and Top3
superstar <- matrix(NA, nrow = length(AllDates), ncol = length(AllClasses),
                    dimnames = list(as.character(AllDates), AllClasses))

# Looping
for(date in 1:length(AllDates)){
  for(class in AllClasses){
    if(date == 1){
      # First NewTop1 = First Top1
      superstar[date, class] <- unlist(top1[[class]][date])
    } else {
      # If superstar in date-1 is in the Top3 of date now,
      if(superstar[date-1, class] %in% as.numeric(unlist(top3[[class]][date]))){
        # still superstar
        superstar[date,class] <- superstar[date-1, class]
      } else{
        # new superstar is highest scorer of date now
        superstar[date,class] <- unlist(top1[[class]][date])
      }
    }
  }
}
# painful for me trying to figure out how to convert superstar numbers to names but this worked
superstar.char <- as.data.frame(matrix(levels(df[,"Students"])[superstar], ncol = length(AllClasses)))
dimnames(superstar.char) <- dimnames(superstar)
superstar.char # superstar with Students as characters

Let me know if you have any difficulties!


问:
C++ String-type independent algorithms
I'm trying to derive a technique for writing string-algorithms that is truly independent of the underlying type of string.

Background: the prototypes for GetIndexOf and FindOneOf are either overloaded or templated variations on:

```<code>int GetIndexOf(const char * pszInner, const char * pszString);
const char * FindOneOf(const char * pszString, const char * pszSetOfChars);
</code>```

This issue comes up in the following template function:

```<code>// return index of, or -1, the first occurrence of any given char in target
template <typename T>
inline int FindIndexOfOneOf(const T * str, const T * pszSearchChars)
{
    return GetIndexOf(FindOneOf(str, pszSearchChars), str);
}
</code>```

Objectives:

 1. I would like this code to work for CStringT<>, const char *, const wchar_t * (and should be trivial to extend to std::string)

 2. I don't want to pass anything by copy (only by const & or const *)

In an attempt to solve these two objectives, I thought I might be able to use a type-selector of sorts to derive the correct interfaces on the fly:

```<code>namespace details {

    template <typename T>
    struct char_type_of
    {
        // typedef T type; error for invalid types (i.e. anything for which there is not a specialization)
    };

    template <>
    struct char_type_of<const char *>
    {
        typedef char type;
    };

    template <>
    struct char_type_of<const wchar_t *>
    {
        typedef wchar_t type;
    };

    template <>
    struct char_type_of<CStringA>
    {
        typedef CStringA::XCHAR type;
    };

    template <>
    struct char_type_of<CStringW>
    {
        typedef CStringW::XCHAR type;
    };

}

#define CHARTYPEOF(T) typename details::char_type_of<T>::type
</code>```

Which allows:

```<code>template <typename T>
inline int FindIndexOfOneOf(T str, const CHARTYPEOF(T) * pszSearchChars)
{
    return GetIndexOf(FindOneOf(str, pszSearchChars), str);
}
</code>```

This should guarantee that the second argument is passed as const  *, and should not determine T (rather only the first argument should determine T).

But the problem with this approach is that T, when str is a CStringT<>, is a copy of the CStringT<> rather than a reference to it: hence we have an unnecessary copy.

Trying to rewrite the above as:

```<code>template <typename T>
inline int FindIndexOfOneOf(T & str, const CHARTYPEOF(T) * pszSearchChars)
{
    return GetIndexOf(FindOneOf(str, pszSearchChars), str);
}
</code>```

Makes it impossible for the compiler (VS2008) to generate a correct instance of FindIndexOfOneOf<> for:

```<code>FindIndexOfOneOf(_T("abc"), _T("def"));
    error C2893: Failed to specialize function template 'int FindIndexOfOneOf(T &,const details::char_type_of<T>::type *)'
    With the following template arguments: 'const char [4]'
</code>```

This is a generic problem I've had with templates since they were introduced (yes, I'm that old): That it's been essentially impossible to construct a way to handle both old C-style arrays and newer class based entities (perhaps best highlighted by const char [4] vs. CString<> &).

The STL/std library "solved" this issue (if one can really call it solving) by instead using pairs of iterators everywhere instead of a reference to the thing itself.  I could go this route, except it sucks IMO, and I don't want to have to litter my code with two-arguments everywhere a single argument properly handled should have been.

Basically, I'm interested in an approach - such as using some sort of stringy_traits - that would allow me to write GetIndexOfOneOf<> (and other similar template functions) where the argument is the string (not a pair of (being, end] arguments), and the template that is then generated be correct based on that string-argument-type (either const  * or const CString<> &).

So the Question: How might I write FindIndexOfOneOf<> such that its arguments can be any of the following without ever creating a copy of the underlying arguments:

 1. FindIndexOfOneOf(_T("abc"), _T("def"));

 2. CString str; FindIndexOfOneOf(str, _T("def"));

 3. CString str; FindIndexOfOneOf(T("abc"), str);

 3. CString str; FindIndexOfOneOf(str, str);

Related threads to this one that have lead me to this point:

A better way to declare a char-type appropriate CString<>

  Templated string literals

答:
Alternative to my previous answer, if you don't want to install tr1.

Add the following template specializations to cover the deduced T type when the first argument is a reference.

```<code>template<unsigned int N>
struct char_type_of<const wchar_t[N]>
{
    typedef wchar_t type;
};

template<unsigned int N>
struct char_type_of<const char[N]>
{
    typedef char type;
};
</code>```

Title: C++ String-type independent algorithms

Body:
I'm trying to derive a technique for writing string-algorithms that is truly independent of the underlying type of string.

Background: the prototypes for GetIndexOf and FindOneOf are either overloaded or templated variations on:

int GetIndexOf(const char * pszInner, const char * pszString);
const char * FindOneOf(const char * pszString, const char * pszSetOfChars);

This issue comes up in the following template function:

// return index of, or -1, the first occurrence of any given char in target
template <typename T>
inline int FindIndexOfOneOf(const T * str, const T * pszSearchChars)
{
    return GetIndexOf(FindOneOf(str, pszSearchChars), str);
}

Objectives:

 1. I would like this code to work for CStringT<>, const char *, const wchar_t * (and should be trivial to extend to std::string)

 2. I don't want to pass anything by copy (only by const & or const *)

In an attempt to solve these two objectives, I thought I might be able to use a type-selector of sorts to derive the correct interfaces on the fly:

namespace details {

    template <typename T>
    struct char_type_of
    {
        // typedef T type; error for invalid types (i.e. anything for which there is not a specialization)
    };

    template <>
    struct char_type_of<const char *>
    {
        typedef char type;
    };

    template <>
    struct char_type_of<const wchar_t *>
    {
        typedef wchar_t type;
    };

    template <>
    struct char_type_of<CStringA>
    {
        typedef CStringA::XCHAR type;
    };

    template <>
    struct char_type_of<CStringW>
    {
        typedef CStringW::XCHAR type;
    };

}

#define CHARTYPEOF(T) typename details::char_type_of<T>::type

Which allows:

template <typename T>
inline int FindIndexOfOneOf(T str, const CHARTYPEOF(T) * pszSearchChars)
{
    return GetIndexOf(FindOneOf(str, pszSearchChars), str);
}

This should guarantee that the second argument is passed as const  *, and should not determine T (rather only the first argument should determine T).

But the problem with this approach is that T, when str is a CStringT<>, is a copy of the CStringT<> rather than a reference to it: hence we have an unnecessary copy.

Trying to rewrite the above as:

template <typename T>
inline int FindIndexOfOneOf(T & str, const CHARTYPEOF(T) * pszSearchChars)
{
    return GetIndexOf(FindOneOf(str, pszSearchChars), str);
}

Makes it impossible for the compiler (VS2008) to generate a correct instance of FindIndexOfOneOf<> for:

FindIndexOfOneOf(_T("abc"), _T("def"));
    error C2893: Failed to specialize function template 'int FindIndexOfOneOf(T &,const details::char_type_of<T>::type *)'
    With the following template arguments: 'const char [4]'

This is a generic problem I've had with templates since they were introduced (yes, I'm that old): That it's been essentially impossible to construct a way to handle both old C-style arrays and newer class based entities (perhaps best highlighted by const char [4] vs. CString<> &).

The STL/std library "solved" this issue (if one can really call it solving) by instead using pairs of iterators everywhere instead of a reference to the thing itself.  I could go this route, except it sucks IMO, and I don't want to have to litter my code with two-arguments everywhere a single argument properly handled should have been.

Basically, I'm interested in an approach - such as using some sort of stringy_traits - that would allow me to write GetIndexOfOneOf<> (and other similar template functions) where the argument is the string (not a pair of (being, end] arguments), and the template that is then generated be correct based on that string-argument-type (either const  * or const CString<> &).

So the Question: How might I write FindIndexOfOneOf<> such that its arguments can be any of the following without ever creating a copy of the underlying arguments:

 1. FindIndexOfOneOf(_T("abc"), _T("def"));

 2. CString str; FindIndexOfOneOf(str, _T("def"));

 3. CString str; FindIndexOfOneOf(T("abc"), str);

 3. CString str; FindIndexOfOneOf(str, str);

Related threads to this one that have lead me to this point:

A better way to declare a char-type appropriate CString<>

  Templated string literals

Body:
Alternative to my previous answer, if you don't want to install tr1.

Add the following template specializations to cover the deduced T type when the first argument is a reference.

template<unsigned int N>
struct char_type_of<const wchar_t[N]>
{
    typedef wchar_t type;
};

template<unsigned int N>
struct char_type_of<const char[N]>
{
    typedef char type;
};


问:
Proper Git merging as is relates to repo history
Here is the scenario:

I have one branch named 'develop'. I branch off from this branch, the new branch is 'foo2'. After 3 commits on foo2, I then checkout develop branch and merge the changes on foo2 into develop:

git merge foo2

I then run:

git log --graph

I do not see foo2 in the graph. Did I do something incorrect with merging? Or is it something else entirely?

The branch foo2 still exists

答: You won't see any reference to foo2. Only the commits that were merged into develop from foo2. </p>


问:
Sorting score - lowest first
I have a script here and it is showing the users first with the highest score. How can I make it to show 1st the users with lower scores. Because I have a timestamp made in storyline and the faster they crack the code (it's a game) the better they are. Here is the code:

I'm not a JS expert and I'm here to learn more about this while asking.

```<code>// Usage
//  1. Save your GAS Project
//
//  2. Click: Run > setup
//
//  3. Click: Publish > Deploy as web app
//    - enter Project Version Description (optional)
//    - set security level and enable service ( execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and paste it into the Leaderboard JavaScript file (first line)
//

/*
** Do Not Edit Below This Line **
*/

// Create a new property service to maintain variables accross instances.
var SCRIPT_PROP = PropertiesService.getScriptProperties();

// What to do when a when we recieve an HTTP GET request
function doGet(e) {
    // For this simple app we only need to do one thing.
    return addUser(e.parameter['id'], e.parameter['score'])
}

// Add our user record and return the list of top ten.
function addUser(id, score) {
    //Open the spreadsheet we set up by it's ID
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    //Get the first sheet
    var sheet = doc.getSheets()[0];
    // we want a public lock, one that locks for all invocations
    var lock = LockService.getPublicLock();
    lock.waitLock(30000); // wait 30 seconds before conceding defeat.
    //wrap everything in a try/catch to handle errors
    try {
        var timeNow = new Date() //create a timestamp
        var nextRow = sheet.getLastRow() + 1; // get next empty row
        //create an array of data to put into the row
        var row = [
            [id, score, timeNow]
        ];
        //put the data into the row
        sheet.getRange(nextRow, 1, 1, 3).setValues(row);
        //sort the sheet with our custom function
        sortByScore(sheet)
        // get the top ten with our custom function
        var top10 = getTop10(sheet)
        // get this user's rank from our custom function
        var userRank = findUserRank(id, score, timeNow, sheet);
        //retun a JSON with the top ten and our user
        return ContentService.createTextOutput(JSON.stringify({
            "result": "success",
            "users": top10,
            "user": userRank
        })).setMimeType(ContentService.MimeType.JSON);
    } catch (e) {//something went wrong. Return an error
        return ContentService.createTextOutput(JSON.stringify({
            "result": "error",
            "error": e
        })).setMimeType(ContentService.MimeType.JSON);
    } finally { //release lock
        lock.releaseLock();
    }
}

//sort the sheet by column two (score)
function sortByScore(sheet) {
    //find the last row with data
    var lastRow = sheet.getLastRow()
    // get the range of data
    var range = sheet.getRange(2, 1, lastRow, 3)
    //sort by score
    range.sort({
        column: 2,
        ascending: false
    });
}

// gets the top ten users
function getTop10(sheet) {
    //get the first ten rows
    var range = sheet.getRange(2, 1, 10, 3)
    var users = range.getValues()
    var top10 = []; //we'll store those ten users in this array
    //loop thru all ten and create a user object for each
    for (row = 0, len = users.length; row < len; row++) {
        if (users[row][0] != '') {//if the row is not empty
            var user = {}; //our user object
            //add data for each user
            user.id = users[row][0]
            user.score = +users[row][1]
            user.date = +users[row][2]
            //push this user into the array of users
            top10.push(user)
        }
    }
    //return the top ten
    return top10
}

//find this users rank. In case they have multiple records we use the timestamp to get this record.
function findUserRank(id, score, timeNow, sheet) {
    //find the last row with data
    var lastRow = sheet.getLastRow()
    //get the data from the range
    var range = sheet.getRange(2, 1, lastRow, 3)
    var users = range.getValues()
    var user = {}; //create a user object
    //loop thru all rows to find our user
    for (row = 0, len = users.length; row < len; row++) {
        //if this row is our user
        if (users[row][0] == id && users[row][1] == score && users[row][2] == timeNow.toString()) {
            //add data to the user object
            user.id = users[row][0]
            user.score = +users[row][1]
            user.date = +users[row][2]
            //add the users rank (what row were they?)
            user.rank = row + 1
            break //exit our loop
        }
    }
    //return this user's data
    return user
}

//Setup our spreadsheet
function setup() {
    //get the spreadsheet
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    //save the spreadsheet's id for later
    SCRIPT_PROP.setProperty("key", doc.getId());
    //get the first sheet
    var sheet = doc.getSheets()[0];
    //create an array of labels
    var row = [
        ["ID", "score", "Timestamp"]
    ];
    //set the first row of the sheet to our labels
    sheet.getRange(1, 1, 1, 3).setValues(row);
}
</code>```

Thanks in advance.

答:
Change the ascending property to true.

```<code>function sortByScore(sheet) {
//find the last row with data
var lastRow = sheet.getLastRow()
// get the range of data
var range = sheet.getRange(2, 1, lastRow, 3)
//sort by score
range.sort({
    column: 2,
    ascending: true
});
}
</code>```

Title: Sorting score - lowest first

Body:
I have a script here and it is showing the users first with the highest score. How can I make it to show 1st the users with lower scores. Because I have a timestamp made in storyline and the faster they crack the code (it's a game) the better they are. Here is the code:

I'm not a JS expert and I'm here to learn more about this while asking.

// Usage
//  1. Save your GAS Project
//
//  2. Click: Run > setup
//
//  3. Click: Publish > Deploy as web app
//    - enter Project Version Description (optional)
//    - set security level and enable service ( execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and paste it into the Leaderboard JavaScript file (first line)
//

/*
** Do Not Edit Below This Line **
*/

// Create a new property service to maintain variables accross instances.
var SCRIPT_PROP = PropertiesService.getScriptProperties();

// What to do when a when we recieve an HTTP GET request
function doGet(e) {
    // For this simple app we only need to do one thing.
    return addUser(e.parameter['id'], e.parameter['score'])
}

// Add our user record and return the list of top ten.
function addUser(id, score) {
    //Open the spreadsheet we set up by it's ID
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    //Get the first sheet
    var sheet = doc.getSheets()[0];
    // we want a public lock, one that locks for all invocations
    var lock = LockService.getPublicLock();
    lock.waitLock(30000); // wait 30 seconds before conceding defeat.
    //wrap everything in a try/catch to handle errors
    try {
        var timeNow = new Date() //create a timestamp
        var nextRow = sheet.getLastRow() + 1; // get next empty row
        //create an array of data to put into the row
        var row = [
            [id, score, timeNow]
        ];
        //put the data into the row
        sheet.getRange(nextRow, 1, 1, 3).setValues(row);
        //sort the sheet with our custom function
        sortByScore(sheet)
        // get the top ten with our custom function
        var top10 = getTop10(sheet)
        // get this user's rank from our custom function
        var userRank = findUserRank(id, score, timeNow, sheet);
        //retun a JSON with the top ten and our user
        return ContentService.createTextOutput(JSON.stringify({
            "result": "success",
            "users": top10,
            "user": userRank
        })).setMimeType(ContentService.MimeType.JSON);
    } catch (e) {//something went wrong. Return an error
        return ContentService.createTextOutput(JSON.stringify({
            "result": "error",
            "error": e
        })).setMimeType(ContentService.MimeType.JSON);
    } finally { //release lock
        lock.releaseLock();
    }
}

//sort the sheet by column two (score)
function sortByScore(sheet) {
    //find the last row with data
    var lastRow = sheet.getLastRow()
    // get the range of data
    var range = sheet.getRange(2, 1, lastRow, 3)
    //sort by score
    range.sort({
        column: 2,
        ascending: false
    });
}

// gets the top ten users
function getTop10(sheet) {
    //get the first ten rows
    var range = sheet.getRange(2, 1, 10, 3)
    var users = range.getValues()
    var top10 = []; //we'll store those ten users in this array
    //loop thru all ten and create a user object for each
    for (row = 0, len = users.length; row < len; row++) {
        if (users[row][0] != '') {//if the row is not empty
            var user = {}; //our user object
            //add data for each user
            user.id = users[row][0]
            user.score = +users[row][1]
            user.date = +users[row][2]
            //push this user into the array of users
            top10.push(user)
        }
    }
    //return the top ten
    return top10
}

//find this users rank. In case they have multiple records we use the timestamp to get this record.
function findUserRank(id, score, timeNow, sheet) {
    //find the last row with data
    var lastRow = sheet.getLastRow()
    //get the data from the range
    var range = sheet.getRange(2, 1, lastRow, 3)
    var users = range.getValues()
    var user = {}; //create a user object
    //loop thru all rows to find our user
    for (row = 0, len = users.length; row < len; row++) {
        //if this row is our user
        if (users[row][0] == id && users[row][1] == score && users[row][2] == timeNow.toString()) {
            //add data to the user object
            user.id = users[row][0]
            user.score = +users[row][1]
            user.date = +users[row][2]
            //add the users rank (what row were they?)
            user.rank = row + 1
            break //exit our loop
        }
    }
    //return this user's data
    return user
}

//Setup our spreadsheet
function setup() {
    //get the spreadsheet
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    //save the spreadsheet's id for later
    SCRIPT_PROP.setProperty("key", doc.getId());
    //get the first sheet
    var sheet = doc.getSheets()[0];
    //create an array of labels
    var row = [
        ["ID", "score", "Timestamp"]
    ];
    //set the first row of the sheet to our labels
    sheet.getRange(1, 1, 1, 3).setValues(row);
}

Thanks in advance.

Body:
Change the ascending property to true.

function sortByScore(sheet) {
//find the last row with data
var lastRow = sheet.getLastRow()
// get the range of data
var range = sheet.getRange(2, 1, lastRow, 3)
//sort by score
range.sort({
    column: 2,
    ascending: true
});
}


问:
need a MYSQL query
I am new to mysql,
I have a table grand_score_master its data is shown in this image

I need a query such that, I will pass a user_id say CBS_00002 and it will return me the rows where the grand_level is highest for different packages.

e.g.

Please help me with this.

答:
Your current query is missing two things.  First, you should be using GROUP BY, because you want to find the maximum grand level for each package group, not from the entire table.  Second, you should use a subquery to find the maximum levels, and then use this to restrict the records which you want appearing in your result set.

```<code>SELECT t1.*
FROM grand_score_master t1
INNER JOIN
(
    SELECT package_id, MAX(grand_level) AS max_grand_level
    FROM grand_score_master
    GROUP BY package_id
) t2
    ON t1.package_id  = t2.package_id AND
       t1.grand_level = t2.max_grand_level
</code>```

Title: need a MYSQL query

Body:
Your current query is missing two things.  First, you should be using GROUP BY, because you want to find the maximum grand level for each package group, not from the entire table.  Second, you should use a subquery to find the maximum levels, and then use this to restrict the records which you want appearing in your result set.

SELECT t1.*
FROM grand_score_master t1
INNER JOIN
(
    SELECT package_id, MAX(grand_level) AS max_grand_level
    FROM grand_score_master
    GROUP BY package_id
) t2
    ON t1.package_id  = t2.package_id AND
       t1.grand_level = t2.max_grand_level


问:
Find matching entries in list which are different
I have two lists. The first one contains entries like

RB Leipzig vs SV Darmstadt 98

Hertha Berlin vs Hoffenheim

..

and in the second contains basically the same entries but could but written in different forms. For example:

Hertha BSC vs TSG Hoffenheim

RB Leipzig vs Darmstadt 98

..

and so on. Both lists represent the same sport games but they can use alternate team names and don't appear in the same order.

My goal (hehe pun) is to unify both lists to one and match the same entries and discard entries which don't appear in both lists.

I already tried to use Levensthein distance and fuzzy search.
I thought about using machine learning but have no idea how to start with that.

Would appriciate any help and ideas!

答:
You can use a BK-tree (I googled C# implementations and found two: 1, 2).  Use the Levenshtein distance as the metric.  Optionally, delete the all-uppercase substrings from the names in the lists in order to improve the metric (just be careful that this doesn't accidentally leave you with empty strings for names).

```<code>1. Put the names from the first list in the BK-tree
2. Look up the names from the second list in the BK-tree
  a. Assign an integer token to the name pair, stored in a Map<Integer, Tuple<String, String>>
  b. Replace each team name with the token
3. Sort each token pair (so [8 vs 4] becomes [4 vs 8])
4. Sort each list by its first token in the token pair,
   then by the second token in the token pair (so the list
   would look like [[1 vs 2], [1 vs 4], [2 vs 4]])
</code>```

Now you just iterate through the two lists

```<code>int i1 = 0
int i2 = 0
while(i1 < list1.length && i2 < list2.length) {
  if(list1[i1].first == list2[i2].first && list1[i1].second == list2[i2].second) {
    // match
    i1++
    i2++
  } else if(list1[i1].first < list2[i2].first) {
    i1++
  } else if(list1[i1].first > list2[i2].first) {
    i2++
  } else if(list1[i1].second < list2[i2].second {
    i1++
  } else {
    i2++
  }
}
</code>```

Body:
You can use a BK-tree (I googled C# implementations and found two: 1, 2).  Use the Levenshtein distance as the metric.  Optionally, delete the all-uppercase substrings from the names in the lists in order to improve the metric (just be careful that this doesn't accidentally leave you with empty strings for names).

1. Put the names from the first list in the BK-tree
2. Look up the names from the second list in the BK-tree
  a. Assign an integer token to the name pair, stored in a Map<Integer, Tuple<String, String>>
  b. Replace each team name with the token
3. Sort each token pair (so [8 vs 4] becomes [4 vs 8])
4. Sort each list by its first token in the token pair,
   then by the second token in the token pair (so the list
   would look like [[1 vs 2], [1 vs 4], [2 vs 4]])

Now you just iterate through the two lists

int i1 = 0
int i2 = 0
while(i1 < list1.length && i2 < list2.length) {
  if(list1[i1].first == list2[i2].first && list1[i1].second == list2[i2].second) {
    // match
    i1++
    i2++
  } else if(list1[i1].first < list2[i2].first) {
    i1++
  } else if(list1[i1].first > list2[i2].first) {
    i2++
  } else if(list1[i1].second < list2[i2].second {
    i1++
  } else {
    i2++
  }
}


问:
Separation between Header and first cell -- In plain UITableView
I have a table with with Plain style and only one section. I have a implemented viewForHeaderInSection: to add a custom view in the section header.

I am  not able to see a separation line between my table section header view and my first
cell.  [See the attached image]

What am I doing wrong?

答: Custom headers and footers do not contain separators below/above them. You'll need to implement the separator yourself in the custom view (or switch to grouped style, which will show the outline of the group above and below it even with a custom header/footer).</p>


问:
Finding occurrences of a word in a string in python 3
I'm trying to find the number of occurrences of a word in a string.

```<code>word = "dog"
str1 = "the dogs barked"
</code>```

I used the following to count the occurrences:

```<code>count = str1.count(word)
</code>```

The issue is I want an exact match. So the count for this sentence would be 0.
Is that possible?

答:
Let us consider the example s = "suvotisuvojitsuvo".
If you want to count no of distinct count "suvo" and "suvojit" then you use the count() method... count distinct i.e) you don't count the suvojit to suvo.. only count the lonely "suvo".

```<code>suvocount = s.count("suvo") // #output: 3
suvojitcount = s.count("suvojit") //# output : 1
</code>```

Then find the lonely suvo count you have to negate from the suvojit count.

```<code>lonelysuvo = suvocount - suvojicount //# output: 3-1 -> 2
</code>```

Body:
I'm trying to find the number of occurrences of a word in a string.

word = "dog"
str1 = "the dogs barked"

I used the following to count the occurrences:

count = str1.count(word)

The issue is I want an exact match. So the count for this sentence would be 0.
Is that possible?

Body:
Let us consider the example s = "suvotisuvojitsuvo".
If you want to count no of distinct count "suvo" and "suvojit" then you use the count() method... count distinct i.e) you don't count the suvojit to suvo.. only count the lonely "suvo".

suvocount = s.count("suvo") // #output: 3
suvojitcount = s.count("suvojit") //# output : 1

Then find the lonely suvo count you have to negate from the suvojit count.

lonelysuvo = suvocount - suvojicount //# output: 3-1 -> 2


问:
Google VR + Unity = tracking stuttering / jittering / choppy
Launching GVRDemo scene using Unity5.4.2f2-GVR13 installation package I'm experiencing unsteady tracking on my Samsung Galaxy S7. As you can see on an attached video it's not caused by low frame rate nor any of my code since the only thing I've changed in the scene is switching the cubeRoom object with a textured sphere object which better visualises the issue:

https://youtu.be/_NRQNbtdpuI

It doesn't matter if I change the quality setting from Fantastic to Fastest.

As you can see the frame rate doesn't drop around the stuttering moments, so it's not about the CPU/GPU performance

As I test the Google Street View app for example, there's no such issue – is it because it's been written natively for Android?
On the other hand I've noticed games like VR Fantasy with tracking system  behaving differently – more smoothly due to the delay in the reaction time regarding the device's movement (looks nice, but causes nausea after 5 seconds). This makes me believe there is an issue with Google VR tracking.

Is anyone experiencing the same thing? What might be the reason for it?

答:
I'm using Unity5.4.2f2-GVR13 too, and I think it's just random.

Charging up your phone and controller, and rebooting the phone seems to help a lot.


问:
how to make runnable instance to wait in one thread and notify by some othrer threads?
in the below code, one runnable instance is waiting to get notify. how to  notify this thread by some other thread should i use method or one more class which contains thread to notify.. i am stuck here please help...</p>

```<code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.cgi.sample.jms.requestor.RequestorApplication.Runner;

public class RequestorApplication {

    public static String correlationId;

    static ArrayList<Runner> list = new ArrayList<Runner>();

    static Map<Long, Runner> map = new HashMap<Long, Runner>();

    static Runner runner;

    public static void main(String args[]) throws Exception {

        RequestorApplication application = new RequestorApplication();

        application.waiter(map);

        System.out.println("All the threads are started");
    }

    public void waiter(Map<Long, Runner> map) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 2; i++) {

            Runner instance = new Runner();

            System.out.println("Executing thread " + " with " + Thread.currentThread().getName());

            long threadId = Thread.currentThread().getId();

            String threadname = Thread.currentThread().getName();

            executor.execute(instance);

            RequestorApplication.runner = instance;

            synchronized (RequestorApplication.runner) {

                map.put(threadId, RequestorApplication.runner);

                try {
                    RequestorApplication.runner.wait();
                    // notifier(map);
                    System.out.println(threadname + "  Thread entered into waiting state!!!");
                    // Thread.currentThread().wait();
                    System.out.println(threadname + "  Thread woke up from wait!!!!!");

                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }

    }

    public void notifier(Map<Long, Runner> map) {
        synchronized (RequestorApplication.runner) {

            for (Map.Entry<Long, Runner> entry : map.entrySet()) {

                System.out.println("stored threads in map are--->" + map.get(entry.getKey()));

                entry.getValue().notify();
            }

        }

    }

    class Runner implements Runnable {
        public void run() {
            System.out.println("runner invoked");

        }

    }

}
</code>```

答:
in the below code, one runnable instance is waiting to get notify...

You are using an ExecutorService thread-pool but completely missing one of the great features of it.  When you add a job to the thread-pool, use the submit(...) method which returns a Future object.  You then can call future.get() to wait for the job to complete and return a value.  You should never need to do your own waiting, etc..

```<code>Future<Void> future = executor.submit(instance);
// now we wait for the thread to complete
future.get();
</code>```

Also, although it works, it is considered very bad form to call Thread.wait() directly.  It happens that a notify() is called when the thread finishes but that is an implementation detail that should be relied on.  Either join with a Thread or use the Future.get() above.  Also, if the thread returned before you called wait() you might miss the notify() and your code would never return.

Lastly, as @vijayraj34 points out, your code is right now single threaded because you submit each job and then immediately wait for it.  What you should be doing is forking all of your threads and saving the Future objects in a collection.  Then once you are done starting the jobs you can wait for each Future in turn.

Something like:

```<code>List<Future<Void>> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
   Runner instance = new Runner();
   // save the futures for later
   futures.add(executor.submit(instance));
}
// after we submit all of our jobs we shutdown the thread-pool
executor.shutdown();
...
// now we go back and wait for all of the runners that have been working in the background
for (Future<Void> future : futures) {
   future.get();
}
</code>```

Body:
in the below code, one runnable instance is waiting to get notify. how to  notify this thread by some other thread should i use method or one more class which contains thread to notify.. i am stuck here please help...

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.cgi.sample.jms.requestor.RequestorApplication.Runner;

public class RequestorApplication {

    public static String correlationId;

    static ArrayList<Runner> list = new ArrayList<Runner>();

    static Map<Long, Runner> map = new HashMap<Long, Runner>();

    static Runner runner;

    public static void main(String args[]) throws Exception {

        RequestorApplication application = new RequestorApplication();

        application.waiter(map);

        System.out.println("All the threads are started");
    }

    public void waiter(Map<Long, Runner> map) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 2; i++) {

            Runner instance = new Runner();

            System.out.println("Executing thread " + " with " + Thread.currentThread().getName());

            long threadId = Thread.currentThread().getId();

            String threadname = Thread.currentThread().getName();

            executor.execute(instance);

            RequestorApplication.runner = instance;

            synchronized (RequestorApplication.runner) {

                map.put(threadId, RequestorApplication.runner);

                try {
                    RequestorApplication.runner.wait();
                    // notifier(map);
                    System.out.println(threadname + "  Thread entered into waiting state!!!");
                    // Thread.currentThread().wait();
                    System.out.println(threadname + "  Thread woke up from wait!!!!!");

                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }

    }

    public void notifier(Map<Long, Runner> map) {
        synchronized (RequestorApplication.runner) {

            for (Map.Entry<Long, Runner> entry : map.entrySet()) {

                System.out.println("stored threads in map are--->" + map.get(entry.getKey()));

                entry.getValue().notify();
            }

        }

    }

    class Runner implements Runnable {
        public void run() {
            System.out.println("runner invoked");

        }

    }

}

Body:
in the below code, one runnable instance is waiting to get notify...

You are using an ExecutorService thread-pool but completely missing one of the great features of it.  When you add a job to the thread-pool, use the submit(...) method which returns a Future object.  You then can call future.get() to wait for the job to complete and return a value.  You should never need to do your own waiting, etc..

Future<Void> future = executor.submit(instance);
// now we wait for the thread to complete
future.get();

Also, although it works, it is considered very bad form to call Thread.wait() directly.  It happens that a notify() is called when the thread finishes but that is an implementation detail that should be relied on.  Either join with a Thread or use the Future.get() above.  Also, if the thread returned before you called wait() you might miss the notify() and your code would never return.

Lastly, as @vijayraj34 points out, your code is right now single threaded because you submit each job and then immediately wait for it.  What you should be doing is forking all of your threads and saving the Future objects in a collection.  Then once you are done starting the jobs you can wait for each Future in turn.

Something like:

List<Future<Void>> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
   Runner instance = new Runner();
   // save the futures for later
   futures.add(executor.submit(instance));
}
// after we submit all of our jobs we shutdown the thread-pool
executor.shutdown();
...
// now we go back and wait for all of the runners that have been working in the background
for (Future<Void> future : futures) {
   future.get();
}