问:
Find the Last Cell Value of the 2nd Column Set for each 1st Column Cell in EXCEL
I have the following structured table in excel where 1000s of rows included.

I want to return the Last Cell Value of Column B for Each value in Column A.

For example:

For Cell A1 -> I want to return the Cell B5.

For Cell A6 -> I want to return the Cell B9.

I have tried with VLOOKUP, HLOOKUP, INDEX likewise so many formulas where I ended with more conflict situations. Can anyone please write down a Formula to give my requirement a life?

答:
Try this shorter, without helper column and non-array formula solution

In C1, formula copied down :

```<code>=IF(A1="","",INDEX(B1:B$9,MATCH(1,FREQUENCY(1,0+(A2:A$9<>"")),0)))
</code>```

Body:
Try this shorter, without helper column and non-array formula solution

In C1, formula copied down :

=IF(A1="","",INDEX(B1:B$9,MATCH(1,FREQUENCY(1,0+(A2:A$9<>"")),0)))


来源: stackexchange

问:
How to show excel sheet chart in excel VBA userform
I have a userform with two controls. One combobox called ComboBox1 and an image called image1. I am trying to show a chart on a sheet to this image1 during ComboBox1 change event as below

```<code>Private Sub ComboBox1_Change()
  Call UpdateChart
End Sub

Private Sub UpdateChart()

Dim sTempFile As String
Dim oChart As Chart

sTempFile = Environ("temp") & "\temp.gif"

Set oChart = Worksheets(UserForm1.ComboBox1.Value).ChartObjects("Chart 1").Chart

oChart.Export Filename:=sTempFile, FilterName:="GIF"

UserForm1.Image1.Picture = LoadPicture(sTempFile)

Kill sTempFile

End Sub
</code>```

This is working perfectly fine. But once I clicked on the image, ComboBox1 change event is not working anymore. In other words, the chart is not changing according to combobox change if I clicked on the image. Does anyone know why?
PS: I took the above code from some other site and modified to suit my needs.

Edit 1

ComboBox1 populating as below during Userform initialization.

```<code>Private Sub UserForm_Initialize()
With UserForm1.ComboBox1
    Dim ws As Worksheet
    For Each ws In Worksheets
        Select Case ws.Name
            Case "MainPage", "Raw Data"

            Case Else
                .AddItem ws.Name
        End Select
    Next ws
End With
End Sub
</code>```

ComboBox1 values are the sheet names

答:
Try this - adding Me.Repaint fixed it for me

```<code>Private Sub UpdateChart()

    Dim sTempFile As String
    Dim oChart As Chart

    sTempFile = Environ("temp") & "\temp.gif"

    Set oChart = Worksheets(Me.ComboBox1.Value).ChartObjects("Chart 1").Chart

    oChart.Export Filename:=sTempFile, FilterName:="GIF"

    Me.Image1.Picture = LoadPicture(sTempFile)

    Me.Repaint   '<<<<<

    Kill sTempFile

End Sub
</code>```

FYI within a form's code it's better to use Me instead of (eg) UserForm1 - that way you can rename the form if you need without having to edit all the code.

ContentLicense: CC BY-SA 4.0

Body:
I have a userform with two controls. One combobox called ComboBox1 and an image called image1. I am trying to show a chart on a sheet to this image1 during ComboBox1 change event as below

Private Sub ComboBox1_Change()
  Call UpdateChart
End Sub

Private Sub UpdateChart()

Dim sTempFile As String
Dim oChart As Chart

sTempFile = Environ("temp") & "\temp.gif"

Set oChart = Worksheets(UserForm1.ComboBox1.Value).ChartObjects("Chart 1").Chart

oChart.Export Filename:=sTempFile, FilterName:="GIF"

UserForm1.Image1.Picture = LoadPicture(sTempFile)

Kill sTempFile

End Sub

This is working perfectly fine. But once I clicked on the image, ComboBox1 change event is not working anymore. In other words, the chart is not changing according to combobox change if I clicked on the image. Does anyone know why?
PS: I took the above code from some other site and modified to suit my needs.

Edit 1

ComboBox1 populating as below during Userform initialization.

Private Sub UserForm_Initialize()
With UserForm1.ComboBox1
    Dim ws As Worksheet
    For Each ws In Worksheets
        Select Case ws.Name
            Case "MainPage", "Raw Data"

            Case Else
                .AddItem ws.Name
        End Select
    Next ws
End With
End Sub

ComboBox1 values are the sheet names

Body:
Try this - adding Me.Repaint fixed it for me

Private Sub UpdateChart()

    Dim sTempFile As String
    Dim oChart As Chart

    sTempFile = Environ("temp") & "\temp.gif"

    Set oChart = Worksheets(Me.ComboBox1.Value).ChartObjects("Chart 1").Chart

    oChart.Export Filename:=sTempFile, FilterName:="GIF"

    Me.Image1.Picture = LoadPicture(sTempFile)

    Me.Repaint   '<<<<<

    Kill sTempFile

End Sub

FYI within a form's code it's better to use Me instead of (eg) UserForm1 - that way you can rename the form if you need without having to edit all the code.


问:
Memoization By Hand in Python Function Using Tuples as Cache Keys
I'm trying to implement by-hand memoization in the following function, which calculates the optimal please of eating chocolates given that waiting supposedly increases the pleasure:

```<code>def joy(chocs, day):
    n = len(chocs)
    if n == 1:
        return day * chocs[0]
    left = day * chocs[0] + joy(chocs[1:], day + 1)
    right = day * chocs[n - 1] + joy(chocs[:n - 1], day + 1)
    return max(left, right)
</code>```

I want to use a cache dictionary to store prvious results, but I'm stuck on the implementation. Here's my attempt so far:

```<code>def joy(chocs, day, cache={}):
    if (chocs, day) in cache:
        return cache[(chocs, day)]
    n = len(chocs)
    if n == 1:
        return day * chocs[0]
    left = day * chocs[0] + joy(chocs[1:], day + 1)
    right = day * chocs[n - 1] + joy(chocs[:n - 1], day + 1)
    return max(left, right)
</code>```

I'm stuck on what to use as the key/value for storing the left/right results.

Can anyone help me to complete the memoized version of the function please?

答:
Store the result in your cache before you return.

result = max(left, right)
cache[(chocs, day)] = result
return result
```

There's no need to store the result of the base case.

Body:
I'm trying to implement by-hand memoization in the following function, which calculates the optimal please of eating chocolates given that waiting supposedly increases the pleasure:

def joy(chocs, day):
    n = len(chocs)
    if n == 1:
        return day * chocs[0]
    left = day * chocs[0] + joy(chocs[1:], day + 1)
    right = day * chocs[n - 1] + joy(chocs[:n - 1], day + 1)
    return max(left, right)

I want to use a cache dictionary to store prvious results, but I'm stuck on the implementation. Here's my attempt so far:

def joy(chocs, day, cache={}):
    if (chocs, day) in cache:
        return cache[(chocs, day)]
    n = len(chocs)
    if n == 1:
        return day * chocs[0]
    left = day * chocs[0] + joy(chocs[1:], day + 1)
    right = day * chocs[n - 1] + joy(chocs[:n - 1], day + 1)
    return max(left, right)

I'm stuck on what to use as the key/value for storing the left/right results.

Can anyone help me to complete the memoized version of the function please?

Body:
Store the result in your cache before you return.

result = max(left, right)
cache[(chocs, day)] = result
return result

There's no need to store the result of the base case.


问:
how to fix this Zabbix alert template to work?
Zabbix Version: 4.0 LTS

```<code># template

Alert: {EVENT.NAME}
Severity: {EVENT.SEVERITY}

Top cpu:
{HOST.NAME:sys.process.top.cpu.last()}

Top mem:
{HOST.NAME:sys.process.top.mem.last()}

Problem started at {EVENT.TIME} on {EVENT.DATE}

</code>```

Render result:

```<code>Alert: test top usage
Severity: Disaster

Top cpu:
*UNKNOWN*

Top mem:
*UNKNOWN*

Problem started at 03:35:00 on 2020.05.29
</code>```

How to fix it to normal? I hope it could get the value of the current host.

答:
It should use the {{HOST.HOST}:sys.process.top.cpu.last()} to work.

More information could refer to this online document.

https://books.google.com.hk/books?id=xgjVDQAAQBAJ&pg=PA333&lpg=PA333&dq=zabbix+%7B%7BHOST.NAME%7D%7D:key.last()%7D&source=bl&ots=zQHgguJ0hm&sig=ACfU3U3-FOGUIJjtJSvpoC_l5YXpx6l7fQ&hl=zh-CN&sa=X&redir_esc=y&sourceid=cndr#v=onepage&q=zabbix%20%7B%7BHOST.NAME%7D%7D%3Akey.last()%7D&f=false

Body:
Zabbix Version: 4.0 LTS

# template

Alert: {EVENT.NAME}
Severity: {EVENT.SEVERITY}

Top cpu:
{HOST.NAME:sys.process.top.cpu.last()}

Top mem:
{HOST.NAME:sys.process.top.mem.last()}

Problem started at {EVENT.TIME} on {EVENT.DATE}

Render result:

Alert: test top usage
Severity: Disaster

Top cpu:
*UNKNOWN*

Top mem:
*UNKNOWN*

Problem started at 03:35:00 on 2020.05.29

How to fix it to normal? I hope it could get the value of the current host.


问:
How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server
I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

```<code>void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock);
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1\n"; break;
        case 2: msg = "Case 2\n"; break;
        case 3: msg = "Case 3\n"; break;
        case 4: msg = "Case 4\n"; break;
        default: msg  = "Case default\n"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

</code>```

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

答:
Instead of this:

```<code>try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        auto sock = acceptor.accept();
        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();

    }
</code>```

Use it:

```<code>try{
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);

        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();
}
</code>```

and also include header files:

```<code>#include <thread>
#include <chrono>
</code>```

(Optional) you can also use this_thread::sleep_for instead of  sleep()
std::this_thread::sleep_for(std::chrono::seconds(10));

The problem of passing a socket to the thread is solved.

Now, for conversing a HEARTBEAT between a client and a server. Complete code can be checked from here:

Client code HEARTBEAT transfer in every 5 seconds

Server code for giving response to the client

Body:
I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock);
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1\n"; break;
        case 2: msg = "Case 2\n"; break;
        case 3: msg = "Case 3\n"; break;
        case 4: msg = "Case 4\n"; break;
        default: msg  = "Case default\n"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

Body:
Instead of this:

try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        auto sock = acceptor.accept();
        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();

    }

Use it:

try{
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);

        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();
}

and also include header files:

#include <thread>
#include <chrono>

(Optional) you can also use this_thread::sleep_for instead of  sleep()
std::this_thread::sleep_for(std::chrono::seconds(10));

The problem of passing a socket to the thread is solved.

Now, for conversing a HEARTBEAT between a client and a server. Complete code can be checked from here:

Client code HEARTBEAT transfer in every 5 seconds

Server code for giving response to the client


问:
OpenCV - Video doesn't play after saving in Python
I tried to save a video after it changes resolution to 300x300 on Python, but my video can't play after saving with

```<code>0xc10100be error: "This file isn't playable. That might be because the file type is unsupported, the file extension is incorrect, or the file is corrupt."
</code>```

Here is my program:

```<code>import numpy as np
import cv2

cap = cv2.VideoCapture("F:\\mi\\Camera\\2b7d9eccaddffffe3c9ba70b7fe6c12e(0).mp4")
cv2.namedWindow("vid1", 0)
cv2.resizeWindow("vid1", 300,300)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (300,300))

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('vid1',frame)
    out.write(frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()
</code>```

What is wrong?

答:
I appears to me that you're not doing anything with "out".

You should add:

```<code>out.write(frame)
</code>```

inside the loop.

Body:
I tried to save a video after it changes resolution to 300x300 on Python, but my video can't play after saving with

0xc10100be error: "This file isn't playable. That might be because the file type is unsupported, the file extension is incorrect, or the file is corrupt."

Here is my program:

import numpy as np
import cv2

cap = cv2.VideoCapture("F:\\mi\\Camera\\2b7d9eccaddffffe3c9ba70b7fe6c12e(0).mp4")
cv2.namedWindow("vid1", 0)
cv2.resizeWindow("vid1", 300,300)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (300,300))

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('vid1',frame)
    out.write(frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

What is wrong?

Body:
I appears to me that you're not doing anything with "out".

You should add:

out.write(frame)

inside the loop.


问:
How to use PendingIntent instead of an Intent with ConnectivityManager.ConnectivityAction with a callback in C# Xamarin API 28?
I need to make a simple callback in Xamarin, to check if the network status is connected or disconnected.

I have so far been doing it with this code:

```<code>class NetworkControl : INetworkControl
{
    private readonly INetworkControl.ICallback _callback;
    private readonly Context _context;
    private readonly NetworkBroadcastReceiver _receiver = new NetworkBroadcastReceiver();

    public NetworkControl(INetworkControl.ICallback callback, Context context)
    {
        _callback = callback;
        _context = context;
        IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
        context.RegisterReceiver(_receiver, filter);
    }

    public INetworkControl.ICallback Callback => _callback;

    public INetworkControl.NetworkStatus Status
    {
        get
        {
            var current = Connectivity.NetworkAccess;
            if (current == NetworkAccess.Internet)
            {
                return INetworkControl.NetworkStatus.Connected;
            }
            return INetworkControl.NetworkStatus.Disconnected;
        }
    }
}

class NetworkBroadcastReceiver : BroadcastReceiver
{

    private static String TAG = "NetworkBroadcastReceiver";

    public override void OnReceive(Context context, Intent intent)
    {

       if (ShellBridge.Instance != null)
       {
           if (intent.Action.Equals(ConnectivityManager.ConnectivityAction))
           {
               NetworkInfo ni = (NetworkInfo)intent.Extras.Get(ConnectivityManager.ExtraNetworkInfo);
               if (ni.isConnected)
               {
                   // do something if connected
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               } else
               {
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               }

           }

       }

    }
</code>```

The problem is, the function ConnectivityManager.ConnectivityAction in the Intent creating is depricated, and will soon be obsolete. After searching, I found that the pendingIntent should be used for that, but I could not find any valid example of how to use it.

The closest to what I need is this:

```<code>https://stackoverflow.com/questions/58588132/how-to-use-registernetworkcallback-with-pendingintent
</code>```

But, it has not all the information I need.
I need it to be all programmatically, without changing the manifest, for, my app should be a fore- and background app.

Please help, and thank you for your time.

答:
You don't need to reinvent the wheel. You can achieve all that with Xamarin Essentials' Connectivity.

Besides checking if there is a connectivity like this:

var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
    // Connection to internet is available
}
```

<p>you can also track when the connectivity type changes:</p>

<pre class="lang-cs prettyprint-override"><code>public class ConnectivityTest
{
    public ConnectivityTest()
    {
        // Register for connectivity changes, be sure to unsubscribe when finished
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }

    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        var access = e.NetworkAccess;
        var profiles = e.ConnectionProfiles;
    }
}
</code>```

Body:
I need to make a simple callback in Xamarin, to check if the network status is connected or disconnected.

I have so far been doing it with this code:

class NetworkControl : INetworkControl
{
    private readonly INetworkControl.ICallback _callback;
    private readonly Context _context;
    private readonly NetworkBroadcastReceiver _receiver = new NetworkBroadcastReceiver();

    public NetworkControl(INetworkControl.ICallback callback, Context context)
    {
        _callback = callback;
        _context = context;
        IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
        context.RegisterReceiver(_receiver, filter);
    }

    public INetworkControl.ICallback Callback => _callback;

    public INetworkControl.NetworkStatus Status
    {
        get
        {
            var current = Connectivity.NetworkAccess;
            if (current == NetworkAccess.Internet)
            {
                return INetworkControl.NetworkStatus.Connected;
            }
            return INetworkControl.NetworkStatus.Disconnected;
        }
    }
}

class NetworkBroadcastReceiver : BroadcastReceiver
{

    private static String TAG = "NetworkBroadcastReceiver";

    public override void OnReceive(Context context, Intent intent)
    {

       if (ShellBridge.Instance != null)
       {
           if (intent.Action.Equals(ConnectivityManager.ConnectivityAction))
           {
               NetworkInfo ni = (NetworkInfo)intent.Extras.Get(ConnectivityManager.ExtraNetworkInfo);
               if (ni.isConnected)
               {
                   // do something if connected
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               } else
               {
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               }

           }

       }

    }

The problem is, the function ConnectivityManager.ConnectivityAction in the Intent creating is depricated, and will soon be obsolete. After searching, I found that the pendingIntent should be used for that, but I could not find any valid example of how to use it.

The closest to what I need is this:

https://stackoverflow.com/questions/58588132/how-to-use-registernetworkcallback-with-pendingintent

But, it has not all the information I need.
I need it to be all programmatically, without changing the manifest, for, my app should be a fore- and background app.

Please help, and thank you for your time.

Body:
You don't need to reinvent the wheel. You can achieve all that with Xamarin Essentials' Connectivity.

Besides checking if there is a connectivity like this:

var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
    // Connection to internet is available
}

you can also track when the connectivity type changes:

public class ConnectivityTest
{
    public ConnectivityTest()
    {
        // Register for connectivity changes, be sure to unsubscribe when finished
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }

    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        var access = e.NetworkAccess;
        var profiles = e.ConnectionProfiles;
    }
}


问:
New volume in ec2 instance not reflecting
I have a volume of 250 gb initially in one of my ec2 instance. I have increased the volume to 300gb. I could able to see that 300gb using the below command

But when i do df-h command i could not see the 300gb volume. Please help i am new to AWS

答:
New volumes should be formatted to be accessible. Resized existing volumes should also be modified (resized) from the inside of the operating system.

The general information on how to do this safely (e.g. with snapshots) is given in the following AWS documentation:

Making an Amazon EBS volume available for use on Linux

Extending a Linux file system after resizing a volume

Based on the discussion in comments, two commands were used to successfully solve the problem:

sudo growpart /dev/xvda 1

sudo resize2fs /dev/xvda1


答:
Records count are differing each tables, that's why value increasing due to duplication of records, to avoid this take sum before joining a tables,. It will give better results and also your expected result also wrong for the sample data.

Suggestion: To better result you can replace RIGHT OUTER JOIN with LEFT OUTER JOIN.

Here is the code:

```<code>--------Table Creation Part-----
CREATE TABLE #tblretailer
(
ID INT,
[NAME] VARCHAR(50),
PLACE VARCHAR(25),
PHONE VARCHAR(10),
)
GO

CREATE TABLE #tbldraw
(
ID INT,
RetailerID  INT,
DrawNumber INT,
[Count] INT,
CreatedDate DATE
)
GO

CREATE TABLE #Tbl_ABC
(
ID INT,
RetailerID  INT,
ANum INT,
BNum INT,
CNum INT,
ACount INT,
BCount INT,
CCount INT,
CreatedDate DATE
)
GO

CREATE TABLE #Tbl_ABACBC
(
ID INT,
RetailerID  INT,
ANum INT,
BNum INT,
CNum INT,
ABCount INT,
ACCount INT,
BCCount INT,
CreatedDate DATE
)
GO

/*
DROP TABLE #tblretailer, #tbldraw, #Tbl_ABC, #Tbl_ABACBC
GO
*/
-----Value Insert-------
INSERT INTO #tblretailer
SELECT 3, 'Zen Commmunications','Navi mumbai','3456728102'
UNION ALL
SELECT 4, 'ASpire Systems','New Delhi','4324535453'
UNION ALL
SELECT 5, 'Zen Commmunications','New Delhi','4324535454'
GO

INSERT INTO #tbldraw
SELECT 2368, 4, 123, 10, '2020-06-01'
UNION ALL
SELECT 2370, 4, 777, 15, '2020-06-01'
UNION ALL
SELECT 2371, 3, 153, 100, '2020-06-01'
UNION ALL
SELECT 2372, 3, 758, 50, '2020-06-01'
UNION ALL
SELECT 2374, 3, 777, 10, '2020-06-01'
GO

INSERT INTO #Tbl_ABC
SELECT 21, 4, 1, 2, 3, 10, 5, 15, '2020-06-01'
UNION ALL
SELECT 22, 4, 1, 2, 3, 10, 20, 15, '2020-06-01'
UNION ALL
SELECT 23, 3, 1, 2, 3, 10, 25, 0, '2020-06-01'
UNION ALL
SELECT 24, 3, 1, 2, 3, 80, 0, 0, '2020-06-01'
UNION ALL
SELECT 25, 3, 1, 2, 3, 10, 5, 20, '2020-06-01'
GO

INSERT INTO #Tbl_ABACBC
SELECT 9, 4, 12, 20, 30, 10, 10, 10, '2020-06-01'
UNION ALL
SELECT 10, 4, 12, 20, 30, 15, 15, 15, '2020-06-01'
UNION ALL
SELECT 11, 3, 12, 20, 30, 15, 20, 0, '2020-06-01'
UNION ALL
SELECT 12, 3, 12, 20, 30, 0, 10, 20, '2020-06-01'
GO

----Query Part-----
DECLARE @Date DATE = '2020-06-01'

SELECT
    RETAILER.id,
    NAME AS retailername,
    atotal,
    Btotal,
    Ctotal,
    strtotal,
   -- SUM(ISNULL(boxcount, 0)) AS boxtotal,
    abtotal,
    actotal,
    bctotal
FROM
    #tblretailer AS RETAILER
RIGHT JOIN
    (
    SELECT
            ABC.retailerid
            , SUM(ISNULL(acount, 0)) AS atotal
            , SUM(ISNULL(bcount, 0)) AS Btotal
            , SUM(ISNULL(ccount, 0)) AS Ctotal
    FROM
            #tbl_abc  AS ABC
    WHERE
            ISNULL(ABC.createddate, CAST(GETDATE() AS DATE)) = @Date
    GROUP BY
            ABC.retailerid
     ) AS ABC ON ABC.retailerid = RETAILER.id
RIGHT JOIN
    (
    SELECT
            DRAW.retailerid
            --, SUM(ISNULL(boxcount, 0)) AS boxtotal
            , SUM(ISNULL(count, 0)) AS strtotal
    FROM
            #tbldraw  AS DRAW
    WHERE
            ISNULL(DRAW.createddate, CAST(GETDATE() AS DATE)) = @Date
    GROUP BY
            DRAW.retailerid
    ) AS DR ON DR.retailerid = RETAILER.id
RIGHT JOIN
    (
    SELECT
            ABACBC.retailerid
            , SUM(ISNULL(abcount, 0)) AS abtotal
            , SUM(ISNULL(account, 0)) AS actotal
            , SUM(ISNULL(bccount, 0)) AS bctotal
    FROM
            #tbl_abacbc  AS ABACBC
    WHERE
            ISNULL(ABACBC.createddate, CAST(GETDATE() AS DATE)) = @Date
    GROUP BY
            ABACBC.retailerid
     ) AS ABACBC ON ABACBC.retailerid = RETAILER.id
--GROUP BY
--    RETAILER.id, RETAILER.NAME , RETAILER.straightrate, RETAILER.boxrate, RETAILER.abcrate, RETAILER.abrate
</code>```

Result :

```<code>id  retailername    atotal  Btotal  Ctotal  strtotal    abtotal actotal bctotal
1   3   Zen Commmunications 100 30  20  160 15  30  20
2   4   ASpire Systems  20  25  30  25  25  25  25
</code>```

Title: SQL multiple tables join problem with SUM Results Multiples times Higher Value

Body:
I want to join these 4 tables

tblretailer

tbldraw

Tbl_ABC

Tbl_ABACBC

'tblretailer ' is the main table. Sample data from 'tblratailer' looks like this:

+----+---------------------+-------------+------------+--------------+---------+---------+--------+-------------+
| ID |        Name         |    Place    |   Phone    | StraightRate | BoxRate | AbcRate | AbRate | CreatedDate |
+----+---------------------+-------------+------------+--------------+---------+---------+--------+-------------+
|  3 | Zen Commmunications | Navi mumbai | 3456728102 |            8 |       8 |    8.50 |      7 | 2020-05-02  |
|  4 | ASpire Systems      | New Delhi   | 4324535453 |         8.50 |    8.50 |       9 |      8 | 2020-05-02  |
|  5 | excel Systems       | New Delhi   | 4324535453 |         8.50 |    8.50 |       9 |      8 | 2020-05-02  |
+----+---------------------+-------------+------------+--------------+---------+---------+--------+-------------+

Sample data for tbldraw

+------+------------+-------------+-------+-------------+----------+
|  ID  | RetailerID | DrawNumberr | Count | CreatedDate | BoxCount |
+------+------------+-------------+-------+-------------+----------+
| 2368 |          4 |         123 |    10 | 2020-06-01  |       20 |
| 2370 |          4 |         777 |    15 | 2020-06-01  |       18 |
| 2371 |          3 |         153 |   100 | 2020-06-01  |       20 |
| 2372 |          3 |         758 |    50 | 2020-06-01  |       20 |
| 2374 |          3 |         777 |    10 | 2020-06-01  |        5 |
+------+------------+-------------+-------+-------------+----------+

Sample data for Tbl_ABC

+----+------------+------+------+------+--------+--------+--------+-------------+
| ID | RetailerID | ANum | BNum | CNum | ACount | BCount | CCount | CreatedDate |
+----+------------+------+------+------+--------+--------+--------+-------------+
| 21 |          4 |    1 | 2    | 3    |     10 |      5 |     15 | 2020-06-01  |
| 22 |          4 |    3 | 2    | 3    |     10 |     20 |     15 | 2020-06-01  |
| 23 |          3 |    2 | 6    | NULL |     10 |     25 |      0 | 2020-06-01  |
| 24 |          3 |    1 | NULL | NULL |     80 |      0 |      0 | 2020-06-01  |
| 25 |          3 |    4 | 5    | 8    |     10 |      5 |     20 | 2020-06-01  |
+----+------------+------+------+------+--------+--------+--------+-------------+

Sample data for Tbl_ABACBC

+----+------------+-------+-------+-------+---------+---------+---------+-------------+
| ID | RetailerID | ABNum | ACNum | BCNum | ABCount | ACCount | BCCount | CreatedDate |
+----+------------+-------+-------+-------+---------+---------+---------+-------------+
|  9 |          4 |    12 |    20 |    30 |      10 |      10 |      10 | 2020-06-01  |
| 10 |          4 |    55 |    23 |    26 |      15 |      15 |      15 | 2020-06-01  |
| 11 |          3 |    12 |    89 |     0 |      15 |      20 |       0 | 2020-06-01  |
| 12 |          3 |     0 |    20 |    25 |       0 |      10 |      20 | 2020-06-01  |
+----+------------+-------+-------+-------+---------+---------+---------+-------------+

and my SQL Server Stored Procedure code is given below

DECLARE @Date DATE = '2020-06-01'

--  SELECT * FROM tblDraw
SELECT
    RETAILER.id,
    NAME AS retailername,
    SUM(ISNULL(acount, 0)) AS atotal,
    SUM(ISNULL(bcount, 0)) AS Btotal,
    SUM(ISNULL(ccount, 0)) AS Ctotal,
    SUM(ISNULL(count, 0)) AS strtotal,
    SUM(ISNULL(boxcount, 0)) AS boxtotal,
    SUM(ISNULL(abcount, 0)) AS abtotal,
    SUM(ISNULL(account, 0)) AS actotal,
    SUM(ISNULL(bccount, 0)) AS bctotal
FROM
    tblretailer RETAILER
RIGHT JOIN
    tbl_abc ABC ON ABC.retailerid = RETAILER.id
RIGHT JOIN
    tbldraw DRAW ON DRAW.retailerid = RETAILER.id
RIGHT JOIN
    tbl_abacbc ABACBC ON ABACBC.retailerid = RETAILER.id
WHERE
    (ISNULL(ABC.createddate, CAST(GETDATE() AS DATE)) = @Date
     OR ISNULL(DRAW.createddate, CAST(GETDATE() AS DATE)) = @Date
     OR ISNULL(ABACBC.createddate, CAST(GETDATE() AS DATE)) = @Date)
GROUP BY
    RETAILER.id, RETAILER.NAME, RETAILER.straightrate,
    RETAILER.boxrate, RETAILER.abcrate, RETAILER.abrate

But the results are wrong with this code and not producing the expected result. It counts 4 times higher - I think there is a problem with join.

Result is

    +----+---------------------+--------+--------+--------+----------+----------+---------+---------+---------+
    | ID |    retailername     | atotal | btotal | ctotal | strtotal | boxtotal | abtotal | actotal | bctotal |
    +----+---------------------+--------+--------+--------+----------+----------+---------+---------+---------+
    |  3 | Zen Commmunications |    360 |    100 |    0   |      600 |      160 |     135 |     120 |     80  |
    |  4 | ASpire Systems      |     80 |    100 |    120 |      100 |      152 |     100 |     100 |     100 |
    +----+---------------------+--------+--------+--------+----------+----------+---------+---------+---------+

The expected result is

+----+--------------------+--------+--------+--------+-----------+----------+---------+---------+---------+
| ID |    retailername    | atotal | btotal | ctotal |  strtotal | boxtotal | abtotal | actotal | bctotal |
+----+--------------------+--------+--------+--------+-----------+----------+---------+---------+---------+
|  3 | Zen Communucations |     90 |     25 |      0 |       150 |       40 |      15 |      30 |      20 |
|  4 | Aspire Systems     |     20 |     25 |     30 |        25 |       38 |      25 |      25 |      25 |
+----+--------------------+--------+--------+--------+-----------+----------+---------+---------+---------+

Can anyone please help me to solve this.

Body:
Records count are differing each tables, that's why value increasing due to duplication of records, to avoid this take sum before joining a tables,. It will give better results and also your expected result also wrong for the sample data.

Suggestion: To better result you can replace RIGHT OUTER JOIN with LEFT OUTER JOIN.

Here is the code:

--------Table Creation Part-----
CREATE TABLE #tblretailer
(
ID INT,
[NAME] VARCHAR(50),
PLACE VARCHAR(25),
PHONE VARCHAR(10),
)
GO

CREATE TABLE #tbldraw
(
ID INT,
RetailerID  INT,
DrawNumber INT,
[Count] INT,
CreatedDate DATE
)
GO

CREATE TABLE #Tbl_ABC
(
ID INT,
RetailerID  INT,
ANum INT,
BNum INT,
CNum INT,
ACount INT,
BCount INT,
CCount INT,
CreatedDate DATE
)
GO

CREATE TABLE #Tbl_ABACBC
(
ID INT,
RetailerID  INT,
ANum INT,
BNum INT,
CNum INT,
ABCount INT,
ACCount INT,
BCCount INT,
CreatedDate DATE
)
GO

/*
DROP TABLE #tblretailer, #tbldraw, #Tbl_ABC, #Tbl_ABACBC
GO
*/
-----Value Insert-------
INSERT INTO #tblretailer
SELECT 3, 'Zen Commmunications','Navi mumbai','3456728102'
UNION ALL
SELECT 4, 'ASpire Systems','New Delhi','4324535453'
UNION ALL
SELECT 5, 'Zen Commmunications','New Delhi','4324535454'
GO

INSERT INTO #tbldraw
SELECT 2368, 4, 123, 10, '2020-06-01'
UNION ALL
SELECT 2370, 4, 777, 15, '2020-06-01'
UNION ALL
SELECT 2371, 3, 153, 100, '2020-06-01'
UNION ALL
SELECT 2372, 3, 758, 50, '2020-06-01'
UNION ALL
SELECT 2374, 3, 777, 10, '2020-06-01'
GO

INSERT INTO #Tbl_ABC
SELECT 21, 4, 1, 2, 3, 10, 5, 15, '2020-06-01'
UNION ALL
SELECT 22, 4, 1, 2, 3, 10, 20, 15, '2020-06-01'
UNION ALL
SELECT 23, 3, 1, 2, 3, 10, 25, 0, '2020-06-01'
UNION ALL
SELECT 24, 3, 1, 2, 3, 80, 0, 0, '2020-06-01'
UNION ALL
SELECT 25, 3, 1, 2, 3, 10, 5, 20, '2020-06-01'
GO

INSERT INTO #Tbl_ABACBC
SELECT 9, 4, 12, 20, 30, 10, 10, 10, '2020-06-01'
UNION ALL
SELECT 10, 4, 12, 20, 30, 15, 15, 15, '2020-06-01'
UNION ALL
SELECT 11, 3, 12, 20, 30, 15, 20, 0, '2020-06-01'
UNION ALL
SELECT 12, 3, 12, 20, 30, 0, 10, 20, '2020-06-01'
GO

----Query Part-----
DECLARE @Date DATE = '2020-06-01'

SELECT
    RETAILER.id,
    NAME AS retailername,
    atotal,
    Btotal,
    Ctotal,
    strtotal,
   -- SUM(ISNULL(boxcount, 0)) AS boxtotal,
    abtotal,
    actotal,
    bctotal
FROM
    #tblretailer AS RETAILER
RIGHT JOIN
    (
    SELECT
            ABC.retailerid
            , SUM(ISNULL(acount, 0)) AS atotal
            , SUM(ISNULL(bcount, 0)) AS Btotal
            , SUM(ISNULL(ccount, 0)) AS Ctotal
    FROM
            #tbl_abc  AS ABC
    WHERE
            ISNULL(ABC.createddate, CAST(GETDATE() AS DATE)) = @Date
    GROUP BY
            ABC.retailerid
     ) AS ABC ON ABC.retailerid = RETAILER.id
RIGHT JOIN
    (
    SELECT
            DRAW.retailerid
            --, SUM(ISNULL(boxcount, 0)) AS boxtotal
            , SUM(ISNULL(count, 0)) AS strtotal
    FROM
            #tbldraw  AS DRAW
    WHERE
            ISNULL(DRAW.createddate, CAST(GETDATE() AS DATE)) = @Date
    GROUP BY
            DRAW.retailerid
    ) AS DR ON DR.retailerid = RETAILER.id
RIGHT JOIN
    (
    SELECT
            ABACBC.retailerid
            , SUM(ISNULL(abcount, 0)) AS abtotal
            , SUM(ISNULL(account, 0)) AS actotal
            , SUM(ISNULL(bccount, 0)) AS bctotal
    FROM
            #tbl_abacbc  AS ABACBC
    WHERE
            ISNULL(ABACBC.createddate, CAST(GETDATE() AS DATE)) = @Date
    GROUP BY
            ABACBC.retailerid
     ) AS ABACBC ON ABACBC.retailerid = RETAILER.id
--GROUP BY
--    RETAILER.id, RETAILER.NAME , RETAILER.straightrate, RETAILER.boxrate, RETAILER.abcrate, RETAILER.abrate

Result :

id  retailername    atotal  Btotal  Ctotal  strtotal    abtotal actotal bctotal
1   3   Zen Commmunications 100 30  20  160 15  30  20
2   4   ASpire Systems  20  25  30  25  25  25  25


问:
Huawei Tool Converter Cannot Resolve Symbol 'xms'
I'm using the HMS Toolkit- Converter to add HMS API to my app automatically. After it converts import com.google.android.gms.analytics.HitBuilders; into import org.xms.g.analytics.HitBuilders; it tells me that Cannot Resolve Symbole 'xms'. I also tried going to HMS repository and add the Analytics Kit then hit Apply but it gives me an error HMS Analytics Kit  applyplugin dependence added failed:/Users.....

How can I resolve the issue on 'xms' during the conversion? (I used Add HMS API conversion policy.)

答:
How to open a file with the suffix "XMS"?

Do you have to use  software?

The memory located after 1MB  called extended memory.

Generally, programs cannot directly use extended memory.

The usage of extended memory is supported by XMS (extended memory specification), so the extended memory is sometimes referred to as XMS.

Before using extended memory, you should add the command of HIMEM.SYS in the CONFIG.SYS firstly.

Here is the link about what is XMS.

Here is the link reffering to the extended memory of Huawei mobile phone.


问:
How to count rows which are divided into other variables as a whole?
This way i get one river and all provinces it flows through are counted:

```<code>SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER
</code>```

This way i get the same river multiple times and it counts for every country the provinces the river flows thorugh together:

```<code>SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY
</code>```

I want to count the countries the river flows through but some country are divided into different provinces.
If so the country should be count as one and not by number of provinces.

```<code>CREATE TABLE Country
(Name VARCHAR(40) NOT NULL UNIQUE,
 Code VARCHAR(4) CONSTRAINT CountryKey PRIMARY KEY,
 Capital VARCHAR(40),
 Province VARCHAR(40),
 Area INTEGER CONSTRAINT CountryArea
   CHECK (Area >= 0),
 Population INTEGER CONSTRAINT CountryPop
   CHECK (Population >= 0));
</code>```

```<code>CREATE TABLE geo_River
(River VARCHAR(40) ,
 Country VARCHAR(4) ,
 Province VARCHAR(40) ,
 CONSTRAINT GRiverKey PRIMARY KEY (Province ,Country, River) );
</code>```

答:
You need to use distinct within count. Also if you are not doing a join then no need to provide table name before columns.

```<code>SELECT
  RIVER,
  COUNT(distinct COUNTRY)
FROM Geo_River
GROUP BY
  RIVER
</code>```

Body:
This way i get one river and all provinces it flows through are counted:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER

This way i get the same river multiple times and it counts for every country the provinces the river flows thorugh together:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY

I want to count the countries the river flows through but some country are divided into different provinces.
If so the country should be count as one and not by number of provinces.

CREATE TABLE Country
(Name VARCHAR(40) NOT NULL UNIQUE,
 Code VARCHAR(4) CONSTRAINT CountryKey PRIMARY KEY,
 Capital VARCHAR(40),
 Province VARCHAR(40),
 Area INTEGER CONSTRAINT CountryArea
   CHECK (Area >= 0),
 Population INTEGER CONSTRAINT CountryPop
   CHECK (Population >= 0));

CREATE TABLE geo_River
(River VARCHAR(40) ,
 Country VARCHAR(4) ,
 Province VARCHAR(40) ,
 CONSTRAINT GRiverKey PRIMARY KEY (Province ,Country, River) );

Body:
You need to use distinct within count. Also if you are not doing a join then no need to provide table name before columns.

SELECT
  RIVER,
  COUNT(distinct COUNTRY)
FROM Geo_River
GROUP BY
  RIVER


答:
just invert your logic

```<code>def joy(chocs, day, cache={}):
    if (chocs, day) not in cache:
        n = len(chocs)
        if n == 1:
            cache[(chocs,day)] = day * chocs[0]
        else:
            left = day * chocs[0] + joy(chocs[1:], day + 1)
            right = day * chocs[n - 1] + joy(chocs[:n - 1], day + 1)
            cache[(chocs,day)] = max(left, right)
    return cache[(chocs, day)]
</code>```

this way your cache is ensured

Title: Memoization By Hand in Python Function Using Tuples as Cache Keys

Body:
just invert your logic

def joy(chocs, day, cache={}):
    if (chocs, day) not in cache:
        n = len(chocs)
        if n == 1:
            cache[(chocs,day)] = day * chocs[0]
        else:
            left = day * chocs[0] + joy(chocs[1:], day + 1)
            right = day * chocs[n - 1] + joy(chocs[:n - 1], day + 1)
            cache[(chocs,day)] = max(left, right)
    return cache[(chocs, day)]

this way your cache is ensured


问:
How to get matched array object based on their values in javascript
I would like to know how to get the array object based on values in javascript.
I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

```<code>var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

</code>```

Expected Output:

```<code>[
 {name: "country", value: "countries"}
]
</code>```

答:
You can can with this:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
];
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
];

var item = obj1.find(item => obj2.map(x => Object.values(x)[0]).indexOf(item.value) > -1);

console.log(item);```
</div>
</div>
</p>

<p>Get all of the object property values from <code>obj2</code> to an array. Then making an array to check existing with <code>obj1</code></p>

<hr>

<p>Or using <em>for</em> loop:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
];
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
];

for (var obj of obj2) {
  var values = Object.values(obj);

  var item = obj1.find(item => values.indexOf(item.value) > -1);

  if (item) {
    console.log(item);
  }
}</code>```

Body:
I would like to know how to get the array object based on values in javascript.
I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

Expected Output:

[
 {name: "country", value: "countries"}
]

Body:
You can can with this:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
];
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
];

var item = obj1.find(item => obj2.map(x => Object.values(x)[0]).indexOf(item.value) > -1);

console.log(item);

Get all of the object property values from obj2 to an array. Then making an array to check existing with obj1

Or using for loop:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
];
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
];

for (var obj of obj2) {
  var values = Object.values(obj);

  var item = obj1.find(item => values.indexOf(item.value) > -1);

  if (item) {
    console.log(item);
  }
}


问:
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.

I don't quite understand why this flush operation is needed.

Anyone have any insight?

答:
"When you send output to a stream, it does not necessarily get printed immediately. Rather, it may wait in a buffer until some unspecified event, e.g. buffer full enough, reading from input, or exit from program. The details may vary."

http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200109/notes/io.html

ContentLicense: CC BY-SA 3.0

Title: stdout and need to flush it C++


问:
What is the difference between SBT and IDEA when creating a Scala project in intelliJ?
When creting a project in IntelliJ, I am given options for sbt, Lightbend Project Starter, IDEA, Play 2.x, Dotty(experimental). What do these options mean, and how could I learn more about them?</p>

答: Dotty is the name of the future version of the language (Scala 3). See https://dotty.epfl.ch/.</p>


问:
Regex python find uppercase names
I have a text file of the type:

[...speech...]

NAME_OF_SPEAKER_1: [...speech...]

NAME_OF_SPEAKER_2: [...speech...]

My aim is to isolate the speeches of the various speakers. They are clearly identified because the name  of each speaker is always indicated in uppercase letters (name+surname). However, in the speeches there can be nouns (not people's names) which are in uppercase letter, but there is only one word that is actually long enough to give me issue (it has four letter, say it is 'ABCD'). I was thinking to identifiy the position of each speaker's name (I assume every name long at least 3 letters) with something like

```<code>re.search('[A-Z^(ABCD)]{3,}',text_to_search)
</code>```

in order to exclude that specific (constant) word 'ABCD'. However, the command identifies that word instead of excluding it. Any ideas about how to overcome this problem?

答:
In the pattern that you tried, you get partial matches, as there are no boundaries and [A-Z^(ABCD)]{3,} will match 3 or more times any of the listed characters.

A-Z will also match ABCD, so it could also be written as [A-Z^)(]{3,}

Instead of using the negated character class, you could assert that the word that consists only of uppercase chars A-Z does not contain ABCD using a negative lookahead (?!

```<code>\b(?![A-Z]*ABCD)[A-Z]{3,}\b
</code>```

Regex demo

If the name should start with 3 uppercase char, and can contain also lowercase chars, an underscore or digits, you could add \w* after matching 3 uppercase chars:

```<code>\b(?![A-Z]*ABCD)[A-Z]{3}\w*\b
</code>```

Regex demo

Title: Regex python find uppercase names

Body:
I have a text file of the type:

[...speech...]

NAME_OF_SPEAKER_1: [...speech...]

NAME_OF_SPEAKER_2: [...speech...]

My aim is to isolate the speeches of the various speakers. They are clearly identified because the name  of each speaker is always indicated in uppercase letters (name+surname). However, in the speeches there can be nouns (not people's names) which are in uppercase letter, but there is only one word that is actually long enough to give me issue (it has four letter, say it is 'ABCD'). I was thinking to identifiy the position of each speaker's name (I assume every name long at least 3 letters) with something like

re.search('[A-Z^(ABCD)]{3,}',text_to_search)

in order to exclude that specific (constant) word 'ABCD'. However, the command identifies that word instead of excluding it. Any ideas about how to overcome this problem?

Body:
In the pattern that you tried, you get partial matches, as there are no boundaries and [A-Z^(ABCD)]{3,} will match 3 or more times any of the listed characters.

A-Z will also match ABCD, so it could also be written as [A-Z^)(]{3,}

Instead of using the negated character class, you could assert that the word that consists only of uppercase chars A-Z does not contain ABCD using a negative lookahead (?!

\b(?![A-Z]*ABCD)[A-Z]{3,}\b

Regex demo

If the name should start with 3 uppercase char, and can contain also lowercase chars, an underscore or digits, you could add \w* after matching 3 uppercase chars:

\b(?![A-Z]*ABCD)[A-Z]{3}\w*\b

Regex demo


问:
How to stack columns under each-other with Flexbox? Can't get layout working
I'm having problems trying to stack two divs under each other on the right-hand side alongside a content area div.

Like so,

content area | right div 1
              | right div 2

However, they all just sit inline in 3 columns. I want 2 columns, column 1 then the right side 2 divs under each other.

I need these 2 divs not to be wrapped in a container or aside as I want div 2 to use position: sticky

Here is a demo:
https://codepen.io/pbul2004/pen/xxZKyVR

/* CSS */

.container {
  display: flex;
}

.content {
  max-width: 100%;
  flex-basis: 74%;
  border: 1px solid black;
  width: 300px;
}

.right-side {
  align-self: flex-start;
  flex: 1 1;
  flex-basis: 40%;
  min-width: 338px;
  display: block;
  width: 400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--HTML:-->

<div class="container">
  <div class="content">content area here</div>
  <div class="right-side personal-info">personal info here</div>
  <div class="right-side product-info">this div sticky</div>
</div></code>```

答:
I need these 2 divs not to be wrapped in a container or aside as I want div 2 to use position: sticky

I'm not sure I understand that part of your question, but why don't you simply wrap the last two divs with a parent div?

In other words:

```<code><div class="container">
  <div class="content">content area here</div>
  <div>
    <div class="right-side personal-info">personal info here</div>
    <div class="right-side product-info">this div sticky</div>
  </div>
</div>
</code>```

Body:
I'm having problems trying to stack two divs under each other on the right-hand side alongside a content area div.

Like so,

content area | right div 1
              | right div 2

However, they all just sit inline in 3 columns. I want 2 columns, column 1 then the right side 2 divs under each other.

I need these 2 divs not to be wrapped in a container or aside as I want div 2 to use position: sticky

Here is a demo:
https://codepen.io/pbul2004/pen/xxZKyVR

/* CSS */

.container {
  display: flex;
}

.content {
  max-width: 100%;
  flex-basis: 74%;
  border: 1px solid black;
  width: 300px;
}

.right-side {
  align-self: flex-start;
  flex: 1 1;
  flex-basis: 40%;
  min-width: 338px;
  display: block;
  width: 400px;
}

content area here

personal info here

this div sticky

Body:
I need these 2 divs not to be wrapped in a container or aside as I want div 2 to use position: sticky

I'm not sure I understand that part of your question, but why don't you simply wrap the last two divs with a parent div?

In other words:

<div class="container">
  <div class="content">content area here</div>
  <div>
    <div class="right-side personal-info">personal info here</div>
    <div class="right-side product-info">this div sticky</div>
  </div>
</div>


问:
Simple cron job for generating random wallpaper with nitrogen
I am trying to create a cron job that will change my desktop wallpaper every minute. I created a new job using crontab -e.

*/1 * * * * /usr/bin/nitrogen --set-zoom-fill --random /home/rkr/Pictures/wallpapers-master/

The command works on the shell very well. The cron job is also running and visible in /var/log/syslog.
I tried to debug it by sending the output to a log file, which reports a warning about nitrogen :

(nitrogen:10468): Gtk-WARNING **: 09:37:01.654: cannot open display:

I don't think that is the issue though. To further verify if my cron is working I tried :

*/1 * * * * touch /home/rkr/Videos/file and the file was created.

Now I am confused if this is the issue with nitrogen.

答:
Hello

It depends...
I think the issue is the environment.
Having a Terminal open in X and type:

```<code>env | grep DISPLAY
</code>```

This gives the information you need to set the Display for nitrogen.
Because the cronjob sh/bash dont have this variable set.
Now your best friend is env too for starting nitrogen in crontab.

```<code>env -i DISPLAY=:0.0 nitrogen
</code>```

...much fun.

Body:
Hello

It depends...
I think the issue is the environment.
Having a Terminal open in X and type:

env | grep DISPLAY

This gives the information you need to set the Display for nitrogen.
Because the cronjob sh/bash dont have this variable set.
Now your best friend is env too for starting nitrogen in crontab.

env -i DISPLAY=:0.0 nitrogen

...much fun.


问:
JavaFX: stage.setOnCloseRequest() not working
I have a main window on top of which an error dialog opens. At that point an overlay is displayed between the main window and the error dialog (part of the main window stage).

mainWindowOverlay.setManaged(true)
When the error dialog is closed, the overlay should disappear.

errorStage.setOnCloseRequest(we -> overlayOff())
I don't know if the close event isn' t registered or if there's another problem but the overlay stays after the error dialog has been closed.

Any ideas?

controllerMainWindow.java

```<code>package packageA;
import [...];

public class controllerMainWindow extends AbstractController
{
    @FXML
    private AnchorPane mainWindowOverlay;
    @FXML
    private Button btnError;
    //---------------------------------------------------------------------------------------------------
    public void initialize()
    {
        mainWindowOverlay.setManaged(false);
    }
    //---------------------------------------------------------------------------------------------------
    @FXML
    public void handleButtonAction(ActionEvent event)
    {
            try {
                if (event.getSource().equals(btnError)) {
                    FXMLLoader errorLoader = new FXMLLoader();
                    errorLoader.setLocation(getClass().getResource("errorDialog.fxml"));
                    controllerErrorDialog errorController = new controllerErrorDialog();
                    errorLoader.setController(errorController);
                    Parent layout;
                    layout = errorLoader.load();
                    Scene errorScene = new Scene(layout);
                    Stage errorStage = new Stage();
                    errorStage.initStyle(StageStyle.UNDECORATED);
                    errorController.setStage(errorStage);
                    if(this.main!=null) {
                        errorStage.initOwner(main.getPrimaryStage());
                    }
                    customerServiceOverlay.setManaged(true);
                    errorStage.initModality(Modality.APPLICATION_MODAL);
                    errorStage.setScene(errorScene);
                    errorStage.setX(750);
                    errorStage.setY(425);
                    errorStage.setOnCloseRequest(we -> overlayOff());
                    errorStage.showAndWait();
                }
            } catch (IOException exceptionHandleButtonAction) {
                System.out.println("Error on handleButtonAction.");
                exceptionHandleButtonAction.printStackTrace();
                return;
            }
    }
    //---------------------------------------------------------------------------------------------------
    public void overlayOff()
    {
        customerServiceOverlay.setManaged(false);
    }
    //---------------------------------------------------------------------------------------------------
}

</code>```

controllerErrorDialog.java

```<code>package packageA;
import [...];

public class controllerErrorDialog extends AbstractController implements Initializable {
    @FXML
    private Button btnClose;
    @FXML
    private Stage stage = null;
    //---------------------------------------------------------------------------------------------------
    @Override
    public void initialize(URL url, ResourceBundle rb)
    {

    }
    //---------------------------------------------------------------------------------------------------
    public void setStage(Stage stage)
    {
        this.stage = stage;
    }
    //---------------------------------------------------------------------------------------------------
    @FXML
    public void handleButtonAction(ActionEvent event)
    {
        stage.fireEvent(new javafx.stage.WindowEvent(stage,
        javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST));
        stage.close();
    }
    //---------------------------------------------------------------------------------------------------
}
</code>```

答: Solution provided by @James_D and @anko.

Body:
I have a main window on top of which an error dialog opens. At that point an overlay is displayed between the main window and the error dialog (part of the main window stage).

mainWindowOverlay.setManaged(true)
When the error dialog is closed, the overlay should disappear.

errorStage.setOnCloseRequest(we -> overlayOff())
I don't know if the close event isn' t registered or if there's another problem but the overlay stays after the error dialog has been closed.

Any ideas?

controllerMainWindow.java

package packageA;
import [...];

public class controllerMainWindow extends AbstractController
{
    @FXML
    private AnchorPane mainWindowOverlay;
    @FXML
    private Button btnError;
    //---------------------------------------------------------------------------------------------------
    public void initialize()
    {
        mainWindowOverlay.setManaged(false);
    }
    //---------------------------------------------------------------------------------------------------
    @FXML
    public void handleButtonAction(ActionEvent event)
    {
            try {
                if (event.getSource().equals(btnError)) {
                    FXMLLoader errorLoader = new FXMLLoader();
                    errorLoader.setLocation(getClass().getResource("errorDialog.fxml"));
                    controllerErrorDialog errorController = new controllerErrorDialog();
                    errorLoader.setController(errorController);
                    Parent layout;
                    layout = errorLoader.load();
                    Scene errorScene = new Scene(layout);
                    Stage errorStage = new Stage();
                    errorStage.initStyle(StageStyle.UNDECORATED);
                    errorController.setStage(errorStage);
                    if(this.main!=null) {
                        errorStage.initOwner(main.getPrimaryStage());
                    }
                    customerServiceOverlay.setManaged(true);
                    errorStage.initModality(Modality.APPLICATION_MODAL);
                    errorStage.setScene(errorScene);
                    errorStage.setX(750);
                    errorStage.setY(425);
                    errorStage.setOnCloseRequest(we -> overlayOff());
                    errorStage.showAndWait();
                }
            } catch (IOException exceptionHandleButtonAction) {
                System.out.println("Error on handleButtonAction.");
                exceptionHandleButtonAction.printStackTrace();
                return;
            }
    }
    //---------------------------------------------------------------------------------------------------
    public void overlayOff()
    {
        customerServiceOverlay.setManaged(false);
    }
    //---------------------------------------------------------------------------------------------------
}

controllerErrorDialog.java

package packageA;
import [...];

public class controllerErrorDialog extends AbstractController implements Initializable {
    @FXML
    private Button btnClose;
    @FXML
    private Stage stage = null;
    //---------------------------------------------------------------------------------------------------
    @Override
    public void initialize(URL url, ResourceBundle rb)
    {

    }
    //---------------------------------------------------------------------------------------------------
    public void setStage(Stage stage)
    {
        this.stage = stage;
    }
    //---------------------------------------------------------------------------------------------------
    @FXML
    public void handleButtonAction(ActionEvent event)
    {
        stage.fireEvent(new javafx.stage.WindowEvent(stage,
        javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST));
        stage.close();
    }
    //---------------------------------------------------------------------------------------------------
}


问:
Memory assignment in C through pointers
I am learning how to use pointers, so i wrote the below program to assign integer values in the interval [1,100] to some random locations in the memory.

When i read those memory locations, printf displays all the values and then gives me a segmentation fault. This seems an odd behavior, because i was hoping to see either all the values OR a seg fault, but not both at the same time.

Can someone please explain why i got to see both?

Thanks. Here is the code

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

int main()
{
    char first = 'f';
    char *ptr_first = &first;
    int i=1;
    for(i=1;i<101;i++)
        *(ptr_first+i) = i;
    for(i=1;i<101;i++)
        printf("%d\n", *(ptr_first+i));
    return EXIT_SUCCESS;
}
</code>```

答:
You're accessing memory past beyond that assigned to first. It is just one character, and, through the ptr_first pointer, you're accessing 100 positions past this character to unreserved memory. This may lead to segfaults.

You have to ensure the original variable has enough memory reserved for the pointer accesses. For example:

```<code>char first[100];
</code>```

This will convert first in an array of 100 chars (basically a memory space of 100 bytes that you can access via pointer).

Note also that you're inserting int into the char pointer. This will work, but the value of the int will be truncated. You should be using char as the type of i.

Title: Memory assignment in C through pointers

Body:
I am learning how to use pointers, so i wrote the below program to assign integer values in the interval [1,100] to some random locations in the memory.

When i read those memory locations, printf displays all the values and then gives me a segmentation fault. This seems an odd behavior, because i was hoping to see either all the values OR a seg fault, but not both at the same time.

Can someone please explain why i got to see both?

Thanks. Here is the code

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

int main()
{
    char first = 'f';
    char *ptr_first = &first;
    int i=1;
    for(i=1;i<101;i++)
        *(ptr_first+i) = i;
    for(i=1;i<101;i++)
        printf("%d\n", *(ptr_first+i));
    return EXIT_SUCCESS;
}

Body:
You're accessing memory past beyond that assigned to first. It is just one character, and, through the ptr_first pointer, you're accessing 100 positions past this character to unreserved memory. This may lead to segfaults.

You have to ensure the original variable has enough memory reserved for the pointer accesses. For example:

char first[100];

This will convert first in an array of 100 chars (basically a memory space of 100 bytes that you can access via pointer).

Note also that you're inserting int into the char pointer. This will work, but the value of the int will be truncated. You should be using char as the type of i.


问:
Change the file format using browser-image-compression library in reactjs?
In this example I am using the filetype option as .png but its not working as expected.

```<code>import imageCompression from 'browser-image-compression';

const compressImage = async (pic) => {
  const options = {
    maxSizeMB: 1,
    maxWidthOrHeight: 1024,
    useWebWorker: true,
    fileType: '.png',
  };

  const compressedPic = await imageCompression(pic, options);
  console.log('compressed', compressedPic.size);
  console.log('compressd pic title', compressedPic.name);
};

</code>```

答:
In 'browser-image-compression' sources you can see that

```<code>@param {string} [options.fileType] - default to be the original mime type from the image file
</code>```

You should use file mime type rather than .png extension, so try to use image/png instead.

Body:
In this example I am using the filetype option as .png but its not working as expected.

import imageCompression from 'browser-image-compression';

const compressImage = async (pic) => {
  const options = {
    maxSizeMB: 1,
    maxWidthOrHeight: 1024,
    useWebWorker: true,
    fileType: '.png',
  };

  const compressedPic = await imageCompression(pic, options);
  console.log('compressed', compressedPic.size);
  console.log('compressd pic title', compressedPic.name);
};

Body:
In 'browser-image-compression' sources you can see that

@param {string} [options.fileType] - default to be the original mime type from the image file

You should use file mime type rather than .png extension, so try to use image/png instead.


问:
Pulling Function definitions out of a static C library's source code to avoid library compilation
I have a program that uses a huge library, call it libhuge (compilation takes a long time). My Makefile first compiles libhuge and archives it. Then compiles my programs source code into object files
gcc -c $CFLAGS $OBJS

Then links them all to libhuge.a. I tried compiling without linking to that library and saw there were very few (12 functions) that were missing definitions. Is it possible to automatically pull those definitions from my libhuge, and compile only those functions in an object file so I won't have to compile the whole library?

Let's put it this way! I have some functions I would like to further look into from a library. How do I find their definitions?

答:
Add a rule in your Makefile that checks for the libhuge.a and only if it doesn't exist then build the libhuge.a library:

```<code><path>/libhuge.a:
    <commands to build libhuge.a>

<your program>: <path>/libhuge.a
     <commands to build your code>
</code>```

The first time when libhuge.a does not exist,  it will build the entire libhuge.a. But once the library exists, it won't build it again.

Body:
Add a rule in your Makefile that checks for the libhuge.a and only if it doesn't exist then build the libhuge.a library:

<path>/libhuge.a:
    <commands to build libhuge.a>

<your program>: <path>/libhuge.a
     <commands to build your code>

The first time when libhuge.a does not exist,  it will build the entire libhuge.a. But once the library exists, it won't build it again.


问:
A javascript reactjs question about props
Here is the simple App.js code:

```<code>import React from 'react'
import Member from './Member'

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]
  for (const member of members) {
    return <Member {...member} />
  }
}

export default App
</code>```

Here is the Member.js:

```<code>import React from 'react'

function Member ({ name, age }) {
  return (
  <div>
    {name}
    <hr />
    {age}
  </div>)
}

export default Member
</code>```

The problem is only the first object {name:'Andy', age: 22} shows in the browser. How can I change the code to show all three of them?
I am new to Javascript and React. I just can't figure it out. Can anyone help? Thanks a lot.

答:
Please bear in mind that the other answers use member name as the key which is poor practice. Imagine if you had two members with the same name, then you'd get the duplicate key error.

Try:

```<code>import React from 'react'
import Member from './Member'

function App () {

  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]

  return  (
    members.map((member, index) => (
      <Member key={`${member.name}${index}`} {...member} />
    ))
  )
}

export default App
</code>```

Body:
Here is the simple App.js code:

import React from 'react'
import Member from './Member'

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]
  for (const member of members) {
    return <Member {...member} />
  }
}

export default App

Here is the Member.js:

import React from 'react'

function Member ({ name, age }) {
  return (

    {name}

    {age}

)
}

export default Member

The problem is only the first object {name:'Andy', age: 22} shows in the browser. How can I change the code to show all three of them?
I am new to Javascript and React. I just can't figure it out. Can anyone help? Thanks a lot.

Body:
Please bear in mind that the other answers use member name as the key which is poor practice. Imagine if you had two members with the same name, then you'd get the duplicate key error.

Try:

import React from 'react'
import Member from './Member'

function App () {

  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]

  return  (
    members.map((member, index) => (
      <Member key={`${member.name}${index}`} {...member} />
    ))
  )
}

export default App


答:
This is happening because as soon as the first iteration is initiated you are returning the jsx and thus it shows only the first member.

Here how you can loop on all members

```<code>return (
  <React.Fragment>
    {members.map(member => <Member key={member.name} {...member} /> )}
  </React.Fragment>
)
</code>```

Title: A javascript reactjs question about props

Body:
This is happening because as soon as the first iteration is initiated you are returning the jsx and thus it shows only the first member.

Here how you can loop on all members

return (
  <React.Fragment>
    {members.map(member => <Member key={member.name} {...member} /> )}
  </React.Fragment>
)


问:
how to read and write into a file using streamwriter and streamreader
I am trying to read the content from a .csv file and storing it in a variable. Later I am writing that content into a newfile. Code is executing successfully but the data is not appearing in new file. Any suggestions please?

Here is my code:

```<code>    Dim ioFile As New System.IO.StreamReader("C:\sample.csv")

    Dim ioLine As String
    Dim ioLines As String
    ioLine = ioFile.ReadLine
    ioLines = ioLine
    While Not ioLine = ""
        ioLine = ioFile.ReadLine
        ioLines = ioLines & vbCrLf & ioLine

    End While
    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
    ioWriter.WriteLine(ioLines)
    ioFile.Close()
    ioWriter.Close()
</code>```

答:
There are some very short and very good tutorials on the MSDN site:

How to: Write text to a file

How to: Read text from a file

Body:
I am trying to read the content from a .csv file and storing it in a variable. Later I am writing that content into a newfile. Code is executing successfully but the data is not appearing in new file. Any suggestions please?

Here is my code:

    Dim ioFile As New System.IO.StreamReader("C:\sample.csv")

    Dim ioLine As String
    Dim ioLines As String
    ioLine = ioFile.ReadLine
    ioLines = ioLine
    While Not ioLine = ""
        ioLine = ioFile.ReadLine
        ioLines = ioLines & vbCrLf & ioLine

    End While
    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
    ioWriter.WriteLine(ioLines)
    ioFile.Close()
    ioWriter.Close()


问:
Artifact not found in JCenter after name change
I recently updated the name and artifact name of some of my packages in JCenter (example) and I updated the coordinates in Gradle accordingly. However, the new artifacts are not found no matter what I do.

I checked JCenter directly, and they appear to be there. Is there something that I need to do to get it to work again?

答:
Please note that when you submit a JCenter inclusion request for a particular package, all the artifactIDs present under the groupID will be included in the JCenter. If you add additional artifactIDs under the already included groupID , those artifactIDs will not be mirrored in JCenter because JCenter hosts Single path for a single package.

In your case for the package "kodein-di-android-components" there are two artifactIDs under the groupID "com/eygraber"
1. kodein-android-components
2. kodein-di-android-components

Only the First artifactID "kodein-android-components" is included in JCenter,
In order to add the second artifactID "kodein-di-android-components" create a new
Bintray package for the artifactID "kodein-di-android-components" and include all the files under the path GroupID+ artifactID i.e com/eygraber/kodein-di-android-components so that the package will be hosted in JCenter under the path
https://jcenter.bintray.com/com/eygraber


答:
As soon as you call return, it will exit the function and return the result of the expression beside the return keyword. Even though you are returning within a for loop, your code will return the value immediately from the function.

If instead you want to return an array of items, you can use map, like this:

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ];
  return {members.map((member, index) => <Member key={index} {...member} />)};
}
```

map allows you to execute a function over every element in an array, and then return that modified array. When creating a collection of elements, they each need a unique (unique to the collection) key attribute. I am using the index of the item in the array here.

Body:
As soon as you call return, it will exit the function and return the result of the expression beside the return keyword. Even though you are returning within a for loop, your code will return the value immediately from the function.

If instead you want to return an array of items, you can use map, like this:

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ];
  return {members.map((member, index) => <Member key={index} {...member} />)};
}

map allows you to execute a function over every element in an array, and then return that modified array. When creating a collection of elements, they each need a unique (unique to the collection) key attribute. I am using the index of the item in the array here.


问:
How to get Kubernetes cluster name from K8s API
As stated in the title, is it possible to find out a K8s cluster name from the API? I looked around the API and could not find it.</p>

答:
Well this returns precisely one thing, a cluster name

K8s:
kubectl config view -o jsonpath='{.clusters[].name}{"\n"}'

Openshift:
oc config view -o jsonpath='{.clusters[].name}{"\n"}'


问:
Django / PIL - save thumbnail version right when image is uploaded
This is my forms.py:

```<code>class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UserImages
        fields = ['photo']
</code>```

and this is my models.py:

```<code>class UserImages(models.Model):
    user = models.ForeignKey(User)
    photo = models.ImageField(upload_to=get_file_path)
</code>```

and this is my view:

```<code>def uploadImageView(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('/')
    else:
        form = UploadImageForm()

    return render(request, 'uploadImagePage.html', {'uploadImageForm': form})
</code>```

But this only saves the image being uploaded. How do I save a thumbnail version of the image as well with the thumbnail version of the image having the exact same name except with the word 'thumbail' after it?

The tutorials I read said I can do

```<code>im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
</code>```

to get a thumbnail but in my situation, the image isn't even saved yet.

答:
there is super easier way,

in model:

```<code>def upload_thumb_dir(self, filename):
        path = f'path_to_thumb.jpg'
        return path

thumb = ProcessedImageField(upload_to=upload_thumb_dir,
    processors=[ResizeToFill(192, 108)],
    max_length= 255,
    format='JPEG',
    default='preview.jpg',
    options={'quality': 80},
    null=True, blank=True
)
# ...
def save(self, *args, **kwargs):
    self.thumb = self.rawfile.file
    super(VersionPreviews, self).save(*args, **kwargs)
</code>```

Body:
This is my forms.py:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UserImages
        fields = ['photo']

and this is my models.py:

class UserImages(models.Model):
    user = models.ForeignKey(User)
    photo = models.ImageField(upload_to=get_file_path)

and this is my view:

def uploadImageView(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('/')
    else:
        form = UploadImageForm()

    return render(request, 'uploadImagePage.html', {'uploadImageForm': form})

But this only saves the image being uploaded. How do I save a thumbnail version of the image as well with the thumbnail version of the image having the exact same name except with the word 'thumbail' after it?

The tutorials I read said I can do

im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)

to get a thumbnail but in my situation, the image isn't even saved yet.

Body:
there is super easier way,

in model:

def upload_thumb_dir(self, filename):
        path = f'path_to_thumb.jpg'
        return path

thumb = ProcessedImageField(upload_to=upload_thumb_dir,
    processors=[ResizeToFill(192, 108)],
    max_length= 255,
    format='JPEG',
    default='preview.jpg',
    options={'quality': 80},
    null=True, blank=True
)
# ...
def save(self, *args, **kwargs):
    self.thumb = self.rawfile.file
    super(VersionPreviews, self).save(*args, **kwargs)


问:
Can you divide the entries of two tables?
I have 2 tables in Stata: one shows the count of total parents in each state that had a divorce in the specific divorce year cohort,  the other shows the count of divorced parents with csphycus == 2 in each state and divorce year cohort.

I want a table that displays the percentage of parents who has csphycus ==2 for each state and each divorce year cohort.
So  I want to divide the counts in these two tables. How should I do it?

答:
Your mean is </p>

```<code>egen double numer = total(rdasecwt * (csphycus == 2)), by(statefip yrdivbin)
egen double denom = total(rdasecwt), by(statefip yrdivbin)
gen wanted = 100 * numer/denom
</code>```

<p>You can show it by some variation on </p>

```<code>tabdisp statefip yrdivbin, c(wanted) format(%2.1f)
</code>```

Body:
Your mean is

egen double numer = total(rdasecwt * (csphycus == 2)), by(statefip yrdivbin)
egen double denom = total(rdasecwt), by(statefip yrdivbin)
gen wanted = 100 * numer/denom

You can show it by some variation on

tabdisp statefip yrdivbin, c(wanted) format(%2.1f)


问:
Can I dock a div against another div in IE 8?
Consider this page: http://losthobbit.net/temp/docking.html

Here's the HTML:

```<code><html>
<head>
    <title></title>
</head>
<body>
    <div style="position: absolute; bottom: 0; right: 0; top: 0; width: 259; background-color: #00FF00">
        <input type="button" style="position: absolute; left: 161; top: 30; width: 75; height: 25"/>
    </div>
    <div style="position: absolute; bottom: 0; right: 259; left: 0; height: 100; background-color: #00FFFF">
        <input type="button" style="position: absolute; right: 10; top: 30; width: 75; height: 25"/>
    </div>
</body>
</html>
</code>```

In Chrome & FireFox this works perfectly.  The second div docks against the first div.

Is it possible to get this working in IE8?

Thank you in advance, wonderful people :)

答: Add units for example "px" to your css values. IE likes it more that way, not so forgiving as FF or Ch :)</p>

Body:
Consider this page: http://losthobbit.net/temp/docking.html

Here's the HTML:

    <title></title>

        <input type="button" style="position: absolute; left: 161; top: 30; width: 75; height: 25"/>

        <input type="button" style="position: absolute; right: 10; top: 30; width: 75; height: 25"/>

In Chrome & FireFox this works perfectly.  The second div docks against the first div.

Is it possible to get this working in IE8?

Thank you in advance, wonderful people :)