问:
Is there a way to get the device name using adb? For example, if the device name is John Doe's Nexus, how to get the name using a command?
I have an android device, which when registered to an account renames itself after the account name. I need to get that name using adb. </p>

答:
You can use

```<code>adb shell dumpsys bluetooth_manager
</code>```

See full answer here: Find connected bluetooth device name using adb?

Body:
You can use

adb shell dumpsys bluetooth_manager

See full answer here: Find connected bluetooth device name using adb?


来源: stackexchange

问:
Should I use std::cerr and exit() instead of throwing an exception?
I'm relatively new to C++ and I am just wondering, what are the main differences between just throwing an exception or writing std::cerr and exit()? I know that if a exception isn't caught the program will exit. Are there any use cases for std::cerr or should I always throw exceptions? Or should I never use std::cerr in general? Are there some best practices for this?

throw std::runtime_error("runtime error msg");
```

<p>OR</p>

<pre class="lang-cpp prettyprint-override"><code>std::cerr << "cerr error msg";
exit(1);
</code>```

Are both versions OK?

答:
The main difference between the two, is that you can catch and handle exception (raise with throw). There are two pros for this action:

A. You can throw an exception and handle it without crashing your program.

B. When handling exception, they will automatically call the destructors of your objects. For example:

```<code>try {
    A a;
    throw runtime_error("A"); // Throw exception A
} catch (...) { // Catch exception A & Call a's object destructor.
    throw runtime_error("B"); // Throw exception B and crush (if no one else catch it).
}
</code>```

You want to use the throw and not the exit(1) option, if you think about future working on this code (or if someone else needs to continue your work on this code).

For more details please see: Are destructors run when calling exit()? & Are destructors called after a throw in C++?

ContentLicense: CC BY-SA 4.0

Body:
I'm relatively new to C++ and I am just wondering, what are the main differences between just throwing an exception or writing std::cerr and exit()? I know that if a exception isn't caught the program will exit. Are there any use cases for std::cerr or should I always throw exceptions? Or should I never use std::cerr in general? Are there some best practices for this?

throw std::runtime_error("runtime error msg");

OR

std::cerr << "cerr error msg";
exit(1);

Are both versions OK?

Body:
The main difference between the two, is that you can catch and handle exception (raise with throw). There are two pros for this action:

A. You can throw an exception and handle it without crashing your program.

B. When handling exception, they will automatically call the destructors of your objects. For example:

try {
    A a;
    throw runtime_error("A"); // Throw exception A
} catch (...) { // Catch exception A & Call a's object destructor.
    throw runtime_error("B"); // Throw exception B and crush (if no one else catch it).
}

You want to use the throw and not the exit(1) option, if you think about future working on this code (or if someone else needs to continue your work on this code).

For more details please see: Are destructors run when calling exit()? & Are destructors called after a throw in C++?


问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

答:
How about</p>

```<code>set(A).difference(subset_of_A)
</code>```

ContentLicense: CC BY-SA 3.0

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
How about

set(A).difference(subset_of_A)


问:
Sqlite order by rows order
I am using this query

```<code>"select * from SomeTable group by SomeColumn"
</code>```

It is returns list with accenting order, but i need to same order like in database.

For example the order in database is:

```<code>p

a

s
</code>```

But result is:

```<code>a

i

p
</code>```

Sample

The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul

答:
By the rules of SQL, you can't count on getting records back in any specific order without specifying an ORDER BY clause in your SQL query.

In practice servers sometimes return values in the order in which they're inserted, in the order of the first index created, or in the order of the primary key--but you can't count on this behavior, and in fact I've seen the behavior change between database maintenance windows or after the database version is upgraded. You definitely wouldn't want to count on a DB engine to give you back records in any particular order if you write a SELECT statement without an ORDER BY clause.

The only real way to get your records back in the order you inserted them is to create a timestamp column and then sort on it during the SELECT. If you don't want to worry about populating that column on INSERT, have that column auto-populate itself with a timestamp (depending on your DB engine).

Title: Sqlite order by rows order

Body:
I am using this query

"select * from SomeTable group by SomeColumn"

It is returns list with accenting order, but i need to same order like in database.

For example the order in database is:

p

a

s

But result is:

a

i

p

Sample

The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul


问:
Values missing or misaligned when entering multiple rows from form - PHP/MYSQLI
I am trying to submit multiple rows from a form into MySQL database using PHP (having used Insert multiple rows to database from HTML form using MySQLi and multiple other articles as reference).

The problem I am encountering is that the first row submits fine but subsequent rows submit some values I did not expect.

I have tried multiple ways of looping through the rows (see commented lines) to address this but not found a solution yet.

```<code>// $number = count($_POST["ps_id"]);
  // echo $number;
  $ps_id     = $_POST["ps_id"];
  $ds_id = $_POST["ds_id"];
  $hole_id = $_POST["hole_id"];
  $strokes = $_POST["strokes"];
  $hole_strokes  = $_POST["hole_strokes"];
  $par = $_POST["hole_par"];
  $pkey = $_POST["pkey"];
  $c_id  = $_POST["c_id"];
  $this_hole = $_POST["holeno"];

  $stmt = $con->prepare("INSERT INTO strokes (players_id, days_id, hole_id, strokes, points, net_strokes, par, pkey, course_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

  // for ($i=0; $i<count($ds_id); $i++) {
  // for ($i=0; $i<$number; $i++) {
  foreach ($_POST['ps_id'] as $i => $ps_id){
      $ds_id = $ds_id[$i];
      $hole_id = $hole_id[$i];
      $strokes = $strokes[$i];
      $hole_strokes = $hole_strokes[$i];
      $par = $par[$i];
      $pkey = $pkey[$i];
      $c_id = $c_id[$i];
      // $ps_id = $ps_id[$i];
      $net_strokes += ((int)$strokes-(int)$hole_strokes);
      $pts += ((int)$par-(int)$net_strokes)+2;
      if ($pts < 0) {
        $points = 0;
      } else {
        $points = $pts;
      }

      $stmt->bind_param('iiiiiiiii', $ps_id, $ds_id, $hole_id, $strokes, $points, $net_strokes, $par, $pkey, $c_id);
      // echo "ds_id: ".$ds_id." and hole_id: ".$hole_id." and strokes: ".$strokes." and points: ".$points." and net_strokes: ".$net_strokes." and pts: ".$pts." and pkey: ".$pkey." and par: ".$par." and c_id: ".$c_id." and ps_id: ".$ps_id."<br><br><br>";

      $stmt->execute();

      // setcookie('g_holeno', $nexthole, 3600, '/');
      // header("Location: ../open/index.php?s=1");

  }
      // echo "Success";
      $nexthole += (int)$this_hole[0]+1;
      // echo "Next hole: ".$nexthole;
  $stmt->close();
</code>```

Values for subsequent rows are properly formatted when submitted from the form:

```<code>ps_id[]: 1
strokes[]: 4
ds_id[]: 7
pkey[]: 5
holeno[]: 1
hole_id[]: 19
hole_par[]: 4
c_id[]: 4
hole_strokes[]: 1
ps_id[]: 2
strokes[]: 4
ds_id[]: 7
pkey[]: 5
holeno[]: 1
hole_id[]: 19
hole_par[]: 4
c_id[]: 4
hole_strokes[]: 1
ps_id[]: 3
strokes[]: 4
...
</code>```

...but for rows 2 onwards only ps_id (players_id) and net_strokes submits correctly to db:

```<code>id, days_id, hole_id, strokes, points, net_strokes, par, pkey, course_id, players_id
'103','7','19','4','3','3','4','5','4','1'
'104','0','9','0','2','3','0','0','0','2'
'105','0','0','0','1','3','0','0','0','3'
'106','0','0','0','0','3','0','0','0','4'
</code>```

I suspect the error is somehow associated with the calculated variables but have not been able to find a solution on my own.

答:
You overwrite your data every iteration:

```<code>$ds_id = $ds_id[$i];     // array `$ds_id` becomes SINGLE value
$hole_id = $hole_id[$i]; // same here and so on
// etc
</code>```

Body:
I am trying to submit multiple rows from a form into MySQL database using PHP (having used Insert multiple rows to database from HTML form using MySQLi and multiple other articles as reference).

The problem I am encountering is that the first row submits fine but subsequent rows submit some values I did not expect.

I have tried multiple ways of looping through the rows (see commented lines) to address this but not found a solution yet.

// $number = count($_POST["ps_id"]);
  // echo $number;
  $ps_id     = $_POST["ps_id"];
  $ds_id = $_POST["ds_id"];
  $hole_id = $_POST["hole_id"];
  $strokes = $_POST["strokes"];
  $hole_strokes  = $_POST["hole_strokes"];
  $par = $_POST["hole_par"];
  $pkey = $_POST["pkey"];
  $c_id  = $_POST["c_id"];
  $this_hole = $_POST["holeno"];

  $stmt = $con->prepare("INSERT INTO strokes (players_id, days_id, hole_id, strokes, points, net_strokes, par, pkey, course_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

  // for ($i=0; $i<count($ds_id); $i++) {
  // for ($i=0; $i<$number; $i++) {
  foreach ($_POST['ps_id'] as $i => $ps_id){
      $ds_id = $ds_id[$i];
      $hole_id = $hole_id[$i];
      $strokes = $strokes[$i];
      $hole_strokes = $hole_strokes[$i];
      $par = $par[$i];
      $pkey = $pkey[$i];
      $c_id = $c_id[$i];
      // $ps_id = $ps_id[$i];
      $net_strokes += ((int)$strokes-(int)$hole_strokes);
      $pts += ((int)$par-(int)$net_strokes)+2;
      if ($pts < 0) {
        $points = 0;
      } else {
        $points = $pts;
      }

      $stmt->bind_param('iiiiiiiii', $ps_id, $ds_id, $hole_id, $strokes, $points, $net_strokes, $par, $pkey, $c_id);
      // echo "ds_id: ".$ds_id." and hole_id: ".$hole_id." and strokes: ".$strokes." and points: ".$points." and net_strokes: ".$net_strokes." and pts: ".$pts." and pkey: ".$pkey." and par: ".$par." and c_id: ".$c_id." and ps_id: ".$ps_id."

";

      $stmt->execute();

      // setcookie('g_holeno', $nexthole, 3600, '/');
      // header("Location: ../open/index.php?s=1");

  }
      // echo "Success";
      $nexthole += (int)$this_hole[0]+1;
      // echo "Next hole: ".$nexthole;
  $stmt->close();

Values for subsequent rows are properly formatted when submitted from the form:

ps_id[]: 1
strokes[]: 4
ds_id[]: 7
pkey[]: 5
holeno[]: 1
hole_id[]: 19
hole_par[]: 4
c_id[]: 4
hole_strokes[]: 1
ps_id[]: 2
strokes[]: 4
ds_id[]: 7
pkey[]: 5
holeno[]: 1
hole_id[]: 19
hole_par[]: 4
c_id[]: 4
hole_strokes[]: 1
ps_id[]: 3
strokes[]: 4
...

...but for rows 2 onwards only ps_id (players_id) and net_strokes submits correctly to db:

id, days_id, hole_id, strokes, points, net_strokes, par, pkey, course_id, players_id
'103','7','19','4','3','3','4','5','4','1'
'104','0','9','0','2','3','0','0','0','2'
'105','0','0','0','1','3','0','0','0','3'
'106','0','0','0','0','3','0','0','0','4'

I suspect the error is somehow associated with the calculated variables but have not been able to find a solution on my own.

Body:
You overwrite your data every iteration:

$ds_id = $ds_id[$i];     // array `$ds_id` becomes SINGLE value
$hole_id = $hole_id[$i]; // same here and so on
// etc


问:
Using LocalStorage to determine what page open when user return to my book site
I'm developing a site that will have some books, I know how to save the last page opened of the book using LocalStorage

Now I want open the last page when the book is opened again.

I just need this,but I don't know how to do it. When the book is opened go to the last page.

I'm using javascript to do it

Updated

```<code>//Save and restore position

// save position Next
var bookName = (document.getElementsByClassName("menu-title"))
    function salvePositionNext()
   {
   var locationBook = (document.getElementsByClassName("nav-chapters
   next"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters next"));
   localStorage.setItem(bookName[0], locationBook[0])

 }

 //Save position Previous
 function salvePositionPrevious()
 {
   var locationBook = (document.getElementsByClassName("nav-chapters previous"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters previous"));
   localStorage.setItem(bookName[0], locationBook[0])
 }
 //Load Last Page
 function loadLastPage()
 {
   if(localStorage.getItem(bookName[0])){
 location.replace(localStorage.getItem(bookName[0]))
   }
 }
 // End of save and restore position
</code>```

答:
Functions used to save and restore position of a book in my site, the page go to last position is just book root. then when this page is loaded go to URL locationBook (value of bookName key)

```<code>//Save and restore position

// save position Next
var bookName = (document.getElementsByClassName("menu-title"))
    function salvePositionNext()
   {
   var locationBook = (document.getElementsByClassName("nav-chapters
   next"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters next"));
   localStorage.setItem(bookName[0], locationBook[0])

 }

 //Save position Previous
 function salvePositionPrevious()
 {
   var locationBook = (document.getElementsByClassName("nav-chapters previous"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters previous"));
   localStorage.setItem(bookName[0], locationBook[0])
 }
 //Load Last Page
 function loadLastPage()
 {
   if(localStorage.getItem(bookName[0])){
 location.replace(localStorage.getItem(bookName[0]))
   }
 }
 // End of save and restore position
</code>```

Body:
I'm developing a site that will have some books, I know how to save the last page opened of the book using LocalStorage

Now I want open the last page when the book is opened again.

I just need this,but I don't know how to do it. When the book is opened go to the last page.

I'm using javascript to do it

Updated

//Save and restore position

// save position Next
var bookName = (document.getElementsByClassName("menu-title"))
    function salvePositionNext()
   {
   var locationBook = (document.getElementsByClassName("nav-chapters
   next"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters next"));
   localStorage.setItem(bookName[0], locationBook[0])

 }

 //Save position Previous
 function salvePositionPrevious()
 {
   var locationBook = (document.getElementsByClassName("nav-chapters previous"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters previous"));
   localStorage.setItem(bookName[0], locationBook[0])
 }
 //Load Last Page
 function loadLastPage()
 {
   if(localStorage.getItem(bookName[0])){
 location.replace(localStorage.getItem(bookName[0]))
   }
 }
 // End of save and restore position

Body:
Functions used to save and restore position of a book in my site, the page go to last position is just book root. then when this page is loaded go to URL locationBook (value of bookName key)

//Save and restore position

// save position Next
var bookName = (document.getElementsByClassName("menu-title"))
    function salvePositionNext()
   {
   var locationBook = (document.getElementsByClassName("nav-chapters
   next"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters next"));
   localStorage.setItem(bookName[0], locationBook[0])

 }

 //Save position Previous
 function salvePositionPrevious()
 {
   var locationBook = (document.getElementsByClassName("nav-chapters previous"));
   var locationBook = (document.getElementsByClassName("mobile-nav-chapters previous"));
   localStorage.setItem(bookName[0], locationBook[0])
 }
 //Load Last Page
 function loadLastPage()
 {
   if(localStorage.getItem(bookName[0])){
 location.replace(localStorage.getItem(bookName[0]))
   }
 }
 // End of save and restore position


问:
Use of inserted and deleted tables for logging - is my concept sound?
I have a table with a simple identity column primary key. I have written a 'For Update' trigger that, among other things, is supposed to log the changes of certain columns to a log table. Needless to say, this is the first time I've tried this.

Essentially as follows:

```<code>Declare Cursor1 Cursor for
     select a.*, b.*
     from inserted a
     inner join deleted b on a.OrderItemId = b.OrderItemId
</code>```

(where OrderItemId is the actual name of the primary identity key).

I then do the usual open the cursor and go into a fetch next loop. With the columns I want to test, I do:

if Update(Field1)
   begin
          ..... do some logging
   end

The columns include varchars, bits, and datetimes. It works, sometimes. The problem is that the log function is writing the a and b values of the field to a log and in some cases, it appears that the before and after values are identical.

I have 2 questions:

Am I using the Update function correctly?

Am I accessing the before and after values correctly?

Is there a better way?

答:
If you are using SQL Server 2016 or higher, I would recommend skipping this trigger entirely and instead using system-versioned temporal tables.

Not only will it eliminate the need for (and performance issues around) the trigger, it'll be easier to query the historical data.

Body:
I have a table with a simple identity column primary key. I have written a 'For Update' trigger that, among other things, is supposed to log the changes of certain columns to a log table. Needless to say, this is the first time I've tried this.

Essentially as follows:

Declare Cursor1 Cursor for
     select a.*, b.*
     from inserted a
     inner join deleted b on a.OrderItemId = b.OrderItemId

(where OrderItemId is the actual name of the primary identity key).

I then do the usual open the cursor and go into a fetch next loop. With the columns I want to test, I do:

if Update(Field1)
   begin
          ..... do some logging
   end

The columns include varchars, bits, and datetimes. It works, sometimes. The problem is that the log function is writing the a and b values of the field to a log and in some cases, it appears that the before and after values are identical.

I have 2 questions:

Am I using the Update function correctly?

Am I accessing the before and after values correctly?

Is there a better way?


问:
Url encoding issue with url connection
Please help me to encode the url:

```<code>http://dsxsd.com/def/fss/default/files/10 رسم الصباح - 1.mp3
</code>```

I need to download this file in android app.
when i am trying to make url connection it gives me 404. but on browser the url is working.
when i pasted browser encoded url its working fine.

But i can't hardcore the things as i have my urls like this coming from server.

I tried to encode using Urlencoder.encode(url,"UTF-8");
but server call gives me wrong url I am getting "java.net.MalformedURLException: Protocol not found: http%3A%2F%........

have this url not separate path params and query params to encode separately.

please help me in it.

答:
If you only have the URL, use this method</p>

```<code>private String encodeUrl(String link) throws UnsupportedEncodingException {
    Uri uri = (Uri.parse(link));
    String result = null;
    if (Objects.equals(uri.getScheme(), "content")) {
        try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        }
    }
    if (result == null) {
        result = uri.getPath();
        int cut = Objects.requireNonNull(result).lastIndexOf('/');
        if (cut != -1) {
            result = result.substring(cut + 1);
        }
    }
    return link.replace(result
            ,URLEncoder.encode(result, "UTF-8")
                    .replace("+", "%20"));
}
</code>```

Title: Url encoding issue with url connection

Body:
Please help me to encode the url:

http://dsxsd.com/def/fss/default/files/10 رسم الصباح - 1.mp3

I need to download this file in android app.
when i am trying to make url connection it gives me 404. but on browser the url is working.
when i pasted browser encoded url its working fine.

But i can't hardcore the things as i have my urls like this coming from server.

I tried to encode using Urlencoder.encode(url,"UTF-8");
but server call gives me wrong url I am getting "java.net.MalformedURLException: Protocol not found: http%3A%2F%........

have this url not separate path params and query params to encode separately.

please help me in it.

Body:
If you only have the URL, use this method

private String encodeUrl(String link) throws UnsupportedEncodingException {
    Uri uri = (Uri.parse(link));
    String result = null;
    if (Objects.equals(uri.getScheme(), "content")) {
        try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        }
    }
    if (result == null) {
        result = uri.getPath();
        int cut = Objects.requireNonNull(result).lastIndexOf('/');
        if (cut != -1) {
            result = result.substring(cut + 1);
        }
    }
    return link.replace(result
            ,URLEncoder.encode(result, "UTF-8")
                    .replace("+", "%20"));
}


问:
render a different component based on a condition within a loop
I created a simple Minesweeper game and when it comes to the decision, which cell to render there are three possibilities:

Unrevealed cell

Revealed mine cell

Revealed neutral cell

I created a row component that renders all the cells contained by the row.

```<code><template>
  <div class="row">

    <component
        v-for="(cell, columnIndex) in row"
        :key="columnIndex"
    />

  </div>
</template>
</code>```

I have to add the conditional statements now. From the docs there is a is tag so I tried to extend my code to

```<code><component
    v-for="(cell, columnIndex) in row"
    :key="columnIndex"
    :is="
        if(cell.revealed){
            if(cell.isMine) {
                <RevealedMineCell/>
            } else {
                <RevealedNeutralCell
                    :mineNeighbours="cell.mineNeighbours"
                />
            }
        } else {
            <UnrevealedCell
                :unrevealedCell="cell"
                :x="columnIndex"
                :y="rowIndex"
                @cellClicked="onCellClicked"
            />
        }
    "
/>
</code>```

but I am mixing JavaScript code with HTML code and this is invalid. All I want to do is something like this pseudo code

```<code><component
    v-for="(cell, columnIndex) in row"
    :key="columnIndex"
>
    <v-if="cell.revealed && cell.isMine">
        <RevealedMineCell/>
    </v-if>
    <v-else-if="cell.revealed && !cell.isMine">
        <RevealedNeutralCell
            :mineNeighbours="cell.mineNeighbours"
        />
    </v-else-if>
    <v-else>
        <UnrevealedCell
            :unrevealedCell="cell"
            :x="columnIndex"
            :y="rowIndex"
            @cellClicked="onCellClicked"
        />
    </v-else>
</component>
</code>```

How can I achieve this?

答:
You can achieve this inside methods.</p>

```<code><component
    v-for="(cell, columnIndex) in row"
    :key="columnIndex"
    v-bind="getProps(cell)"
    :is="getCellComponent(cell)"
/>

import RevealedMineCell from ...
import RevealedNeutralCell from ...
import UnrevealedMineCell from ...

...
  methods: {
    getProps (cell) {
        if(cell.revealed){
           if(cell.isMine) {
               return {};
            } else {
               return {
                   mineNeighbours: cell.mineNeighbours
               };
            }
        } else {
            return {
                 unrevealedCell: cell,
                 ...
                 ...
                 cellClicked: this.onCellClicked
                 ...
                 ...
            };
        }
    },
    getCellComponent (cell) {
       if(cell.revealed){
           if(cell.isMine) {
               return RevealedMineCell;
            } else {
               return RevealedNeutralCell;
            }
        } else {
            return UnrevealedCell;
        }
  }
...
</code>```

Body:
I created a simple Minesweeper game and when it comes to the decision, which cell to render there are three possibilities:

Unrevealed cell

Revealed mine cell

Revealed neutral cell

I created a row component that renders all the cells contained by the row.

<template>

    <component
        v-for="(cell, columnIndex) in row"
        :key="columnIndex"
    />

</template>

I have to add the conditional statements now. From the docs there is a is tag so I tried to extend my code to

<component
    v-for="(cell, columnIndex) in row"
    :key="columnIndex"
    :is="
        if(cell.revealed){
            if(cell.isMine) {
                <RevealedMineCell/>
            } else {
                <RevealedNeutralCell
                    :mineNeighbours="cell.mineNeighbours"
                />
            }
        } else {
            <UnrevealedCell
                :unrevealedCell="cell"
                :x="columnIndex"
                :y="rowIndex"
                @cellClicked="onCellClicked"
            />
        }
    "
/>

but I am mixing JavaScript code with HTML code and this is invalid. All I want to do is something like this pseudo code

<component
    v-for="(cell, columnIndex) in row"
    :key="columnIndex"
>
    <v-if="cell.revealed && cell.isMine">
        <RevealedMineCell/>
    </v-if>
    <v-else-if="cell.revealed && !cell.isMine">
        <RevealedNeutralCell
            :mineNeighbours="cell.mineNeighbours"
        />
    </v-else-if>
    <v-else>
        <UnrevealedCell
            :unrevealedCell="cell"
            :x="columnIndex"
            :y="rowIndex"
            @cellClicked="onCellClicked"
        />
    </v-else>
</component>

How can I achieve this?

Body:
You can achieve this inside methods.

<component
    v-for="(cell, columnIndex) in row"
    :key="columnIndex"
    v-bind="getProps(cell)"
    :is="getCellComponent(cell)"
/>

import RevealedMineCell from ...
import RevealedNeutralCell from ...
import UnrevealedMineCell from ...

...
  methods: {
    getProps (cell) {
        if(cell.revealed){
           if(cell.isMine) {
               return {};
            } else {
               return {
                   mineNeighbours: cell.mineNeighbours
               };
            }
        } else {
            return {
                 unrevealedCell: cell,
                 ...
                 ...
                 cellClicked: this.onCellClicked
                 ...
                 ...
            };
        }
    },
    getCellComponent (cell) {
       if(cell.revealed){
           if(cell.isMine) {
               return RevealedMineCell;
            } else {
               return RevealedNeutralCell;
            }
        } else {
            return UnrevealedCell;
        }
  }
...


问:
Program to view what a webpage would look through a mobile phone
I know this might off subject but what's a good program let's me view what a website might look like on a iPhone or other mobile device which connects to the Internet. Dreamweaver cs3 might have this but I can't find it anyone know?</p>

答: Iphone Similutor is one which i use and its work perfectally fine and its avlaible with iphone SDK</p>

OwnerDisplayName: Sarmenhb

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Ashutosh Singh


问:
What purpose does a .DDF file have?
Hey can someone tell me what the Field, File and Index .ddf files do in pervasive. Do they have to changed or be updated when a table definition changes? Any insight would be GREATLY appreciated.

Cheers.

答:
FILE.DDF links the underlying Btrieve Data files to a logical table name.

FIELD.DDF uses the File Id from FILE.DDF to define all of the fields including offsets, data types, etc for each table.

INDEX.DDF defines the indexes on the fields in FIELD.DDF.

They are the field information meta date used by PSQL to access the data files in a relation access method (ODBC, OLEDB, ADO.NET, etc).

They do have to be changed if the underlying data file is changed through Btrieve.  If the table definition changes through SQL (like ALTER TABLE statements), the Pervasive Control Center, DTI (Distributed Tuning Interface), DTO (Distributed Tuning Object), PDAC, ActiveX, or DDF Builder then the DDFs are updated automatically.

Title: What purpose does a .DDF file have?


问:
Calling write! is outputting string wrapped in Ok() in rust
When trying to read a file and write it to another file, each line is getting wrapped inside of Ok() when using write!. I have been unable to discover what I am doing wrong, hopefully someone will have an idea.

I have been able to isolate the issue to something having to do with the {:#?}.

If I put regulat text in the "" it prints fine and outside the Ok(). Has anyone else come across this?

Thanks

use std::fs::File;
use std::io::{BufReader, BufRead};
use std::io::{Write, Error};

fn main() -> Result<(), Error> {

    let ofile = File::open("test.xml")?;
    let mut new_file = File::create("output.xml")?;
    let input = BufReader::new(ofile);

    for line in input.lines() {
        write!(new_file, "{:#?}", line)?;
    }

    Ok(())
}
```

<p>Input</p>

<pre class="lang-xml prettyprint-override"><code><?xml version = '1.0' encoding = 'UTF-8'?>
<Configuration xmlns="configuration" configType="TEST_RULE" actionType="NEW RULE">
   <Reference>
      <Code>AV</Code>
      <Name>TESTER</Name>
   </Reference>
   <ConfigItems>
      <ConfigItem>
         <description>Test Description</description>
      </ConfigItem>
   </ConfigItems>
</Configuration>

</code>```

Resultant output

```<code>Ok(
    "<?xml version = \'1.0\' encoding = \'UTF-8\'?>"
)Ok(
    "<Configuration xmlns=\"configuration\" configType=\"TEST_RULE\" actionType=\"NEW RULE\">"
)Ok(
    "   <Reference>"
)Ok(
    "      <Code>AV</Code>"
)Ok(
    "      <Name>TESTER</Name>"
)Ok(
    "   </Reference>"
)Ok(
    "   <ConfigItems>"
)Ok(
    "      <ConfigItem>"
)Ok(
    "         <description>Test Description</description>"
)Ok(
    "      </ConfigItem>"
)Ok(
    "   </ConfigItems>"
)Ok(
    "</Configuration>"
)
</code>```

Fix:
As per the response below, I changed the write! to the following and it fixed the issue.

write!(new_file, "{}\n", line?)?;

```

答:
Calling .lines() on a BufReader gives you an io::Lines, whose associated Item-type is std::io::Result<String>. That is, while iterating over .lines(), the iterator yields either an Ok(String) (in case the read succeeded) or an Err(io::Error) (in case an io-error occured while reading the next line). That is why you see Ok(...) being printed.

It's common to see something like the following:

```<code>for line in input.lines() {
    // If `line` is `Ok(String)`, re-assign `line`; return the error otherwise.
    let line = line?;
    // Possible read-errors have been dealt with, `line` is a `String`.
    write!(new_file, "{:#?}", line)?;
}
</code>```

In case you are confused about the type of something, it is also common practice to assign to a variable of either your expected or some "absurd" type, just to get the compiler to yell at you.

```<code>for line in input.lines() {
    let line: String = line; // line should be a String, right?
    let line: () = line; // I have no idea what line is, but it's not () for sure
    write!(new_file, "{:#?}", line)?;
}
</code>```

Both let line: ... = line will cause the compiler to raise an error because line is Result<String> and can't be assigned to a variable that is fixed to some other type; now you know that line is actually Result<String> and not String as expected.

Body:
When trying to read a file and write it to another file, each line is getting wrapped inside of Ok() when using write!. I have been unable to discover what I am doing wrong, hopefully someone will have an idea.

I have been able to isolate the issue to something having to do with the {:#?}.

If I put regulat text in the "" it prints fine and outside the Ok(). Has anyone else come across this?

Thanks

use std::fs::File;
use std::io::{BufReader, BufRead};
use std::io::{Write, Error};

fn main() -> Result<(), Error> {

    let ofile = File::open("test.xml")?;
    let mut new_file = File::create("output.xml")?;
    let input = BufReader::new(ofile);

    for line in input.lines() {
        write!(new_file, "{:#?}", line)?;
    }

    Ok(())
}

Input

<?xml version = '1.0' encoding = 'UTF-8'?>
<Configuration xmlns="configuration" configType="TEST_RULE" actionType="NEW RULE">
   <Reference>
      AV
      <Name>TESTER</Name>
   </Reference>
   <ConfigItems>
      <ConfigItem>
         <description>Test Description</description>
      </ConfigItem>
   </ConfigItems>
</Configuration>

Resultant output

Ok(
    "<?xml version = \'1.0\' encoding = \'UTF-8\'?>"
)Ok(
    "<Configuration xmlns=\"configuration\" configType=\"TEST_RULE\" actionType=\"NEW RULE\">"
)Ok(
    "   <Reference>"
)Ok(
    "      AV"
)Ok(
    "      <Name>TESTER</Name>"
)Ok(
    "   </Reference>"
)Ok(
    "   <ConfigItems>"
)Ok(
    "      <ConfigItem>"
)Ok(
    "         <description>Test Description</description>"
)Ok(
    "      </ConfigItem>"
)Ok(
    "   </ConfigItems>"
)Ok(
    "</Configuration>"
)

Fix:
As per the response below, I changed the write! to the following and it fixed the issue.

write!(new_file, "{}\n", line?)?;

Body:
Calling .lines() on a BufReader gives you an io::Lines, whose associated Item-type is std::io::Result<String>. That is, while iterating over .lines(), the iterator yields either an Ok(String) (in case the read succeeded) or an Err(io::Error) (in case an io-error occured while reading the next line). That is why you see Ok(...) being printed.

It's common to see something like the following:

for line in input.lines() {
    // If `line` is `Ok(String)`, re-assign `line`; return the error otherwise.
    let line = line?;
    // Possible read-errors have been dealt with, `line` is a `String`.
    write!(new_file, "{:#?}", line)?;
}

In case you are confused about the type of something, it is also common practice to assign to a variable of either your expected or some "absurd" type, just to get the compiler to yell at you.

for line in input.lines() {
    let line: String = line; // line should be a String, right?
    let line: () = line; // I have no idea what line is, but it's not () for sure
    write!(new_file, "{:#?}", line)?;
}

Both let line: ... = line will cause the compiler to raise an error because line is Result<String> and can't be assigned to a variable that is fixed to some other type; now you know that line is actually Result<String> and not String as expected.


问:
Understanding undocumented Vue.js attributes ( Vue + Pug )
So i was just browsing through certain vue.js code HERE. and came across the following code below:

```<code>menu-dropdown.task-dropdown(
  v-if="!isRunningYesterdailies",
  :right="task.type === 'reward'",
  ref="taskDropdown",
  v-b-tooltip.hover.top="$t('options')"
)
</code>```

I don't quite understand this attribute :right that is inserted in the code ? What is it doing and what is its purpose , i am new to Vue.js , but by looking around a bit i was able to find documentation for the rest of the attributes except this attribute called :right ? Can anybody shed some light on this ?

答:
The : in front of html attributes is a shorthand for the v-bind directive. what v-bind allows you to do is have a variable value to the specified html attribute.
ex: v-bind:alt="kittenPhotoDescription" is the same as doing alt:"kittenPhotoDescription".

Here is where it's found in the docs.

Body:
So i was just browsing through certain vue.js code HERE. and came across the following code below:

menu-dropdown.task-dropdown(
  v-if="!isRunningYesterdailies",
  :right="task.type === 'reward'",
  ref="taskDropdown",
  v-b-tooltip.hover.top="$t('options')"
)

I don't quite understand this attribute :right that is inserted in the code ? What is it doing and what is its purpose , i am new to Vue.js , but by looking around a bit i was able to find documentation for the rest of the attributes except this attribute called :right ? Can anybody shed some light on this ?


问:
Speech to text app replaces old text with new
The app overwrites the old text with the new one but that's not the purpose. I want the new text to retain old text in addition to new, like turning old and new into strings and then combining them?</p>

```<code>final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);

final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {

    @Override
    public void onResults(Bundle bundle) {
        //getting all the matches
        ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

        //displaying the first match
        if (matches != null)
            resultText.setText(matches.get(0));
    }

});
</code>```

答:
So you want to append the results to the TextView ?

That's easy:

```<code>resultText.append(matches.get(0));
</code>```

With space:

```<code>resultText.append(" " + matches.get(0));
</code>```

Another way:

```<code>resultText.setText(resultText.getText() + " " + matches.get(0));
</code>```

Body:
The app overwrites the old text with the new one but that's not the purpose. I want the new text to retain old text in addition to new, like turning old and new into strings and then combining them?

final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);

final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {

    @Override
    public void onResults(Bundle bundle) {
        //getting all the matches
        ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

        //displaying the first match
        if (matches != null)
            resultText.setText(matches.get(0));
    }

});

Body:
So you want to append the results to the TextView ?

That's easy:

resultText.append(matches.get(0));

With space:

resultText.append(" " + matches.get(0));

Another way:

resultText.setText(resultText.getText() + " " + matches.get(0));


问:
In flutter how i can check if location is enabled?
I have problem when user entered google map page without location enabled the map wont updated so i want to check if the user have location enabled  beforehand so i need function  that return true if location enabled  and false if not.</p>

答:
use permission handler plugin

```<code>ServiceStatus serviceStatus = await PermissionHandler().checkServiceStatus(PermissionGroup.location);
bool enabled = (serviceStatus == ServiceStatus.enabled);
</code>```

you can also show a rationale for requesting permission (Android only)

```<code>bool isShown = await PermissionHandler().shouldShowRequestPermissionRationale(PermissionGroup.location);
</code>```

or Location Plugin

```<code>var location = Location();
bool enabled = await location.serviceEnabled();
</code>```

and request to enable it by

```<code>bool gotEnabled = await location.requestService();
</code>```

Body:
use permission handler plugin

ServiceStatus serviceStatus = await PermissionHandler().checkServiceStatus(PermissionGroup.location);
bool enabled = (serviceStatus == ServiceStatus.enabled);

you can also show a rationale for requesting permission (Android only)

bool isShown = await PermissionHandler().shouldShowRequestPermissionRationale(PermissionGroup.location);

or Location Plugin

var location = Location();
bool enabled = await location.serviceEnabled();

and request to enable it by

bool gotEnabled = await location.requestService();


问:
Passing tokens from lexer to parser
I am writing a handcrafted lexer and a parser in C++. I have written the lexer in such a way that if it finds for example a ; it prints "SEMICOLON", if it finds while it prints "KEYWORD", if it finds hello it prints "IDENTIFIER" ,etc,etc. However now I need to pass these tokens to a parser. How can this be done for example using a list? And I found that I need to store the token type and token value

答:
You are obviously not using the classical approach, where a parser calls a scanner to get the next token. Usually pull parsers are used. Meaning, the Parser pulls tokens from the Scanner (Lexer) by calling a corresponding function. The most common scanner/parser-generators Lex/Yacc or Flex/Bison use this approach. So, the parser calls something like getNextToken and then the scanner reads bytes from the input stream, until it finds a token. It will not return before the token (or an error) has been detected.

There are also push parsers. Here the input stream is read by the parser or something else (e.g. a socket) and then stuffed into the scanner, until a token can be identified, which is then returned. This is a little bit more complicated, because the scanner needs to maintain the state. Latest Bison versions support this method.

Common for both is is the use of a class or struct (POD) "Token". This class contains usually the token type and one ore more attributes, like a value. And many, often overloaded, setters and getters. This is normally the main interface between parser ans scanner.

As far as I understand your approach, you are first running the scanner, consume the whole input and collect all tokens. Also possible. You would then store all tokens (as dscribed above) in a std::vector (or other stl::container). The vector will then be accessed by the parser.

For this communication you could use the mediator pattern or you can embed the container in a "context"-class and exchange this between the scanner and the parser.

You can also add a member function to your scanner class (getToken) which returns one element of your container of tokens. For that you need to maintain state. An iterator for your scanner that would basically call the iterator of the underlying container, would also be a good proposal. With that you can easily iterate over your tokens and implement (maybe) necessary actions like reading a look ahead symbol or "unget" something.

The above should basically answer your questions.

And, for easy grammars this will work. But for more complex grammars I would recommend the classical approach. There may be a necessity for context dependent scanning. E.g. the same keyword may produce a different token. This cannot be handled by your approach.

I would recommend to read about Lex and Yacc, not because you should use it, but to get a deeper understanding. Or, of course, read the Dragon book or something like "Crafting a Compiler with C"

You may also want to look at 2 compiler examples here

Hope I could help a little.

Title: Passing tokens from lexer to parser


问:
Classloader specific properties
We developed an application container that creates a new classloader for each independent application running in the container.  When a specific application is invoked, the Thread's context classloader is set appropriately with the application's classloader.

Avoiding the use of ThreadLocal, is it possible to store properties within a classloader, such that you would be able to retrieve, in this case, application-specific properties directly from the classloader.

For example, I want to be able to somehow save and then later retrieve properties when accessing the context classloader:

```<code>Thread.currentThread().getContextClassLoader()
</code>```

Is this possible?  Or is ThreadLocal the only viable option?

答:
Rather than casting the classloader, you can have it load a custom properties class, e.g.

```<code>public class AppClassloaderProperties
{
   static Properties appProperties = loadAppProperties();

   static private Properties loadAppProperties() {
        // fetch app properties - does not need to be thread-safe, since each invocation
        // of this method will be on a different .class instance
   }

   static public final Properties getApplicationProperties() {
      // this method should be thread-safe, returning the immutable properties is simplest
      return new Properties(appProperteis);
   }
}
</code>```

Since this class is loaded as part of the application's classloader, a new class is provided for each application. The AppClassloaderProperties class for each application will be distinct. Each application can then get its classloader properties by calling

```<code>Properties props = AppClassloaderProperties.getApplicationProperties();
// use the properties
</code>```

No need for thread locals or casting the current classloader.

Title: Classloader specific properties

Body:
We developed an application container that creates a new classloader for each independent application running in the container.  When a specific application is invoked, the Thread's context classloader is set appropriately with the application's classloader.

Avoiding the use of ThreadLocal, is it possible to store properties within a classloader, such that you would be able to retrieve, in this case, application-specific properties directly from the classloader.

For example, I want to be able to somehow save and then later retrieve properties when accessing the context classloader:

Thread.currentThread().getContextClassLoader()

Is this possible?  Or is ThreadLocal the only viable option?

Body:
Rather than casting the classloader, you can have it load a custom properties class, e.g.

public class AppClassloaderProperties
{
   static Properties appProperties = loadAppProperties();

   static private Properties loadAppProperties() {
        // fetch app properties - does not need to be thread-safe, since each invocation
        // of this method will be on a different .class instance
   }

   static public final Properties getApplicationProperties() {
      // this method should be thread-safe, returning the immutable properties is simplest
      return new Properties(appProperteis);
   }
}

Since this class is loaded as part of the application's classloader, a new class is provided for each application. The AppClassloaderProperties class for each application will be distinct. Each application can then get its classloader properties by calling

Properties props = AppClassloaderProperties.getApplicationProperties();
// use the properties

No need for thread locals or casting the current classloader.


问:
How to count sum of occurrences of my list of words in dataframe row?
I want to count the occurrences of words of my list in a given dataframe column for each line.

Code:

```<code> d2 = {}
 for key, lst in dict_.items():
    col_names = [element for element in lst if isinstance(element, str)]
    regex_lists = [element for element in lst if isinstance(element, list)]
    regex_list = functools.reduce(lambda x, y: x+y, regex_lists)
    map_function = lambda s: len(re.findall(r'|'.join(regex_list).lower(),  str(s).lower()))
   df_regex_count = df[col_names].applymap(map_function)
   df[key] = [sum(lst_tmp) for lst_tmp in    df_regex_count.values.tolist()]
</code>```

My dataframe is:

```<code> d = {'Column_1': ['mango juice pret Orange No manner  Emman snow', ' préts No  scan eblanc'],}
 df = pd.DataFrame(data=d)
</code>```

My list of words

```<code>list_1 = ['mango juice', 'Mango' ,'Orange', 'pr[éeêè]t[s]?']
dict = {"s1": ['Column_1', list_1]}
</code>```

The output of s1 is [3,1] but it must me [4,1]. Because 'mango juice',mango,Orange,pret

dictionary

Creation of lists for csv file.

```<code>df['Word'] = r'\b' + df[' Word'].astype(str) + r'\b'
df.groupby('Country').agg(",".join).reset_index()
group1 =df[df['Country']== 1]
list1.append("|".join(group1['Word']))
</code>```

答:
re.findall returns all non-overlapping matches of a pattern in a string.

It means that the string is consumed while searching for a match in the pattern. So if a substring of a match is a match itself, is missed.

This is what happens with 'mango' and 'mango juice' in your case, since your regex combines all the strings to be matched with an or.

If you want to look for overlapping cases, do not combine the words to search with | in the regex but perform a search for each word.

```<code>def map_function(s, reglst):
    matches = [len(re.findall(rg.lower(), s.lower())) for rg in reglst]
    return sum(matches)
</code>```

Here I redefine your map_function. It uses a list comprehension to perform re.findall once for each single word of regex_list and returns the sum of all occurrences.

Then your code would be:

```<code>for key, lst in dict_.items():
    col_names = [element for element in lst if isinstance(element, str)]
    regex_lists = [element for element in lst if isinstance(element, list)]
    regex_list = functools.reduce(lambda x, y: x+y, regex_lists)
    df_regex_count = df[col_names].applymap(lambda s : map_function(s, regex_list))
    df[key] = [sum(lst_tmp) for lst_tmp in df_regex_count.values.tolist()]
</code>```

Now df s:

```<code>                                        Column_1  s1
0  mango juice pret Orange No manner  Emman snow   4
1                          préts No  scan eblanc   1
</code>```

EDIT

You need your regex list list1 to be something of the like:

```<code>list1 = [r'\bmango juice\b', r'\bMango\b' ,r'\bOrange\b', r'\bpr[éeêè]t[s]?\b']
</code>```

So a list which one word per element. Looking at your code, you probably can create it in this way:

```<code>df['Word'] = r'\b' + df[' Word'].astype(str) + r'\b'
df.groupby('Country').agg(",".join).reset_index()
group1 =df[df['Country']== 1]
list1.extend(group1['Word'])
</code>```

Body:
I want to count the occurrences of words of my list in a given dataframe column for each line.

Code:

 d2 = {}
 for key, lst in dict_.items():
    col_names = [element for element in lst if isinstance(element, str)]
    regex_lists = [element for element in lst if isinstance(element, list)]
    regex_list = functools.reduce(lambda x, y: x+y, regex_lists)
    map_function = lambda s: len(re.findall(r'|'.join(regex_list).lower(),  str(s).lower()))
   df_regex_count = df[col_names].applymap(map_function)
   df[key] = [sum(lst_tmp) for lst_tmp in    df_regex_count.values.tolist()]

My dataframe is:

 d = {'Column_1': ['mango juice pret Orange No manner  Emman snow', ' préts No  scan eblanc'],}
 df = pd.DataFrame(data=d)

My list of words

list_1 = ['mango juice', 'Mango' ,'Orange', 'pr[éeêè]t[s]?']
dict = {"s1": ['Column_1', list_1]}

The output of s1 is [3,1] but it must me [4,1]. Because 'mango juice',mango,Orange,pret

dictionary

Creation of lists for csv file.

df['Word'] = r'\b' + df[' Word'].astype(str) + r'\b'
df.groupby('Country').agg(",".join).reset_index()
group1 =df[df['Country']== 1]
list1.append("|".join(group1['Word']))

Body:
re.findall returns all non-overlapping matches of a pattern in a string.

It means that the string is consumed while searching for a match in the pattern. So if a substring of a match is a match itself, is missed.

This is what happens with 'mango' and 'mango juice' in your case, since your regex combines all the strings to be matched with an or.

If you want to look for overlapping cases, do not combine the words to search with | in the regex but perform a search for each word.

def map_function(s, reglst):
    matches = [len(re.findall(rg.lower(), s.lower())) for rg in reglst]
    return sum(matches)

Here I redefine your map_function. It uses a list comprehension to perform re.findall once for each single word of regex_list and returns the sum of all occurrences.

Then your code would be:

for key, lst in dict_.items():
    col_names = [element for element in lst if isinstance(element, str)]
    regex_lists = [element for element in lst if isinstance(element, list)]
    regex_list = functools.reduce(lambda x, y: x+y, regex_lists)
    df_regex_count = df[col_names].applymap(lambda s : map_function(s, regex_list))
    df[key] = [sum(lst_tmp) for lst_tmp in df_regex_count.values.tolist()]

Now df s:

                                        Column_1  s1
0  mango juice pret Orange No manner  Emman snow   4
1                          préts No  scan eblanc   1

EDIT

You need your regex list list1 to be something of the like:

list1 = [r'\bmango juice\b', r'\bMango\b' ,r'\bOrange\b', r'\bpr[éeêè]t[s]?\b']

So a list which one word per element. Looking at your code, you probably can create it in this way:

df['Word'] = r'\b' + df[' Word'].astype(str) + r'\b'
df.groupby('Country').agg(",".join).reset_index()
group1 =df[df['Country']== 1]
list1.extend(group1['Word'])


问:
Could not install 'xlwings' in my Ubuntu machine
I am trying to install xlwings module in my Ubuntu machine but failed as below

```<code>pip3 install xlwings
Collecting xlwings
  Using cached https://files.pythonhosted.org/packages/cc/c9/6bb1849dbee6e8a40beb9a0d21df9787bee45cda1d0bb575a0cd388dd260/xlwings-0.15.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-u90aes_a/xlwings/setup.py", line 33, in <module>
        raise OSError("currently only Windows and OSX are supported.")
    OSError: currently only Windows and OSX are supported.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-u90aes_a/xlwings/
</code>```

What is the resolution of this error? Is xlwings not supported in Ubuntu? I also tried to install the same manually as below but failed too.

```<code>cd xlwings
python setup.py install
</code>```

Any suggestion will be highly appreciated.

Update on 10th July 2019

I ran code export INSTALL_ON_LINUX=1 and then installed xlwings. Installation was fine.
However when I tried to import xlwings in Python, that failed with below error:

```<code>Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import xlwings
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/xlwings/__init__.py", line 44, in <module>
    from . import _xlmac as xlplatform
  File "/usr/local/lib/python3.6/dist-packages/xlwings/_xlmac.py", line 10, in <module>
    import aem
ModuleNotFoundError: No module named 'aem'
</code>```

I could not install package aem with below error:

```<code>pip3 install aem
Collecting aem
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/aem/
</code>```

Any solution will be highly appreciated.

答: You could potentially install Anaconda for Windows within Wine and then also install Excel within Wine and then maybe, maybe (no promises), you might find that xlwings... just... might... work... ... but there will likely be many speed bumps along the way...

Body:
I am trying to install xlwings module in my Ubuntu machine but failed as below

pip3 install xlwings
Collecting xlwings
  Using cached https://files.pythonhosted.org/packages/cc/c9/6bb1849dbee6e8a40beb9a0d21df9787bee45cda1d0bb575a0cd388dd260/xlwings-0.15.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-u90aes_a/xlwings/setup.py", line 33, in <module>
        raise OSError("currently only Windows and OSX are supported.")
    OSError: currently only Windows and OSX are supported.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-u90aes_a/xlwings/

What is the resolution of this error? Is xlwings not supported in Ubuntu? I also tried to install the same manually as below but failed too.

cd xlwings
python setup.py install

Any suggestion will be highly appreciated.

Update on 10th July 2019

I ran code export INSTALL_ON_LINUX=1 and then installed xlwings. Installation was fine.
However when I tried to import xlwings in Python, that failed with below error:

Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import xlwings
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/xlwings/__init__.py", line 44, in <module>
    from . import _xlmac as xlplatform
  File "/usr/local/lib/python3.6/dist-packages/xlwings/_xlmac.py", line 10, in <module>
    import aem
ModuleNotFoundError: No module named 'aem'

I could not install package aem with below error:

pip3 install aem
Collecting aem
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/aem/

Any solution will be highly appreciated.


问:
Conditional formatting based on another cell's text
I have a Google Sheets table of names and statistics that go along with said names. I'm trying to use a dropdown menu on a specific cell so that when I select a specific name from the dropdown, all of the cells that start with the same name will be highlighted.</p>

答:
Assuming the dropdown is in B2. Please select entire sheet and: Format > Conditional formatting..., Format cells if... Custom formula is and:

```<code>=regexmatch(A1,"^"&$B$2)
</code>```

with highlighting of your choice and Done.

Since for all of the cells that start with the same name this could be slow.

Body:
Assuming the dropdown is in B2. Please select entire sheet and: Format > Conditional formatting..., Format cells if... Custom formula is and:

=regexmatch(A1,"^"&$B$2)

with highlighting of your choice and Done.

Since for all of the cells that start with the same name this could be slow.


问:
How to change a thread's Runnable target during runtime
I want to build my own ExecutorService in Java which is able to 'submit(Callable task)' a given task.
I intended to use a thread pool comprising several 'Threads(Runnable target)'.
The idea is to create a fixed number of threads which dequeue FutureTask objects from a list that has been filled by the 'submit' method. The FutureTask objects have been created within the submit method as well.
My problem is that I can only hand over a Runnable object(here: FutureTask) to a thread when the thread is created (via constructor), but obviously FutureTasks need to be assigned to a thread dynamically (when the item is removed from the list).
Is there any way to do this?</p>

```<code>// content of submit, parameter: myTask
FutureTask<V> newFutureTask = new FutureTask<V>(myTask);
taskQueue = new BlockingQueue<FutureTask<V>>();
try {
    taskQueue.put(newFutureTask);
} catch (InterruptedException ex) { }
return newFutureTask;

// remove item from list and hand it over to thread
// method within MyThread extends Thread (thread pool) class
void exec() {
    FutureTask<V> task;
    try {
        task = taskQueue.take();
        // TODO: run task somehow????
        } catch(InterruptedException ex) { }
}
</code>```

答:
See a bit of pseudo code:

```<code>while (true) {
   task = fetch task
   If no task: wait/yield
   Else: execute task
}
</code>```

In other words: you simply have to implement a run() method that loops and executes the run method of any Runnable (or whatever is passed to it). If no work is available, that methods sleeps, or waits to be notified.

Body:
I want to build my own ExecutorService in Java which is able to 'submit(Callable task)' a given task.
I intended to use a thread pool comprising several 'Threads(Runnable target)'.
The idea is to create a fixed number of threads which dequeue FutureTask objects from a list that has been filled by the 'submit' method. The FutureTask objects have been created within the submit method as well.
My problem is that I can only hand over a Runnable object(here: FutureTask) to a thread when the thread is created (via constructor), but obviously FutureTasks need to be assigned to a thread dynamically (when the item is removed from the list).
Is there any way to do this?

// content of submit, parameter: myTask
FutureTask<V> newFutureTask = new FutureTask<V>(myTask);
taskQueue = new BlockingQueue<FutureTask<V>>();
try {
    taskQueue.put(newFutureTask);
} catch (InterruptedException ex) { }
return newFutureTask;

// remove item from list and hand it over to thread
// method within MyThread extends Thread (thread pool) class
void exec() {
    FutureTask<V> task;
    try {
        task = taskQueue.take();
        // TODO: run task somehow????
        } catch(InterruptedException ex) { }
}

Body:
See a bit of pseudo code:

while (true) {
   task = fetch task
   If no task: wait/yield
   Else: execute task
}

In other words: you simply have to implement a run() method that loops and executes the run method of any Runnable (or whatever is passed to it). If no work is available, that methods sleeps, or waits to be notified.


问:
Setup: C++ in VS Code under Linux (tasks.json and launch.json)
How to configure VS Code launch.json for C++ development under Linux?

The official documentation does not provide a launch.json sampleofficial documentation for WSL.

Unfortunately, I can not get a succesful build and debug configuration of tasks.json and launch.json for "pure Linux/no WSL".

I am looking for recent versions of the two files, that are as generic as possible (use variables wherever possible in the json-files).

My current c_cpp_properties.json:

```<code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}
</code>```

答:
Try this .vscode/launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}
```
<p>And <code>.vscode/tasks.json</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                // "cwd": "/usr/bin"
                "cwd": "${workspaceFolder}"
            }
        }
    ],
    "version": "2.0.0"
}
</code>```

Body:
How to configure VS Code launch.json for C++ development under Linux?

The official documentation does not provide a launch.json sampleofficial documentation for WSL.

Unfortunately, I can not get a succesful build and debug configuration of tasks.json and launch.json for "pure Linux/no WSL".

I am looking for recent versions of the two files, that are as generic as possible (use variables wherever possible in the json-files).

My current c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}

Body:
Try this .vscode/launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

And .vscode/tasks.json:

{
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                // "cwd": "/usr/bin"
                "cwd": "${workspaceFolder}"
            }
        }
    ],
    "version": "2.0.0"
}


问:
Incorrect utf-8 characters displayed in node.js, how to fix that?
I am a beginner in node.js and i tried to set up a HTTP server. I came from web Javascript and i know very little about node.js. I tried a code from nodejs.org, which worked, but when i tried characters like this "á" or "Š", it displayed incorrectly.

I tried using libraries like express.js, it fixed the problem, but i am vanilla - i don't like librariess and it proved difficult for me to even show different pages with different URLs.

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

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Vítejte na mojí webové stránce!');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
</code>```

The result:
VĂtejte na mojĂ webovĂ© strĂˇnce!

答:
What @thomas said: You need to send a header to the browser to tell it which character set to use rendering your text.

```<code>res.setHeader('Content-Type', 'text/plain; charset=utf-8');
</code>```

Some browsers on some host machines may sometimes do the right thing rendering text if you don't do this. But you should not rely on that chance, especially for plain text.

Pro tip: The entire point of nodejs as a platform is to organize your use of good libraries. Node is not a block of wood from which you carve a sculpture, it's a set of lego blocks: really good lego blocks. There's no point in avoiding libraries unless you want to reinvent the flat tire.  You can't avoid them: you use the http library already. (Yes, it's built in, but it's still a library.)

It's fine to learn by using minimal libraries. But if you want to actually serve rendered html or files from your file system, you need to use express.

Body:
I am a beginner in node.js and i tried to set up a HTTP server. I came from web Javascript and i know very little about node.js. I tried a code from nodejs.org, which worked, but when i tried characters like this "á" or "Š", it displayed incorrectly.

I tried using libraries like express.js, it fixed the problem, but i am vanilla - i don't like librariess and it proved difficult for me to even show different pages with different URLs.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Vítejte na mojí webové stránce!');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

The result:
VĂtejte na mojĂ webovĂ© strĂˇnce!

Body:
What @thomas said: You need to send a header to the browser to tell it which character set to use rendering your text.

res.setHeader('Content-Type', 'text/plain; charset=utf-8');

Some browsers on some host machines may sometimes do the right thing rendering text if you don't do this. But you should not rely on that chance, especially for plain text.

Pro tip: The entire point of nodejs as a platform is to organize your use of good libraries. Node is not a block of wood from which you carve a sculpture, it's a set of lego blocks: really good lego blocks. There's no point in avoiding libraries unless you want to reinvent the flat tire.  You can't avoid them: you use the http library already. (Yes, it's built in, but it's still a library.)

It's fine to learn by using minimal libraries. But if you want to actually serve rendered html or files from your file system, you need to use express.


问:
How to have text closer to image?
I've been fiddling around with Css and got to have my text and image be responsive on mobile. When I shrink my browser the image the text shrinks to show the image, but now my lorem ipsum text is pushed down. I'm not using padding or margin for this to happen, I'm trying to keep all of my text in a div but there seems to be alot of margin on text.

I've looked over my code and couldn't find anything that would cause this, and delete each segment of code to try and see if it fixes the problem. Nothing seems to work.

html:

```<code><body>

    <table >
    <tr>
        <td >Home</td> <!--Made 8 boxes, 100%/8boxes is 12.5, so to make them even just assign 12.5%-->
        <td >About Us</td> <!--Can see how CSS comes in handy...could just call td{width:12.5%; align:center;-->
        <td`enter code here` >Contact Us</td>
        <td >Menus</td>
        <td >Varieties</td>
        <td >Feedback</td>
        <td >SignUp</td>
        <td >Login</td>
    </tr>
    </table>

    <p id="mainWall"></p>
    <h1 class="mImageText">Paratore's Pizza</h1>

    <p>
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
    </p>

</body>
</html>

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    height: 75vh;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    top: 50%;
    transform: translateY(-175%);
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }
</code>```

I expect the text to come closer to the image instead of being all the way down requiring a scroll

答: Your mImageText class has a translateY of -175%. This, plus the height of the mainWall class is causing the gap. Try changing the height of mainWall to something smaller, like 10vh, and remove the translateY from mImageText

Title: How to have text closer to image?

Body:
I've been fiddling around with Css and got to have my text and image be responsive on mobile. When I shrink my browser the image the text shrinks to show the image, but now my lorem ipsum text is pushed down. I'm not using padding or margin for this to happen, I'm trying to keep all of my text in a div but there seems to be alot of margin on text.

I've looked over my code and couldn't find anything that would cause this, and delete each segment of code to try and see if it fixes the problem. Nothing seems to work.

html:

        Home
        About Us
        <td`enter code here` >Contact Us
        Menus
        Varieties
        Feedback
        SignUp
        Login

Paratore's Pizza

        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    height: 75vh;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    top: 50%;
    transform: translateY(-175%);
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }

I expect the text to come closer to the image instead of being all the way down requiring a scroll


问:
Get a PHP object's ancestors in the inheritance tree
I have an object and want to list all parent classes up until stdClass or whatever.

I have added a polymorphic field to my database table (say categories) and want to automate my finder method so that super classes are also returned, this way i can jump into the inheritance tree at a point i know not necessarily the final subclass:

```<code>FoodCategory::find_by_id(10) === Category::find_by_id(10)

SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');
</code>```

Roughly i guess:

```<code>function get_class_lineage($object){
    $class = get_parent_class($object);
    $lineage = array();
    while($class != 'stdClass'){
        $dummy_object = new $class();
        $lineage[] = $class = get_parent_class($dummy_object);
    }

    return $lineage;
}
</code>```

But this instantiates an object, does anyone know how to achieve this without?

Thanks for any input, i feel like i'm missing something obvious here.

答:
Using Reflection

```<code>$class = new ReflectionClass($object);

$lineage = array();

while ($class = $class->getParentClass()) {
    $lineage[] = $class->getName();
}

echo "Lineage: " . implode(", ", $lineage);
</code>```

ReflectionClass accepts either the name of the class or an object.

Body:
I have an object and want to list all parent classes up until stdClass or whatever.

I have added a polymorphic field to my database table (say categories) and want to automate my finder method so that super classes are also returned, this way i can jump into the inheritance tree at a point i know not necessarily the final subclass:

FoodCategory::find_by_id(10) === Category::find_by_id(10)

SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');

Roughly i guess:

function get_class_lineage($object){
    $class = get_parent_class($object);
    $lineage = array();
    while($class != 'stdClass'){
        $dummy_object = new $class();
        $lineage[] = $class = get_parent_class($dummy_object);
    }

    return $lineage;
}

But this instantiates an object, does anyone know how to achieve this without?

Thanks for any input, i feel like i'm missing something obvious here.

Body:
Using Reflection

$class = new ReflectionClass($object);

$lineage = array();

while ($class = $class->getParentClass()) {
    $lineage[] = $class->getName();
}

echo "Lineage: " . implode(", ", $lineage);

ReflectionClass accepts either the name of the class or an object.


问:
Exit from while loop which started inside a async method
How to break the while loop which inside an async method. Please refer below code

I have tried many ways but none of them worked for me

```<code>async void TotalTimer(string time)
{
    while (true)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        await Task.Delay(1000);

        if (string.IsNullOrEmpty(time))
        {
            break;
        }
    }
}
</code>```

I need to stop and exit from the loop

Updated code:

```<code>async Task TotalTimer(CancellationToken token)
{
    var intime = await App.Database.GetRecentIn();
    InTime = DateTime.Parse(intime.datetime).ToString("hh:mm tt");

    while (!token.IsCancellationRequested)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        Console.WriteLine(TotalTime); // to see it's working
        await Task.Delay(1000);

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
}

void StatCounting()
{
    var cts = new CancellationTokenSource();
   _= TotalTimer(cts.Token);
}

void StopCounting()
{
    var cts = new CancellationTokenSource();
    cts.Cancel();
   _= TotalTimer(cts.Token);

    _=Finalize();
}
</code>```

答:
Use CancellationToken like this:

```<code>using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        private string TotalTime;

        static void Main(string[] args)
        {
            new Program().Run();
        }

        private void Run()
        {
            var cts = new CancellationTokenSource();
            TotalTimer("00:00:00", cts.Token);

            Console.ReadLine(); // waits for you to press 'Enter' to stop TotalTimer execution.
            cts.Cancel();
            Console.WriteLine("Press 'Enter' to exit the program.");
            Console.ReadLine();  // waits for you to press 'Enter' to exit the program. See, TotalTimer stopped.
        }

        // your original method modified
        async void TotalTimer(string time, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
                TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
                Console.WriteLine(TotalTime); // to see it's working
                await Task.Delay(5000, token);
            }
        }
    }
}
</code>```

Update

@Henk Holterman, according to edits history if (string.IsNullOrEmpty(time)) looks like an attempt to break the loop from outside. But it's pointless for two reasons:

strings are immutable

if time is null or empty DateTime.Parse(time) (it was in the original post) throws before the check

Adding the token to Task.Delay is a good point. Doing so saves resources, though makes no difference to observable behaviour.

Update2

@Argon, the code is independent to wpf, winforms, console or whatever. See minimal wpf example bellow. I checked it's working. If something does not work with you concrete code, you maybe hiding some details from us.

```<code>using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string TotalTime;
        private CancellationTokenSource cts;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cts = new CancellationTokenSource();
            TotalTimer("00:00:00", cts.Token);
        }

        async void TotalTimer(string time, CancellationToken token)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
                    TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
                    label1.Content = TotalTime;
                    await Task.Delay(5000, token);
                }
            }
            catch(OperationCanceledException)
            {
                label1.Content = "Canceled";
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
        }
    }
}
</code>```

Body:
How to break the while loop which inside an async method. Please refer below code

I have tried many ways but none of them worked for me

async void TotalTimer(string time)
{
    while (true)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        await Task.Delay(1000);

        if (string.IsNullOrEmpty(time))
        {
            break;
        }
    }
}

I need to stop and exit from the loop

Updated code:

async Task TotalTimer(CancellationToken token)
{
    var intime = await App.Database.GetRecentIn();
    InTime = DateTime.Parse(intime.datetime).ToString("hh:mm tt");

    while (!token.IsCancellationRequested)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        Console.WriteLine(TotalTime); // to see it's working
        await Task.Delay(1000);

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
}

void StatCounting()
{
    var cts = new CancellationTokenSource();
   _= TotalTimer(cts.Token);
}

void StopCounting()
{
    var cts = new CancellationTokenSource();
    cts.Cancel();
   _= TotalTimer(cts.Token);

    _=Finalize();
}

Body:
Use CancellationToken like this:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        private string TotalTime;

        static void Main(string[] args)
        {
            new Program().Run();
        }

        private void Run()
        {
            var cts = new CancellationTokenSource();
            TotalTimer("00:00:00", cts.Token);

            Console.ReadLine(); // waits for you to press 'Enter' to stop TotalTimer execution.
            cts.Cancel();
            Console.WriteLine("Press 'Enter' to exit the program.");
            Console.ReadLine();  // waits for you to press 'Enter' to exit the program. See, TotalTimer stopped.
        }

        // your original method modified
        async void TotalTimer(string time, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
                TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
                Console.WriteLine(TotalTime); // to see it's working
                await Task.Delay(5000, token);
            }
        }
    }
}

Update

@Henk Holterman, according to edits history if (string.IsNullOrEmpty(time)) looks like an attempt to break the loop from outside. But it's pointless for two reasons:

strings are immutable

if time is null or empty DateTime.Parse(time) (it was in the original post) throws before the check

Adding the token to Task.Delay is a good point. Doing so saves resources, though makes no difference to observable behaviour.

Update2

@Argon, the code is independent to wpf, winforms, console or whatever. See minimal wpf example bellow. I checked it's working. If something does not work with you concrete code, you maybe hiding some details from us.

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string TotalTime;
        private CancellationTokenSource cts;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cts = new CancellationTokenSource();
            TotalTimer("00:00:00", cts.Token);
        }

        async void TotalTimer(string time, CancellationToken token)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
                    TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
                    label1.Content = TotalTime;
                    await Task.Delay(5000, token);
                }
            }
            catch(OperationCanceledException)
            {
                label1.Content = "Canceled";
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
        }
    }
}


问:
Old values get duplication in For each loop
I am getting values from Firebase. But the problem occur when i try to add values in array previous values get repeated. Can anyone tell me how can i put values in Array . i want to show those values in recyclerview.

Code :

```<code>    bookCollection
            .get().addOnSuccessListener {
                booksSnapshot->
                if (!booksSnapshot.isEmpty){
                    var booksArray = arrayListOf<Book>()
                    for (bookSnapshot in booksSnapshot.documents){
                        val hashmap = bookSnapshot.data
                        hashmap?.put("id", bookSnapshot.id)
                        bookCollection.document(bookSnapshot.id).collection("pages")
                                .get().addOnSuccessListener {
                                    pagesSnapshot->
                                    hashmap?.put("page_count", pagesSnapshot.documents.size)
                                    val bookData = Gson().toJson(hashmap)
                                    val book = Gson().fromJson<Book>(bookData, Book::class.java)
                                    booksArray.add(book)
                                }

                    }
                }
            }
</code>```

Log for array :

```<code>E/books: [co.myapp.myapplication.Book@d6f7f62]
E/books: [co.myapp.myapplication.Book@d6f7f62, co.syntags.myapplication.Book@93c49b0]
</code>```

Thanks in advance

答:
You have to clear your ForEach loop booksArray before adding new values.
Because when you are adding new values that is added as the next items in your array.

Use booksArray.clear() Before adding new values where you are using booksArray.add(book)

Replace this  var booksArray = arrayListOf<Book>() With var booksArray = ArrayList<Book>()

Body:
I am getting values from Firebase. But the problem occur when i try to add values in array previous values get repeated. Can anyone tell me how can i put values in Array . i want to show those values in recyclerview.

Code :

    bookCollection
            .get().addOnSuccessListener {
                booksSnapshot->
                if (!booksSnapshot.isEmpty){
                    var booksArray = arrayListOf<Book>()
                    for (bookSnapshot in booksSnapshot.documents){
                        val hashmap = bookSnapshot.data
                        hashmap?.put("id", bookSnapshot.id)
                        bookCollection.document(bookSnapshot.id).collection("pages")
                                .get().addOnSuccessListener {
                                    pagesSnapshot->
                                    hashmap?.put("page_count", pagesSnapshot.documents.size)
                                    val bookData = Gson().toJson(hashmap)
                                    val book = Gson().fromJson<Book>(bookData, Book::class.java)
                                    booksArray.add(book)
                                }

                    }
                }
            }

Log for array :

E/books: [co.myapp.myapplication.Book@d6f7f62]
E/books: [co.myapp.myapplication.Book@d6f7f62, co.syntags.myapplication.Book@93c49b0]

Thanks in advance


问:
Rendering an array.map() in React
I am having a problem where I am trying to use array of data to render a
 element. In the code below the console logs are working fine, but the list items aren't appearing.

```<code>var Main = React.createClass({
  getInitialState: function(){
    return {
      data: dataRecent
    }
  },

  render: function(){
    return (
      <div>
        <ul>
          {
           this.state.data.map(function(item, i){
             console.log('test');
             <li>Test</li>
           })
         }
        </ul>
      </div>
    )
  }
});

ReactDOM.render(<Main />, document.getElementById('app'));
</code>```

What am I doing wrong? Please feel free to point out anything that isn't best practice.

答:
I've come cross an issue with the implementation of this solution.

If you have a custom component you want to iterate through and you want to share the state it will not be available as the .map() scope does not recognize the general state() scope.
I've come to this solution:

`

```<code>class RootComponent extends Component() {
    constructor(props) {
        ....
        this.customFunction.bind(this);
        this.state = {thisWorks: false}
        this.that = this;
    }
    componentDidMount() {
        ....
    }
    render() {
       let array = this.thatstate.map(() => {
           <CustomComponent that={this.that} customFunction={this.customFunction}/>
       });

    }
    customFunction() {
        this.that.setState({thisWorks: true})
    }
}

class CustomComponent extend Component {

    render() {
        return <Button onClick={() => {this.props.customFunction()}}
    }
}
</code>```

In constructor bind without this.that
Every use of any function/method inside the root component should be used with this.that

Title: Rendering an array.map() in React

Body:
I am having a problem where I am trying to use array of data to render a
 element. In the code below the console logs are working fine, but the list items aren't appearing.

var Main = React.createClass({
  getInitialState: function(){
    return {
      data: dataRecent
    }
  },

  render: function(){
    return (

          {
           this.state.data.map(function(item, i){
             console.log('test');

Test

           })
         }

    )
  }
});

ReactDOM.render(, document.getElementById('app'));

What am I doing wrong? Please feel free to point out anything that isn't best practice.

Body:
I've come cross an issue with the implementation of this solution.

If you have a custom component you want to iterate through and you want to share the state it will not be available as the .map() scope does not recognize the general state() scope.
I've come to this solution:

`

class RootComponent extends Component() {
    constructor(props) {
        ....
        this.customFunction.bind(this);
        this.state = {thisWorks: false}
        this.that = this;
    }
    componentDidMount() {
        ....
    }
    render() {
       let array = this.thatstate.map(() => {
           <CustomComponent that={this.that} customFunction={this.customFunction}/>
       });

    }
    customFunction() {
        this.that.setState({thisWorks: true})
    }
}

class CustomComponent extend Component {

    render() {
        return <Button onClick={() => {this.props.customFunction()}}
    }
}

In constructor bind without this.that
Every use of any function/method inside the root component should be used with this.that


问:
Does the 'S' in SQL stand for "standard" or "structured"?
I'm thinking "structured", but my dad claims that when he taught a class that involved SQL (decades ago), they used "standard".  I was wondering if this changed over time, or is he mistaken?  I googled it with "standard" and did see some pages that said that's what it stands for.  Any old timers willing to give a history lesson?</p>

答:
The original wasn't even SQL acronym, it was SEQUEL:  (from wiki)

SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL (Structured English Query Language), was designed to manipulate and retrieve data stored in IBM's original quasi-relational database management system, System R, which a group at IBM San Jose Research Laboratory had developed during the 1970s.[8] The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based Hawker Siddeley aircraft company