问:
Custom toast on Android: a simple example
I'm new to Android programming. What is a simple example showing a custom toast notification on Android?</p>

答:
It is very simple to create our own custom Toast.

Just follow the below steps.

Step-1

Create the custom layout that you want to

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/black"
    android:orientation="vertical"
    android:padding="@dimen/size_10dp"
    app:cardCornerRadius="@dimen/size_8dp"
    app:cardElevation="@dimen/size_8dp">

    <TextView
        android:id="@+id/txt_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/size_12dp"
        android:textAlignment="center"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_16sp"
        tools:text="Hello Test!!" />

</androidx.cardview.widget.CardView>
</code>```

Step-2

Now create the custom class that extends with Toast.

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.shop.shoppinggare.R;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Text;

public class CustomToast extends Toast {
    private Context context;
    private String message;

    public CustomToast(Context context, String message) {
        super(context);
        this.context = context;
        this.message = message;
        View view = LayoutInflater.from(context).inflate(R.layout.toast_custom, null);
        TextView txtMsg = view.findViewById(R.id.txt_message);
        txtMsg.setText(StringUtils.capitalize(message));
        setView(view);
        setDuration(Toast.LENGTH_LONG);

    }

}
</code>```

We have created the custom toast.

Step-3

Now, finally, how can we use it.

```<code>new CustomToast(contex,"message").show();
</code>```

Enjoy!!

Body:
It is very simple to create our own custom Toast.

Just follow the below steps.

Step-1

Create the custom layout that you want to

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/black"
    android:orientation="vertical"
    android:padding="@dimen/size_10dp"
    app:cardCornerRadius="@dimen/size_8dp"
    app:cardElevation="@dimen/size_8dp">

    <TextView
        android:id="@+id/txt_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/size_12dp"
        android:textAlignment="center"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_16sp"
        tools:text="Hello Test!!" />

</androidx.cardview.widget.CardView>

Step-2

Now create the custom class that extends with Toast.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.shop.shoppinggare.R;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Text;

public class CustomToast extends Toast {
    private Context context;
    private String message;

    public CustomToast(Context context, String message) {
        super(context);
        this.context = context;
        this.message = message;
        View view = LayoutInflater.from(context).inflate(R.layout.toast_custom, null);
        TextView txtMsg = view.findViewById(R.id.txt_message);
        txtMsg.setText(StringUtils.capitalize(message));
        setView(view);
        setDuration(Toast.LENGTH_LONG);

    }

}

We have created the custom toast.

Step-3

Now, finally, how can we use it.

new CustomToast(contex,"message").show();

Enjoy!!


来源: stackexchange

问:
UK Districts Not Mapping Power BI
Folks, my issue should be simple.

I am trying to map UK districts in Kent. But when I try to map the district of Medway I get the following;

This is obviously a polygon for all of Kent. My question is what alias do I need for Medway to get it to map correctly. When you turn on the rest of the districts there is no issue at all. but as you can see Medway is missing.

I have tried the following iterations;

Medway Towns

Medway UA

Medway Unitary Authority

答: I discovered you can cheese it, but selecting one of the Medway towns such as Rochester, Gillingham, Chatham or Strood. Is there a better solution? Now I am stuck with the issue of the hover-over saying Rochester

ContentLicense: CC BY-SA 4.0

Title: UK Districts Not Mapping Power BI


问:
How to capture logs of a command run through `docker-compose exec -d` in background?
Consider a docker-compose.yml file like this:

```<code>version: '3'

services:
  test:
    image: ubuntu:18.04
    tty: true

</code>```

I can bring up the services in background by running docker-compose up -d

Now I can run commands on this container by using docker-compose exec

For example:

```<code>docker-compose exec test ls -lrt | head -3
</code>```

When I run the above command, I get the output on my terminal

```<code>total 64
drwxr-xr-x   8 root root 4096 May 23  2017 lib
drwxr-xr-x   2 root root 4096 Apr 24  2018 home
</code>```

Now what I want is to be able to run the above command in background which I can do with

```<code>docker-compose exec -d test ls -lrt | head -3
</code>```

The command will run in the background which is fine. But how can I access the output of the above command?

答:
You can redirect output in a file inside your container and output the content of this file afterward, such as:</p>

```<code># execute command and redirect to output.log in container
docker-compose exec -d test sh -c 'ls -lrt | head -3 > /tmp/output.log'

# retrieve output content
docker-compose exec test cat /tmp/output.log
</code>```

Body:
Consider a docker-compose.yml file like this:

version: '3'

services:
  test:
    image: ubuntu:18.04
    tty: true

I can bring up the services in background by running docker-compose up -d

Now I can run commands on this container by using docker-compose exec

For example:

docker-compose exec test ls -lrt | head -3

When I run the above command, I get the output on my terminal

total 64
drwxr-xr-x   8 root root 4096 May 23  2017 lib
drwxr-xr-x   2 root root 4096 Apr 24  2018 home

Now what I want is to be able to run the above command in background which I can do with

docker-compose exec -d test ls -lrt | head -3

The command will run in the background which is fine. But how can I access the output of the above command?

Body:
You can redirect output in a file inside your container and output the content of this file afterward, such as:

# execute command and redirect to output.log in container
docker-compose exec -d test sh -c 'ls -lrt | head -3 > /tmp/output.log'

# retrieve output content
docker-compose exec test cat /tmp/output.log


问:
Java Threadpool vs. new Thread in high request scenario
I have some old java code for a REST service that uses a separate thread for every incoming request. I.e. the main loop would loop on socket.accept() and hand off the socket to a Runnable which then would start up its own background thread and invoke run on itself. This worked admiringly well for a while until recently i noticed that the lag of accept to processing the request would get unacceptable under high load. When i say admiringly well, i mean that it was handling 100-200 requests a second without significant CPU usage. The performance only degraded when other daemons were adding load as well and then only once load exceeded 5. When the machine was under high load (5-8) from a combination of other processes, the time from accept to processing would get ridiculously high (500ms to 3000ms) while the actual processing stayed sub-10ms. This is all on dual-core centos 5 systems.

Having been used to Threadpools on .NET, i assumed that thread creation was the culprit and i thought i'd apply the same pattern in java. Now my Runnable is executed with ThreadPool.Executor (and the pool uses and ArrayBlockingQueue). Again, it works great under most scenarios unless the machine load gets high, then the time from creating the runnable until run() is invoked exhibits about the same ridiculous timing. But worse, the system load nearly doubled (10-16) with the threadpool logic in place. So now i get the same latency problems with double the load.

My suspicion is that the lock contention of the queue is worse than the previous new thread start-up cost that had no locks. Can anyone share their experience of new thread vs. threadpool. And if my suspicion is correct, anyone have an alternative approach to dealing with a threadpool without lock contention?

I'd be tempted to just make the whole system single-threaded since i don't know how much my threading helps and IO doesn't seem to be an issue, but I do get some requests that are long-lived that would then block everything.

thanks,
arne

UPDATE: I switched over to Executors.newFixedThreadPool(100); and while it maintained the same processing capacity, load pretty much immediately doubled and running it for 12 hours showed load staying consistently at 2x. I guess in my case a new thread per request is cheaper.

答:
Sun's implementation of Thread, although very much faster than it used to be, does have locking. IIRC, ArrayBlockingQueue should not actually lock at all when busy. Therefore it's profiler time (or even just a few ctrl-\s or jstacks).

System load just tells you how many threads are queued. It's not necessarily very useful.

OwnerDisplayName: Arne Claassen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Arne Claassen

OwnerDisplayName: Tom Hawtin - tackline


问:
Send Message to selected user using laravel
I am trying to send message to selected user  unfortunately I am facing error how to fix it ? thanks.

please check error
  https://flareapp.io/share/67OAAVmr#F59

controller

```<code>                public function chataction(REQUEST $request)
                {
                $user = Auth::user();
                $m = $user->Chats()->create([
               'chat_message' => $request->input('message'),
               'from_user_id' =>Auth::user()->id,
               'to_user_id' =>$request->input('id'),
               ]);
               return ['status' => 'Message Sent!'];
                }
</code>```

html view

```<code>          <form action="{{route('chat.action')}}" method="post">
          @csrf
          <input type="hidden" name="id" >
          <div class="input-group">
          <input type="text" id="chatmessage" name="message" placeholder="Type Message ..."
          class="form-control">
          <span class="input-group-append">
          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>
          </span>
          </div>
          </form>
</code>```

答:
1 - Modify your App\Chat model so $fillable looks like this:

```<code>protected $fillable = ['chat_message', 'from_user_id', 'to_user_id'];
</code>```

2 - Modify your controller to use Illuminate\Http\Request and change your method argument's capitalisation from REQUEST to Request.

```<code>use Illuminate\Http\Request;

public function chataction(Request $request)
{
     ...
}
</code>```

To answer your question in comments,

This is what your method should look like this:

```<code>use Illuminate\Http\Request;

public function chataction(Request $request)
{
 $user = Auth::user();

 if($request->id == $user->id){
     return response("Can't message yourself!");
 }

 $m = $user->Chats()->create([
      'chat_message' => $request->input('message'),
      'from_user_id' => $user->id,
      'to_user_id' => $request->input('id'),
      ]);

  return ['status' => 'Message Sent!'];
}
</code>```

Note: Please update your question to include your query regarding comparison between from_user_id and to_user_id for the benefit of future visitors.

Body:
I am trying to send message to selected user  unfortunately I am facing error how to fix it ? thanks.

please check error
  https://flareapp.io/share/67OAAVmr#F59

controller

                public function chataction(REQUEST $request)
                {
                $user = Auth::user();
                $m = $user->Chats()->create([
               'chat_message' => $request->input('message'),
               'from_user_id' =>Auth::user()->id,
               'to_user_id' =>$request->input('id'),
               ]);
               return ['status' => 'Message Sent!'];
                }

html view

          <form action="{{route('chat.action')}}" method="post">
          @csrf
          <input type="hidden" name="id" >

          <input type="text" id="chatmessage" name="message" placeholder="Type Message ..."
          class="form-control">

          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>

          </form>

Body:
1 - Modify your App\Chat model so $fillable looks like this:

protected $fillable = ['chat_message', 'from_user_id', 'to_user_id'];

2 - Modify your controller to use Illuminate\Http\Request and change your method argument's capitalisation from REQUEST to Request.

use Illuminate\Http\Request;

public function chataction(Request $request)
{
     ...
}

To answer your question in comments,

This is what your method should look like this:

use Illuminate\Http\Request;

public function chataction(Request $request)
{
 $user = Auth::user();

 if($request->id == $user->id){
     return response("Can't message yourself!");
 }

 $m = $user->Chats()->create([
      'chat_message' => $request->input('message'),
      'from_user_id' => $user->id,
      'to_user_id' => $request->input('id'),
      ]);

  return ['status' => 'Message Sent!'];
}

Note: Please update your question to include your query regarding comparison between from_user_id and to_user_id for the benefit of future visitors.


问:
Multiply each row of one dataframe by all rows of a second dataframe
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

```<code>df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Can somebody point me to an efficient way to do this in R?

答:
Another idea via base R using outer,

```<code>data.frame(id = rep(df2$id, each = nrow(df1)),
           mapply(function(x, y)c(outer(x, y, `*`)), df1, df2[-1])
           )
</code>```

which gives,

```<code>  id intercept  age male
1  a       3.4 3.20 0.07
2  a       3.6 2.00 0.06
3  a       3.7 2.40 0.07
4  b       3.4 3.60 0.00
5  b       3.6 2.25 0.00
6  b       3.7 2.70 0.00
</code>```

Body:
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))

Can somebody point me to an efficient way to do this in R?

Body:
Another idea via base R using outer,

data.frame(id = rep(df2$id, each = nrow(df1)),
           mapply(function(x, y)c(outer(x, y, `*`)), df1, df2[-1])
           )

which gives,

  id intercept  age male
1  a       3.4 3.20 0.07
2  a       3.6 2.00 0.06
3  a       3.7 2.40 0.07
4  b       3.4 3.60 0.00
5  b       3.6 2.25 0.00
6  b       3.7 2.70 0.00


问:
Run script on remote computer and pass creds to remote script
Requirement: must be run from local machine on remote machine with creds passed to the remote machine script.

```<code>$server = 'SRV1'
$credential = Get-Credential
$credentials = Get-Credential
Invoke-Command -ComputerName $server -Credential $credential -ScriptBlock {
    C:\foo.ps1 $credentials
 }
</code>```

foo.ps1 requires functions that need $credentials

Inside foo.ps1

```<code>param($credentials)
</code>```

答:
You can't use the Variable $credentials in the scriptBlock on the other computer without passing it as a parameter:
Pass arguments to a scriptblock in powershell</p>

Body:
Requirement: must be run from local machine on remote machine with creds passed to the remote machine script.

$server = 'SRV1'
$credential = Get-Credential
$credentials = Get-Credential
Invoke-Command -ComputerName $server -Credential $credential -ScriptBlock {
    C:\foo.ps1 $credentials
 }

foo.ps1 requires functions that need $credentials

Inside foo.ps1

param($credentials)


问:
Getting NullPointerException in getDrawable method on Glide
I have an imageview and I'll like to get the Bitmap of it...

Here is my code:

Setting the imageview:

```<code>ImageView imageView;
imageView =  findViewById(R.id.image_wallpaper);
Glide.with(this).load(current_image.getImageURL()).into(imageView);
</code>```

Getting the bitmap:

```<code>setButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        DisplayMetrics metrics = new DisplayMetrics();

        imageView.invalidate();  // I get the crash with or without that line
        Bitmap mBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();  // CRASH HERE

        // more things using the mBitmap

    }
});
</code>```

The crash log:

```<code>Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
com.XXXX.XXXXXXX.ImageActivity$4.onClick (ImageActivity.java:170)
android.view.View.performClick (View.java:5246)
android.view.View$PerformClick.run (View.java:21200)
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:6946)
java.lang.reflect.Method.invoke (Method.java)
java.lang.reflect.Method.invoke (Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1404)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1199)
</code>```

I'm using last version of Glide:

```<code>implementation 'com.github.bumptech.glide:glide:4.9.0'                   // glide
</code>```

This crash log comes from Firebase Crashlytics, a lot of users get that error, but I'm unable to reproduce it on my devices.

What's the problem? How can I fix it?

Thanks

答:
Could you please post your imageView initialization ?
If not done you need to initialize it first :</p>

```<code>ImageView imageView = findViewById(R.id.myimageViewId);
</code>```

Body:
I have an imageview and I'll like to get the Bitmap of it...

Here is my code:

Setting the imageview:

ImageView imageView;
imageView =  findViewById(R.id.image_wallpaper);
Glide.with(this).load(current_image.getImageURL()).into(imageView);

Getting the bitmap:

setButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        DisplayMetrics metrics = new DisplayMetrics();

        imageView.invalidate();  // I get the crash with or without that line
        Bitmap mBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();  // CRASH HERE

        // more things using the mBitmap

    }
});

The crash log:

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
com.XXXX.XXXXXXX.ImageActivity$4.onClick (ImageActivity.java:170)
android.view.View.performClick (View.java:5246)
android.view.View$PerformClick.run (View.java:21200)
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:6946)
java.lang.reflect.Method.invoke (Method.java)
java.lang.reflect.Method.invoke (Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1404)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1199)

I'm using last version of Glide:

implementation 'com.github.bumptech.glide:glide:4.9.0'                   // glide

This crash log comes from Firebase Crashlytics, a lot of users get that error, but I'm unable to reproduce it on my devices.

What's the problem? How can I fix it?

Thanks

Body:
Could you please post your imageView initialization ?
If not done you need to initialize it first :

ImageView imageView = findViewById(R.id.myimageViewId);


问:
Bash tool to get nth line from a file
Is there a "canonical" way of doing that? I've been using head -n | tail -1 which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.

By "canonical" I mean a program whose main function is doing that.

答:
head and pipe with tail will be slow for a huge file. I would suggest sed like this:

```<code>sed 'NUMq;d' file
</code>```

Where NUM is the number of the line you want to print; so, for example, sed '10q;d' file to print the 10th line of file.

Explanation:

NUMq will quit immediately when the line number is NUM.

d will delete the line instead of printing it; this is inhibited on the last line because the q causes the rest of the script to be skipped when quitting.

If you have NUM in a variable, you will want to use double quotes instead of single:

```<code>sed "${NUM}q;d" file
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash tool to get nth line from a file

Body:
head and pipe with tail will be slow for a huge file. I would suggest sed like this:

sed 'NUMq;d' file

Where NUM is the number of the line you want to print; so, for example, sed '10q;d' file to print the 10th line of file.

Explanation:

NUMq will quit immediately when the line number is NUM.

d will delete the line instead of printing it; this is inhibited on the last line because the q causes the rest of the script to be skipped when quitting.

If you have NUM in a variable, you will want to use double quotes instead of single:

sed "${NUM}q;d" file


问:
Application Insights showing in Live metrics, but not in log analytics
So I created a Class library that configures microservices's Application Insights. These are the Application Insights configuration methods:

And this is how I use them in the Startup.cs class of each microservice:

It seems to be working fine, according to the debug logs:

I am even able to see the live metrics in azure correctly:

However, the data does not get 'saved' in Log Analytics, so I cannot run any query on the data (it always returns 0 results).

I thought that this could probably be because of the following code in the Program.cs of each microservice:

I thought that maybe the application insights logger was not configured correctly (not explicitely setting the instrumentation key). However, I tried to set the instrumentation key of the TelemetryConfiguration to the hardcoded Instrumentation Key, but it did not do anything.

I did read through this documentation: https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core
But I do not seem like I am missing any step (I call AddApplicationInsights and AddApplicationInsightsKubernetesEnricher).

I was wondering if anyone could see the issue, I really do not know how the data could be seen by live metrics and not Log Analytics.

Note: I did try to add application insights before implementing the library with the exact same code (the default code that VS generates when you right click on project > Setup Application Insights and it worked perfectly.

Many many thanks!

答:
Here is the summarization for others who may also have the same issue:

As per Dmitry mentioned, the correct format in vs output should be Microsoft.ApplicationInsights.Dev.GUID, not Microsoft.ApplicationInsights.Dev.instrumenationkey=GUID. Here is the screenshot for the correct one:

And as per op's comment, in keyvault,  just copy pasted the connection string in the keyvault instead of the instrumentation key which causes this error. The solution is change it to instrumentation key directly in keyvault.


问:
Laravel having column name in where clause static method
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

```<code>$user = User::whereName('john')->first(); // added `name` as a column name
</code>```

When called this code to SQL it generates

```<code>$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?
</code>```

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

答:
Try This </p>

```<code>$user = User::where('name','john')->first();
</code>```

Body:
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

$user = User::whereName('john')->first(); // added `name` as a column name

When called this code to SQL it generates

$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

Body:
Try This

$user = User::where('name','john')->first();


问:
How to convert xml data into csv/excel/table in Azure
we need to convert XML data into csv/excel/table in Azure cloud.

below is the sample xml code.

```<code><SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Body>
           <ns2:getProjectsResponse
               xmlns:ns2="http://www.logic8.com/eq/webservices/generated">
               <ns2:Project>
                   <ns2:fileName>P10001</ns2:fileName>
                   <ns2:alias>project1</ns2:alias>
               </ns2:Project>
               <ns2:Project>
                   <ns2:fileName>P10002</ns2:fileName>
                   <ns2:alias>project2</ns2:alias>
               </ns2:Project>
       <ns2:Project>
                   <ns2:fileName>P10003</ns2:fileName>
                   <ns2:alias>project3</ns2:alias>
               </ns2:Project>
           </ns2:getProjectsResponse>
       </SOAP-ENV:Body>
   </SOAP-ENV:Envelope>
</code>```

Expected output:

Can anyone help me on this.

答:
You could try this way, firstly convert xml to json then use create csv table action to implement it.  The below is my test flow.

I use blob to get the xml content. The Compose action input is json(xml(body('Get_blob_content'))), then will get thejson data. Then is the Create CSV table From, ause the from data should be array, so it should be outputs('Compose')['SOAP-ENV:Envelope']['SOAP-ENV:Body']['ns2:getProjectsResponse']['ns2:Project'].

The last thing is customize the header and the value, the ProjectID value should be item()['ns2:fileName'] and the ProjectDescription should be item()['ns2:alias'].

And here is the flow output, suppose this is what you want, hope this could help you.

Body:
we need to convert XML data into csv/excel/table in Azure cloud.

below is the sample xml code.

<SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Body>
           <ns2:getProjectsResponse
               xmlns:ns2="http://www.logic8.com/eq/webservices/generated">
               <ns2:Project>
                   <ns2:fileName>P10001</ns2:fileName>
                   <ns2:alias>project1</ns2:alias>
               </ns2:Project>
               <ns2:Project>
                   <ns2:fileName>P10002</ns2:fileName>
                   <ns2:alias>project2</ns2:alias>
               </ns2:Project>
       <ns2:Project>
                   <ns2:fileName>P10003</ns2:fileName>
                   <ns2:alias>project3</ns2:alias>
               </ns2:Project>
           </ns2:getProjectsResponse>
       </SOAP-ENV:Body>
   </SOAP-ENV:Envelope>

Expected output:

Can anyone help me on this.


问:
Returns without a "return" command

C programming language, compiled with gcc, terminal bash in WSL

I have written a recursive function, to find the lowest number in an array, which works just fine.

```<code>/*01*/    int minimo(int array[], int n)
/*02*/    {
/*03*/      static int min = 0;
/*04*/
/*05*/      if (n == N)
/*06*/      {
/*07*/          return array[n-1];
/*08*/      }
/*09*/      else
/*10*/      {
/*11*/          min = minimo(array, n+1);
/*12*/          if(array[n]<min){
/*13*/              min = array[n];
/*14*/          }
/*15*/      }
/*16*/    }
</code>```

The only problem is that it shouldn't work, because it doesn't return "min" to the caller...

```<code>int main()
{
    //Var
    int array[N] = {10, 2, 5, 1, 7};
    printf("Min: %d\n", minimo(array, 0));
}
</code>```

My concern is actually a problem, but not on my machine onto which the function works just fine as it is;
it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Between line 15-16 I have to add return min;

```<code>/*15*/      }
            return min;
/*16*/    }
</code>```

My questions for you are the following:

How can  a function return a variable automatically?

Is it possible that it does return the only variable that I created (static int min)?

Or is it a "problem" related to the static attribute that the variable has?

Does it have anything to do with the nature of the function (recursive)?

This is my first post, please be kind if I'm breaking any forum rule.

答:
My concern is actually a problem, but not on my machine onto which the function works just fine as it is; it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Typical example of undefined behavior. Works on one machine but not another. Works at daytime but not nighttime. Works with one compiler but not another. When you invoke undefined behavior, the C standard imposes no requirements on how the code should behave.

C11 standard 6.9.1.12

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

In your code, that is precisely what happens. You invoke undefined behavior when you try to print the return value.

Contrary to what many believes, it IS completely allowed to omit the return statement in a non-void function. It only becomes undefined behavior if you try to use the non-existent return value.

To avoid this, always compile with at least -Wall -Wextra.

Title: Returns without a "return" command

Body:
C programming language, compiled with gcc, terminal bash in WSL

I have written a recursive function, to find the lowest number in an array, which works just fine.

/*01*/    int minimo(int array[], int n)
/*02*/    {
/*03*/      static int min = 0;
/*04*/
/*05*/      if (n == N)
/*06*/      {
/*07*/          return array[n-1];
/*08*/      }
/*09*/      else
/*10*/      {
/*11*/          min = minimo(array, n+1);
/*12*/          if(array[n]<min){
/*13*/              min = array[n];
/*14*/          }
/*15*/      }
/*16*/    }

The only problem is that it shouldn't work, because it doesn't return "min" to the caller...

int main()
{
    //Var
    int array[N] = {10, 2, 5, 1, 7};
    printf("Min: %d\n", minimo(array, 0));
}

My concern is actually a problem, but not on my machine onto which the function works just fine as it is;
it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Between line 15-16 I have to add return min;

/*15*/      }
            return min;
/*16*/    }

My questions for you are the following:

How can  a function return a variable automatically?

Is it possible that it does return the only variable that I created (static int min)?

Or is it a "problem" related to the static attribute that the variable has?

Does it have anything to do with the nature of the function (recursive)?

This is my first post, please be kind if I'm breaking any forum rule.


问:
Javascript appendChild callback?
I need to add an HTML5 video to a page with the following code:

```<code>document.querySelector("#mydiv").appendChild(video);
console.debug(document.querySelector("video").clientWidth);
</code>```

My problem is, the second line returns 0 because it takes a while for the video tag to load the video it's going to play. If I manually type the second line in the console once the page is loaded, I get the actual value. Is there a better way to get this value than using timeouts to periodically check if the value's been updated?

答:
I needed to do something similar and stumbled upon this question, as I though maybe there is a callback for this. Turns out there is not. So here is another way of doing it using Window.requestAnimationFrame().

It would look something like this:

// Prepare the new element
let video = document.createElement('video');

// Add the element to the DOM. Works with any element
document.querySelector("#mydiv").appendChild(video);

// Updateing the DOM will cause a re-render, which we can hook into
window.requestAnimationFrame(() => {
  console.debug(document.querySelector("video").clientWidth);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mydiv">Video goes here:</div></code>```

Check the console to see that it works.

Title: Javascript appendChild callback?

Body:
I need to add an HTML5 video to a page with the following code:

document.querySelector("#mydiv").appendChild(video);
console.debug(document.querySelector("video").clientWidth);

My problem is, the second line returns 0 because it takes a while for the video tag to load the video it's going to play. If I manually type the second line in the console once the page is loaded, I get the actual value. Is there a better way to get this value than using timeouts to periodically check if the value's been updated?

Body:
I needed to do something similar and stumbled upon this question, as I though maybe there is a callback for this. Turns out there is not. So here is another way of doing it using Window.requestAnimationFrame().

It would look something like this:

// Prepare the new element
let video = document.createElement('video');

// Add the element to the DOM. Works with any element
document.querySelector("#mydiv").appendChild(video);

// Updateing the DOM will cause a re-render, which we can hook into
window.requestAnimationFrame(() => {
  console.debug(document.querySelector("video").clientWidth);
});

<div id="mydiv">Video goes here:</div>

Check the console to see that it works.


问:
Android - Custom Button gets stuck "Pressed"
I've created a custom button in my Android app that has basically two different views.  There is an image for when the button isn't being pressed and another image for use while it is being pressed.  Below is how I've implemented the button and how it responds to the user.

```<code>private void registerListeners() {

    calcButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            calcButton.requestFocusFromTouch();
            calcButton.setImageResource(R.drawable.calc_button_pressed);
            return false;
        }
    });

    calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });

    calcButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mathCalculation();
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });
}
</code>```

My problem is that there is a "bug" where if the user touches the button and drags their figure off the button the button stay pressed down.  The one work around I've implemented above is the "setOnFocusChangeListener" so once the user select something it else it will pop back up.

I want to have it so the button pops back out when the user drags there touched figure off the button.

All suggestions are greatly appreciated!!!

Thank you,

答:
You don't need to write a separate button class to get that behavior, you can implement it through a drawable xml. Have this in your xml and set it as the background for your button:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
      android:drawable="@drawable/calc_button_pressed" />
    <item android:drawable="@drawable/calc_button_not_pressed" />
</selector>
</code>```

Body:
I've created a custom button in my Android app that has basically two different views.  There is an image for when the button isn't being pressed and another image for use while it is being pressed.  Below is how I've implemented the button and how it responds to the user.

private void registerListeners() {

    calcButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            calcButton.requestFocusFromTouch();
            calcButton.setImageResource(R.drawable.calc_button_pressed);
            return false;
        }
    });

    calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });

    calcButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mathCalculation();
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });
}

My problem is that there is a "bug" where if the user touches the button and drags their figure off the button the button stay pressed down.  The one work around I've implemented above is the "setOnFocusChangeListener" so once the user select something it else it will pop back up.

I want to have it so the button pops back out when the user drags there touched figure off the button.

All suggestions are greatly appreciated!!!

Thank you,

Body:
You don't need to write a separate button class to get that behavior, you can implement it through a drawable xml. Have this in your xml and set it as the background for your button:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
      android:drawable="@drawable/calc_button_pressed" />
    <item android:drawable="@drawable/calc_button_not_pressed" />
</selector>


问:
GUI settings for adding borders to images in TinyMCE editor of Connections 6
We switched from CKEditor to the new TinyMCE editor in Connections 6 CR5. This was a huge improvement. But out of the box, TinyMCE misses some of the features from CKEditor. For example setting borders on images in a way that could be handled by end users (so no manual HTML/CSS changes).

How can we add such a feature to TinyMCE, that the users get some image property dialog that allows setting image borders?

答:
The image plugin has a configuration property image_advtab, which is set to false by default. I tried to enable it and now we see the advanced tab in the image propertys, which allows setting a border (and also advanced attributes) easily:

To enable it, we need to re-add the plugin, since this allows to override it's variables. Add the following to the externalPlugins array in config.js (which is located in ${CUSTOMIZATION_DIR}/javascript/tiny/editors/connections/config.js):

```<code>{
  name: "image",
  url: pluginBaseDir + "image/plugin.min.js",
  settings: {
    image_advtab: true
  }
}
</code>```

pluginBaseDir is defined above the editor config:

```<code>  var pluginBaseDir = "/connections/resources/web/tiny.editors.connections/tinymce/plugins/";
</code>```

Body:
The image plugin has a configuration property image_advtab, which is set to false by default. I tried to enable it and now we see the advanced tab in the image propertys, which allows setting a border (and also advanced attributes) easily:

To enable it, we need to re-add the plugin, since this allows to override it's variables. Add the following to the externalPlugins array in config.js (which is located in ${CUSTOMIZATION_DIR}/javascript/tiny/editors/connections/config.js):

{
  name: "image",
  url: pluginBaseDir + "image/plugin.min.js",
  settings: {
    image_advtab: true
  }
}

pluginBaseDir is defined above the editor config:

  var pluginBaseDir = "/connections/resources/web/tiny.editors.connections/tinymce/plugins/";


问:
Over how to separate UpdateTarget and Filter
Imagine following table with columns

```<code>TrackingID | CompletionIndicator | Flag2
</code>```

Now I want to count all positions on Tracking ID level with Completion Indicator = 0 but I want to update on Tracking ID level.

With below code only lines with 0 are updated. (logically!). But how can I separate the filter and the update target?

```<code>UPDATE UPDATETarget
SET Flag2 = New_Index
FROM (
    SELECT Flag2
        ,COUNT(*) OVER (
            PARTITION BY TrackingID ORDER BY id DESC
            ) AS New_Index
    FROM [dbo].Feedback
    WHERE CompletionIndicator = 0
    ) AS UPDATETarget
</code>```

答:
If I understand you right you can have multiple entries of TrackingID in this table.
So probably this will do what you want to do, a bit old-style, with WITH it is more recommended

```<code>UPDATE FB
SET Flag2 = Src.NewIndex
FROM [dbo].Feedback AS FB
    JOIN
        (SELECT TrackingID, COUNT(*) AS NewIndex
        FROM [dbo].Feedback
        WHERE CompletionIndicator = 0
        GROUP BY TrackingID) AS Src
        ON Src.TrackingID = FB.TrackingID;
</code>```

I would suggest always double-check what you expect to update by that query with SELECT first.

```<code>SELECT FB.*, Src.NewIndex
FROM [dbo].Feedback AS FB
    JOIN
        (SELECT TrackingID, COUNT(*) AS NewIndex
        FROM [dbo].Feedback
        WHERE CompletionIndicator = 0
        GROUP BY TrackingID) AS Src
        ON Src.TrackingID = FB.TrackingID;
</code>```

Body:
Imagine following table with columns

TrackingID | CompletionIndicator | Flag2

Now I want to count all positions on Tracking ID level with Completion Indicator = 0 but I want to update on Tracking ID level.

With below code only lines with 0 are updated. (logically!). But how can I separate the filter and the update target?

UPDATE UPDATETarget
SET Flag2 = New_Index
FROM (
    SELECT Flag2
        ,COUNT(*) OVER (
            PARTITION BY TrackingID ORDER BY id DESC
            ) AS New_Index
    FROM [dbo].Feedback
    WHERE CompletionIndicator = 0
    ) AS UPDATETarget

Body:
If I understand you right you can have multiple entries of TrackingID in this table.
So probably this will do what you want to do, a bit old-style, with WITH it is more recommended

UPDATE FB
SET Flag2 = Src.NewIndex
FROM [dbo].Feedback AS FB
    JOIN
        (SELECT TrackingID, COUNT(*) AS NewIndex
        FROM [dbo].Feedback
        WHERE CompletionIndicator = 0
        GROUP BY TrackingID) AS Src
        ON Src.TrackingID = FB.TrackingID;

I would suggest always double-check what you expect to update by that query with SELECT first.

SELECT FB.*, Src.NewIndex
FROM [dbo].Feedback AS FB
    JOIN
        (SELECT TrackingID, COUNT(*) AS NewIndex
        FROM [dbo].Feedback
        WHERE CompletionIndicator = 0
        GROUP BY TrackingID) AS Src
        ON Src.TrackingID = FB.TrackingID;


问:
pusher beam is not integrating in ios
i am integrating pusher beam with ios app. i am getting error while setting beamCleint user id. i am getting error "Optional(PushNotifications.TokenProviderError.error("[PushNotifications] - Changing the userId is not allowed."))" any help would be appreciated. thanks in advance
here is my code

```<code>let tokenProvider = BeamsTokenProvider(authURL: "............") { () -> AuthData in
            let sessionToken = "\(defaults.string(forKey: kUserToken ) ?? "")"
            let headers = ["Authorization": "Bearer \(sessionToken)"]
            let queryParams: [String: String] = [:]
            return AuthData(headers: headers, queryParams: queryParams)
        }

        self.beamsClient.setUserId("\(userId)", tokenProvider: tokenProvider, completion: { error in
            guard error == nil else {
                print(error.debugDescription)
                return
            }

            print("Successfully authenticated with Pusher Beams")
        }) ```
```

答: Have you previously set a userId on this device? You may need to ensure you have cleared the device state using the clearAllState method. See https://pusher.com/docs/beams/reference/ios#-clearallstate

Title: pusher beam is not integrating in ios

Body:
i am integrating pusher beam with ios app. i am getting error while setting beamCleint user id. i am getting error "Optional(PushNotifications.TokenProviderError.error("[PushNotifications] - Changing the userId is not allowed."))" any help would be appreciated. thanks in advance
here is my code

let tokenProvider = BeamsTokenProvider(authURL: "............") { () -> AuthData in
            let sessionToken = "\(defaults.string(forKey: kUserToken ) ?? "")"
            let headers = ["Authorization": "Bearer \(sessionToken)"]
            let queryParams: [String: String] = [:]
            return AuthData(headers: headers, queryParams: queryParams)
        }

        self.beamsClient.setUserId("\(userId)", tokenProvider: tokenProvider, completion: { error in
            guard error == nil else {
                print(error.debugDescription)
                return
            }

            print("Successfully authenticated with Pusher Beams")
        }) ```


问:
Visual Studio 2019 won't update
I have Visual Studio 2019 v16.1.6 installed on my Windows 10 x64 machine. My Visual Studio installer doesn't find any updates and thinks that 16.1.6 is the latest version. I've tried deleting the Visual Studio installer folder — which triggers a reinstall of it — but to no avail. I've also tried uninstalling VS, which didn't work.

Anyone had a problem like this before? My machine was re-imaged recently and it's possible a prerequisite for upgrading VS is missing. Could there be a windows patch or other software I could be missing?

答: I fixed this myself. The installer was reading a json file on my work's network to check for updates, rather than going out to the web. Fixed it by deleting a registry key pointing to the local network location.</p>

Title: Visual Studio 2019 won't update


问:
FormatDateTime - Integer arithmetic overflow C++
I'm using a C++ builder function which allows me to format a time received from my microcontroller as below:

```<code>void DisplayTime(unsigned long SecondsSince1900, unsigned short FractionOfSecond, AnsiString* DecodedString)
{
    TDateTime WindowsDate;
    double FloatingDate;
    FloatingDate = SecondsSince1900 + (FractionOfSecond / 65536.0);

    if ( (SecondsSince1900 & 0x80000000) == 0 )
    {// Seconds since wraps around during year 2036.
     // When the top bit is clear we assume that the date is after 2036         rather than before 1968.
        FloatingDate += 0x100000000;//this line is the cause of the warning
    }

    FloatingDate /= SECONDS_IN_DAY ;
    WindowsDate = FloatingDate ;
    *DecodedString = FormatDateTime(" yyyy/mm/dd hh:mm:ss ", WindowsDate);
}
</code>```

Using this code I get the following warning:

Integer arithmetic overflow

Is there any solution to avoid this issue?

答:
Although some compilers will interpret the constant 0x100000000 as a 64-bit integer, it seems that yours does not - which makes it too big to fit into a 32-bit integer (hence the warning).

A simple way around this is to replace the integer constant with a double value:

FloatingDate += 4294967296.0;
```

<p>Alternatively (if your compiler supports it) you can add the <code>uLL</code> suffix to the integer constant:</p>

<pre class="lang-cpp prettyprint-override"><code>FloatingDate += 0x100000000uLL;
</code>```

But this may cause a different warning (conversion from unsigned long long to double can cause loss of precision).

Body:
I'm using a C++ builder function which allows me to format a time received from my microcontroller as below:

void DisplayTime(unsigned long SecondsSince1900, unsigned short FractionOfSecond, AnsiString* DecodedString)
{
    TDateTime WindowsDate;
    double FloatingDate;
    FloatingDate = SecondsSince1900 + (FractionOfSecond / 65536.0);

    if ( (SecondsSince1900 & 0x80000000) == 0 )
    {// Seconds since wraps around during year 2036.
     // When the top bit is clear we assume that the date is after 2036         rather than before 1968.
        FloatingDate += 0x100000000;//this line is the cause of the warning
    }

    FloatingDate /= SECONDS_IN_DAY ;
    WindowsDate = FloatingDate ;
    *DecodedString = FormatDateTime(" yyyy/mm/dd hh:mm:ss ", WindowsDate);
}

Using this code I get the following warning:

Integer arithmetic overflow

Is there any solution to avoid this issue?

Body:
Although some compilers will interpret the constant 0x100000000 as a 64-bit integer, it seems that yours does not - which makes it too big to fit into a 32-bit integer (hence the warning).

A simple way around this is to replace the integer constant with a double value:

FloatingDate += 4294967296.0;

Alternatively (if your compiler supports it) you can add the uLL suffix to the integer constant:

FloatingDate += 0x100000000uLL;

But this may cause a different warning (conversion from unsigned long long to double can cause loss of precision).


问:
The border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?
I am trying to make a table with rounded corners using the CSS border-radius property. The table styles I'm using look something like this:

```<code>table {
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px
}
</code>```

Here's the problem. I also want to set the border-collapse:collapse property, and when that is set border-radius no longer works. Is there a CSS-based way I can get the same effect as border-collapse:collapse without actually using it?

It seems that a large part of the problem is that setting the table to have rounded corners does not affect the corners of the corner td elements. If the table was all one color, this wouldn't be a problem since I could just make the top and bottom td corners rounded for the first and last row respectively. However, I am using different background colors for the table to differentiate the headings and for striping, so the inner td elements would show their rounded corners as well.

Surrounding the table with another element with round corners doesn't work because the table's square corners "bleed through."

Specifying border width to 0 doesn't collapse the table.

Bottom td corners still square after setting cellspacing to zero.

The tables are generated in PHP, so I could just apply a different class to each of the outer th/tds and style each corner separately. I'd rather not do this, since it's not very elegant and a bit of a pain to apply to multiple tables, so please keep suggestions coming.

I'd like to do this without JavaScript.

答:
Here is a way:

div {
  border: 2px solid red;
  overflow: hidden;
  border-radius: 14px;
  transform: rotate(0deg);
}
table {
  border-spacing: 0;
  background-color: blue;
  height: 100%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <tr>
      <td><br></td>
    </tr>
  </table>
</div></code>```

Or

```<code>    div {
      ...
      overflow: hidden;
      border-radius: 14px;
      position: relative;
      z-index: 1;
    }

</code>```

Body:
I am trying to make a table with rounded corners using the CSS border-radius property. The table styles I'm using look something like this:

table {
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px
}

Here's the problem. I also want to set the border-collapse:collapse property, and when that is set border-radius no longer works. Is there a CSS-based way I can get the same effect as border-collapse:collapse without actually using it?

It seems that a large part of the problem is that setting the table to have rounded corners does not affect the corners of the corner td elements. If the table was all one color, this wouldn't be a problem since I could just make the top and bottom td corners rounded for the first and last row respectively. However, I am using different background colors for the table to differentiate the headings and for striping, so the inner td elements would show their rounded corners as well.

Surrounding the table with another element with round corners doesn't work because the table's square corners "bleed through."

Specifying border width to 0 doesn't collapse the table.

Bottom td corners still square after setting cellspacing to zero.

The tables are generated in PHP, so I could just apply a different class to each of the outer th/tds and style each corner separately. I'd rather not do this, since it's not very elegant and a bit of a pain to apply to multiple tables, so please keep suggestions coming.

I'd like to do this without JavaScript.

LastEditorDisplayName: vamin

Body:
Here is a way:

div {
  border: 2px solid red;
  overflow: hidden;
  border-radius: 14px;
  transform: rotate(0deg);
}
table {
  border-spacing: 0;
  background-color: blue;
  height: 100%;
  width: 100%;
}

<div>
  <table>
    <tr>
      <td><br></td>
    </tr>
  </table>
</div>

Or

    div {
      ...
      overflow: hidden;
      border-radius: 14px;
      position: relative;
      z-index: 1;
    }


问:
Take a list in input remove all duplicates and count how many they are
I have tried to make this function but sometimes I get a problem on runtime. I need to take in input a list like 1-2-3-2-4-6-1-2 and the list should be modified as 1-2-3-4-6 so once for every node and I should save how many times is a node repeated so for example 1 is repeated 2 times the 2 is repeated 3 times etc.
But sometimes it doesn't work I cannot understand why.
If you run it following what I wrote just after you'll see the problem:
How many nodes: 5 than write 1, 1, 2, 4, 2 and the output should be 1, 2 -> 2, 2 -> 4 (that means 1 is repeated two times, 2 is repeated two times and 4 is repeated 1 time). If I give in input 1, 2, 3, 2, 1 I get the "right output" plus a garbage value. More are the numbers higher is the probability that it doesn't work :(</p>

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

typedef struct Node{
   int val;
   int rip;
   struct Node *next;
} node;

node *modify(node *head);

void print(node *head2);

int main(){

   int m, i;

   printf("How many nodes: \n");
   scanf("%d", &m);

   node *head = NULL;
   head = (node *)malloc(sizeof(node));
   node *temp = head;
   node *head2 = NULL;
  for(i=0; i < m; i++){
       temp->next = (node *)malloc(sizeof(node));
       printf("Write the value in position %d: \n", i);
       scanf("%d", &temp->val);
       temp = temp->next;
       temp->next = NULL;
   }

   head2 = modify(head);

   print(head2);

   return 0;
}

node *modify(node *head){

   int counter, pass, m;

   node *curr = head;
   node *track = head;

while (track->next != NULL){
       counter = 0;
       pass = 0;
       m = track->val;
       while((curr)->next != NULL){
           if(m == (curr)->val){
               pass++;
               counter++;
               if(pass > 1){
                   node *removed = curr;
                   curr = (curr)->next;
                   free(removed);
               }
               if(pass == 1)
                   curr = curr->next;
           }
           else{
               curr = (curr)->next;
           }
       }
       track->rip = counter;
       track = track->next;
       curr = track;
   }

return head;
}

void print(node *head2){

   while(head2->next != NULL){
       printf("%d, %d -> ", head2->val, head2->rip);
       head2 = head2->next;
   }
   printf("\n");
}
</code>```

答:
The error is here:

```<code>           if(pass > 1){
               node *removed = curr;
               curr = (curr)->next;
               free(removed);
           }
</code>```

This code frees the node that should be removed but does not link the previous one to the next one, so the list becomes incorrect. As you do not re-use the freed memory, it keeps its previous values but you do invoke Undefined Behaviour by using it.

You will have to track the previous record to fix the links. A possible code could be:

```<code>while (track->next != NULL){
   counter = 0;
   pass = 0;
   node *old = NULL;
   m = track->val;
   curr = track;
   while((curr)->next != NULL){
       node *next = curr->next;
       if(m == (curr)->val){
           pass++;
           counter++;
           if(pass > 1){
               old->next = next;  // old cannot be NULL because pass>1
               free(curr);
               curr = NULL;
           }
       }
       if (curr != NULL) old = curr;
       curr = next;
   }
   track->rip = counter;
   track = track->next;
}
</code>```

Body:
I have tried to make this function but sometimes I get a problem on runtime. I need to take in input a list like 1-2-3-2-4-6-1-2 and the list should be modified as 1-2-3-4-6 so once for every node and I should save how many times is a node repeated so for example 1 is repeated 2 times the 2 is repeated 3 times etc.
But sometimes it doesn't work I cannot understand why.
If you run it following what I wrote just after you'll see the problem:
How many nodes: 5 than write 1, 1, 2, 4, 2 and the output should be 1, 2 -> 2, 2 -> 4 (that means 1 is repeated two times, 2 is repeated two times and 4 is repeated 1 time). If I give in input 1, 2, 3, 2, 1 I get the "right output" plus a garbage value. More are the numbers higher is the probability that it doesn't work :(

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

typedef struct Node{
   int val;
   int rip;
   struct Node *next;
} node;

node *modify(node *head);

void print(node *head2);

int main(){

   int m, i;

   printf("How many nodes: \n");
   scanf("%d", &m);

   node *head = NULL;
   head = (node *)malloc(sizeof(node));
   node *temp = head;
   node *head2 = NULL;
  for(i=0; i < m; i++){
       temp->next = (node *)malloc(sizeof(node));
       printf("Write the value in position %d: \n", i);
       scanf("%d", &temp->val);
       temp = temp->next;
       temp->next = NULL;
   }

   head2 = modify(head);

   print(head2);

   return 0;
}

node *modify(node *head){

   int counter, pass, m;

   node *curr = head;
   node *track = head;

while (track->next != NULL){
       counter = 0;
       pass = 0;
       m = track->val;
       while((curr)->next != NULL){
           if(m == (curr)->val){
               pass++;
               counter++;
               if(pass > 1){
                   node *removed = curr;
                   curr = (curr)->next;
                   free(removed);
               }
               if(pass == 1)
                   curr = curr->next;
           }
           else{
               curr = (curr)->next;
           }
       }
       track->rip = counter;
       track = track->next;
       curr = track;
   }

return head;
}

void print(node *head2){

   while(head2->next != NULL){
       printf("%d, %d -> ", head2->val, head2->rip);
       head2 = head2->next;
   }
   printf("\n");
}

Body:
The error is here:

           if(pass > 1){
               node *removed = curr;
               curr = (curr)->next;
               free(removed);
           }

This code frees the node that should be removed but does not link the previous one to the next one, so the list becomes incorrect. As you do not re-use the freed memory, it keeps its previous values but you do invoke Undefined Behaviour by using it.

You will have to track the previous record to fix the links. A possible code could be:

while (track->next != NULL){
   counter = 0;
   pass = 0;
   node *old = NULL;
   m = track->val;
   curr = track;
   while((curr)->next != NULL){
       node *next = curr->next;
       if(m == (curr)->val){
           pass++;
           counter++;
           if(pass > 1){
               old->next = next;  // old cannot be NULL because pass>1
               free(curr);
               curr = NULL;
           }
       }
       if (curr != NULL) old = curr;
       curr = next;
   }
   track->rip = counter;
   track = track->next;
}


问:
Excel 365 - Open csv files automatically (list separator solution not working)
If I opened a csv file, Excel used to automatically format it into columns. At some point in the past Excel just stopped doing this.

I'm using Office 365 Business, Excel version 1803. Windows 10 ver 1709

I want to be able to double click on a csv file and have it open automatically formatted into columns.

This is not machine specific as my coworker has an identical issue on a different brand of computer.

So far I have tried the following:

Changing the list separator: I cannot find the list separator setting in office 365, I think it may have been buried or removed.

The "decimal separator" is a comma.

Creating a simple csv to test with. I tested with this csv and it still has the same problem:

Date,Count
2018-01-02,22
2018-01-03,24

I do know I can use text to columns and write macros to accomplish this. I want to avoid those if possible so I can just open a csv and it's formatted.

Thanks, any insights here would be great. I am really hoping it is some system or excel setting.

答:
I came across this and I hope that 1 year and 10 months later it will still help somebody.
Had the same problem and solved it by "Change date, time or number formats" in the Control Panel.
Standard the Format is "Match Windows display language"
My Windows is in English (list separator = ",") but I live in Belgium where the list separator is ";"
So in formats, I changed the Format to "Dutch (Belgium)". That solved it for me.

Once you change your country, double-check in "Additional Settings" if the separator is what you want. Keep in mind that also other things might change, such as decimal symbol and digit grouping symbol.
If you don't want that, you might only want to change the separator and don't change the country.

Best regards,
Koen


问:
Swift- Using Delegation to display on tableView
In trying to learn to use the delegate in Swift. The problem is I used the delegate to append a string value (from pickCourse() to ViewController()) to sampleArr; however, it does seem to append but does not show up on the ViewController()'s tableview. I tried to use viewWillAppear but I have no luck. Does anyone know how I can get the sampleArr to appear on ViewController()'s tableview after I selected a someString value in pickCourses() which automatically popbacks to ViewController()?

```<code>import UIKit

class ViewController: UITableViewController, testingDelegate {

    let cellId = "Something"

    var sampleArr : [String] = []

    func sendDataback(data: String) {
        sampleArr.append(data)
        tableView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)

        navigationItem.title = "Testing Delegate??"
        navigationController?.navigationBar.prefersLargeTitles = true

        self.view.backgroundColor = UIColor.white

        let button1 = UIBarButtonItem(title: "Add A String", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

    }

    @objc func addTapped(sender: UIBarButtonItem!) {

        let destination = PickCourses()
        destination.delegate = self
        navigationController?.pushViewController(destination, animated: true)
    }

}
</code>```

```<code>import UIKit

protocol testingDelegate {
    func sendDataback(data: String)
}

class PickCourses: UITableViewController {

    var delegate: testingDelegate?

    let cellId = "leariningtopassdata"

    let someString = [
        "One One One One",
        "Two Two Two Two",
        "Three Three Three Three",
        "Four Four Four",
        "Five Five Five"
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Pick Some String"
        navigationController?.navigationBar.prefersLargeTitles = true

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView() //removes extra line in UITableView

        tableView.isScrollEnabled = false //disables scrolling
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return someString.count
        }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        let stringlabel = self.someString[indexPath.row]
        cell.textLabel?.text = stringlabel

        return cell
    }

    let vc = ViewController()

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)
        let data = someString[indexPath.row]
        delegate?.sendDataback(data: data)
        self.navigationController?.popViewController(animated: true)
    }

}
</code>```

答:
You should read UITableViewController:

You must also override the data source and delegate methods required
  to fill your table with data.

I can't find where you override the data source methods in ViewController. You did this only in PickCourses.

Body:
In trying to learn to use the delegate in Swift. The problem is I used the delegate to append a string value (from pickCourse() to ViewController()) to sampleArr; however, it does seem to append but does not show up on the ViewController()'s tableview. I tried to use viewWillAppear but I have no luck. Does anyone know how I can get the sampleArr to appear on ViewController()'s tableview after I selected a someString value in pickCourses() which automatically popbacks to ViewController()?

import UIKit

class ViewController: UITableViewController, testingDelegate {

    let cellId = "Something"

    var sampleArr : [String] = []

    func sendDataback(data: String) {
        sampleArr.append(data)
        tableView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)

        navigationItem.title = "Testing Delegate??"
        navigationController?.navigationBar.prefersLargeTitles = true

        self.view.backgroundColor = UIColor.white

        let button1 = UIBarButtonItem(title: "Add A String", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

    }

    @objc func addTapped(sender: UIBarButtonItem!) {

        let destination = PickCourses()
        destination.delegate = self
        navigationController?.pushViewController(destination, animated: true)
    }

}

import UIKit

protocol testingDelegate {
    func sendDataback(data: String)
}

class PickCourses: UITableViewController {

    var delegate: testingDelegate?

    let cellId = "leariningtopassdata"

    let someString = [
        "One One One One",
        "Two Two Two Two",
        "Three Three Three Three",
        "Four Four Four",
        "Five Five Five"
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Pick Some String"
        navigationController?.navigationBar.prefersLargeTitles = true

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView() //removes extra line in UITableView

        tableView.isScrollEnabled = false //disables scrolling
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return someString.count
        }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        let stringlabel = self.someString[indexPath.row]
        cell.textLabel?.text = stringlabel

        return cell
    }

    let vc = ViewController()

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)
        let data = someString[indexPath.row]
        delegate?.sendDataback(data: data)
        self.navigationController?.popViewController(animated: true)
    }

}


问:
Should I normalize this table?
I have a table Items which stores fetched book data from Amazon.  This Amazon data is inserted into Items as users browse the site, so any INSERT that occurs needs to be efficient.

Here's the table:

```<code>CREATE TABLE IF NOT EXISTS `items` (
  `Item_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Item_ISBN` char(13) DEFAULT NULL,
  `Title` varchar(255) NOT NULL,
  `Edition` varchar(20) DEFAULT NULL,
  `Authors` varchar(255) DEFAULT NULL,
  `Year` char(4) DEFAULT NULL,
  `Publisher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Item_ID`),
  UNIQUE KEY `Item_Data` (`Item_ISBN`,`Title`,`Edition`,`Authors`,`Year`,`Publisher`),
  KEY `ISBN` (`Item_ISBN`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=1 ;
</code>```

Normalizing this table would presumably mean creating tables for Titles, Authors, and Publishers.  My concern with doing this is that the insert would become too complex.. To insert a single Item, I'd have to:

Check for the Publisher in Publishers to SELECT Publisher_ID, otherwise insert it and use mysql_insert_id() to get Publisher_ID.

Check for the Authors in Authors to SELECT Authors_ID, otherwise insert it and use mysql_insert_id() to get Authors_ID.

Check for the Title in Titles to SELECT Title_ID, otherwise insert it and use mysql_insert_id() to get Title_ID.

Use those ID's to finally insert the Item (which may in fact be a duplicate, so this whole process would have been a waste..)

Does that argue against normalization for this table?

Note: The goal of Items is not to create a comprehensive database of books, so that a user would say "Show me all the books by Publisher X."  The Items table is just used to cache Items for my users' search results.

答: Considering your goal, I definitely wouldn't normalize this.

Title: Should I normalize this table?

Body:
I have a table Items which stores fetched book data from Amazon.  This Amazon data is inserted into Items as users browse the site, so any INSERT that occurs needs to be efficient.

Here's the table:

CREATE TABLE IF NOT EXISTS `items` (
  `Item_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Item_ISBN` char(13) DEFAULT NULL,
  `Title` varchar(255) NOT NULL,
  `Edition` varchar(20) DEFAULT NULL,
  `Authors` varchar(255) DEFAULT NULL,
  `Year` char(4) DEFAULT NULL,
  `Publisher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Item_ID`),
  UNIQUE KEY `Item_Data` (`Item_ISBN`,`Title`,`Edition`,`Authors`,`Year`,`Publisher`),
  KEY `ISBN` (`Item_ISBN`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=1 ;

Normalizing this table would presumably mean creating tables for Titles, Authors, and Publishers.  My concern with doing this is that the insert would become too complex.. To insert a single Item, I'd have to:

Check for the Publisher in Publishers to SELECT Publisher_ID, otherwise insert it and use mysql_insert_id() to get Publisher_ID.

Check for the Authors in Authors to SELECT Authors_ID, otherwise insert it and use mysql_insert_id() to get Authors_ID.

Check for the Title in Titles to SELECT Title_ID, otherwise insert it and use mysql_insert_id() to get Title_ID.

Use those ID's to finally insert the Item (which may in fact be a duplicate, so this whole process would have been a waste..)

Does that argue against normalization for this table?

Note: The goal of Items is not to create a comprehensive database of books, so that a user would say "Show me all the books by Publisher X."  The Items table is just used to cache Items for my users' search results.


答:
I suppose you defined N somewhere (probably N=5 in you case).

<s> Most compilers automatically adds "return 0" statement if return statement is missing. </s>

* See comments for more info. Actually it is an Undefined Behavior*

In you recursive function, is better to pass the remaining length of the array and stop when you reach n==0.

Avoid to look at global variables or defines inside functions.

```<code>int minimo(int array[], int n)
{
  ...
  if (n == 0)
  ...
            min = minimo(array, n-1);
  ...
}
</code>```

(other modification required)

Actually you should know the length of array only on main function, so call it as:

```<code>printf("Min: %d\n", minimo(array, N));
</code>```

Title: Returns without a "return" command

Body:
C programming language, compiled with gcc, terminal bash in WSL

I have written a recursive function, to find the lowest number in an array, which works just fine.

/*01*/    int minimo(int array[], int n)
/*02*/    {
/*03*/      static int min = 0;
/*04*/
/*05*/      if (n == N)
/*06*/      {
/*07*/          return array[n-1];
/*08*/      }
/*09*/      else
/*10*/      {
/*11*/          min = minimo(array, n+1);
/*12*/          if(array[n]<min){
/*13*/              min = array[n];
/*14*/          }
/*15*/      }
/*16*/    }

The only problem is that it shouldn't work, because it doesn't return "min" to the caller...

int main()
{
    //Var
    int array[N] = {10, 2, 5, 1, 7};
    printf("Min: %d\n", minimo(array, 0));
}

My concern is actually a problem, but not on my machine onto which the function works just fine as it is;
it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Between line 15-16 I have to add return min;

/*15*/      }
            return min;
/*16*/    }

My questions for you are the following:

How can  a function return a variable automatically?

Is it possible that it does return the only variable that I created (static int min)?

Or is it a "problem" related to the static attribute that the variable has?

Does it have anything to do with the nature of the function (recursive)?

This is my first post, please be kind if I'm breaking any forum rule.

Body:
I suppose you defined N somewhere (probably N=5 in you case).

<s> Most compilers automatically adds "return 0" statement if return statement is missing. </s>

* See comments for more info. Actually it is an Undefined Behavior*

In you recursive function, is better to pass the remaining length of the array and stop when you reach n==0.

Avoid to look at global variables or defines inside functions.

int minimo(int array[], int n)
{
  ...
  if (n == 0)
  ...
            min = minimo(array, n-1);
  ...
}

(other modification required)

Actually you should know the length of array only on main function, so call it as:

printf("Min: %d\n", minimo(array, N));


问:
Where can i find a dataset of handwritten broken numbers or floats or digits?
I m looking for DATASET of HANDWRITTEN BROKEN NUMBERS or floats or digits which means for example a teacher s handwritten mark of students or anything like these images below

thank you in advance

example

答:
You can start with the most popular handwritten digits dataset.

Here's a link to the website from where you can download.

http://yann.lecun.com/exdb/mnist/

http://cis.jhu.edu/~sachin/digit/digit.html


问:
i am finding this.myScrollContainer.nativeElement.scrollHeight but getting Cannot read property 'nativeElement' of undefined
When i open this template I need to find out one div scrollHeight from the code this.myScrollContainer.nativeElement.scrollHeight. But I am getting nativeElement. Actually div scroll is coming top to bottom. What I need to do is scroll bottom to top. Does anyone know what is the issue?

<ng-template #ModalReviewHistory>

        {{ "workFlowCommentsHistory.commentModalTitle" | translate }}
        <button
          type="button"
          class="close pull-right"
          aria-label="Close"
          (click)="modalRef.hide()"
        >
          ×
        </button>

          {{ "workFlowCommentsHistory.noCommentMessage" | translate }}

                  {{ comments?.creator?.firstName }} |
                  {{ comments.role }}

                  {{ comments?.creator?.createdAt | myDateFormat }}

                    <button
                      (click)="clickViewMore(comments.id, FeedbackModel)"
                      type="button"
                      class="btn btn-outline-primary font-12 btn-sm"
                    >
                      {{ "workFlowCommentsHistory.viewBtn" | translate }}
                    </button>

                  <button
                    (click)="onClickReplyToComment(i, comments)"
                    class="btn btn-outline-primary btn-sm"
                    title="Reply"
                  >

                  </button>

                {{ comments?.contents }}

                      {{ reply.creator }} |
                      {{ reply.createdAt | myDateFormat }}

                  {{ reply?.contents }}

            <form [formGroup]="lineNumberReplyCommentForm" novalidate>

                  <textarea
                    placeholder="Your comment goes here..."
                    pInputTextarea
                    formControlName="comment"
                    class="form-control"
                    rows="2"
                    style="width: 350px;"
                  ></textarea>

                    {{
                        "lineComments.viewLineComment.replyCommentValidation"
                          | translate
                      }}

                <button
                  (click)="submitlineNumberReplyCommentForm()"
                  class="btn btn-primary"
                >
                  {{ "lineComments.viewLineComment.replyBtn" | translate }}
                </button>

            </form>

        <button
          (click)="modalRef.hide()"
          type="button"
          class="btn btn-outline-primary"
        >
          {{ "prReviewResponseModal.cancel" | translate }}
        </button>

      </ng-template>
```

```          @ViewChild('scrollMe')  myScrollContainer: ElementRef;
          @ViewChild('ModalReviewHistory') ModalReviewHistory: ElementRef;
    onShowReviewerList() {
     this.modalRef = this.modalService.show(this.ModalReviewHistory,
        Object.assign({}, {
          class: 'gray modal-lg'
        },
        this.config));
    this.scrollToBottom();
    }
    scrollToBottom() {
      this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    }
```

答:
<ng-template> isn't a physical element in the DOM. Converting this to a
 or something that is created in the DOM should fix your problem.

For example:

```<code><div #ModalReviewHistory>
  <!-- modal stuff here -->
</div>
</code>```

You can diagnose this by inspecting the HTML that gets created. You will see that <ng-template> doesn't exist.

Body:
When i open this template I need to find out one div scrollHeight from the code this.myScrollContainer.nativeElement.scrollHeight. But I am getting nativeElement. Actually div scroll is coming top to bottom. What I need to do is scroll bottom to top. Does anyone know what is the issue?

<ng-template #ModalReviewHistory>

        {{ "workFlowCommentsHistory.commentModalTitle" | translate }}
        <button
          type="button"
          class="close pull-right"
          aria-label="Close"
          (click)="modalRef.hide()"
        >
          ×
        </button>

          {{ "workFlowCommentsHistory.noCommentMessage" | translate }}

                  {{ comments?.creator?.firstName }} |
                  {{ comments.role }}

                  {{ comments?.creator?.createdAt | myDateFormat }}

                    <button
                      (click)="clickViewMore(comments.id, FeedbackModel)"
                      type="button"
                      class="btn btn-outline-primary font-12 btn-sm"
                    >
                      {{ "workFlowCommentsHistory.viewBtn" | translate }}
                    </button>

                  <button
                    (click)="onClickReplyToComment(i, comments)"
                    class="btn btn-outline-primary btn-sm"
                    title="Reply"
                  >

                  </button>

                {{ comments?.contents }}

                      {{ reply.creator }} |
                      {{ reply.createdAt | myDateFormat }}

                  {{ reply?.contents }}

            <form [formGroup]="lineNumberReplyCommentForm" novalidate>

                  <textarea
                    placeholder="Your comment goes here..."
                    pInputTextarea
                    formControlName="comment"
                    class="form-control"
                    rows="2"
                    style="width: 350px;"
                  ></textarea>

                    {{
                        "lineComments.viewLineComment.replyCommentValidation"
                          | translate
                      }}

                <button
                  (click)="submitlineNumberReplyCommentForm()"
                  class="btn btn-primary"
                >
                  {{ "lineComments.viewLineComment.replyBtn" | translate }}
                </button>

            </form>

        <button
          (click)="modalRef.hide()"
          type="button"
          class="btn btn-outline-primary"
        >
          {{ "prReviewResponseModal.cancel" | translate }}
        </button>

      </ng-template>

          @ViewChild('scrollMe')  myScrollContainer: ElementRef;
          @ViewChild('ModalReviewHistory') ModalReviewHistory: ElementRef;
    onShowReviewerList() {
     this.modalRef = this.modalService.show(this.ModalReviewHistory,
        Object.assign({}, {
          class: 'gray modal-lg'
        },
        this.config));
    this.scrollToBottom();
    }
    scrollToBottom() {
      this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    }

Body:
<ng-template> isn't a physical element in the DOM. Converting this to a <div> or something that is created in the DOM should fix your problem.

For example:

<div #ModalReviewHistory>
  <!-- modal stuff here -->
</div>

You can diagnose this by inspecting the HTML that gets created. You will see that <ng-template> doesn't exist.


问:
Action not dispatching using react/ redux/ typescript
I get the error:

node_modules\react-native\Libraries\Core\ExceptionsManager.js:86 TypeError: Cannot read property 'videos' of undefined

This error is located at:
      in Connect(HomeHeader) (at AppNavigator.tsx:116)
      in RCTView (at View.js:35)

App.tsx:

```<code>const App = () => {
  return (
    <ImageBackground
      source={require('./assets/images/TC_background.jpg')}
      style={styles.container}>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <AppNavigator
            ref={navigatorRef => {
              NavigationService.setTopLevelNavigator(navigatorRef);
            }}
          />
        </PersistGate>
      </Provider>
    </ImageBackground>
  );
};
</code>```

AppNavigator.tsx:

```<code>const config = {
    contentOptions: {
        activeTintColor: '#e91e63',
        inactiveTintColor: '#ffffff',
        itemStyle: {
            flexDirection: 'row-reverse',
        },
    },
    drawerWidth: 200,
    drawerPosition: 'left',
    contentComponent: SideMenu,
    drawerBackgroundColor: '#00000020',
    cardStyle: {
        backgroundColor: 'transparent',
        opacity: 1,
    },
};

const withHeader = (
    screen: Function,
    routeName: string,
    Header: any,
): StackNavigator =>
    createStackNavigator(
        {
            [routeName]: {
                screen,
                navigationOptions: ({routeName, props}) => ({
                    header: props => <Header {...props} />,
                }),
            },
        },
        {
            initialRoute: 'Home',
            cardStyle: {
                backgroundColor: 'transparent',
                opacity: 1,
            },
            transitionConfig: () => ({
                containerStyle: {
                    backgroundColor: 'transparent',
                },
            }),
        },
    );

const routes = {
    ....
};

const NestedDrawer = createDrawerNavigator(routes, config);

const MainStack = createStackNavigator(
    {
        Home: {
            screen: HomeScreen,
            navigationOptions: ({ props }) => ({
                header: (props: any) => <HomeHeader {...props} />,
            }),
        },
        ...
    },
    {
        initialRoute: 'Home',
        cardStyle: {
            backgroundColor: 'transparent',
            opacity: 1,
        },
    },
);

export default createAppContainer(MainStack);
</code>```

HomeHeader:

```<code>class HomeHeader extends Component {
    constructor(props) {
        super(props);
        this.state = { term: "", videos: [] };
        this.onSubmitEdit = this.onSubmitEdit.bind(this);
    }
    componentDidMount() {
        this.SearchFilterFunction("");
    }
    SearchFilterFunction(term) {
        const { filteredVideo } = this.props;
        filteredVideo(term);
    }

    onSubmitEdit() {
        const {
            navigation: { navigate },
            initSearch
        } = this.props;

        navigate("VideoEpisodes");
    }

    onPress(id) {
        const {
            navigation,
            initSearch,
            navigation: { dispatch }
        } = this.props;
        initSearch();

        const resetAction = StackActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({
                    routeName: "VideoPlayer",
                    params: { id }
                })
            ]
        });
        dispatch(resetAction);
    }
    separator = () => <View style={styles.separator} />;
    render() {
        const {
            navigation,
            videos,
            search: { term },
            scene: {
                route: { routeName: title }
            }
        } = this.props;
        return (
            <..... />
        );
    }
}
const mapDispatchToProps = dispatch => ({
    filteredVideo: data => dispatch(filteredVideo(data)),
    initSearch: () => dispatch(initSearch())
});

const mapStateToProps = state => {
    return {
        videos: state.iaApp.videos,
        search: state.iaApp.search
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(HomeHeader);

const styles = StyleSheet.create({
    container: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        padding: 10,
        marginTop: Platform.OS === "ios" ? 20 : 0,
        paddingTop: Platform.OS === "ios" ? 20 : 10
    },
    title: {
        color: "#fff",
        fontSize: 18
    },
    separator: {
        borderBottomColor: "#d1d0d4",
        borderBottomWidth: 1
    }
});
</code>```

HomeScreen:

```<code>class HomeScreen extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
  }
  componentDidMount() {
    const {fetchData} = this.props;
    fetchData();
  }

  render() {
    const {videos} = this.props;

    return (
      <View style={styles.container}>
        <HomeMenu {...this.props} />
      </View>
    );
  }
}

const mapDispatchToProps = (dispatch: any) => ({
  fetchData: () => dispatch(fetchData()),
});
const mapStateToProps = (state: any) => {
  return {
    videos: state.IaApp.videos,
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(HomeScreen);
</code>```

答:
Try to change the name of the props as sometimes the same props and dispatch action function name doesn't work

Instead of:

```<code>const mapDispatchToProps = (dispatch: any) => ({
  fetchData: () => dispatch(fetchData()),
});
</code>```

change to:

```<code>const mapDispatchToProps = (dispatch: any) => ({
  _fetchData: () => dispatch(fetchData()),
});
</code>```

and call this:

```<code> componentDidMount() {
    const {_fetchData} = this.props;
    _fetchData();
  }
</code>```

let me know if this works

Body:
I get the error:

node_modules\react-native\Libraries\Core\ExceptionsManager.js:86 TypeError: Cannot read property 'videos' of undefined

This error is located at:
      in Connect(HomeHeader) (at AppNavigator.tsx:116)
      in RCTView (at View.js:35)

App.tsx:

const App = () => {
  return (
    <ImageBackground
      source={require('./assets/images/TC_background.jpg')}
      style={styles.container}>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <AppNavigator
            ref={navigatorRef => {
              NavigationService.setTopLevelNavigator(navigatorRef);
            }}
          />
        </PersistGate>
      </Provider>
    </ImageBackground>
  );
};

AppNavigator.tsx:

const config = {
    contentOptions: {
        activeTintColor: '#e91e63',
        inactiveTintColor: '#ffffff',
        itemStyle: {
            flexDirection: 'row-reverse',
        },
    },
    drawerWidth: 200,
    drawerPosition: 'left',
    contentComponent: SideMenu,
    drawerBackgroundColor: '#00000020',
    cardStyle: {
        backgroundColor: 'transparent',
        opacity: 1,
    },
};

const withHeader = (
    screen: Function,
    routeName: string,
    Header: any,
): StackNavigator =>
    createStackNavigator(
        {
            [routeName]: {
                screen,
                navigationOptions: ({routeName, props}) => ({
                    header: props => ,
                }),
            },
        },
        {
            initialRoute: 'Home',
            cardStyle: {
                backgroundColor: 'transparent',
                opacity: 1,
            },
            transitionConfig: () => ({
                containerStyle: {
                    backgroundColor: 'transparent',
                },
            }),
        },
    );

const routes = {
    ....
};

const NestedDrawer = createDrawerNavigator(routes, config);

const MainStack = createStackNavigator(
    {
        Home: {
            screen: HomeScreen,
            navigationOptions: ({ props }) => ({
                header: (props: any) => <HomeHeader {...props} />,
            }),
        },
        ...
    },
    {
        initialRoute: 'Home',
        cardStyle: {
            backgroundColor: 'transparent',
            opacity: 1,
        },
    },
);

export default createAppContainer(MainStack);

HomeHeader:

class HomeHeader extends Component {
    constructor(props) {
        super(props);
        this.state = { term: "", videos: [] };
        this.onSubmitEdit = this.onSubmitEdit.bind(this);
    }
    componentDidMount() {
        this.SearchFilterFunction("");
    }
    SearchFilterFunction(term) {
        const { filteredVideo } = this.props;
        filteredVideo(term);
    }

    onSubmitEdit() {
        const {
            navigation: { navigate },
            initSearch
        } = this.props;

        navigate("VideoEpisodes");
    }

    onPress(id) {
        const {
            navigation,
            initSearch,
            navigation: { dispatch }
        } = this.props;
        initSearch();

        const resetAction = StackActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({
                    routeName: "VideoPlayer",
                    params: { id }
                })
            ]
        });
        dispatch(resetAction);
    }
    separator = () => <View style={styles.separator} />;
    render() {
        const {
            navigation,
            videos,
            search: { term },
            scene: {
                route: { routeName: title }
            }
        } = this.props;
        return (
            <..... />
        );
    }
}
const mapDispatchToProps = dispatch => ({
    filteredVideo: data => dispatch(filteredVideo(data)),
    initSearch: () => dispatch(initSearch())
});

const mapStateToProps = state => {
    return {
        videos: state.iaApp.videos,
        search: state.iaApp.search
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(HomeHeader);

const styles = StyleSheet.create({
    container: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        padding: 10,
        marginTop: Platform.OS === "ios" ? 20 : 0,
        paddingTop: Platform.OS === "ios" ? 20 : 10
    },
    title: {
        color: "#fff",
        fontSize: 18
    },
    separator: {
        borderBottomColor: "#d1d0d4",
        borderBottomWidth: 1
    }
});

HomeScreen:

class HomeScreen extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
  }
  componentDidMount() {
    const {fetchData} = this.props;
    fetchData();
  }

  render() {
    const {videos} = this.props;

    return (
      <View style={styles.container}>
        <HomeMenu {...this.props} />
      </View>
    );
  }
}

const mapDispatchToProps = (dispatch: any) => ({
  fetchData: () => dispatch(fetchData()),
});
const mapStateToProps = (state: any) => {
  return {
    videos: state.IaApp.videos,
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(HomeScreen);

Body:
Try to change the name of the props as sometimes the same props and dispatch action function name doesn't work

Instead of:

const mapDispatchToProps = (dispatch: any) => ({
  fetchData: () => dispatch(fetchData()),
});

change to:

const mapDispatchToProps = (dispatch: any) => ({
  _fetchData: () => dispatch(fetchData()),
});

and call this:

 componentDidMount() {
    const {_fetchData} = this.props;
    _fetchData();
  }

let me know if this works