问:
How to add a specific word to a new column when it is a value in a list within a column
supposed my data set

```<code>name what
A    apple[red]
B    cucumber[green]
C    dog
C    orange
D    banana
D    monkey
E    cat
F    carrot
.
.
</code>```

I want to create and specify a list, and if the column contains a value contained in that list, I want to make the specified value a new column.

list value

```<code>fruit = ['apple', 'banana', 'orange']
animal = ['dog', 'monkey', 'cat']
vegetable = ['cucumber', 'carrot']
</code>```

result what I want

```<code>name what     class
A    apple    fruit
B    cucumber vegetable
C    dog      animal
C    orange   fruit
D    banana   fruit
D    monkey   animal
E    cat      animal
F    carrot   vegetable
</code>```

List values and column values do not 'match' and must be contained.

thank you for reading.

答:
Use Series.map with dictionary created from lists and swapped keys with values with flattening:

```<code>fruit = ['apple', 'banana', 'orange']
animal = ['dog', 'monkey', 'cat']
vegetable = ['cucumber', 'carrot']

d = {'fruit':fruit, 'animal':animal,'vegetable':vegetable}
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
</code>```

Loop alternative of dictionary comprehension:

```<code>d1 = {}
for oldk, oldv in d.items():
    for k in oldv:
        d1[k] = oldk
</code>```

And then:

```<code>df['class'] = df['what'].map(d1)
#if need values before first [
#df['class'] = df['what'].str.split('[').str[0].map(d1)
print (df)
  name      what      class
0    A     apple      fruit
1    B  cucumber  vegetable
2    C       dog     animal
3    C    orange      fruit
4    D    banana      fruit
5    D    monkey     animal
6    E       cat     animal
7    F    carrot  vegetable
</code>```

EDIT: For match by subtrings you can loop by dictionary d, check matching by Series.str.contains for mask and set new values:

```<code>d = {'fruit':fruit, 'animal':animal,'vegetable':vegetable}

for k, v in d.items():
    mask = df['what'].str.contains('|'.join(v))
    df.loc[mask, 'class'] = k
print (df)
  name             what      class
0    A       apple[red]      fruit
1    B  cucumber[green]  vegetable
2    C              dog     animal
3    C           orange      fruit
4    D           banana      fruit
5    D           monkey     animal
6    E              cat     animal
7    F           carrot  vegetable
</code>```

If possible multiple words is possible use words boundaries:

```<code>for k, v in d.items():
    pat = '|'.join(r"\b{}\b".format(x) for x in v)
    df.loc[ df['what'].str.contains(pat), 'class'] = k
print (df)
  name             what      class
0    A       apple[red]      fruit
1    B  cucumber[green]  vegetable
2    C              dog     animal
3    C           orange      fruit
4    D           banana      fruit
5    D           monkey     animal
6    E              cat     animal
7    F           carrot  vegetable
</code>```

Body:
supposed my data set

name what
A    apple[red]
B    cucumber[green]
C    dog
C    orange
D    banana
D    monkey
E    cat
F    carrot
.
.

I want to create and specify a list, and if the column contains a value contained in that list, I want to make the specified value a new column.

list value

fruit = ['apple', 'banana', 'orange']
animal = ['dog', 'monkey', 'cat']
vegetable = ['cucumber', 'carrot']

result what I want

name what     class
A    apple    fruit
B    cucumber vegetable
C    dog      animal
C    orange   fruit
D    banana   fruit
D    monkey   animal
E    cat      animal
F    carrot   vegetable

List values and column values do not 'match' and must be contained.

thank you for reading.

Body:
Use Series.map with dictionary created from lists and swapped keys with values with flattening:

fruit = ['apple', 'banana', 'orange']
animal = ['dog', 'monkey', 'cat']
vegetable = ['cucumber', 'carrot']

d = {'fruit':fruit, 'animal':animal,'vegetable':vegetable}
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

Loop alternative of dictionary comprehension:

d1 = {}
for oldk, oldv in d.items():
    for k in oldv:
        d1[k] = oldk

And then:

df['class'] = df['what'].map(d1)
#if need values before first [
#df['class'] = df['what'].str.split('[').str[0].map(d1)
print (df)
  name      what      class
0    A     apple      fruit
1    B  cucumber  vegetable
2    C       dog     animal
3    C    orange      fruit
4    D    banana      fruit
5    D    monkey     animal
6    E       cat     animal
7    F    carrot  vegetable

EDIT: For match by subtrings you can loop by dictionary d, check matching by Series.str.contains for mask and set new values:

d = {'fruit':fruit, 'animal':animal,'vegetable':vegetable}

for k, v in d.items():
    mask = df['what'].str.contains('|'.join(v))
    df.loc[mask, 'class'] = k
print (df)
  name             what      class
0    A       apple[red]      fruit
1    B  cucumber[green]  vegetable
2    C              dog     animal
3    C           orange      fruit
4    D           banana      fruit
5    D           monkey     animal
6    E              cat     animal
7    F           carrot  vegetable

If possible multiple words is possible use words boundaries:

for k, v in d.items():
    pat = '|'.join(r"\b{}\b".format(x) for x in v)
    df.loc[ df['what'].str.contains(pat), 'class'] = k
print (df)
  name             what      class
0    A       apple[red]      fruit
1    B  cucumber[green]  vegetable
2    C              dog     animal
3    C           orange      fruit
4    D           banana      fruit
5    D           monkey     animal
6    E              cat     animal
7    F           carrot  vegetable


来源: stackexchange

问:
Navigation destination is unknown to this NavController?
I am using the navigation graph in my project.
My activity has toolbar and navhostfragment

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.MainActivity">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:title="">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:drawableLeft="@mipmap/ic_launcher_new_round"
            android:gravity="center"
            android:text="@string/app_name"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold"
            android:visibility="gone" />

        <androidx.appcompat.widget.AppCompatImageButton
            android:id="@+id/directory"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:layout_toLeftOf="@+id/settings"
            android:background="@android:color/transparent"
            android:src="@drawable/directory"
            android:tint="@android:color/white"
            android:visibility="gone" />

        <androidx.appcompat.widget.AppCompatImageButton
            android:id="@+id/settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:layout_toLeftOf="@+id/logout"
            android:background="@android:color/transparent"
            android:src="@drawable/settings"
            android:tint="@android:color/white" />

        <androidx.appcompat.widget.AppCompatImageButton
            android:id="@+id/logout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:background="@android:color/transparent"
            android:src="@drawable/logout"
            android:tint="@android:color/white" />

    </RelativeLayout>
</androidx.appcompat.widget.Toolbar>

<fragment
    android:id="@+id/navigationHostFragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/my_toolbar"
    app:navGraph="@navigation/main" />
 </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

In the toolbar I have 2 buttons settings and logout. When I am at the home fragment the settings click work fine but when I am on any other fragment , clicking the settings gives me exception.

My navigation graph is as follows

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
app:startDestination="@id/homeFragment">

<fragment
    android:id="@+id/homeFragment"
    android:name="com.mountmeru.view.HomeFragment"
    android:label="fragment_home"
    tools:layout="@layout/fragment_home" >
    <action
        android:id="@+id/action_homeFragment_to_notificationFragment"
        app:destination="@id/notificationFragment" />
    <action
        android:id="@+id/action_homeFragment_to_categoryFragment"
        app:destination="@id/categoryFragment" />

    <action
        android:id="@+id/action_homeFragment_to_settingsFragment"
        app:destination="@id/settingsFragment" />
</fragment>
<fragment
    android:id="@+id/settingsFragment"
    android:name="com.mountmeru.view.settings.SettingsFragment"
    android:label="fragment_settings"
    tools:layout="@layout/fragment_settings" >
    <action
        android:id="@+id/action_settingsFragment_to_profileFragment"
        app:destination="@id/profileFragment" />
    <action
        android:id="@+id/action_settingsFragment_to_resetPasswordFragment"
        app:destination="@id/resetPasswordFragment" />
</fragment>
</code>```

On click code in activity for settings

```<code>  navigationController.navigate(
            R.id.action_homeFragment_to_settingsFragment)
</code>```

I get the exception when I click from notificationFragment

```<code> java.lang.IllegalArgumentException: navigation destination com.mountmeru:id/action_homeFragment_to_settingsFragment is unknown to this NavController
</code>```

答:
You declare an action just for navigating from HomeFragment to SettingsFragment. This action can only be used with HomeFragment as a starting point, so for other Fragments you get the Exception "{actionId} is unknown to this NavController".

Since you need to navigate to SettingsFragment from several starting points, you can declare a global action

```<code><action android:id="@+id/action_global_settingsFragment"
      app:destination="@id/settingsFragment"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the navigation graph in my project.
My activity has toolbar and navhostfragment

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.MainActivity">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:title="">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:drawableLeft="@mipmap/ic_launcher_new_round"
            android:gravity="center"
            android:text="@string/app_name"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold"
            android:visibility="gone" />

        <androidx.appcompat.widget.AppCompatImageButton
            android:id="@+id/directory"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:layout_toLeftOf="@+id/settings"
            android:background="@android:color/transparent"
            android:src="@drawable/directory"
            android:tint="@android:color/white"
            android:visibility="gone" />

        <androidx.appcompat.widget.AppCompatImageButton
            android:id="@+id/settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:layout_toLeftOf="@+id/logout"
            android:background="@android:color/transparent"
            android:src="@drawable/settings"
            android:tint="@android:color/white" />

        <androidx.appcompat.widget.AppCompatImageButton
            android:id="@+id/logout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:background="@android:color/transparent"
            android:src="@drawable/logout"
            android:tint="@android:color/white" />

    </RelativeLayout>
</androidx.appcompat.widget.Toolbar>

<fragment
    android:id="@+id/navigationHostFragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/my_toolbar"
    app:navGraph="@navigation/main" />
 </androidx.constraintlayout.widget.ConstraintLayout>

In the toolbar I have 2 buttons settings and logout. When I am at the home fragment the settings click work fine but when I am on any other fragment , clicking the settings gives me exception.

My navigation graph is as follows

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
app:startDestination="@id/homeFragment">

<fragment
    android:id="@+id/homeFragment"
    android:name="com.mountmeru.view.HomeFragment"
    android:label="fragment_home"
    tools:layout="@layout/fragment_home" >
    <action
        android:id="@+id/action_homeFragment_to_notificationFragment"
        app:destination="@id/notificationFragment" />
    <action
        android:id="@+id/action_homeFragment_to_categoryFragment"
        app:destination="@id/categoryFragment" />

    <action
        android:id="@+id/action_homeFragment_to_settingsFragment"
        app:destination="@id/settingsFragment" />
</fragment>
<fragment
    android:id="@+id/settingsFragment"
    android:name="com.mountmeru.view.settings.SettingsFragment"
    android:label="fragment_settings"
    tools:layout="@layout/fragment_settings" >
    <action
        android:id="@+id/action_settingsFragment_to_profileFragment"
        app:destination="@id/profileFragment" />
    <action
        android:id="@+id/action_settingsFragment_to_resetPasswordFragment"
        app:destination="@id/resetPasswordFragment" />
</fragment>

On click code in activity for settings

  navigationController.navigate(
            R.id.action_homeFragment_to_settingsFragment)

I get the exception when I click from notificationFragment

 java.lang.IllegalArgumentException: navigation destination com.mountmeru:id/action_homeFragment_to_settingsFragment is unknown to this NavController

Body:
You declare an action just for navigating from HomeFragment to SettingsFragment. This action can only be used with HomeFragment as a starting point, so for other Fragments you get the Exception "{actionId} is unknown to this NavController".

Since you need to navigate to SettingsFragment from several starting points, you can declare a global action

<action android:id="@+id/action_global_settingsFragment"
      app:destination="@id/settingsFragment"/>


问:
Custom handling Future failures in Akka Streams Flow
I try to connect multiple Flows in Akka Streams and handle their errors in different ways depending on the Flow. It can be accomplished using sth like that:

```<code>Flow[String, Either[ProcessingError, String], NotUsed]
</code>```

And then divert response to error handler based on Either value.

My problem is, that some Flows return Future[String] instead of String and I don't know how to evaluate it to be able to catch error after each Flow and handle it in custom way.

答:
To turn the Future into an Either without failing the stream, you can use

```<code>.mapAsync(1){ e =>
  val f: Future[T] = ...
  f.transformWith(_.toEither)
}
</code>```

mapAsync and mapAsyncUnordered are the idiomatic ways to evaluate futures in Akka Streams. Be aware that a failing future in those will fail the stream, to handle errors in-stream, you need to react "immediately" on the future to convert it into Try or Either.

Body:
I try to connect multiple Flows in Akka Streams and handle their errors in different ways depending on the Flow. It can be accomplished using sth like that:

Flow[String, Either[ProcessingError, String], NotUsed]

And then divert response to error handler based on Either value.

My problem is, that some Flows return Future[String] instead of String and I don't know how to evaluate it to be able to catch error after each Flow and handle it in custom way.

Body:
To turn the Future into an Either without failing the stream, you can use

.mapAsync(1){ e =>
  val f: Future[T] = ...
  f.transformWith(_.toEither)
}

mapAsync and mapAsyncUnordered are the idiomatic ways to evaluate futures in Akka Streams. Be aware that a failing future in those will fail the stream, to handle errors in-stream, you need to react "immediately" on the future to convert it into Try or Either.


问:
Delete an array element based on a value that contains a date in PHP 7
I'm trying to delete array elements older than 1 month.

All array elements contains a date value which I'm trying to compare in PHP using strtotime +1 month.

The array looks like this:

```<code>[
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "4q9fenYDD3Czy2fyTkQmIlvj-1590978189-9BBNrQE5.webp",
    "gender": "female",
    "rating": 61231,
    "date": "2020-04-08 02:23:09",
    "description": ""
  },
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "o0SuDVEytVBIMJkveNWamamF-1590990218-27UmvlNd.webp",
    "gender": "male",
    "rating": 0,
    "date": "2020-06-01 03:41:38",
    "description": ""
  }
]
</code>```

I'm checking the array with the following PHP code:

```<code>$datenow = date("Y-m-d H:i:s");
$expireDate = date("Y-m-d H:i:s",strtotime('+1 month',strtotime($datenow)));

foreach ($monthlyArray as $key => $item) {
    $gotDate = $item['date'];
    echo "Comparing Array Date: ($gotDate) with Current Date +1 month: ($expireDate) <br>";
    if ($gotDate > $expireDate) {
        echo $gotDate . " will be removed because of: " . $expireDate ."<br>";
        //unset ($monthlyArray[$key]);
    }
}

</code>```

Note that $monthlyArray contains the array above.

The results I get when I run this code:

```<code>Comparing Array Date: (2020-04-08 02:23:09) with Current Date +1 month: (2020-06-01 09:19:09)
Comparing Array Date: (2020-06-01 03:41:38) with Current Date +1 month: (2020-06-01 09:19:09)
</code>```

As you can see, the if ($gotDate > $expireDate) didn't get fired which is very odd because the first element in the array has a date set to 2020-04-08 02:23:09 which is indeed more than 1 month old.

What am I doing wrong?

答:
I think you have your logic the wrong way round; you should be comparing the datetime in $item plus one month with the current datetime, and if it's earlier than that, the item has expired and should be deleted. You can use array_filter to remove the expired items from the array:

```<code>$monthlyArray = array_filter($monthlyArray, function ($item) {
    $expiry = (new DateTime($item['date']))->modify('+1 month');
    $now = new DateTime();
    return $expiry >= $now;
});

print_r($monthlyArray);
</code>```

Output:

```<code>Array
(
    [1] => Array
        (
            [userid] => f2eca630-f89a-4b7f-b463-d834a2b50a24
            [name] => o0SuDVEytVBIMJkveNWamamF-1590990218-27UmvlNd.webp
            [gender] => male
            [rating] => 0
            [date] => 2020-06-01 03:41:38
            [description] =>
        )
)
</code>```

Demo on 3v4l.org

If performance is an issue, pre-computing $now and using strtotime will be more efficient:

```<code>$now = time();
$monthlyArray = array_filter($monthlyArray, function ($item) use ($now) {
    $expiry = strtotime('+1 month', strtotime($item['date']));
    return $expiry >= $now;
});
</code>```

and a simple foreach with unset is probably faster still:

```<code>$now = time();
foreach ($monthlyArray as $key => $item) {
    $expiry = strtotime('+1 month', strtotime($item['date']));
    if ($expiry < $now) unset($monthlyArray[$key]);
}
</code>```

Body:
I'm trying to delete array elements older than 1 month.

All array elements contains a date value which I'm trying to compare in PHP using strtotime +1 month.

The array looks like this:

[
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "4q9fenYDD3Czy2fyTkQmIlvj-1590978189-9BBNrQE5.webp",
    "gender": "female",
    "rating": 61231,
    "date": "2020-04-08 02:23:09",
    "description": ""
  },
  {
    "userid": "f2eca630-f89a-4b7f-b463-d834a2b50a24",
    "name": "o0SuDVEytVBIMJkveNWamamF-1590990218-27UmvlNd.webp",
    "gender": "male",
    "rating": 0,
    "date": "2020-06-01 03:41:38",
    "description": ""
  }
]

I'm checking the array with the following PHP code:

$datenow = date("Y-m-d H:i:s");
$expireDate = date("Y-m-d H:i:s",strtotime('+1 month',strtotime($datenow)));

foreach ($monthlyArray as $key => $item) {
    $gotDate = $item['date'];
    echo "Comparing Array Date: ($gotDate) with Current Date +1 month: ($expireDate)
";
    if ($gotDate > $expireDate) {
        echo $gotDate . " will be removed because of: " . $expireDate ."
";
        //unset ($monthlyArray[$key]);
    }
}

Note that $monthlyArray contains the array above.

The results I get when I run this code:

Comparing Array Date: (2020-04-08 02:23:09) with Current Date +1 month: (2020-06-01 09:19:09)
Comparing Array Date: (2020-06-01 03:41:38) with Current Date +1 month: (2020-06-01 09:19:09)

As you can see, the if ($gotDate > $expireDate) didn't get fired which is very odd because the first element in the array has a date set to 2020-04-08 02:23:09 which is indeed more than 1 month old.

What am I doing wrong?

Body:
I think you have your logic the wrong way round; you should be comparing the datetime in $item plus one month with the current datetime, and if it's earlier than that, the item has expired and should be deleted. You can use array_filter to remove the expired items from the array:

$monthlyArray = array_filter($monthlyArray, function ($item) {
    $expiry = (new DateTime($item['date']))->modify('+1 month');
    $now = new DateTime();
    return $expiry >= $now;
});

print_r($monthlyArray);

Output:

Array
(
    [1] => Array
        (
            [userid] => f2eca630-f89a-4b7f-b463-d834a2b50a24
            [name] => o0SuDVEytVBIMJkveNWamamF-1590990218-27UmvlNd.webp
            [gender] => male
            [rating] => 0
            [date] => 2020-06-01 03:41:38
            [description] =>
        )
)

Demo on 3v4l.org

If performance is an issue, pre-computing $now and using strtotime will be more efficient:

$now = time();
$monthlyArray = array_filter($monthlyArray, function ($item) use ($now) {
    $expiry = strtotime('+1 month', strtotime($item['date']));
    return $expiry >= $now;
});

and a simple foreach with unset is probably faster still:

$now = time();
foreach ($monthlyArray as $key => $item) {
    $expiry = strtotime('+1 month', strtotime($item['date']));
    if ($expiry < $now) unset($monthlyArray[$key]);
}


问:
How to get text from each cell of an HTML table?
In Selenium 2.0, I have no idea how to traverse through a HTML table in a webpage.  In selenium2.0 javadoc, I found two classes "TableFinder" and "TableCellFinder", but I couldn't find any examples.

I want to do something like this:

```<code>RowCount=Get how many rows are there in the html table

for each row of the table
{
   column_count=Get column count
   for each column
   {
      cell_value=get_text_from(row,col);
      Do something with cell_value
   }
}
</code>```

How can I get the text from each of the table cells?

答:
Thanks for the earlier reply.

I figured out the solutions using selenium 2.0 classes.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTableExample
{
    public static void main(String[] args)
    {
        WebDriver driver = new InternetExplorerDriver();
        driver.get("http://localhost/test/test.html");

        WebElement table_element = driver.findElement(By.id("testTable"));
        List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));

        System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
        int row_num,col_num;
        row_num=1;
        for(WebElement trElement : tr_collection)
        {
            List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
            System.out.println("NUMBER OF COLUMNS="+td_collection.size());
            col_num=1;
            for(WebElement tdElement : td_collection)
            {
                System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
                col_num++;
            }
            row_num++;
        }
    }
}
```

ContentLicense: CC BY-SA 3.0

Body:
In Selenium 2.0, I have no idea how to traverse through a HTML table in a webpage.  In selenium2.0 javadoc, I found two classes "TableFinder" and "TableCellFinder", but I couldn't find any examples.

I want to do something like this:

RowCount=Get how many rows are there in the html table

for each row of the table
{
   column_count=Get column count
   for each column
   {
      cell_value=get_text_from(row,col);
      Do something with cell_value
   }
}

How can I get the text from each of the table cells?


问:
Align output data using Python Pandas
I want to align and organized data on Output. I have an excel file which has 2 sheets - Students, Anime. I already extracted data on excel files but my problem now is the output. This is what i've tried

```<code>file = pd.read_excel("src/doc/x1/students.xlsx", sheet_name=None)
print(file)
</code>```

Output:

```<code>{'Students':       Name        Major     Block
0     Alex     Business  20200525
1     Clay  Engineering  20200526
2  Justine      Science  20200527, 'Anime':      Anime Name             Author
0     One Piece       Eiichiro Oda
1        Naruto  Masashi Kishomoto
2  Dragon Balls     Akira Toriyama}
</code>```

How do I remove the Brackets on each end and align data like this

```<code>    'Students':       Name        Major     Block
                0     Alex     Business  20200525
                1     Clay  Engineering  20200526
                2  Justine      Science  20200527

    'Anime':        Anime Name          Author
             0     One Piece        Eiichiro Oda
             1     Naruto           Masashi Kishomoto
             2     Dragon Balls      Akira Toriyama
</code>```

答:
Note that file is a dictionary where each key is the sheet's name and the value is the Dataframe from that sheet. you can use something like this and change the printing style to whatever you want:

```<code>for key, value in file.items():
    print(key + ":")
    print(value)
</code>```

Title: Align output data using Python Pandas

Body:
I want to align and organized data on Output. I have an excel file which has 2 sheets - Students, Anime. I already extracted data on excel files but my problem now is the output. This is what i've tried

file = pd.read_excel("src/doc/x1/students.xlsx", sheet_name=None)
print(file)

Output:

{'Students':       Name        Major     Block
0     Alex     Business  20200525
1     Clay  Engineering  20200526
2  Justine      Science  20200527, 'Anime':      Anime Name             Author
0     One Piece       Eiichiro Oda
1        Naruto  Masashi Kishomoto
2  Dragon Balls     Akira Toriyama}

How do I remove the Brackets on each end and align data like this

    'Students':       Name        Major     Block
                0     Alex     Business  20200525
                1     Clay  Engineering  20200526
                2  Justine      Science  20200527

    'Anime':        Anime Name          Author
             0     One Piece        Eiichiro Oda
             1     Naruto           Masashi Kishomoto
             2     Dragon Balls      Akira Toriyama

Body:
Note that file is a dictionary where each key is the sheet's name and the value is the Dataframe from that sheet. you can use something like this and change the printing style to whatever you want:

for key, value in file.items():
    print(key + ":")
    print(value)


问:
When I manipulate the dom, v-for no longer stays in sync with a reactive array
It's very confusing - and I would even think there's a bug here.

https://jsbin.com/qadunor/edit?html,js,output

```<code>updateList(containerDom) {
  return () => {
    Array.from(containerDom.querySelectorAll(".list-group-item")).forEach((domItem, idx) => {
      let listItemIndex = this.list.findIndex(listItem => listItem.name === domItem.innerText)
      let listItem = this.list[listItemIndex]
      listItem.pos = idx
      this.list.splice(listItemIndex, 1, listItem)
    })
  }
}
</code>```

If you drag the first list-item ("animal") to the last list-item ("armband") to essentially do a swap (using Sortable.js), you'll see that the list is reactive - you can see it in the output - it updated its position, but the "v-for" loop didn't react properly.

It reacts in some way - but not correctly as you'll see (it incorrectly drops armband into the second position). Now, if I were to just use Sortable.js straight up the swap works fine (ie if I don't handle the onUpdate event - just comment it out). I know I could use VUE.draggable (or whatever it is called, where it maintains an internal list, but for a variety of more complicated reasons I can't use that library). My use-case where I want to use the above technique is irrelevant here - I just want to know why this very particular way fails for "v-for".

I know it has something to do with the fact that Sortable.js does it's own DOM manipulation, but I would expect that once the list array is mutated, that the v-for loop should react appropriately - but it's as if gets confused by what is currently in the DOM.

答:
What I meant was you could creating an exact duplicate of your current list and then have all the names be swapping around (I'm not sure why you're making it overly complicated by using a forEach, since the updateList function passes an oldIndex and newIndex)

```<code>  data() {
     let list = [
        { name: "animal", pos: 0 },
        { name: "aloe", pos: 1 },
        { name: "arm", pos: 2 },
        { name: "arsenal", pos: 3 },
        { name: "antenna", pos: 4 },
        { name: "antler", pos: 5 },
        { name: "armband", pos: 6 },
      ]
    return {
      original_list: JSON.parse(JSON.stringify(list)),
      list: list,
    };
  },

  methods: {
    listToJSON(list) {
      return JSON.stringify(list, null, 2)
    },
    updateList(context) {
      let old = context.oldIndex
      let $new = context.newIndex
      let temp_name = this.original_list[old].name
      this.original_list[old].name = this.original_list[$new].name
      this.original_list[$new].name = temp_name
    }
  },
</code>```

https://jsbin.com/pulapopave/1/edit?html,js,output

Body:
It's very confusing - and I would even think there's a bug here.

https://jsbin.com/qadunor/edit?html,js,output

updateList(containerDom) {
  return () => {
    Array.from(containerDom.querySelectorAll(".list-group-item")).forEach((domItem, idx) => {
      let listItemIndex = this.list.findIndex(listItem => listItem.name === domItem.innerText)
      let listItem = this.list[listItemIndex]
      listItem.pos = idx
      this.list.splice(listItemIndex, 1, listItem)
    })
  }
}

If you drag the first list-item ("animal") to the last list-item ("armband") to essentially do a swap (using Sortable.js), you'll see that the list is reactive - you can see it in the output - it updated its position, but the "v-for" loop didn't react properly.

It reacts in some way - but not correctly as you'll see (it incorrectly drops armband into the second position). Now, if I were to just use Sortable.js straight up the swap works fine (ie if I don't handle the onUpdate event - just comment it out). I know I could use VUE.draggable (or whatever it is called, where it maintains an internal list, but for a variety of more complicated reasons I can't use that library). My use-case where I want to use the above technique is irrelevant here - I just want to know why this very particular way fails for "v-for".

I know it has something to do with the fact that Sortable.js does it's own DOM manipulation, but I would expect that once the list array is mutated, that the v-for loop should react appropriately - but it's as if gets confused by what is currently in the DOM.

Body:
What I meant was you could creating an exact duplicate of your current list and then have all the names be swapping around (I'm not sure why you're making it overly complicated by using a forEach, since the updateList function passes an oldIndex and newIndex)

  data() {
     let list = [
        { name: "animal", pos: 0 },
        { name: "aloe", pos: 1 },
        { name: "arm", pos: 2 },
        { name: "arsenal", pos: 3 },
        { name: "antenna", pos: 4 },
        { name: "antler", pos: 5 },
        { name: "armband", pos: 6 },
      ]
    return {
      original_list: JSON.parse(JSON.stringify(list)),
      list: list,
    };
  },

  methods: {
    listToJSON(list) {
      return JSON.stringify(list, null, 2)
    },
    updateList(context) {
      let old = context.oldIndex
      let $new = context.newIndex
      let temp_name = this.original_list[old].name
      this.original_list[old].name = this.original_list[$new].name
      this.original_list[$new].name = temp_name
    }
  },

https://jsbin.com/pulapopave/1/edit?html,js,output


问:
How to find the type of an object in Go?
How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?

Here is the container from which I am iterating:

```<code>for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
}
</code>```

I am not able to get the type of the object lines in this case which is an array of strings.

答:
You can use: interface{}..(type) as in this playground

package main
import "fmt"
func main(){
    types := []interface{} {"a",6,6.0,true}
    for _,v := range types{
        fmt.Printf("%T\n",v)
        switch v.(type) {
        case int:
           fmt.Printf("Twice %v is %v\n", v, v.(int) * 2)
        case string:
           fmt.Printf("%q is %v bytes long\n", v, len(v.(string)))
       default:
          fmt.Printf("I don't know about type %T!\n", v)
      }
    }
}
```

Body:
How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?

Here is the container from which I am iterating:

for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
}

I am not able to get the type of the object lines in this case which is an array of strings.


问:
How to check if flutter toast already on screen?
I want to show a toast message on my app whenever right condition is met based on some integer values calculation. This condition is met often and I want to show a toast message onScreen. I chose flutter toast plugin for this. But sometimes the method is sending too many toast that toast message consists even after the app is closed. So I want to know if a toast message already on screen and cancel if so.

How do I check if flutter toast already on screen?

Alternatively please suggest me other dialogue showing way on flutter.

```<code>//check if exist then cancel. Or show.
Fluttertoast.showToast(
        msg: "This is condition met Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );
</code>```

答:
please take static bool isShowToast and make it false while when you call toast make their condition</p>

```<code>if(!isShowToast){
 isShowToast=true;
 Fluttertoast.showToast(msg: value).then((value){
 isShowToast=false;
});
}
</code>```

Body:
I want to show a toast message on my app whenever right condition is met based on some integer values calculation. This condition is met often and I want to show a toast message onScreen. I chose flutter toast plugin for this. But sometimes the method is sending too many toast that toast message consists even after the app is closed. So I want to know if a toast message already on screen and cancel if so.

How do I check if flutter toast already on screen?

Alternatively please suggest me other dialogue showing way on flutter.

//check if exist then cancel. Or show.
Fluttertoast.showToast(
        msg: "This is condition met Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );

Body:
please take static bool isShowToast and make it false while when you call toast make their condition

if(!isShowToast){
 isShowToast=true;
 Fluttertoast.showToast(msg: value).then((value){
 isShowToast=false;
});
}


问:
Tkinter Cancel button that stops the whole script
So, basically I am playing with Tkinter and automatization of web page in Python and the thing that I want to add is the window pop up that allows me to select one of two options (today vs tomorrow in my case).
This is the code:

```<code>root = tk.Tk()
def center_window(w=300, h=200):
    # get screen width and height
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    # calculate position x, y
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.geometry("400x450")

Label = tk.Label(root, text = "Select Day", font = ("Helvetica", 15))
Label.pack(pady=50, padx=40)

helv15 = tkFont.Font(family = "Helvetica", size = 15)
root.lift()
v = tk.StringVar()
v.set("Today")
tk.Label(root, textvariable = v).pack()

def close_window():
    root.destroy()

today = tk.Radiobutton(root, text = "Today", variable = v, value = "Today", font = helv15).pack()
tomorrow = tk.Radiobutton(root, text = "Tomorrow", variable = v, value = "Tomorrow", font = helv15).pack()
submit = tk.Button(root, text = "Submit", command = close_window, font = helv15).pack()

center_window(400, 400)

root.mainloop()

###THERE IS A CODE AFTER THIS POINT
</code>```

The button that I want to add is "Cancel" button that stops the execution of the whole code and not just the loop of the Tkinter. Thanks!

答:
This should do the trick, just call exit

```<code>cancel = tk.Button(root, text = "Cancel", command = exit, font = helv15)
cancel.pack()
</code>```

The pack method doesn't return anything, so you'll need to split the lines like this if you want to store the widgets

Body:
So, basically I am playing with Tkinter and automatization of web page in Python and the thing that I want to add is the window pop up that allows me to select one of two options (today vs tomorrow in my case).
This is the code:

root = tk.Tk()
def center_window(w=300, h=200):
    # get screen width and height
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    # calculate position x, y
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.geometry("400x450")

Label = tk.Label(root, text = "Select Day", font = ("Helvetica", 15))
Label.pack(pady=50, padx=40)

helv15 = tkFont.Font(family = "Helvetica", size = 15)
root.lift()
v = tk.StringVar()
v.set("Today")
tk.Label(root, textvariable = v).pack()

def close_window():
    root.destroy()

today = tk.Radiobutton(root, text = "Today", variable = v, value = "Today", font = helv15).pack()
tomorrow = tk.Radiobutton(root, text = "Tomorrow", variable = v, value = "Tomorrow", font = helv15).pack()
submit = tk.Button(root, text = "Submit", command = close_window, font = helv15).pack()

center_window(400, 400)

root.mainloop()

###THERE IS A CODE AFTER THIS POINT

The button that I want to add is "Cancel" button that stops the execution of the whole code and not just the loop of the Tkinter. Thanks!

Body:
This should do the trick, just call exit

cancel = tk.Button(root, text = "Cancel", command = exit, font = helv15)
cancel.pack()

The pack method doesn't return anything, so you'll need to split the lines like this if you want to store the widgets


问:
Receiver 'ClassName' is a forward class and corresponding @interface may not exist
Im currently trying to find a UIPickerTable within the UIPickerView.subviews ... so i loop through and do isKindOfClass:[UIPickerTable class] .... which works.. but because the header of UIPickerTable isn't exposed i get a warning that "receiver 'UIPickerTable' is a forward class and corresponding @interface may not exist'

In order to even be able to compile I do @class UIPickerTable, and obviously it want's me to #include it.

I'm wondering if there's a way to get around seeing this warning.

TIA!

答: Using private APIs in an iPhone application is grounds for rejection from the AppStore (Google's proximity sensing feature not withstanding). Unless you plan to only use the software yourself, don't use private APIs. If there is no way to do what you want without resorting to private APIs, file a bug on Apple's radar. </p>

OwnerDisplayName: dizy

OwnerDisplayName: Barry Wark

ContentLicense: CC BY-SA 2.5


问:
Assistance needed with join query
I have two very simple tables in Oracle 9G:

Customer

```<code>userid | firstName | lastName | email
-------+-----------+----------+---------------------
  1      user1       User1      user1@mail.in
  2      user2       User2      user2@mail.in
</code>```

Order

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1          1          0         12/12/2009    1
2          1          1         13/12/2009    2
3          1          1         14/12/2009    3
4          2          0         12/12/2009    4
5          2          1         16/12/2009    2
6          1          0         14/12/2009    5
7          2          1         17/12/2009    4
8          2          0         10/12/2010    2
</code>```

I want to select all users which have orders of type 0

```<code>select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'
</code>```

The result is:

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1          1          0         12/12/2009    1
4          2          0         12/12/2009    4
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2
</code>```

Now I need to modify this query to bring only last purchase date for each user id and get the result like this:

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2
</code>```

How should I modify my query to get this result?

答:
```<code>SELECT *
FROM order o
WHERE o.orderType ='0'
  AND o.order_date =
      ( SELECT MAX(o2.order_date)
        FROM order o2
        WHERE o2.userid = o.userid
          AND o2.orderType = '0'
      )
</code>```

or

```<code>SELECT o.*
FROM order o
  JOIN
    ( SELECT userid
           , MAX(order_date) AS lastPurchaseDate
      FROM order
      WHERE o.orderType ='0'
      GROUP BY userid
    ) AS grp
    ON grp.userid = o.userid
    AND grp.lastPurchaseDate = o.order_date
</code>```

Title: Assistance needed with join query

Body:
I have two very simple tables in Oracle 9G:

Customer

userid | firstName | lastName | email
-------+-----------+----------+---------------------
  1      user1       User1      user1@mail.in
  2      user2       User2      user2@mail.in

Order

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1          1          0         12/12/2009    1
2          1          1         13/12/2009    2
3          1          1         14/12/2009    3
4          2          0         12/12/2009    4
5          2          1         16/12/2009    2
6          1          0         14/12/2009    5
7          2          1         17/12/2009    4
8          2          0         10/12/2010    2

I want to select all users which have orders of type 0

select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'

The result is:

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1          1          0         12/12/2009    1
4          2          0         12/12/2009    4
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2

Now I need to modify this query to bring only last purchase date for each user id and get the result like this:

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2

How should I modify my query to get this result?

Body:
SELECT *
FROM order o
WHERE o.orderType ='0'
  AND o.order_date =
      ( SELECT MAX(o2.order_date)
        FROM order o2
        WHERE o2.userid = o.userid
          AND o2.orderType = '0'
      )

or

SELECT o.*
FROM order o
  JOIN
    ( SELECT userid
           , MAX(order_date) AS lastPurchaseDate
      FROM order
      WHERE o.orderType ='0'
      GROUP BY userid
    ) AS grp
    ON grp.userid = o.userid
    AND grp.lastPurchaseDate = o.order_date


问:
Yaml If blocks causes missing mapping
I'm trying to add an optional set of parameters when the build running is not on the master branch. The idea is that azure-pipelines-template-variables-private.yml overrides just some of the parameters contained in the group.

This is my template file:

stages:
  - stage: "Tests"
    variables:
      - group: MyLibrary
    ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
      - template: azure-pipelines-template-variables-private.yml
```
<p>This returns the error "Expected a mapping"</p>
<p>Without the if block the behaviour is as expected - the parameters are overwritten. I'm struggling to understand how if blocks work. The docs show how to use variables with Group and variables with templates - but not both together. Though it seems to work together, so I would expect the if statement to work.</p>
<p>Edit: For information I'm including the variable template contents:</p>
<pre class="lang-yaml prettyprint-override"><code>variables:
  - name: MyVar1
    value: 'TEST-$(Build.BuildId)'
  - name: MyVar2
    value: '/Builds/$(BUILD.BUILDID)'
</code>```

答:
I tested the script below and it works well. Hope this helps you :

- stage: build
  jobs:
  - job: run_build

    pool:
      vmImage: 'Ubuntu 16.04'
    variables:
    - group: xxx
    - ${{ if ne(variables['Build.SourceBranchName'], 'refs/heads/master') }}:
      - template: var.yml
    steps:
      - script: echo ${{ variables.test }}
```

Title: Yaml If blocks causes missing mapping

Body:
I'm trying to add an optional set of parameters when the build running is not on the master branch. The idea is that azure-pipelines-template-variables-private.yml overrides just some of the parameters contained in the group.

This is my template file:

stages:
  - stage: "Tests"
    variables:
      - group: MyLibrary
    ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
      - template: azure-pipelines-template-variables-private.yml

This returns the error "Expected a mapping"

Without the if block the behaviour is as expected - the parameters are overwritten. I'm struggling to understand how if blocks work. The docs show how to use variables with Group and variables with templates - but not both together. Though it seems to work together, so I would expect the if statement to work.

Edit: For information I'm including the variable template contents:

variables:
  - name: MyVar1
    value: 'TEST-$(Build.BuildId)'
  - name: MyVar2
    value: '/Builds/$(BUILD.BUILDID)'


问:
ASP.NET MVC application in VS 2019 parser error in Global.asax.cs

Source Error:

  Parser Error Message: Could not load type 'MyProject.MvcApplication'.

Line 1: <%@ Application Codebehind="Global.asax.cs"

  Inherits="MyProject.MvcApplication" Language="C#" %>

I have implemented all solution provided on below links and many more, but I'm not able to fix this issue. Is this related to the IDE? If so, I will open this app in something other than VS2019, then this issue would not occur.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

https://social.msdn.microsoft.com/Forums/windows/en-US/7ad2acb0-42ca-4ee8-9161-681689b60dda/bin-folder-location-causes-quotparser-error-message-could-not-load-typequot-problem?forum=winformssetup

https://www.c-sharpcorner.com/forums/i-am-facing-problem-during-build-my-asp-net-mvc-application

答:
To resolve the issue you could try below workaround:

1)Delete all files from the bin folder of the project. Right-click on the project and click clean and build.

2)Check your global.asax and global.asax.cs are correctly formated.

3)try to remove the site from the iis and recreate it by your self.

If the above way is not working then I suggested you to restart the application OR remove the temporary files in the computer by Run command temp and %temp% OR include the obj folder in to the project and rebuild and run.

Refer this below link for more detail:

"Parser Error Message: Could not load type" in Global.asax

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'


问:
Why boostrap carousel don't show the images (not even the place holders)?
I'm using Bootstrap. I've paste the code from documention on how to use a carousel.

But images won't show. Not even the gray squares, that are used as placeholders why?

Codepen:

https://codepen.io/ogonzales/pen/VweZYbK

Same happens in localhost:

Code:

```<code><div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="..." class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

答: The image is not showing because the image src attribute is set to '...'. Change the source to the source of an image. Then it will work.</p>

Body:
I'm using Bootstrap. I've paste the code from documention on how to use a carousel.

But images won't show. Not even the gray squares, that are used as placeholders why?

Codepen:

https://codepen.io/ogonzales/pen/VweZYbK

Same happens in localhost:

Code:

    Previous

    Next


问:
How to fix Perforce error "Can't clobber writable file" or Perforce Error Message - Can't Clobber Writable File
```<code>Error: Can't clobber writable file : //file name//
</code>```

Solution: When you try to sync a file, perforce expects your files in workspace will have read-only permissions.  If a file is not checked out (by p4 edit) but has write permission then it will throw the above error. Changing the file to read-only and syncing again will solve the issue.  Or try removing the workspace and get the latest revision again.

答: I was using Perforce Software version not the CLI. What worked for me was, I changed the entire project permission to read only and closed the Perforce and opened it again. And then it was able to sync with the cloud. </p>

Body:
Error: Can't clobber writable file : //file name//

Solution: When you try to sync a file, perforce expects your files in workspace will have read-only permissions.  If a file is not checked out (by p4 edit) but has write permission then it will throw the above error. Changing the file to read-only and syncing again will solve the issue.  Or try removing the workspace and get the latest revision again.


问:
Productory with lambda function in Python
Suppose we have a function f(x) = f_1(x)f_2(x)...f_D(x). How can I implement this function f as a productory with a lambda function?

I need this to integrate a productory.

Example f_i = x[i]**m:

```<code> lambda m: x[0]**m*x[1]**m*x[2]**m....x[D-1]**m
</code>```

答:
You can use just a regular function instead. Simply iterate over the elements, take their power of m, and then multiply them into a result.</p>

```<code>def integrate(values, m):
    result = 1
    for value in values:
        result *= (value ** m)
    return result
</code>```

Body:
Suppose we have a function f(x) = f_1(x)f_2(x)...f_D(x). How can I implement this function f as a productory with a lambda function?

I need this to integrate a productory.

Example f_i = x[i]**m:

 lambda m: x[0]**m*x[1]**m*x[2]**m....x[D-1]**m

Body:
You can use just a regular function instead. Simply iterate over the elements, take their power of m, and then multiply them into a result.

def integrate(values, m):
    result = 1
    for value in values:
        result *= (value ** m)
    return result


问:
moving files to their original locations after conversion
I have created a Bash script to convert files from .odt to .pdf, but after conversion, the script moves files into the current working directory. As the script is recurring I want each output file to stay in the location where the original is. Here is the script.

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

for file in $(find -type f -name '*.odt')
do
    echo $file
    libreoffice --headless --convert-to pdf $file
done
</code>```

I have tried setting --outdir to be path of directories but it moves all files to those directories. I want converted files to stay in same directory as original files.

答:
Generate the --outdir value dynamically, and avoid parsing find's output.

```<code>find . -type f -name '*.odt' -print -exec sh -c '
for fpath do
  soffice --headless --convert-to pdf <b>--outdir "${fpath%/*}"</b> "$fpath"
done' _ {} +</code>```

Body:
I have created a Bash script to convert files from .odt to .pdf, but after conversion, the script moves files into the current working directory. As the script is recurring I want each output file to stay in the location where the original is. Here is the script.

#!/bin/bash

for file in $(find -type f -name '*.odt')
do
    echo $file
    libreoffice --headless --convert-to pdf $file
done

I have tried setting --outdir to be path of directories but it moves all files to those directories. I want converted files to stay in same directory as original files.

Body:
Generate the --outdir value dynamically, and avoid parsing find's output.

find . -type f -name '*.odt' -print -exec sh -c '
for fpath do
  soffice --headless --convert-to pdf --outdir "${fpath%/*}" "$fpath"
done' _ {} +


问:
Changing a color of a Bulma button when clicked
I want to change the color of my Bulma button, in my Rails app. Those button are use to filter results on a search page.

So far i did the following, but it is not working the color is not changing:

```<code><%= link_to request.params.merge(category: "9"), class: "button is-rounded", id: "ButtonId" do %>
                                <i class="fas fa-thermometer-full"></i><%= t "services.title" %>
                                <% end %>

<script>
$('#ButtonId').click(function() {
$(this).addClass('has-background-danger');
});
</script>
</code>```

答:
I was not charging Fontawesome correctly, the following solve my problem:

First,

```<code>  yarn add @fortawesome/fontawesome-free
</code>```

After in app/javascript/packs/application.js

```<code>   import "@fortawesome/fontawesome-free/js/all";
</code>```

And in app/javascript/css/main.scss

```<code> @import '@fortawesome/fontawesome-free';
</code>```

Finally in app/javascript/packs/application.js, i removed

```<code>window.jQuery = $;
window.$ = $;
</code>```

Body:
I want to change the color of my Bulma button, in my Rails app. Those button are use to filter results on a search page.

So far i did the following, but it is not working the color is not changing:

<%= link_to request.params.merge(category: "9"), class: "button is-rounded", id: "ButtonId" do %>
                                <%= t "services.title" %>
                                <% end %>

Body:
I was not charging Fontawesome correctly, the following solve my problem:

First,

  yarn add @fortawesome/fontawesome-free

After in app/javascript/packs/application.js

   import "@fortawesome/fontawesome-free/js/all";

And in app/javascript/css/main.scss

 @import '@fortawesome/fontawesome-free';

Finally in app/javascript/packs/application.js, i removed

window.jQuery = $;
window.$ = $;


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

```<code>public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {
</code>```

So here on this code I am getting the error

```<code>this._section.GetType();
</code>```

How can this problem be fixed?

答:
Instead of trying

```<code>_section.GetType()
</code>```

use

```<code>typeof(SingleBanners )
</code>```

Body:
Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {

So here on this code I am getting the error

this._section.GetType();

How can this problem be fixed?

Body:
Instead of trying

_section.GetType()

use

typeof(SingleBanners )


问:
How may overlap happen when destination and source of CopyTo non-static method are the same array?
in the Programming C# 5 book, I've read that:

As well as the static Copy method, the Array class defines a nonstatic CopyTo method, which copies the entire array into a target array, starting
  at the specified offset. This method is present because all arrays implement certain collection  interfaces, including ICollection (where T
  is the array’s element type), which defines this CopyTo method. Copy
  To does not guarantee to handle overlap correctly, and the documen
  tation recommends using Array.Copy in scenarios where you know you
  will be dealing with arrays—CopyTo is just for the benefit of general purpose
  code that can work with any implementation of a collection
  interface.

It says that overlap won't be handled correctly when using CopyTo non-static method. The problem is that I think no overlap may happen when we are using CopyTo on an array! Because, it is trying to copy entire array to the destination. If the destination is the same as source, destination is the same size as source, hence, the only position we can copy to is 0 ( I mean second argument must be zero: myArray.CopyTo(myArray, 0) ), hence, each element is exactly copied at the index, where it already is. So what is the overlap problem this book is talking about?
All I said can be seen in the code below:

```<code>> var a = new int[] { 1, 2, 3 };
> a
int[3] { 1, 2, 3 }
> a.CopyTo(a, 0) // this is the only way I can call this method without
                 // getting error, If I want to pass the same array as first argument
> a
int[3] { 1, 2, 3 }  // nothing went wrong! What is to worry about?
</code>```

Besides the things I said, why may someone copy an array into itself at index 0? What is the point in doing that? What am I missing?

Note that this is not the same question as this SO post. That SO post is about Copy mehtod, not CopyTo.
I think all considerations around overlapping when working with arrays,  only make sense if we pass an array to Copy(). As described in that SO post.

答: The CopyTo call boils down to a call to Array.Copy in array.cs. So yes, this is the same as that SO post.

Body:
in the Programming C# 5 book, I've read that:

As well as the static Copy method, the Array class defines a nonstatic CopyTo method, which copies the entire array into a target array, starting
  at the specified offset. This method is present because all arrays implement certain collection  interfaces, including ICollection (where T
  is the array’s element type), which defines this CopyTo method. Copy
  To does not guarantee to handle overlap correctly, and the documen
  tation recommends using Array.Copy in scenarios where you know you
  will be dealing with arrays—CopyTo is just for the benefit of general purpose
  code that can work with any implementation of a collection
  interface.

It says that overlap won't be handled correctly when using CopyTo non-static method. The problem is that I think no overlap may happen when we are using CopyTo on an array! Because, it is trying to copy entire array to the destination. If the destination is the same as source, destination is the same size as source, hence, the only position we can copy to is 0 ( I mean second argument must be zero: myArray.CopyTo(myArray, 0) ), hence, each element is exactly copied at the index, where it already is. So what is the overlap problem this book is talking about?
All I said can be seen in the code below:

> var a = new int[] { 1, 2, 3 };
> a
int[3] { 1, 2, 3 }
> a.CopyTo(a, 0) // this is the only way I can call this method without
                 // getting error, If I want to pass the same array as first argument
> a
int[3] { 1, 2, 3 }  // nothing went wrong! What is to worry about?

Besides the things I said, why may someone copy an array into itself at index 0? What is the point in doing that? What am I missing?

Note that this is not the same question as this SO post. That SO post is about Copy mehtod, not CopyTo.
I think all considerations around overlapping when working with arrays,  only make sense if we pass an array to Copy(). As described in that SO post.


问:
custom query in laravel datatable
i am trying to do a query on a table likes so

tbl_bottle

```<code>name | type | location
bot1    A       USA
bot2    B
bot3    C       USA
bot4    A        UK
bot5    A        UK

</code>```

so when i load front end it will show
this

```<code>name | type | location
bot1    A       USA
bot1    B
bot3    C       USA
bot4    A        UK
bot5    A        UK

</code>```

but when i type bot1 in search it should give me :

```<code>name | type | location
bot1    A       USA
bot1    B
</code>```

but what i get instead is

```<code>name | type | location
bot1    A       USA
bot1    B
bot3    C       USA
</code>```

this is what i have in my controller

```<code>     $bottle= tbl_bottle::select(
                'name',
                'type',
                'location'
            )->where('location','=','USA')->OrWhere('location','=',' ');

return DataTables::of($bottle)
            ->addColumn('action', function ($bottle) {
                return '<a href="#" class="btn btn-xs btn-primary got=to" id="' . $members->name. '">View Details</a>';
            })->make(true);
</code>```

so the datatable displays this correctly but when i try to search it does not work correctly
what i mean is when i search

so in my front end all i have is

```<code><table id="tbl_bottles" class="table">
<th>Name</th>
<th>Type</th>
<th>Location</th>
<th>Action</th>
</table>
    <script type="text/javascript">
$(document).ready(function () {
    $('#tbl_bottles').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "{{ route('ajax.getBottles') }}",
        "columns": [
            { "data": 'name'},
            {"data": "type"},
            {"data": "location"},
            {"data":"action",orderable:false,searchable:false}
        ],
    });
});
</script>
</code>```

the search input gets plugged in by the datatables
the documentation iam using is https://github.com/yajra/laravel-datatables

答:
Use this code (for raw query)

```<code>$searchValue = $request->input('search')['value']; // Search value from datatable
//-- END DEFAULT DATATABLE QUERY PARAMETER

//-- START DYNAMIC QUERY BINDING
$conditions = '1 = 1';
if (!empty($searchValue)) {
    $conditions .= " AND name LIKE '%" . trim($searchValue) . "%'";
}
//-- END DYNAMIC QUERY BINDING

//-- WE MUST HAVE COUNT ALL RECORDS WITHOUT ANY FILTERS
$countAll = \App\tbl_bottle::count();

//-- CREATE DEFAULT LARAVEL PAGING
$paginate = \App\tbl_bottle::select('*')
    ->whereRaw($conditions)
    ->paginate($limit, ["*"], 'page', $page);
</code>```

Or you can see my blog post Laravel datatables for more details. Its provide sorting and searching too.

Title: custom query in laravel datatable

Body:
i am trying to do a query on a table likes so

tbl_bottle

name | type | location
bot1    A       USA
bot2    B
bot3    C       USA
bot4    A        UK
bot5    A        UK

so when i load front end it will show
this

name | type | location
bot1    A       USA
bot1    B
bot3    C       USA
bot4    A        UK
bot5    A        UK

but when i type bot1 in search it should give me :

name | type | location
bot1    A       USA
bot1    B

but what i get instead is

name | type | location
bot1    A       USA
bot1    B
bot3    C       USA

this is what i have in my controller

     $bottle= tbl_bottle::select(
                'name',
                'type',
                'location'
            )->where('location','=','USA')->OrWhere('location','=',' ');

return DataTables::of($bottle)
            ->addColumn('action', function ($bottle) {
                return 'name. '">View Details';
            })->make(true);

so the datatable displays this correctly but when i try to search it does not work correctly
what i mean is when i search

so in my front end all i have is

Name
Type
Location
Action

the search input gets plugged in by the datatables
the documentation iam using is https://github.com/yajra/laravel-datatables

Body:
Use this code (for raw query)

$searchValue = $request->input('search')['value']; // Search value from datatable
//-- END DEFAULT DATATABLE QUERY PARAMETER

//-- START DYNAMIC QUERY BINDING
$conditions = '1 = 1';
if (!empty($searchValue)) {
    $conditions .= " AND name LIKE '%" . trim($searchValue) . "%'";
}
//-- END DYNAMIC QUERY BINDING

//-- WE MUST HAVE COUNT ALL RECORDS WITHOUT ANY FILTERS
$countAll = \App\tbl_bottle::count();

//-- CREATE DEFAULT LARAVEL PAGING
$paginate = \App\tbl_bottle::select('*')
    ->whereRaw($conditions)
    ->paginate($limit, ["*"], 'page', $page);

Or you can see my blog post Laravel datatables for more details. Its provide sorting and searching too.


问:
tkinter resize frame and contents with main window
I am trying to work out how to control resizing of the window containing a frame. In the code I have three buttons across the top that should to stay exactly where they are.

When I drag the window to expand it, I want the frame and the text box it contains to expand with the master window. I have read that columnconfigure and rowconfigure can be used but not sure how to implement it.

```<code>from tkinter import *
from tkinter import scrolledtext

master_window = Tk()

# Create the buttons
btn_Image = Button(master_window, text='Image')
btn_Image.grid(row=1, column=1, padx=(10), pady=10, sticky=E + W)

btn_File = Button(master_window, text='File')
btn_File.grid(row=1, column=2, padx=(10), pady=10, sticky=E + W)

btn_Folder = Button(master_window, text='Folder')
btn_Folder.grid(row=1, column=3, padx=(10), pady=10, sticky=E + W)

# Group1 Frame ----------------------------------------------------
group1 = LabelFrame(master_window, text="Text Box", padx=5, pady=5)
group1.grid(row=2, column=1, columnspan=3, padx=10, pady=10, sticky=E+W+N+S)

# Create the textbox
txtbox = scrolledtext.ScrolledText(group1, width=40, height=10)
txtbox.grid(row=1, column=1,  columnspan=3, sticky=E+W+N+S)

mainloop()
</code>```

答:
I tkink it would be better to not import everything of tkinter. And also puting funtion calls to main function. Hence I just modify @Billal Begueradj 's pasted code to the following:</p>

```<code># coding: utf-8

try:
    import tkinter as tk
    from tkinter import scrolledtext
except: # Python2 compatible
    import Tkinter as tk
    from Tkinter import scrolledtext

def main():
    master_window = tk.Tk()

    # Parent widget for the buttons
    buttons_frame = tk.Frame(master_window)
    buttons_frame.grid(row=0, column=0, sticky=tk.W+tk.E)

    btn_Image = tk.Button(buttons_frame, text='Image')
    btn_Image.grid(row=0, column=0, padx=(10), pady=10)

    btn_File = tk.Button(buttons_frame, text='File')
    btn_File.grid(row=0, column=1, padx=(10), pady=10)

    btn_Folder = tk.Button(buttons_frame, text='Folder')
    btn_Folder.grid(row=0, column=2, padx=(10), pady=10)

    # Group1 Frame ----------------------------------------------------
    group1 = tk.LabelFrame(master_window, text="Text Box", padx=5, pady=5)
    group1.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky=tk.E+tk.W+tk.N+tk.S)

    master_window.columnconfigure(0, weight=1)
    master_window.rowconfigure(1, weight=1)

    group1.rowconfigure(0, weight=1)
    group1.columnconfigure(0, weight=1)

    # Create the textbox
    txtbox = scrolledtext.ScrolledText(group1, width=40, height=10)
    txtbox.grid(row=0, column=0, sticky=tk.E+tk.W+tk.N+tk.S)

    master_window.mainloop()

if __name__ == '__main__':
    main()
</code>```

Body:
I am trying to work out how to control resizing of the window containing a frame. In the code I have three buttons across the top that should to stay exactly where they are.

When I drag the window to expand it, I want the frame and the text box it contains to expand with the master window. I have read that columnconfigure and rowconfigure can be used but not sure how to implement it.

from tkinter import *
from tkinter import scrolledtext

master_window = Tk()

# Create the buttons
btn_Image = Button(master_window, text='Image')
btn_Image.grid(row=1, column=1, padx=(10), pady=10, sticky=E + W)

btn_File = Button(master_window, text='File')
btn_File.grid(row=1, column=2, padx=(10), pady=10, sticky=E + W)

btn_Folder = Button(master_window, text='Folder')
btn_Folder.grid(row=1, column=3, padx=(10), pady=10, sticky=E + W)

# Group1 Frame ----------------------------------------------------
group1 = LabelFrame(master_window, text="Text Box", padx=5, pady=5)
group1.grid(row=2, column=1, columnspan=3, padx=10, pady=10, sticky=E+W+N+S)

# Create the textbox
txtbox = scrolledtext.ScrolledText(group1, width=40, height=10)
txtbox.grid(row=1, column=1,  columnspan=3, sticky=E+W+N+S)

mainloop()

Body:
I tkink it would be better to not import everything of tkinter. And also puting funtion calls to main function. Hence I just modify @Billal Begueradj 's pasted code to the following:

# coding: utf-8

try:
    import tkinter as tk
    from tkinter import scrolledtext
except: # Python2 compatible
    import Tkinter as tk
    from Tkinter import scrolledtext

def main():
    master_window = tk.Tk()

    # Parent widget for the buttons
    buttons_frame = tk.Frame(master_window)
    buttons_frame.grid(row=0, column=0, sticky=tk.W+tk.E)

    btn_Image = tk.Button(buttons_frame, text='Image')
    btn_Image.grid(row=0, column=0, padx=(10), pady=10)

    btn_File = tk.Button(buttons_frame, text='File')
    btn_File.grid(row=0, column=1, padx=(10), pady=10)

    btn_Folder = tk.Button(buttons_frame, text='Folder')
    btn_Folder.grid(row=0, column=2, padx=(10), pady=10)

    # Group1 Frame ----------------------------------------------------
    group1 = tk.LabelFrame(master_window, text="Text Box", padx=5, pady=5)
    group1.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky=tk.E+tk.W+tk.N+tk.S)

    master_window.columnconfigure(0, weight=1)
    master_window.rowconfigure(1, weight=1)

    group1.rowconfigure(0, weight=1)
    group1.columnconfigure(0, weight=1)

    # Create the textbox
    txtbox = scrolledtext.ScrolledText(group1, width=40, height=10)
    txtbox.grid(row=0, column=0, sticky=tk.E+tk.W+tk.N+tk.S)

    master_window.mainloop()

if __name__ == '__main__':
    main()


问:
Exporting data from R to MYSQL server
```<code>df <- data.frame(category = c("A","B","A","D","E"),
                 date = c("5/10/2005","6/10/2005","7/10/2005","8/10/2005","9/10/2005"),
                 col1 = c(1,NA,2,NA,3),
                 col2 = c(1,2,NA,4,5),
                 col3 = c(2,3,NA,NA,4))
</code>```

I have to insert a data frame that is created in R to mysql server.

I have tried these methods(Efficient way to insert data frame from R to SQL). However, my data also has NA which are fails the whole process of exporting.

Is there a way around to faster upload to data.

```<code>dbWriteTable(cn,name ="table_name",value = df,overwrite=TRUE, row.names = FALSE)
</code>```

The above works but is very slow to upload

The method that I have to use is this :

```<code>before = Sys.time()
chunksize = 1000000 # arbitrary chunk size
for (i in 1:ceiling(nrow(df)/chunksize)) {
  query = paste0('INSERT INTO dashboard_file_new_rohan_testing (',paste0(colnames(df),collapse = ','),') VALUES ')
  vals = NULL
  for (j in 1:chunksize) {
    k = (i-1)*chunksize+j
    if (k <= nrow(df)) {
      vals[j] = paste0('(', paste0(df[k,],collapse = ','), ')')
    }
  }
  query = paste0(query, paste0(vals,collapse=','))
  dbExecute(cn, query)
}
time_chunked = Sys.time() - before
</code>```

Error Encountered:

```<code>Error in .local(conn, statement, ...) :
  could not run statement: Unknown column 'NA' in 'field list'
</code>```

答:
One of the fastest ways to load data into MySQL is to use its LOAD DATA command line tool.  You may try first writing your R data frame to a CSV file, then using MySQL's LOAD DATA to load it:

```<code>write.csv(df, "output.csv", row.names=FALSE)
</code>```

Then from your command line, use:

```<code>LOAD DATA INFILE 'output.csv' INTO TABLE table_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
</code>```

Note that this assumes the CSV file is already on the same machine as MySQL.  If not, and you have it still locally, then use LOAD DATA LOCAL INFILE instead.

You may read MYSQL import data from csv using LOAD DATA INFILE for more help using LOAD DATA.

Edit:

To deal with the issue of NA values, which should represent NULL in MySQL, you may take the approach of first casting the entire data frame to text, and then replacing the NA values with empty string.  LOAD DATA will interpret a missing value in a CSV column as being NULL.  Consider this:

```<code>df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
df[is.na(df)] <- ""
</code>```

Then, use write.csv along with LOAD DATA as described above.

Title: Exporting data from R to MYSQL server

Body:
df <- data.frame(category = c("A","B","A","D","E"),
                 date = c("5/10/2005","6/10/2005","7/10/2005","8/10/2005","9/10/2005"),
                 col1 = c(1,NA,2,NA,3),
                 col2 = c(1,2,NA,4,5),
                 col3 = c(2,3,NA,NA,4))

I have to insert a data frame that is created in R to mysql server.

I have tried these methods(Efficient way to insert data frame from R to SQL). However, my data also has NA which are fails the whole process of exporting.

Is there a way around to faster upload to data.

dbWriteTable(cn,name ="table_name",value = df,overwrite=TRUE, row.names = FALSE)

The above works but is very slow to upload

The method that I have to use is this :

before = Sys.time()
chunksize = 1000000 # arbitrary chunk size
for (i in 1:ceiling(nrow(df)/chunksize)) {
  query = paste0('INSERT INTO dashboard_file_new_rohan_testing (',paste0(colnames(df),collapse = ','),') VALUES ')
  vals = NULL
  for (j in 1:chunksize) {
    k = (i-1)*chunksize+j
    if (k <= nrow(df)) {
      vals[j] = paste0('(', paste0(df[k,],collapse = ','), ')')
    }
  }
  query = paste0(query, paste0(vals,collapse=','))
  dbExecute(cn, query)
}
time_chunked = Sys.time() - before

Error Encountered:

Error in .local(conn, statement, ...) :
  could not run statement: Unknown column 'NA' in 'field list'

Body:
One of the fastest ways to load data into MySQL is to use its LOAD DATA command line tool.  You may try first writing your R data frame to a CSV file, then using MySQL's LOAD DATA to load it:

write.csv(df, "output.csv", row.names=FALSE)

Then from your command line, use:

LOAD DATA INFILE 'output.csv' INTO TABLE table_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Note that this assumes the CSV file is already on the same machine as MySQL.  If not, and you have it still locally, then use LOAD DATA LOCAL INFILE instead.

You may read MYSQL import data from csv using LOAD DATA INFILE for more help using LOAD DATA.

Edit:

To deal with the issue of NA values, which should represent NULL in MySQL, you may take the approach of first casting the entire data frame to text, and then replacing the NA values with empty string.  LOAD DATA will interpret a missing value in a CSV column as being NULL.  Consider this:

df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
df[is.na(df)] <- ""

Then, use write.csv along with LOAD DATA as described above.


问:
How to do "static overloaded const" in C#?
I'm creating a game in C#. Each level is made up of several tiles. Each tile is of a certain type e.g. grass floor, wooden wall, etc.

Ideally I would like to have one base class "Tile" and inherit from it to create classes for each type of tile. I would like to have the properties of the tile some kind of static/const/etc member of the sub-class since each type of tile is only ever going to have the same properties. I.e. I don't want 100 Tiles have a property which all have the same value, that seems rather inefficient.

The problem is you can't do that in C#. Are there any ways to achieve what I want?

My alternative idea was to separate it all into to trees, one with only the class "Tile" which represents an instance and another "TileType" from which I instanciate one object for each type and maybe access them through some kind of "TileTypeCollection". This feels strange though and I would rather do it in the first way.

Are there any general guidelines when dealing with a situation like this?

答:
Can't you just use a static field to back a property on your Tile base class?</p>

```<code>public abstract class Tile
{
  private static string _commonProperty

  public static string CommonProperty
  {
    get { return _commonProperty; }
    set { _commonProperty = value; }
  }
}
</code>```

Body:
Can't you just use a static field to back a property on your Tile base class?

public abstract class Tile
{
  private static string _commonProperty

  public static string CommonProperty
  {
    get { return _commonProperty; }
    set { _commonProperty = value; }
  }
}


问:
how can i look for dynamic string with find elements by xpath?
I use this line of code in order to get links that contain '6z_04n'. However, this string changes according to the month. How can I put dynamically changing string value?

```<code>flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, '6z_04n')]")
</code>```

I want something like:

```<code>flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, flag )]")
</code>```

Unfortunately this is not working

答:
try this:</p>

```<code>xpath = "//"
xpath += "a[contains(@href, 6z_%sn)]" % month
links = driver.find_elements_by_xpath(xpath)
</code>```

Body:
I use this line of code in order to get links that contain '6z_04n'. However, this string changes according to the month. How can I put dynamically changing string value?

flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, '6z_04n')]")

I want something like:

flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, flag )]")

Unfortunately this is not working

Body:
try this:

xpath = "//"
xpath += "a[contains(@href, 6z_%sn)]" % month
links = driver.find_elements_by_xpath(xpath)


问:
Angular : Can't export excel using ExcelJS - error TS2307: Cannot find module 'stream' - error TS2503: Cannot find namespace 'NodeJS'
I was try to export an excel file using ExcelJS

Here is my console in VS Code terminal :

```<code>ERROR in node_modules/exceljs/index.d.ts:1398:22 - error TS2307: Cannot find module 'stream'.

1398  read(stream: import('stream').Stream): Promise<Workbook>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1424:23 - error TS2307: Cannot find module 'stream'.

1424  write(stream: import('stream').Stream, options?: Partial<XlsxWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1511:22 - error TS2307: Cannot find module 'stream'.

1511  read(stream: import('stream').Stream, options?: Partial<CsvReadOptions>): Promise<Worksheet>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1531:23 - error TS2307: Cannot find module 'stream'.

1531  write(stream: import('stream').Stream, options?: Partial<CsvWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1828:19 - error TS2307: Cannot find module 'stream'.

1828            stream: import('stream').Stream;
                               ~~~~~~~~
node_modules/exceljs/index.d.ts:1872:34 - error TS2503: Cannot find namespace 'NodeJS'.

1872             dictionary: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default                                      ~~~~~~
</code>```

here is app.component.html

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> -->

  <!-- serial must : first jquery then popper then bootstrap -->
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> -->

</head>

<body>

    <div class="row">

      <div class="col-md-2">
        <button class="btn btn-secondary" (click)='downloadExcel()'>Download as Excel</button>
      </div>

    </div>

</body>

</html>
</code>```

here is app.component.ts

```<code>import { Component } from '@angular/core';
import * as Excel from 'exceljs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'resttest10';

  async downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];

    worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

    // save under export.xlsx
    await workbook.xlsx.writeFile('export.xlsx');

    // load a copy of export.xlsx
    const newWorkbook = new Excel.Workbook();
    await newWorkbook.xlsx.readFile('export.xlsx');

    const newworksheet = newWorkbook.getWorksheet('My Sheet');
    newworksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];
    await newworksheet.addRow({ id: 3, name: 'New Guy', dob: new Date(2000, 1, 1) });

    await newWorkbook.xlsx.writeFile('export2.xlsx');

    console.log('File is written');
  }
}
</code>```

I don't get it why it is looking for stream module (and more funny thing - Cannot find namespace 'NodeJS' - I can run all other angular NodeJS projects without error)

Please point out why i can't export excel.

答:
In your tsconfig.app.json file add "types": ["node"]

Note, that the "types" are in the compilerOptions section of the tsconfig.

Body:
I was try to export an excel file using ExcelJS

Here is my console in VS Code terminal :

ERROR in node_modules/exceljs/index.d.ts:1398:22 - error TS2307: Cannot find module 'stream'.

1398  read(stream: import('stream').Stream): Promise<Workbook>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1424:23 - error TS2307: Cannot find module 'stream'.

1424  write(stream: import('stream').Stream, options?: Partial<XlsxWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1511:22 - error TS2307: Cannot find module 'stream'.

1511  read(stream: import('stream').Stream, options?: Partial<CsvReadOptions>): Promise<Worksheet>;
                          ~~~~~~~~
node_modules/exceljs/index.d.ts:1531:23 - error TS2307: Cannot find module 'stream'.

1531  write(stream: import('stream').Stream, options?: Partial<CsvWriteOptions>): Promise<void>;
                           ~~~~~~~~
node_modules/exceljs/index.d.ts:1828:19 - error TS2307: Cannot find module 'stream'.

1828            stream: import('stream').Stream;
                               ~~~~~~~~
node_modules/exceljs/index.d.ts:1872:34 - error TS2503: Cannot find namespace 'NodeJS'.

1872             dictionary: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default                                      ~~~~~~

here is app.component.html

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

        <button class="btn btn-secondary" (click)='downloadExcel()'>Download as Excel</button>

here is app.component.ts

import { Component } from '@angular/core';
import * as Excel from 'exceljs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'resttest10';

  async downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];

    worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
    worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

    // save under export.xlsx
    await workbook.xlsx.writeFile('export.xlsx');

    // load a copy of export.xlsx
    const newWorkbook = new Excel.Workbook();
    await newWorkbook.xlsx.readFile('export.xlsx');

    const newworksheet = newWorkbook.getWorksheet('My Sheet');
    newworksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'dob', width: 15, }
    ];
    await newworksheet.addRow({ id: 3, name: 'New Guy', dob: new Date(2000, 1, 1) });

    await newWorkbook.xlsx.writeFile('export2.xlsx');

    console.log('File is written');
  }
}

I don't get it why it is looking for stream module (and more funny thing - Cannot find namespace 'NodeJS' - I can run all other angular NodeJS projects without error)

Please point out why i can't export excel.


问:
Invariant failed: You should not use <Route> outside a <Router>
I use react-router-dom for routing in my React application. Part of my app extracted in another package. List of dependencies looks like this:

./app/dashboard/package.json

```<code>{
  "dependencies": {
    "@app/components": "^1.0.0",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-router-dom": "^5.0.0"
  }
}
</code>```

./app/components/package.json

```<code>{
  "peerDependencies": {
    "react-router-dom": "^5.0.0"
  }
}
</code>```

When I use components from @app/components which require components from react-router-dom I getting this errors:

```<code>Uncaught Error: Invariant failed: You should not use <Route> outside a <Router>
The above error occurred in the <Context.Consumer> component:
Uncaught (in promise) Error: Invariant failed: You should not use <Route> outside a <Router>
</code>```

Why throws this error? In App.js I use BrowserRouter

```<code>import React, { Suspense } from 'react';
import { Switch, Route } from 'react-router-dom';
import { Placeholder } from '@app/components';

const Auth = React.lazy(() => import(/* webpackPrefetch: true */ './pages/Auth'));
const Index = React.lazy(() => import(/* webpackPrefetch: true */ './pages/Index'));

const App = () => (
  <Suspense fallback={<Placeholder />}>
    <Switch>
      <Route path="/auth" component={Auth} />
      <Route path="/" component={Index} />
    </Switch>
  </Suspense>
);

export default App;
</code>```

client.jsx

```<code>import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import App from './App';

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root'),
);
</code>```

答:
Using the <Link> tag in a component that doesn't have the  imported could give this error, try importing the BrowserRouter from 'react-router-dom'

```<code>import {BrowserRouter , Link} from 'react-router-dom';
</code>```

then make sure to wrap your linked tags in the  tag

Body:
I use react-router-dom for routing in my React application. Part of my app extracted in another package. List of dependencies looks like this:

./app/dashboard/package.json

{
  "dependencies": {
    "@app/components": "^1.0.0",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-router-dom": "^5.0.0"
  }
}

./app/components/package.json

{
  "peerDependencies": {
    "react-router-dom": "^5.0.0"
  }
}

When I use components from @app/components which require components from react-router-dom I getting this errors:

Uncaught Error: Invariant failed: You should not use <Route> outside a <Router>
The above error occurred in the <Context.Consumer> component:
Uncaught (in promise) Error: Invariant failed: You should not use <Route> outside a <Router>

Why throws this error? In App.js I use BrowserRouter

import React, { Suspense } from 'react';
import { Switch, Route } from 'react-router-dom';
import { Placeholder } from '@app/components';

const Auth = React.lazy(() => import(/* webpackPrefetch: true */ './pages/Auth'));
const Index = React.lazy(() => import(/* webpackPrefetch: true */ './pages/Index'));

const App = () => (
  <Suspense fallback={<Placeholder />}>
    <Switch>
      <Route path="/auth" component={Auth} />
      <Route path="/" component={Index} />
    </Switch>
  </Suspense>
);

export default App;

client.jsx

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import App from './App';

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root'),
);

Body:
Using the <Link> tag in a component that doesn't have the  imported could give this error, try importing the BrowserRouter from 'react-router-dom'

import {BrowserRouter , Link} from 'react-router-dom';

then make sure to wrap your linked tags in the  tag