问:
Hide options with empty values using javascript
I used the php code to display list of countries in a select box. i used the following php code to display the selectbox with country options

```<code>$array = get_meta_values('post_location', 'project');

echo "<select name='post_location1' id='selection' class='chosen-container chosen-container-single chosen-with-drop chosen-container-active' style='height:30px;width:100%'>";

foreach($array  as $key => $item) {

if($item !== NULL){

echo "<option value='" . $item . "'>"  . $item . "<option>" ;

  }
}
</code>```

This php code created the markup like:

```<code><select name="post_location1" id="selection" class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="height:30px;width:100%">

<option value="Verdi">Verdi</option>

<option></option>

<option value="Brampton, on">Brampton, on</option>

<option></option>

<option value="Sagan Banquet Hall">Sagan Banquet Hall</option>

<option></option>

<option value="Toronto">Toronto</option>

<option></option>

<option value="The Manor by Peter and Paul">The Manor by Peter and Paul</option>

<option></option>

</select>
</code>```

I want to hide or remove the empty options by using javascript or jquery

答:
You are not closing <option> that is why two <option> elements are getting added every iteration: One with correct attributes and another empty.

Correct:

```<code>echo "<option value='" . $item . "'>"  . $item . "<option>" ;
</code>```

To:

```<code>echo "<option value='" . $item . "'>"  . $item . "</option>" ;
</code>```

Otherwise, code looks correct.

Body:
I used the php code to display list of countries in a select box. i used the following php code to display the selectbox with country options

$array = get_meta_values('post_location', 'project');

echo "<select name='post_location1' id='selection' class='chosen-container chosen-container-single chosen-with-drop chosen-container-active' style='height:30px;width:100%'>";

foreach($array  as $key => $item) {

if($item !== NULL){

echo "<option value='" . $item . "'>"  . $item . "<option>" ;

  }
}

This php code created the markup like:

<select name="post_location1" id="selection" class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="height:30px;width:100%">

<option value="Verdi">Verdi</option>

<option></option>

<option value="Brampton, on">Brampton, on</option>

<option></option>

<option value="Sagan Banquet Hall">Sagan Banquet Hall</option>

<option></option>

<option value="Toronto">Toronto</option>

<option></option>

<option value="The Manor by Peter and Paul">The Manor by Peter and Paul</option>

<option></option>

</select>

I want to hide or remove the empty options by using javascript or jquery

Body:
You are not closing <option> that is why two <option> elements are getting added every iteration: One with correct attributes and another empty.

Correct:

echo "<option value='" . $item . "'>"  . $item . "<option>" ;

To:

echo "<option value='" . $item . "'>"  . $item . "</option>" ;

Otherwise, code looks correct.


来源: stackexchange

问:
Calling two functions that use different database using sqlite3 in C
I'm developing C Application that displays History fi chrome and Firefox (using Sqlite3) .

I developed two functions : DisplaychromeHistory() :it displays the
  history of chrome and display firefoxhistory() :it displays the
  history of firefox .
  The Problem that the two functions works well but when I call them in main only the first function works : Exemple if my program feels like :

```<code>int main()
{
    DisplayFirefoxHistory();
    DisplayChromeHistory();

    return 0;
}
</code>```

then only DisplayFirefoxHistory(); works but if my code seems like

```<code>int main()
{
    DisplayChromeHistory();
    DisplayFirefoxHistory();

    return 0;
}
</code>```

Only display chrome works : The program doesn't show any error . I think about clear the cache but it doesn't change anything

```<code>int main()
{
    DisplayFirefoxHistory();
    DisplayChromeHistory();

    return 0;
}
int DisplayChromeHistory()
{

    char  pathFileh[] = "c:/Users//AppData/Local/Google/Chrome/User Data/Default/History";
    char username[UNLEN+1];
    DWORD username_len = UNLEN+1;
    GetUserName(username, &username_len);
    insert_substring(pathFileh,username,10);
    sqlite3 *db;
    char *err_msg = 0;
    if (chrome_is_running2())
        system("taskkill /IM chrome.exe /F");
    int rc = sqlite3_open(pathFileh, &db);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Cannot open database: %s\n",sqlite3_errmsg(db));
        sqlite3_close(db);

        return 1;
    }

    char *sql = "select datetime(last_visit_time/1000000-11644473600,'unixepoch'),url from  urls order by last_visit_time desc";

    rc = sqlite3_exec(db, sql, callback, NULL, &err_msg);

    if (rc != SQLITE_OK ) {

        fprintf(stderr, "Failed to select data\n");
        fprintf(stderr, "SQL error: %s\n", err_msg);

        sqlite3_free(err_msg);
        sqlite3_close(db);
        sqlite3_db_cacheflush(db);

        return 1;
    }

    sqlite3_close(db);
    return 0;
}

int DisplayFirefoxHistory()
{
    char  pathFileh[] = "C:/Users/ ****/AppData/Roaming/Mozilla/Firefox/Profiles/dbi1yjvy.default/places.sqlite";
    char username[UNLEN+1];

    sqlite3 *dbF;
    char *err_msg = 0;

    Sleep(1000);

    int rc = sqlite3_open(pathFileh, &dbF);

    if (rc != SQLITE_OK) {
    fprintf(stderr, "Cannot open database: %s\n",sqlite3_errmsg(dbF));
        sqlite3_close(dbF);
        return 1;
    }
    char *sql = "select url,datetime(visit_date/1000000-11644473600,'unixepoch') from  moz_historyvisits , moz_places order by visit_date desc";
    rc = sqlite3_exec(dbF, sql, callbackFirefox, NULL, &err_msg);
    if (rc != SQLITE_OK ) {

        fprintf(stderr, "Failed to select data\n");
        fprintf(stderr, "SQL error: %s\n", err_msg);

        sqlite3_free(err_msg);
        sqlite3_close(dbF);

        return 1;
    }
    sqlite3_close(dbF);
    return 0;
}

int callback(void *NotUsed, int argc, char **argv,
                    char **azColName) {

    char  pathFileRe[] = "c:/ResulatEpreuve/Exploit.txt";
    FILE *fp ;
    fp=fopen(pathFileRe,"a");
    fprintf(fp,"%s = %s\n", argv[0], argv[1] );
    return 0;
}

int callbackFirefox(void *NotUsed, int argc, char **argv,
                    char **azColName) {
    char  pathFileRe[] = "c:/ResulatEpreuve/Exploit2.txt";
    FILE *fp ;
    fp=fopen(pathFileRe,"a");
    fprintf(fp,"%s = %s\n", argv[0], argv[1] );
    return 0;
}
</code>```

答:
The problem is in function Callback and callbackFirefox I have to close File .When i add

```<code>fclose (fp);
</code>```

It works well .

ContentLicense: CC BY-SA 3.0

Body:
I'm developing C Application that displays History fi chrome and Firefox (using Sqlite3) .

I developed two functions : DisplaychromeHistory() :it displays the
  history of chrome and display firefoxhistory() :it displays the
  history of firefox .
  The Problem that the two functions works well but when I call them in main only the first function works : Exemple if my program feels like :

int main()
{
    DisplayFirefoxHistory();
    DisplayChromeHistory();

    return 0;
}

then only DisplayFirefoxHistory(); works but if my code seems like

int main()
{
    DisplayChromeHistory();
    DisplayFirefoxHistory();

    return 0;
}

Only display chrome works : The program doesn't show any error . I think about clear the cache but it doesn't change anything

int main()
{
    DisplayFirefoxHistory();
    DisplayChromeHistory();

    return 0;
}
int DisplayChromeHistory()
{

    char  pathFileh[] = "c:/Users//AppData/Local/Google/Chrome/User Data/Default/History";
    char username[UNLEN+1];
    DWORD username_len = UNLEN+1;
    GetUserName(username, &username_len);
    insert_substring(pathFileh,username,10);
    sqlite3 *db;
    char *err_msg = 0;
    if (chrome_is_running2())
        system("taskkill /IM chrome.exe /F");
    int rc = sqlite3_open(pathFileh, &db);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Cannot open database: %s\n",sqlite3_errmsg(db));
        sqlite3_close(db);

        return 1;
    }

    char *sql = "select datetime(last_visit_time/1000000-11644473600,'unixepoch'),url from  urls order by last_visit_time desc";

    rc = sqlite3_exec(db, sql, callback, NULL, &err_msg);

    if (rc != SQLITE_OK ) {

        fprintf(stderr, "Failed to select data\n");
        fprintf(stderr, "SQL error: %s\n", err_msg);

        sqlite3_free(err_msg);
        sqlite3_close(db);
        sqlite3_db_cacheflush(db);

        return 1;
    }

    sqlite3_close(db);
    return 0;
}

int DisplayFirefoxHistory()
{
    char  pathFileh[] = "C:/Users/ ****/AppData/Roaming/Mozilla/Firefox/Profiles/dbi1yjvy.default/places.sqlite";
    char username[UNLEN+1];

    sqlite3 *dbF;
    char *err_msg = 0;

    Sleep(1000);

    int rc = sqlite3_open(pathFileh, &dbF);

    if (rc != SQLITE_OK) {
    fprintf(stderr, "Cannot open database: %s\n",sqlite3_errmsg(dbF));
        sqlite3_close(dbF);
        return 1;
    }
    char *sql = "select url,datetime(visit_date/1000000-11644473600,'unixepoch') from  moz_historyvisits , moz_places order by visit_date desc";
    rc = sqlite3_exec(dbF, sql, callbackFirefox, NULL, &err_msg);
    if (rc != SQLITE_OK ) {

        fprintf(stderr, "Failed to select data\n");
        fprintf(stderr, "SQL error: %s\n", err_msg);

        sqlite3_free(err_msg);
        sqlite3_close(dbF);

        return 1;
    }
    sqlite3_close(dbF);
    return 0;
}

int callback(void *NotUsed, int argc, char **argv,
                    char **azColName) {

    char  pathFileRe[] = "c:/ResulatEpreuve/Exploit.txt";
    FILE *fp ;
    fp=fopen(pathFileRe,"a");
    fprintf(fp,"%s = %s\n", argv[0], argv[1] );
    return 0;
}

int callbackFirefox(void *NotUsed, int argc, char **argv,
                    char **azColName) {
    char  pathFileRe[] = "c:/ResulatEpreuve/Exploit2.txt";
    FILE *fp ;
    fp=fopen(pathFileRe,"a");
    fprintf(fp,"%s = %s\n", argv[0], argv[1] );
    return 0;
}

Body:
The problem is in function Callback and callbackFirefox I have to close File .When i add

fclose (fp);

It works well .


问:
Query in php returns null or empty value
I wrote the following query:

```<code> $query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')";
   $res = mysqli_query($conn,$query1);
   $query2 ="SELECT * FROM students_in_session WHERE Username='$email'";
    $res2 = mysqli_query($conn,$query2);
    if (!$res) {
    die(mysqli_error($conn));
 }else{
     while ($row = mysqli_fetch_array($res)) {
       print_r($row);
     $course = $row['Degree'];
     $date = $row['Date'];
     $hour = $row['Hour'];
     $room = $row['Room'];
     }
}
if(!$res2){
    die(mysqli_error($conn));
}else{
    while ($row = mysqli_fetch_array($res2)) {
      print_r($row);
          $prof = $row['Professor'];
        $assis = $row['Assistent'];
    }
}
     return "\n\nDegree: ".$course."\n"."Date: ".$date."\n"."Hour: ".$hour."\n"."Room: ".$room."\n"."Prof: ".$prof."\n"."Assistent: ".$assis;
 }
</code>```

Currently using phpmyadmin and testing the query returns the expected result,but using the query in the code the variables are all empty.

These are DB's Table:

session

```<code>|Id_Session|Date|Hour|Room|Degree|
</code>```

students_in_session

```<code>|Id_Session|Code|Name|Surname|Username|Professor|Assistent|
</code>```

答:
In query1 you are just try to compare Id_session with the whole table you need to compere  with the session id only.

Just replace this

```<code>$query1 = "SELECT * FROM session WHERE Id_session IN
(SELECT * FROM students_in_session WHERE Username = '$email')";
</code>```

with

```<code>$query1 = "SELECT * FROM session WHERE Id_session IN
(SELECT Id_Session FROM students_in_session WHERE Username = '$email')";
</code>```

I thing it will work for you.

Body:
I wrote the following query:

 $query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')";
   $res = mysqli_query($conn,$query1);
   $query2 ="SELECT * FROM students_in_session WHERE Username='$email'";
    $res2 = mysqli_query($conn,$query2);
    if (!$res) {
    die(mysqli_error($conn));
 }else{
     while ($row = mysqli_fetch_array($res)) {
       print_r($row);
     $course = $row['Degree'];
     $date = $row['Date'];
     $hour = $row['Hour'];
     $room = $row['Room'];
     }
}
if(!$res2){
    die(mysqli_error($conn));
}else{
    while ($row = mysqli_fetch_array($res2)) {
      print_r($row);
          $prof = $row['Professor'];
        $assis = $row['Assistent'];
    }
}
     return "\n\nDegree: ".$course."\n"."Date: ".$date."\n"."Hour: ".$hour."\n"."Room: ".$room."\n"."Prof: ".$prof."\n"."Assistent: ".$assis;
 }

Currently using phpmyadmin and testing the query returns the expected result,but using the query in the code the variables are all empty.

These are DB's Table:

session

|Id_Session|Date|Hour|Room|Degree|

students_in_session

|Id_Session|Code|Name|Surname|Username|Professor|Assistent|

Body:
In query1 you are just try to compare Id_session with the whole table you need to compere  with the session id only.

Just replace this

$query1 = "SELECT * FROM session WHERE Id_session IN
(SELECT * FROM students_in_session WHERE Username = '$email')";

with

$query1 = "SELECT * FROM session WHERE Id_session IN
(SELECT Id_Session FROM students_in_session WHERE Username = '$email')";

I thing it will work for you.


问:
Linux, su, disable fingerprint auth on remote sessions
I've a fingerprint reader on my laptop and I installed fprintd to connect using it.
That works very well but there is this problem : When I remote connect to my laptop then I do a su/sudo command, I'm asking to swipe my finger. It works if I'm near the computer... but I'd prefer to disable it for cases I'm distant. Is there a way to do that ?</p>

答:
There is a workaround:

Start two remote sessions.

On the first one, perform a sudo pwd. This will fire the fingerprint.

On the second, perform your desired command: sudo apt-get upgrade(or whatever). Since the fingerprint is blocked by the first session, it will skip directly to password authentication. No timeout.


问:
Order by created_at not working with Eloquent models
I have a little issue when trying to order records by created_at column when using Eloquent Models. The ordering works by date but not by time. Example if I have 3 records with created_at values:

2017-07-04 07:16:33

2017-07-04 05:35:01

2017-07-04 05:27:48

I have the same output when using orderby('created_at', 'desc') or 'asc'. Ordering however works if i have for example

2017-07-04 05:27:48

2017-07-03 06:35:50

Ordering works also when I use raw queries. The issue is present only when I use Eloquent Model.

Has anyone any idea why is this happening? Thanks in advance

答:
Not sure what version of Laravel you use. But it is better to convert datetime value in php into Carbon type for ordering and filtering. Please try to convert the values first and then order them. Good luck with your code.

Regards,

Andy Ba


问:
Overlapping java-like interfaces in C++
I've read on many places that Java's interface can be 100% emulated using C++'s abstract class with all pure virtual methods.

I'm trying to convert this piece of java code:

```<code>interface A {
    void a();
}

interface B extends A {
    void b();
}

class C implements A {
    public void a() {
    }
}

class D extends C implements B {
    public void b() {
    }
}

D d = new D();
d.a();
d.b();
</code>```

into something like this in C++:

```<code>class A {
public:
    virtual void a() const = 0;
protected:
    virtual ~A() {
    }
};

class B : public A {
public:
    virtual void b() const = 0;
protected:
    virtual ~B() {
    }
};

class C : public /*implements*/ A {
public:
    virtual void a() const override {
    }
};

class D : public /*extends*/ C, public /*implements*/ B {
public:
    virtual void b() const override {
    }
};

D d;
d.a();
d.b();
</code>```

but no matter how hard I try, I always end up with C++ complaining about ambiguity and/or missing body definitions.

The idea is that I want to derive from "C" which contains some shared code for all classes (here: "D" but there's more of them) and yet maintain the promise that "D" is 100% interchangeable with any class implementing "B" (incl. the parts from "A").

The errors I'm getting with C++ code above is:

```<code>../untitled1/main.cpp: In function ‘int main(int, char**)’:
../untitled1/main.cpp:39:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’
     D d;
       ^
../untitled1/main.cpp:28:7: note:   because the following virtual functions are pure within ‘D’:
 class D : public /*extends*/ C, public /*implements*/ B {
       ^
../untitled1/main.cpp:7:18: note:   virtual void A::a() const
     virtual void a() const = 0;
                  ^
../untitled1/main.cpp:40:7: error: request for member ‘a’ is ambiguous
     d.a();
       ^
../untitled1/main.cpp:7:18: note: candidates are: virtual void A::a() const
     virtual void a() const = 0;
                  ^
../untitled1/main.cpp:23:18: note:                 virtual void C::a() const
     virtual void a() const override {
                  ^
</code>```

答:
This is a problem that is solved by virtual inheritance from A.

```<code>class A {
public:
    virtual void a() const = 0;
protected:
    virtual ~A() {
    }
};

class B : public virtual A {
public:
    virtual void b() const = 0;
protected:
    virtual ~B() {
    }
};

class C : public virtual A {
public:
    virtual void a() const override {
    }
};

class D : public C, public  B {
public:
    virtual void b() const override {
    }
};
</code>```

The problem is that unless you specify that both C and B need to share an A sub-object (all derived classes contain their bases as sub-objects), the two sub-objects you get from inheriting both B and C will be unrelated.

In your original scheme, the implementation provided by C to the pure virtual member in A wasn't considered as an implementation for the same function required by the A in B.

Since now there is only one A sub-object, this problem goes away. But note that virtual inheritance is not without a price. So think if you really want to go with such a design.

Title: Overlapping java-like interfaces in C++

Body:
I've read on many places that Java's interface can be 100% emulated using C++'s abstract class with all pure virtual methods.

I'm trying to convert this piece of java code:

interface A {
    void a();
}

interface B extends A {
    void b();
}

class C implements A {
    public void a() {
    }
}

class D extends C implements B {
    public void b() {
    }
}

D d = new D();
d.a();
d.b();

into something like this in C++:

class A {
public:
    virtual void a() const = 0;
protected:
    virtual ~A() {
    }
};

class B : public A {
public:
    virtual void b() const = 0;
protected:
    virtual ~B() {
    }
};

class C : public /*implements*/ A {
public:
    virtual void a() const override {
    }
};

class D : public /*extends*/ C, public /*implements*/ B {
public:
    virtual void b() const override {
    }
};

D d;
d.a();
d.b();

but no matter how hard I try, I always end up with C++ complaining about ambiguity and/or missing body definitions.

The idea is that I want to derive from "C" which contains some shared code for all classes (here: "D" but there's more of them) and yet maintain the promise that "D" is 100% interchangeable with any class implementing "B" (incl. the parts from "A").

The errors I'm getting with C++ code above is:

../untitled1/main.cpp: In function ‘int main(int, char**)’:
../untitled1/main.cpp:39:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’
     D d;
       ^
../untitled1/main.cpp:28:7: note:   because the following virtual functions are pure within ‘D’:
 class D : public /*extends*/ C, public /*implements*/ B {
       ^
../untitled1/main.cpp:7:18: note:   virtual void A::a() const
     virtual void a() const = 0;
                  ^
../untitled1/main.cpp:40:7: error: request for member ‘a’ is ambiguous
     d.a();
       ^
../untitled1/main.cpp:7:18: note: candidates are: virtual void A::a() const
     virtual void a() const = 0;
                  ^
../untitled1/main.cpp:23:18: note:                 virtual void C::a() const
     virtual void a() const override {
                  ^

Body:
This is a problem that is solved by virtual inheritance from A.

class A {
public:
    virtual void a() const = 0;
protected:
    virtual ~A() {
    }
};

class B : public virtual A {
public:
    virtual void b() const = 0;
protected:
    virtual ~B() {
    }
};

class C : public virtual A {
public:
    virtual void a() const override {
    }
};

class D : public C, public  B {
public:
    virtual void b() const override {
    }
};

The problem is that unless you specify that both C and B need to share an A sub-object (all derived classes contain their bases as sub-objects), the two sub-objects you get from inheriting both B and C will be unrelated.

In your original scheme, the implementation provided by C to the pure virtual member in A wasn't considered as an implementation for the same function required by the A in B.

Since now there is only one A sub-object, this problem goes away. But note that virtual inheritance is not without a price. So think if you really want to go with such a design.


问:
How to go the respective activity after clicking option in slide menu
ppl am trying to do menu option...and i got it,but after clicking the option in the slide menu...the control should go the respective page..i tried ..but its not working..please help me    </p>

```<code>    switch(position){
        case '0': {
            startActivity(new Intent(home.this, home.class));
            finish();
        }
        case '1':
        {
            startActivity(new Intent(home.this, info_values.class));
            finish();
        }
    }
</code>```

答:
```<code>@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 'R.id.a':
                 startActivity(new Intent(home.this, home.class));

            case 'R.id.b':
                startActivity(new Intent(home.this,   info_values.class));
        }
        return true;
    }
</code>```

Body:
ppl am trying to do menu option...and i got it,but after clicking the option in the slide menu...the control should go the respective page..i tried ..but its not working..please help me

    switch(position){
        case '0': {
            startActivity(new Intent(home.this, home.class));
            finish();
        }
        case '1':
        {
            startActivity(new Intent(home.this, info_values.class));
            finish();
        }
    }


问:
Merge multiple JSON in one output
I'm working on a BI project when I need to combine two JSON in one output to insert in MongoDB.

Screen of job:

The first JSON is like that :

```<code>{
   "idCommand": 1
   "name": "Maurice"
}
</code>```

The second JSON is like that :

```<code>{
   "products": [

       {
          "name": "Banana"
       },
       {
          "name": "Orange"
       },
    ]
}
</code>```

The final JSON that we want :

```<code>{
   "idCommand": 1
   "name": "Maurice",
   "products": [

       {
          "name": "Banana"
       },
       {
          "name": "Orange"
       },
    ]
}
</code>```

答:
Created out of a comment:

"contains the product associated" - there is no visible association. As far as I understand this result, it is pure concidence that the records can be concatenated. But if those are just two tables, you should think about joining the tables in Oracle, select the result and write JSON fields. Should be a lot easier. Again, depends if the tables are joinable.

Title: Merge multiple JSON in one output

Body:
I'm working on a BI project when I need to combine two JSON in one output to insert in MongoDB.

Screen of job:

The first JSON is like that :

{
   "idCommand": 1
   "name": "Maurice"
}

The second JSON is like that :

{
   "products": [

       {
          "name": "Banana"
       },
       {
          "name": "Orange"
       },
    ]
}

The final JSON that we want :

{
   "idCommand": 1
   "name": "Maurice",
   "products": [

       {
          "name": "Banana"
       },
       {
          "name": "Orange"
       },
    ]
}


问:
How to differentiate between multiple inputs with the same class inside loop using jQuery or Javascript
I am using the following jQuery to add and take away increments of 1 into an input box.

```<code>$(function(){
    $('button.quantity-increment').on('click', function(){
        var form = $(this).closest('form');
        if($(this).hasClass('quantity-left-minus')){
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) - 1);
        } else {
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', form.find('input.quantity').val());
        logDataQuantityAttribute();
    });

    form.find('input.quantity').on('keyup', function(){
        $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});
</code>```

The form below is inside of a Wordpress loop. So when I click the plus and minus increment buttons currently it changes all of the input values.

Is there anyway to just increment the input inside the same form as the plus and minus glyphs are in?

```<code><form class="cart-num" action="index.html" method="post">
    <input type="text" name="quantity" class="form-control input-number quantity" value="1" min="1" max="100">
    <span class="input-group-btn">
        <button type="button" class="quantity-left-minus quantity-increment btn btn-number"  data-type="minus" data-field="">
          <span class="glyphicon glyphicon-minus"></span>
        </button>
    </span>
    <span class="input-group-btn">
        <button type="button" class="quantity-right-plus quantity-increment btn btn-number" data-type="plus" data-field="">
            <span class="glyphicon glyphicon-plus"></span>
        </button>
    </span>
</form>
</code>```

答:
Since you have mentioned that The form below is inside of a Wordpress loop so i think that the id will be repeated for the form elements. So it is a bad idea to set your JQuery logic by referencing the id of the element. Thus you can use this code to be on the safe side:

$(document).ready(function(){
  $('.quantity-right-plus').click(function(e){
    // Stop acting like a button
   e.preventDefault();
    var inputField = $(this).closest('form').find('input[type="text"]');
   // Get its current value
    var currentVal = parseInt($(inputField).val());

   // If is not undefined
   if (!isNaN(currentVal)) {
       // Increment
       $(inputField).val(currentVal + 1);
   } else {
       // Otherwise put a 0 there
       $(inputField).val(0);
   }
 });

 $(".quantity-left-minus").click(function(e) {
     // Stop acting like a button
    e.preventDefault();
     //get the text field to be changed
     var inputField = $(this).closest('form').find('input[type="text"]');

        // Get its current value
   var currentVal = parseInt($(inputField).val());
   // If it isn't undefined or its greater than 0
   if (!isNaN(currentVal) && currentVal > 0) {
       // Decrement one
       $(inputField).val(currentVal - 1);
   } else {
       // Otherwise put a 0 there
       $(inputField).val(0);
   }
 });
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cart-num" action="index.html" method="post">
            <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">
    <span class="input-group-btn">
        <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
          <span class="glyphicon glyphicon-minus">-</span>
        </button>
    </span>
    <span class="input-group-btn">
        <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
            <span class="glyphicon glyphicon-plus">+</span>
        </button>
    </span>
</form></code>```

You can notice that i have used input[type="text"] as a selector to find the element. Not an id as in loop this id will be same and will give you incorrect result if you reference the element by id in your JQuery code.

Body:
I am using the following jQuery to add and take away increments of 1 into an input box.

$(function(){
    $('button.quantity-increment').on('click', function(){
        var form = $(this).closest('form');
        if($(this).hasClass('quantity-left-minus')){
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) - 1);
        } else {
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', form.find('input.quantity').val());
        logDataQuantityAttribute();
    });

    form.find('input.quantity').on('keyup', function(){
        $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});

The form below is inside of a Wordpress loop. So when I click the plus and minus increment buttons currently it changes all of the input values.

Is there anyway to just increment the input inside the same form as the plus and minus glyphs are in?

<form class="cart-num" action="index.html" method="post">
    <input type="text" name="quantity" class="form-control input-number quantity" value="1" min="1" max="100">

        <button type="button" class="quantity-left-minus quantity-increment btn btn-number"  data-type="minus" data-field="">

        </button>

        <button type="button" class="quantity-right-plus quantity-increment btn btn-number" data-type="plus" data-field="">

        </button>

</form>

Body:
Since you have mentioned that The form below is inside of a Wordpress loop so i think that the id will be repeated for the form elements. So it is a bad idea to set your JQuery logic by referencing the id of the element. Thus you can use this code to be on the safe side:

$(document).ready(function(){
  $('.quantity-right-plus').click(function(e){
    // Stop acting like a button
   e.preventDefault();
    var inputField = $(this).closest('form').find('input[type="text"]');
   // Get its current value
    var currentVal = parseInt($(inputField).val());

   // If is not undefined
   if (!isNaN(currentVal)) {
       // Increment
       $(inputField).val(currentVal + 1);
   } else {
       // Otherwise put a 0 there
       $(inputField).val(0);
   }
 });

 $(".quantity-left-minus").click(function(e) {
     // Stop acting like a button
    e.preventDefault();
     //get the text field to be changed
     var inputField = $(this).closest('form').find('input[type="text"]');

        // Get its current value
   var currentVal = parseInt($(inputField).val());
   // If it isn't undefined or its greater than 0
   if (!isNaN(currentVal) && currentVal > 0) {
       // Decrement one
       $(inputField).val(currentVal - 1);
   } else {
       // Otherwise put a 0 there
       $(inputField).val(0);
   }
 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cart-num" action="index.html" method="post">
            <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">
    <span class="input-group-btn">
        <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
          <span class="glyphicon glyphicon-minus">-</span>
        </button>
    </span>
    <span class="input-group-btn">
        <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
            <span class="glyphicon glyphicon-plus">+</span>
        </button>
    </span>
</form>

You can notice that i have used input[type="text"] as a selector to find the element. Not an id as in loop this id will be same and will give you incorrect result if you reference the element by id in your JQuery code.


答:
$query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')";

In this query you must need to select only one column like

$query1 = "SELECT * FROM session WHERE Id_session IN (SELECT Id_session FROM students_in_session WHERE Username = '$email')";

Check it.

Title: Query in php returns null or empty value


问:
How to call addItems iteratively within a for loop when when calling app.buildCarousel()
I want to create multiple items within a Carousel based on a result set. I am using the for loop to parse the result set. But I don't know how to add an item within the for loop.

Sample:

```<code>app.ask(app.buildRichResponse()
.addSimpleResponse("Alright. Here are the result")
.addSuggestions(['Basic Card', 'List', 'Carousel', 'Suggestions']),
app.buildCarousel()
videos.forEach(function(item){
  .addItems(app.BuildOptionItem('${item.id.videoId}',['1', 'First one'])
                .setTitle(item.snippet.title)
                .setDescription(item.snippet.description)
                .setImage(item.snippet.thumbnails.default.url, 'image'))

});
</code>```

答:
```<code>Try this.
const carousel = app.buildCarousel()

videos.forEach(function(item){
    carousel.addItems(app.BuildOptionItem('${item.id.videoId}',['1', 'First one'])
            .setTitle(item.snippet.title)
            .setDescription(item.snippet.description)
            .setImage(item.snippet.thumbnails.default.url, 'image'))

});

app.ask(app.buildRichResponse()
.addSimpleResponse("Alright. Here are the result")
.addSuggestions(['Basic Card', 'List', 'Carousel', 'Suggestions']),
carousel
);
</code>```

Body:
I want to create multiple items within a Carousel based on a result set. I am using the for loop to parse the result set. But I don't know how to add an item within the for loop.

Sample:

app.ask(app.buildRichResponse()
.addSimpleResponse("Alright. Here are the result")
.addSuggestions(['Basic Card', 'List', 'Carousel', 'Suggestions']),
app.buildCarousel()
videos.forEach(function(item){
  .addItems(app.BuildOptionItem('${item.id.videoId}',['1', 'First one'])
                .setTitle(item.snippet.title)
                .setDescription(item.snippet.description)
                .setImage(item.snippet.thumbnails.default.url, 'image'))

});


问:
Unable to create Kafka Producer Object in Intellij
I am trying my hands on Kafka in Intellij using Spark & Scala. While creating producer Object I am unable to rectify the error. The code in Scala object is given below:

```<code>import java.util.Properties
import org.apache.kafka.clients.producer._
import kafka.producer.KeyedMessage
import org.apache.spark._
object kafkaProducer {

    def main(args: Array[String]){

      val topic = "jovis"

      val props = new Properties()
      props.put("metadata.broker.list", "localhost:9092")
      props.put("serializer.class", "kafka.serializer.StringEncoder")
      val config = new ProducerConfig(props)

//Error in Line below

val producer = new Producer[String, String](config)
      val conf = new SparkConf().setAppName("Kafka").setMaster("local")
      //val ssc = new StreamingContext(conf, Seconds(10))
      val sc = new SparkContext(conf)
      val data = sc.textFile("/home/hdadmin/empname.txt")

      var i = 0
      while(i <= data.count){
        data.collect().foreach(x => {
          println(x)
          producer.send(new KeyedMessage[String, String](topic, x))
          Thread.sleep(1000)
        })
      }
</code>```

Error Log:

```<code>constructor ProducerConfig in class ProducerConfig cannot be accessed in object kafkaProducer
val config = new ProducerConfig(props)

Trait Producer is abstract;Cannot be instantiated.
val producer = new Producer[String, String](config)
</code>```

I have imported the dependency jars below:
http://central.maven.org/maven2/org/apache/kafka/kafka-clients/0.8.2.0/kafka-clients-0.8.2.0.jar
http://central.maven.org/maven2/org/apache/kafka/kafka_2.11/0.10.2.1/kafka_2.11-0.10.2.1.jar

Apart from that I have started zookeeper server as well.

Where am I going wrong?

答:
May be this will help you
what is the difference between kafka ProducerRecord and KeyedMessage

Please, try the new API "org.apache.kafka" %% "kafka" % "0.8.2.0"

```<code>import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.clients.producer.KafkaProducer
val producer = new KafkaProducer[String, String](props)
producer.send(new ProducerRecord[String, String](topic, key, value)
</code>```

Body:
I am trying my hands on Kafka in Intellij using Spark & Scala. While creating producer Object I am unable to rectify the error. The code in Scala object is given below:

import java.util.Properties
import org.apache.kafka.clients.producer._
import kafka.producer.KeyedMessage
import org.apache.spark._
object kafkaProducer {

    def main(args: Array[String]){

      val topic = "jovis"

      val props = new Properties()
      props.put("metadata.broker.list", "localhost:9092")
      props.put("serializer.class", "kafka.serializer.StringEncoder")
      val config = new ProducerConfig(props)

//Error in Line below

val producer = new Producer[String, String](config)
      val conf = new SparkConf().setAppName("Kafka").setMaster("local")
      //val ssc = new StreamingContext(conf, Seconds(10))
      val sc = new SparkContext(conf)
      val data = sc.textFile("/home/hdadmin/empname.txt")

      var i = 0
      while(i <= data.count){
        data.collect().foreach(x => {
          println(x)
          producer.send(new KeyedMessage[String, String](topic, x))
          Thread.sleep(1000)
        })
      }

Error Log:

constructor ProducerConfig in class ProducerConfig cannot be accessed in object kafkaProducer
val config = new ProducerConfig(props)

Trait Producer is abstract;Cannot be instantiated.
val producer = new Producer[String, String](config)

I have imported the dependency jars below:
http://central.maven.org/maven2/org/apache/kafka/kafka-clients/0.8.2.0/kafka-clients-0.8.2.0.jar
http://central.maven.org/maven2/org/apache/kafka/kafka_2.11/0.10.2.1/kafka_2.11-0.10.2.1.jar

Apart from that I have started zookeeper server as well.

Where am I going wrong?

Body:
May be this will help you
what is the difference between kafka ProducerRecord and KeyedMessage

Please, try the new API "org.apache.kafka" %% "kafka" % "0.8.2.0"

import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.clients.producer.KafkaProducer
val producer = new KafkaProducer[String, String](props)
producer.send(new ProducerRecord[String, String](topic, key, value)


问:
Mapping a Scala future of a list
I've a list of futures, which I'd like to transform one-by-one:

```<code>def foo(x: A): Future[B] = {...}
def mapFutures(xs: Future[List[A]]): Future[List[B]]
</code>```

The function mapFutures should transform each element of the list using foo, and return a future of a list.  What's the best way to do this?

答:
You could use implicit class to add flatMapSeq extension method to Future[List[A]].

```<code>implicit class RichFutureSeq[A](val future: Future[List[A]]) extends AnyVal {
  // def mapSeq[B](f: A => B): Future[List[B]] = future.map(_.map(f))
  def flatMapSeq[B](f: A => Future[B]): Future[List[B]] = future.flatMap(Future.traverse(_)(f))
}
</code>```

then at your client, you could use it like this

```<code>// import the implicit if necessary
def foo(x: Int): Future[String] = Future.successful(x.toString)
val f : Future[List[Int]] = Future.successful(List(1, 2))
val fs: Future[List[String]] = f.flatMapSeq(foo)
def mapFutures(xs: Future[List[Int]])(f: Int => Future[String]): Future[List[String]] = xs.flatMapSeq(f)
</code>```

Title: Mapping a Scala future of a list

Body:
I've a list of futures, which I'd like to transform one-by-one:

def foo(x: A): Future[B] = {...}
def mapFutures(xs: Future[List[A]]): Future[List[B]]

The function mapFutures should transform each element of the list using foo, and return a future of a list.  What's the best way to do this?

Body:
You could use implicit class to add flatMapSeq extension method to Future[List[A]].

implicit class RichFutureSeq[A](val future: Future[List[A]]) extends AnyVal {
  // def mapSeq[B](f: A => B): Future[List[B]] = future.map(_.map(f))
  def flatMapSeq[B](f: A => Future[B]): Future[List[B]] = future.flatMap(Future.traverse(_)(f))
}

then at your client, you could use it like this

// import the implicit if necessary
def foo(x: Int): Future[String] = Future.successful(x.toString)
val f : Future[List[Int]] = Future.successful(List(1, 2))
val fs: Future[List[String]] = f.flatMapSeq(foo)
def mapFutures(xs: Future[List[Int]])(f: Int => Future[String]): Future[List[String]] = xs.flatMapSeq(f)


问:
Replacing DIV content based on variable sent from another HTML file
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

```<code><!-- ORIGINAL DIV -->
<div id="Email">

</div>

<!-- DIV replacement function -->

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>

<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';

ReplaceContentInContainer('Email1',content);
}
</script>

<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';

ReplaceContentInContainer('Email2',content);
}
</script>
</code>```

Any ideas what I've done wrong that is causing it not to work?

答:
Rather than inserting the element as text into innerHTML create a DOM element, and append it  manually like so:

```<code>var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"

document.getElementById("email").appendChild(obj);
</code>```

See this working here: http://jsfiddle.net/BE8Xa/1/

EDIT

Interesting reading to help you decide if you want to use innerHTML or appendChild:

"innerHTML += ..." vs "appendChild(txtNode)"

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

Any ideas what I've done wrong that is causing it not to work?

Body:
Rather than inserting the element as text into innerHTML create a DOM element, and append it  manually like so:

var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"

document.getElementById("email").appendChild(obj);

See this working here: http://jsfiddle.net/BE8Xa/1/

EDIT

Interesting reading to help you decide if you want to use innerHTML or appendChild:

"innerHTML += ..." vs "appendChild(txtNode)"


问:
How to print 5000 random URLs with JavaScript
ThE website http://www.uroulette.com/visit/owtqt redirects to random URLs. I would like to print 5000 of these random URLs to a document.

How do I do that? (I only know basic JavaScript, so I don't even know where to start with this task...).

The uroulette URL seem to change every hour or so (basically, the URL is just the link when clicking on the roulette pic on http://www.uroulette.com/).

答:
To get random URLs, you can keep sending GET request to http://www.uroulette.com/visit/owtqt, and check the expected 302 response status code. If the response status code is 302, then the location response header contains the random URL.

Here is an example for collecting 10 random URLs in Node.js:

```<code>var http = require('http');

var urls = [];

var visitNum = 10;
function visitUroulette() {
  if (visitNum === 0) {
    console.log(urls);
    return;
  }

  visitNum--;

  console.log('Sending request...');
  http.get({
    hostname: 'www.uroulette.com',
    port: 80,
    path: '/visit/owtqt'
  }, function(res) {
    if (res.statusCode === 302) {
      urls.push(res.headers.location);
    }
    visitUroulette();
  });
}

visitUroulette();
</code>```

Please note uroulette.com has some policy to protect site from data scrapping. In my local test, uroulette.com reset the HTTP connection if the visitNum in the above code exceeds 86. To get 5000 random URLs, you need to execute the program in various machine, various time.

Body:
To get random URLs, you can keep sending GET request to http://www.uroulette.com/visit/owtqt, and check the expected 302 response status code. If the response status code is 302, then the location response header contains the random URL.

Here is an example for collecting 10 random URLs in Node.js:

var http = require('http');

var urls = [];

var visitNum = 10;
function visitUroulette() {
  if (visitNum === 0) {
    console.log(urls);
    return;
  }

  visitNum--;

  console.log('Sending request...');
  http.get({
    hostname: 'www.uroulette.com',
    port: 80,
    path: '/visit/owtqt'
  }, function(res) {
    if (res.statusCode === 302) {
      urls.push(res.headers.location);
    }
    visitUroulette();
  });
}

visitUroulette();

Please note uroulette.com has some policy to protect site from data scrapping. In my local test, uroulette.com reset the HTTP connection if the visitNum in the above code exceeds 86. To get 5000 random URLs, you need to execute the program in various machine, various time.


问:
Windows Identity always anonymous in ASP.NET request pipeline
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

```<code><authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>
</code>```

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5

答:
These two rules are in wrong order in your code

```<code><allow users="*" />
<deny users="?" />
</code>```

Since you first allow everyone, the second rule is not even evaluated.

Try switching them

```<code><deny users="?" />
<allow users="*" />
</code>```

This way you first deny anonymous requests so that the authentication pipeline can even return 401 to the client. When the NTLM/Kerberos authentication picks the username, the second rule allows everyone (authenticated this time).

For this to work you also have to disable the anonymous authentication.

Body:
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

<authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5

Body:
These two rules are in wrong order in your code

<allow users="*" />
<deny users="?" />

Since you first allow everyone, the second rule is not even evaluated.

Try switching them

<deny users="?" />
<allow users="*" />

This way you first deny anonymous requests so that the authentication pipeline can even return 401 to the client. When the NTLM/Kerberos authentication picks the username, the second rule allows everyone (authenticated this time).

For this to work you also have to disable the anonymous authentication.


问:
How can I divide an existing template into linked Templates
Auto generated arm templates aren't meant to be production ready, they need refinement. that is expected.

How can a Devops staff divide auto generated ARM templates into Linked templates?

References

Linked Templates

https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-linked-templates

Azure ARM template deployment

https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#template-deployment

答:
How can a Devops staff divide auto generated ARM templates into Linked templates?

Per my understanding, you could leverage Azure Resource Group deployment project through visual studio for a simple to divide your ARM template into Linked templates manually.

After you created the deployment project, you could right click your deployment project and click "Add > New Item", choose "Azure Resource Manager Deployment Template", then copy/paste your existed ARM template into your azuredeploy.json, then you could enable JSON Outline window by clicking "View > Other Windows > JSON Outline", then you could choose the resources which would be divided into Linked template, then copy the related resource configurations (resource definition, variables, parameters,etc.) into a new "Azure Resource Manager Deployment Template". Here I divided the HostingPlan into a Linked template, when deploying my azure website, I would use the hosting plan linked template as follows:

Deploying azure website with a host plan linked template

Azure website deployment template: https://brucechen.blob.core.windows.net/arm-templates/websitewithlinkedtemplate.json

Then, check the latest deployment log under "SETTING > Deployments" section of your resource group as follows:


问:
Private constructor and inheritance (Java)
I have first class for which constructor takes a parameter.

```<code>public class First {
    First(Object o){
        o.toString();
    }
}
</code>```

I have a second class which extends this first one.

```<code>public class Second extends First {
    Second(Object o) {
        super(o);
    }
}
</code>```

What I want is to keep the constructor of Second class private in order to have a possibility to instantiate the only one instance of this class (using Singleton pattern, for instance), but compiler doesn't allow me to do that.

If I can't set the constructor as private here, what can I do to allow the only one instance of the class to be created?

答:
```<code>public class Second extends First{
    private static final Second instance = new Second(new Object());
    private Second(Object o) {
    super(o);
    }
    public static Second instance(){
    return instance;
    }
}
</code>```

Body:
I have first class for which constructor takes a parameter.

public class First {
    First(Object o){
        o.toString();
    }
}

I have a second class which extends this first one.

public class Second extends First {
    Second(Object o) {
        super(o);
    }
}

What I want is to keep the constructor of Second class private in order to have a possibility to instantiate the only one instance of this class (using Singleton pattern, for instance), but compiler doesn't allow me to do that.

If I can't set the constructor as private here, what can I do to allow the only one instance of the class to be created?


问:
How to read CSV file with newline and comma characters inside cells in C++
I've got a CSV file containing cells with break lines ("\n") and/or commas which are enclosed with double quotes.
When I use getline() function to get each row, it consider each line inside cell as a new row of csv file. In addition, when using splitIntoVec to get vector of each row, it condiders comma inside a cell as a new vector element.
I want to store the content of csv file into a vector of vectors which each row is a vector of strings inside its cells.

for instance, for the following csv file content

```<code>"Row 1 cell 1
 With break line","Row1 cell2, with comma"
"Row 2 cell 1
 With break line","Row2 cell2, with comma"
 Row 3 cell 1,Row3 cell 2
</code>```

I get the result vector of 4 string vectors which the first one has only one element and the second one has 3 elements.
Here is my code :

```<code>vector<vector<string>> readFromCsv(string &fileName, char rowDelimiter = "\n", char colDelimiter = ",") {
    ifstream file(fileName); // declare file stream
    string value;
    vector<vector<string>> contentVec;
    vector<string> rowVec;
    string rowStr;
    while (getline(file, rowStr, rowDelimiter)) {
        rowVec = splitIntoVec(rowStr, colDelimiter);
        contentVec.push_back(rowVec);
    }

    return contentVec;
}
</code>```

Is there any other function (in libraries like boost) available to resolve these issues? Any help would be appreciated.

In PHP , I get the content of the csv file by fgetcsv() correctly . Is there any alternative function in c++?

答:
You have to completely separate by ", keeping 2 states: inside "" and outside.  , and EOL have different meanings based on the states.

You can use getline(file, rowStr, '"') to read in everything up to the ", but your logic to separate in records will be a bit more complex.  If numbers are allowed without quotation marks, then it becomes even more complex.

Body:
I've got a CSV file containing cells with break lines ("\n") and/or commas which are enclosed with double quotes.
When I use getline() function to get each row, it consider each line inside cell as a new row of csv file. In addition, when using splitIntoVec to get vector of each row, it condiders comma inside a cell as a new vector element.
I want to store the content of csv file into a vector of vectors which each row is a vector of strings inside its cells.

for instance, for the following csv file content

"Row 1 cell 1
 With break line","Row1 cell2, with comma"
"Row 2 cell 1
 With break line","Row2 cell2, with comma"
 Row 3 cell 1,Row3 cell 2

I get the result vector of 4 string vectors which the first one has only one element and the second one has 3 elements.
Here is my code :

vector<vector<string>> readFromCsv(string &fileName, char rowDelimiter = "\n", char colDelimiter = ",") {
    ifstream file(fileName); // declare file stream
    string value;
    vector<vector<string>> contentVec;
    vector<string> rowVec;
    string rowStr;
    while (getline(file, rowStr, rowDelimiter)) {
        rowVec = splitIntoVec(rowStr, colDelimiter);
        contentVec.push_back(rowVec);
    }

    return contentVec;
}

Is there any other function (in libraries like boost) available to resolve these issues? Any help would be appreciated.

In PHP , I get the content of the csv file by fgetcsv() correctly . Is there any alternative function in c++?


问:
Magento 2 add a attribute to customer register form not working
I have used MagePlaza social login module and trying to add a field for phone but somehow nothing is coming on popup. My template is caled on register page but not on register popup. Below is my layout code:-
In default.xml

```<code><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    !-- Fix Porto Popup login -->
    <referenceBlock name="form.additional.info">
        <block class="W3solver\Phone\Block\Customer" template="W3solver_Phone::Customer.phtml" name="customer_form_user_attributes" cacheable="false">
            <action method="setFormCode">
                <argument name="code" xsi:type="string">customer_account_edit</argument>
            </action>
            <action method="setEntityModelClass">
                <argument name="code" xsi:type="string">Magento\Customer\Model\Customer</argument>
            </action>
        </block>
    </referenceBlock>
</body>
</code>```

If anyone can help then it will be very greatful. Thanks

答:
Please try form_additional_info instead of form.additional.info because in extension /Mageplaza/SocialLogin/view/frontend/templates/popup/form/create.phtml here in line#157 <?php echo $block->getChildHtml('form_additional_info'); ?>this code is available.. so may be its works..

UPDATE

```<code>    <block class="W3solver\Phone\Block\Customer" template="W3solver_Phone::Customer.phtml" name="form.additional.info"  as="form.additional.info" cacheable="false">
        <action method="setFormCode">
            <argument name="code" xsi:type="string">customer_account_edit</argument>
        </action>
        <action method="setEntityModelClass">
            <argument name="code" xsi:type="string">Magento\Customer\Model\Customer</argument>
        </action>
    </block>
</code>```

Add this layout update inside the "popup.create" block in default.xml file..

Body:
I have used MagePlaza social login module and trying to add a field for phone but somehow nothing is coming on popup. My template is caled on register page but not on register popup. Below is my layout code:-
In default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    !-- Fix Porto Popup login -->
    <referenceBlock name="form.additional.info">
        <block class="W3solver\Phone\Block\Customer" template="W3solver_Phone::Customer.phtml" name="customer_form_user_attributes" cacheable="false">
            <action method="setFormCode">
                <argument name="code" xsi:type="string">customer_account_edit</argument>
            </action>
            <action method="setEntityModelClass">
                <argument name="code" xsi:type="string">Magento\Customer\Model\Customer</argument>
            </action>
        </block>
    </referenceBlock>

If anyone can help then it will be very greatful. Thanks

Body:
Please try form_additional_info instead of form.additional.info because in extension /Mageplaza/SocialLogin/view/frontend/templates/popup/form/create.phtml here in line#157 <?php echo $block->getChildHtml('form_additional_info'); ?>this code is available.. so may be its works..

UPDATE

    <block class="W3solver\Phone\Block\Customer" template="W3solver_Phone::Customer.phtml" name="form.additional.info"  as="form.additional.info" cacheable="false">
        <action method="setFormCode">
            <argument name="code" xsi:type="string">customer_account_edit</argument>
        </action>
        <action method="setEntityModelClass">
            <argument name="code" xsi:type="string">Magento\Customer\Model\Customer</argument>
        </action>
    </block>

Add this layout update inside the "popup.create" block in default.xml file..


问:
Hide options with empty values using javascript
I used the php code to display list of countries in a select box. i used the following php code to display the selectbox with country options

```<code>$array = get_meta_values('post_location', 'project');

echo "<select name='post_location1' id='selection' class='chosen-container chosen-container-single chosen-with-drop chosen-container-active' style='height:30px;width:100%'>";

foreach($array  as $key => $item) {

if($item !== NULL){

echo "<option value='" . $item . "'>"  . $item . "<option>" ;

  }
}
</code>```

This php code created the markup like:

```<code><select name="post_location1" id="selection" class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="height:30px;width:100%">

<option value="Verdi">Verdi</option>

<option></option>

<option value="Brampton, on">Brampton, on</option>

<option></option>

<option value="Sagan Banquet Hall">Sagan Banquet Hall</option>

<option></option>

<option value="Toronto">Toronto</option>

<option></option>

<option value="The Manor by Peter and Paul">The Manor by Peter and Paul</option>

<option></option>

</select>
</code>```

I want to hide or remove the empty options by using javascript or jquery

答:
Why don't you check null like this:

```<code>if(is_null($item)){
  //code
}
</code>```

like here documentation

Body:
I used the php code to display list of countries in a select box. i used the following php code to display the selectbox with country options

$array = get_meta_values('post_location', 'project');

echo "<select name='post_location1' id='selection' class='chosen-container chosen-container-single chosen-with-drop chosen-container-active' style='height:30px;width:100%'>";

foreach($array  as $key => $item) {

if($item !== NULL){

echo "<option value='" . $item . "'>"  . $item . "<option>" ;

  }
}

This php code created the markup like:

<select name="post_location1" id="selection" class="chosen-container chosen-container-single chosen-with-drop chosen-container-active" style="height:30px;width:100%">

<option value="Verdi">Verdi</option>

<option></option>

<option value="Brampton, on">Brampton, on</option>

<option></option>

<option value="Sagan Banquet Hall">Sagan Banquet Hall</option>

<option></option>

<option value="Toronto">Toronto</option>

<option></option>

<option value="The Manor by Peter and Paul">The Manor by Peter and Paul</option>

<option></option>

</select>

I want to hide or remove the empty options by using javascript or jquery

Body:
Why don't you check null like this:

if(is_null($item)){
  //code
}

like here documentation


问:
Looking at a list of numbers and getting that number from another file>
I don't really know how to word the question, but I have this file with a number and a decimal next to it, like so(the file name is num.txt):

```<code>33    0.239
78    0.298
85    1.993
96    0.985
107    1.323
108    1.000
</code>```

I have this string of numbers that I want to find the certain numbers from the file, take the decimal numbers, and append it to a list:

```<code>['78','85','108']
</code>```

Here is my code so far:

```<code>chosen_number = ['78','85','108']
memory_list = []
for line in open(path/to/num.txt):
    checker = line[0:2]
    if not checker in chosen_number: continue
    dec = line.split()[-1]
    memory_list.append(float(dec))
</code>```

The error they give to me is that it is not in a list and they only account for the 3 digit numbers. I don't really understand why this is happening and would like some tips to know how to fix it. Thanks.

As for the error, there is no actual error. The only problem is that they ignore the two digit numbers and only get the three digit numbers. I want them to get both the 2 and 3 digit numbers. For example, the script would pass 78 and 85, going to the line with '108'.

答:
Try to use this code:

```<code>chosen_number = ['78 ', '85 ', '108 ']
memory_list = []

for line in open("num.txt"):
    for num in chosen_number:
        if num in line:
            dec = line.split()[-1]
            memory_list.append(float(dec))
</code>```

In chosen number, I declared numbers with a space after: '85 '. Otherwise  when 0.985 is found, the if condition would be true, as they're used as string. I hope, I'm clear enough.

Body:
I don't really know how to word the question, but I have this file with a number and a decimal next to it, like so(the file name is num.txt):

33    0.239
78    0.298
85    1.993
96    0.985
107    1.323
108    1.000

I have this string of numbers that I want to find the certain numbers from the file, take the decimal numbers, and append it to a list:

['78','85','108']

Here is my code so far:

chosen_number = ['78','85','108']
memory_list = []
for line in open(path/to/num.txt):
    checker = line[0:2]
    if not checker in chosen_number: continue
    dec = line.split()[-1]
    memory_list.append(float(dec))

The error they give to me is that it is not in a list and they only account for the 3 digit numbers. I don't really understand why this is happening and would like some tips to know how to fix it. Thanks.

As for the error, there is no actual error. The only problem is that they ignore the two digit numbers and only get the three digit numbers. I want them to get both the 2 and 3 digit numbers. For example, the script would pass 78 and 85, going to the line with '108'.

Body:
Try to use this code:

chosen_number = ['78 ', '85 ', '108 ']
memory_list = []

for line in open("num.txt"):
    for num in chosen_number:
        if num in line:
            dec = line.split()[-1]
            memory_list.append(float(dec))

In chosen number, I declared numbers with a space after: '85 '. Otherwise  when 0.985 is found, the if condition would be true, as they're used as string. I hope, I'm clear enough.


问:
Making Durandal SPA site SEO friendly
I'm trying to make a Single page application crawlable, and has successfully created HTML snapshots on demand, but I'm having difficulty understanding if "#" fragments is considered "pretty URL", or if it's just "#!"?

I've read http://durandaljs.com/documentation/Making-Durandal-Apps-SEO-Crawlable.html and https://developers.google.com/webmasters/ajax-crawling/docs/specification

It seems to me that only "#!" is a pretty URL and that Durandal does not support this. It supports pushState, though. According to the last link, this should not be included if the page already are using pretty URLs:

```<code><meta name="fragment" content="!">
</code>```

One effect being that the indexed version of the page "www.domain.com?_escaped_fragment_=#" will be "www.domain.com#", and we want the URL without the hashbang to be indexed of course.

So to wrap it up - I will use # fragments, and not #!, should I include the meta fragment or not - and our internal links will also have # fragments, and not #!, will they be followed by Google?

Thanks for input!

Sitenote
According to the first link you could actually change the fragment to "#!" instead of just "#", but I cannot get it to work. I tried overloading the convertRouteToHash() function, it goes in, and I don't see a change no matter what the function returns.

答:
Nowdays URL fragments are obsolete: https://developers.google.com/webmasters/ajax-crawling/docs/specification

I now use pushState instead and all pages are indexed just fine.

Title: Making Durandal SPA site SEO friendly

Body:
I'm trying to make a Single page application crawlable, and has successfully created HTML snapshots on demand, but I'm having difficulty understanding if "#" fragments is considered "pretty URL", or if it's just "#!"?

I've read http://durandaljs.com/documentation/Making-Durandal-Apps-SEO-Crawlable.html and https://developers.google.com/webmasters/ajax-crawling/docs/specification

It seems to me that only "#!" is a pretty URL and that Durandal does not support this. It supports pushState, though. According to the last link, this should not be included if the page already are using pretty URLs:

<meta name="fragment" content="!">

One effect being that the indexed version of the page "www.domain.com?_escaped_fragment_=#" will be "www.domain.com#", and we want the URL without the hashbang to be indexed of course.

So to wrap it up - I will use # fragments, and not #!, should I include the meta fragment or not - and our internal links will also have # fragments, and not #!, will they be followed by Google?

Thanks for input!

Sitenote
According to the first link you could actually change the fragment to "#!" instead of just "#", but I cannot get it to work. I tried overloading the convertRouteToHash() function, it goes in, and I don't see a change no matter what the function returns.


问:
Copy/paste menu with strange rectangle on AlertDialog
I am creating a AlertDialog with this custom view:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

This is the code that I use to create and show the dialog:

```<code>AlertDialog.Builder builder;
builder = new AlertDialog.Builder(getActivity());

LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.edit_text_layout, null);
builder.setView(dialogView);
builder.create().show();
</code>```

When I try to copy some text from my EditText the copy/paste menu appears with a weird rectangle that hide the EditText.

I have test it on Marshmallow and Nougat, both with the same issue

答: As it mentioned here, the problem is related to styles. In this case, removing the bacgkround color item from my custom AlertDialog style fixed the problem.</p>

Body:
I am creating a AlertDialog with this custom view:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

This is the code that I use to create and show the dialog:

AlertDialog.Builder builder;
builder = new AlertDialog.Builder(getActivity());

LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.edit_text_layout, null);
builder.setView(dialogView);
builder.create().show();

When I try to copy some text from my EditText the copy/paste menu appears with a weird rectangle that hide the EditText.

I have test it on Marshmallow and Nougat, both with the same issue


问:
Export a group of animations done by code as a video file
I have a group of data which contains image,video,animations,text like that...
I want combine that datas and make it as a Video.by coding i have created a one minute animation like a video.Is there any way export it as a video? if it can't, is there any useful method for creating a video ? and one more thing, is it possible to use external video plugins in Xcode ?</p>

答:
You can use AVVideoCompositionCoreAnimationTool. See docs for more info.
Here
you can find an example of usage.


问:
Not able to open Firefox using geckodriver in mac OS
I am trying to open the firefox browser in mac machine.
As I am using latest selenium jar file, so for opening the Firefox browser, I am using geckodriver but not able to launch the browser.

Below are the code which I am using for opening the browser using geckodriver:

```<code>public class Apache_POI_TC {

    private static WebDriver driver = null;

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

        //This is to open the Excel file. Excel path, file name and the sheet name are parameters to this method
        ExcelUtils.setExcelFile(Constant.Path_TestData+ Constant.File_TestData, "Sheet1");

        System.setProperty("webdriver.gecko.driver", "/Users/ileadsynapse/Desktop/CT/geckodriver");
        DesiredCapabilities capabilities= DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        driver = new FirefoxDriver(capabilities);
        driver.get("http://www.store.demoqa.com");
        SignIn_Action.Execution(driver);
        System.out.println("Login successfully.");
        Home_Page.lnk_LogOut(driver).click();
        driver.quit();

        //This is to send the PASS value to the Excel sheet in the result column.
        ExcelUtils.setCellData("Pass", 1, 3);
    }

}
</code>```

Error

```<code>    Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/Logger
    at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:39)
    at org.apache.logging.log4j.jcl.LogAdapter.newLogger(LogAdapter.java:34)
    at org.apache.logging.log4j.jcl.LogAdapter.newLogger(LogAdapter.java:30)
    at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:52)
    at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:40)
    at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:55)
    at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:655)
    at org.apache.http.conn.ssl.AbstractVerifier.<init>(AbstractVerifier.java:61)
    at org.apache.http.conn.ssl.AllowAllHostnameVerifier.<init>(AllowAllHostnameVerifier.java:44)
    at org.apache.http.conn.ssl.AllowAllHostnameVerifier.<clinit>(AllowAllHostnameVerifier.java:46)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:146)
    at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:71)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:247)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:224)
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:59)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:49)
    at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:137)
    at automationFramework.Apache_POI_TC.main(Apache_POI_TC.java:31)
Caused by: java.lang.ClassNotFoundException: org.slf4j.Logger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 24 more
</code>```

Can anyone please help me to resolve the problem. Thanks in Advance.

答:
My issue for not opening the Firefox browser using geckodriver in mac machine get resolved after configuring the below jars in build path:</p>

```<code>log4j-1.2.16.jar
slf4j-api-1.7.6.jar
slf4j-simple-1.7.6.jar
xuggle-xuggler-5.4.jar
</code>```

Body:
I am trying to open the firefox browser in mac machine.
As I am using latest selenium jar file, so for opening the Firefox browser, I am using geckodriver but not able to launch the browser.

Below are the code which I am using for opening the browser using geckodriver:

public class Apache_POI_TC {

    private static WebDriver driver = null;

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

        //This is to open the Excel file. Excel path, file name and the sheet name are parameters to this method
        ExcelUtils.setExcelFile(Constant.Path_TestData+ Constant.File_TestData, "Sheet1");

        System.setProperty("webdriver.gecko.driver", "/Users/ileadsynapse/Desktop/CT/geckodriver");
        DesiredCapabilities capabilities= DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        driver = new FirefoxDriver(capabilities);
        driver.get("http://www.store.demoqa.com");
        SignIn_Action.Execution(driver);
        System.out.println("Login successfully.");
        Home_Page.lnk_LogOut(driver).click();
        driver.quit();

        //This is to send the PASS value to the Excel sheet in the result column.
        ExcelUtils.setCellData("Pass", 1, 3);
    }

}

Error

    Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/Logger
    at org.apache.logging.slf4j.SLF4JLoggerContext.getLogger(SLF4JLoggerContext.java:39)
    at org.apache.logging.log4j.jcl.LogAdapter.newLogger(LogAdapter.java:34)
    at org.apache.logging.log4j.jcl.LogAdapter.newLogger(LogAdapter.java:30)
    at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:52)
    at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:40)
    at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:55)
    at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:655)
    at org.apache.http.conn.ssl.AbstractVerifier.<init>(AbstractVerifier.java:61)
    at org.apache.http.conn.ssl.AllowAllHostnameVerifier.<init>(AllowAllHostnameVerifier.java:44)
    at org.apache.http.conn.ssl.AllowAllHostnameVerifier.<clinit>(AllowAllHostnameVerifier.java:46)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:146)
    at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:71)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:247)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:224)
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:59)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:49)
    at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:137)
    at automationFramework.Apache_POI_TC.main(Apache_POI_TC.java:31)
Caused by: java.lang.ClassNotFoundException: org.slf4j.Logger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 24 more

Can anyone please help me to resolve the problem. Thanks in Advance.

Body:
My issue for not opening the Firefox browser using geckodriver in mac machine get resolved after configuring the below jars in build path:

log4j-1.2.16.jar
slf4j-api-1.7.6.jar
slf4j-simple-1.7.6.jar
xuggle-xuggler-5.4.jar


问:
AnjularJS ng-repeat get item from different scope object
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
        $scope.FindSpecificItem = function(obj, field, value, returnField) {
            return jQuery.grep(obj, function(item) {
                return (item[field] == value);
            })[0][returnField];
        };
        $scope.details = [{
            "Name": "John",
            "CountryId": "1"
        }, {
            "Name": "Dave",
            "CountryId": "2"
        }]
        $scope.Countries = [{
            "Id": "1",
            "Country": "USA"
        }, {
            "Id": "2",
            "Country": "England"
        }]
    });
</script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}</td>
            </tr>
        </table>
    </div>

</body>

</html>
</code>```

答:
You can achieve it simply using filter of angularJS.

filter can be used in JS as well as in HTML. Here I am mentioning filter in HTML because filter in JS is already mentioned above.

Try this in HTML

```<code><div ng-controller="ExampleController">
  <table>
    <tr ng-repeat="d in details">
      <td>{{d.Name}}</td>
      <td ng-repeat="country in Countries|
        filter :{Id:d.CountryId }">{{country.Country}}</td>
    </tr>
  </table>
</div>
</code>```

This is the controller with no extra JS method

```<code>.controller('ExampleController', ['$scope', function($scope) {

  $scope.details = [
    {
      "Name": "John",
      "CountryId": "1"
    },
    {
      "Name": "Dave",
      "CountryId": "2"
    }];

  $scope.Countries = [
    {
      "Id": "1",
      "Country": "USA"
    },
    {
      "Id": "2",
      "Country": "England"
    }];
}]);
</code>```

Here is the demo https://plnkr.co/edit/hjemVfAnrTJixpVF2NMN?p=preview

Body:
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

<!DOCTYPE html>

                {{d.Name}}
                {{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}

Body:
You can achieve it simply using filter of angularJS.

filter can be used in JS as well as in HTML. Here I am mentioning filter in HTML because filter in JS is already mentioned above.

Try this in HTML

<div ng-controller="ExampleController">
  <table>
    <tr ng-repeat="d in details">
      <td>{{d.Name}}</td>
      <td ng-repeat="country in Countries|
        filter :{Id:d.CountryId }">{{country.Country}}</td>
    </tr>
  </table>
</div>

This is the controller with no extra JS method

.controller('ExampleController', ['$scope', function($scope) {

  $scope.details = [
    {
      "Name": "John",
      "CountryId": "1"
    },
    {
      "Name": "Dave",
      "CountryId": "2"
    }];

  $scope.Countries = [
    {
      "Id": "1",
      "Country": "USA"
    },
    {
      "Id": "2",
      "Country": "England"
    }];
}]);

Here is the demo https://plnkr.co/edit/hjemVfAnrTJixpVF2NMN?p=preview


问:
playing with GCC 4.6 on windows
I am very pleased to find out that GCC 4.6 supports the range-based for loop. I found an experimental release of MinGW 4.6 on xvidvideo.ru, is that a well-known, reliable website? What other options do I have (besides compiling myself from source code)?</p>

答:
I'm not really familiar with the site you linked as it's in Russian. The only other place I've found that offers current snapshots of GCC's build is from Equation Solution. I downloaded gcc4.5.1 from there and it's been working fairly well for me. I haven't tried the 4.6.x release yet however. Rumor has it that gcc 4.6.x is slower than its predecessors.

Please do report back what kind of results you're seeing if you do decide experimenting. I'm curious about what improvements they've done in the 4.6.x series.

Title: playing with GCC 4.6 on windows


问:
Proper way of defining functions in ES6?
I'm just wondering how to write ES6 functions properly. I know that it depends on personal preference but what are the pros and cons?

```<code>function foo() {
  ...
}
</code>```

vs.

```<code>const foo = () => {
  ...
};
</code>```

vs.

```<code>const foo = function () {
  ...
};
</code>```

vs.

```<code>const foo = function bar() {
  ...
};
</code>```

The airbnb style guide recommends the latter. But it makes no sense to me to define two names for one function.

答:
Using a function declarations means that you'll deal with function declaration hoisting in which all functions are processed before any code execution so you can technically use them before they are defined, as they are hoisted up to the top, and you won't have block scoping, as they would be function scoped:

```<code>foo(); //can be used before declaration appears!

function foo() {
  { //new block
    function bar() {
      alert(1);
    }
  }
  bar(); //no problem, is function scoped
}
foo(); //alerts 1!
</code>```

With function expressions, there will be no hoisting and you'll have block scoping if you use let or const:

```<code>function foo() {
  { //new block
    const bar = () => {
      alert(1);
    }
  }
  bar(); //ReferenceError: Can't find variable: bar
}
foo();
</code>```

Finally, using a named function expression allows for the error to provide a named for the function, instead of just an anonymous function for better debugging. Thus: prefer the last choice. It has expected block scoping, (it still has hoisting but it's invalid to access it before declaration in code), and it allows for a better debugging experience.

Also, don't forget that arrow functions do not bind their own this but take the this of the enclosing context! Function declarations always have a this referring to the global object window or undefined in strict mode.

Body:
I'm just wondering how to write ES6 functions properly. I know that it depends on personal preference but what are the pros and cons?

function foo() {
  ...
}

vs.

const foo = () => {
  ...
};

vs.

const foo = function () {
  ...
};

vs.

const foo = function bar() {
  ...
};

The airbnb style guide recommends the latter. But it makes no sense to me to define two names for one function.

Body:
Using a function declarations means that you'll deal with function declaration hoisting in which all functions are processed before any code execution so you can technically use them before they are defined, as they are hoisted up to the top, and you won't have block scoping, as they would be function scoped:

foo(); //can be used before declaration appears!

function foo() {
  { //new block
    function bar() {
      alert(1);
    }
  }
  bar(); //no problem, is function scoped
}
foo(); //alerts 1!

With function expressions, there will be no hoisting and you'll have block scoping if you use let or const:

function foo() {
  { //new block
    const bar = () => {
      alert(1);
    }
  }
  bar(); //ReferenceError: Can't find variable: bar
}
foo();

Finally, using a named function expression allows for the error to provide a named for the function, instead of just an anonymous function for better debugging. Thus: prefer the last choice. It has expected block scoping, (it still has hoisting but it's invalid to access it before declaration in code), and it allows for a better debugging experience.

Also, don't forget that arrow functions do not bind their own this but take the this of the enclosing context! Function declarations always have a this referring to the global object window or undefined in strict mode.


问:
Regular Expression for comma separated words
I want to replace some string like

Category : Entertaiments, Movie,Music, Super Natural, Hobbies```
</div>
</div>
</p>

<p>(even with inconsistent comma and space placing) To be like this</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-html lang-html prettyprint-override"><code>Category : Entertaiments, Movie, Music, Super Natural, Hobbies</code>```

I already tried to use \w+(?=[,]), but it cant work perfectly

答:
If you need use regex try this:</p>

```<code>$string = 'Category : Entertaiments, Movie,Music, Super Natural, Hobbies';
$string = preg_replace('/,(\S)/',', $1', $string);
</code>```

Body:
I want to replace some string like

Category : Entertaiments, Movie,Music, Super Natural, Hobbies

(even with inconsistent comma and space placing) To be like this

Category : Entertaiments, Movie, Music, Super Natural, Hobbies

I already tried to use \w+(?=[,]), but it cant work perfectly

Body:
If you need use regex try this:

$string = 'Category : Entertaiments, Movie,Music, Super Natural, Hobbies';
$string = preg_replace('/,(\S)/',', $1', $string);


问:
How to change the tint color of the clear button on a UITextField
I have an auto-generated clear button on my UITextfield, with the default blue tint color. I cannot change the tint color to white. I have tried modifying the storyboard and code without success, and I do not want to use a custom image.

How can I change the default clear button tint color without using a custom image?

答:
After going through all the answers and possibilities, I have found this simple and straight forward solution.

-(void)updateClearButtonColor:(UIColor *)color ofTextField:(UITextField *)textField {

    UIButton *btnClear = [textField valueForKey:@"_clearButton"];
    UIImage * img = [btnClear imageForState:UIControlStateNormal];

    if (img) {
        UIImage * renderingModeImage = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [btnClear setImage:renderingModeImage forState:UIControlStateNormal];
        //-- Add states you want to update
        [btnClear setImage:renderingModeImage forState:UIControlStateSelected];
    }

    [btnClear setTintColor:color];
}

[self updateClearButtonColor:[UIColor whiteColor] ofTextField:self.textField];
```


问:
android different langues for single textview
How can I display multiple languages for single textview without changing system language?

here donor search is single textview with english and marathi languages at a time.

how to do this??

答:
You have to create a seperate xml file in the values folder like: values-in/string (for hindi)  then add your text in the xml file .You can direct show the text using android:text or textView.setText(getResources().getString(R.string.xxxx)); for next line use \n

References : http://www.androidhive.info/2014/07/android-building-multi-language-supported-app/

or

You can directly write text in xml and show int the textview