问:
how to call the .aar file activity from parent activity in android studio when a button is clicked in parent app?
I am trying to import the .aar in the parent app, the .aar file contains multiple activities and functions,
what I am trying to do here is imported the aar file in the libs folder which is present in the app[directly pasted inside] folder, and then implemented it in build Gradle, but I am getting an android resource link failed.

You can check these images of what I have done in the coding part

this is the error i am getting

and this is how I called the libs folder

I called the lib folder like this

In the manifest file, I try to call the activity like this

in the child manifest I commented on the activity tag, it showed duplicate

can anyone help me to fix this issue, when I click a button in parent activity which is in mainactivity.kt it should go to child activity which is present in aar file, named HomeActivity.

both manifest files

This the new error i am getting

```<code>  Process: com.example.myapplication, PID: 9182
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/live.hms.app2.ui.home.HomeActivity}: android.view.InflateException: Binary XML file line #46 in com.example.myapplication:layout/activity_home: Binary XML file line #46 in com.example.myapplication:layout/activity_home: Error inflating class androidx.fragment.app.FragmentContainerView
</code>```

which is

答:
The aar file has it own manifest file in it. You don't need to decare HomeActivity in the manifest file of app module. Android studio can help you merge all the manifest files into one file.

Just directly use HomeActivity in MainActivity:

```<code>Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
</code>```

Body:
I am trying to import the .aar in the parent app, the .aar file contains multiple activities and functions,
what I am trying to do here is imported the aar file in the libs folder which is present in the app[directly pasted inside] folder, and then implemented it in build Gradle, but I am getting an android resource link failed.

You can check these images of what I have done in the coding part

this is the error i am getting

and this is how I called the libs folder

I called the lib folder like this

In the manifest file, I try to call the activity like this

in the child manifest I commented on the activity tag, it showed duplicate

can anyone help me to fix this issue, when I click a button in parent activity which is in mainactivity.kt it should go to child activity which is present in aar file, named HomeActivity.

both manifest files

This the new error i am getting

  Process: com.example.myapplication, PID: 9182
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/live.hms.app2.ui.home.HomeActivity}: android.view.InflateException: Binary XML file line #46 in com.example.myapplication:layout/activity_home: Binary XML file line #46 in com.example.myapplication:layout/activity_home: Error inflating class androidx.fragment.app.FragmentContainerView

which is

Body:
The aar file has it own manifest file in it. You don't need to decare HomeActivity in the manifest file of app module. Android studio can help you merge all the manifest files into one file.

Just directly use HomeActivity in MainActivity:

Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);


来源: stackexchange

问:
Application Error from heroku for NestJS app
There isn’t an error showed in the log when deploying my NestJS app to heroku but actually it doesn’t works with a messages saying « Application Error ...»  and the blur thing is that, the app was working perfectly there connected from GitHub. Then I deleted that app and git clone it for a very deep change but I didn’t touched the heroku configurations that I made for the first deployment. So I don’t know what exactly is the issue. App is running perfectly locally on process.env.PORT || 8080</p>

答:
finally i found my issue solution. so if bro you have the same issue, make sure all the heroku's configurations are perfectly done so at that time, no issue will show in the log but your NestTs app is't working with Application Error showing, just run the follow command: nest build or npm run build, and when it's done, open the folder automatically generated named dist on top of your others folders in the root directory of your NestTs app, in that folder (dist) is listed all the files and folders you have in your root directory and some of those files has extension js, then try to find a file named main.js, and write down it's location like (dist/src/main.js or dist/main.js) and put that location in your package.json under script in start:prod value.

```<code>    ...
"scripts": {
"start:prod": "node dist/main.js", /*here where you should add the
loction of main.js don't forget to add the extension .js*/
},
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
finally i found my issue solution. so if bro you have the same issue, make sure all the heroku's configurations are perfectly done so at that time, no issue will show in the log but your NestTs app is't working with Application Error showing, just run the follow command: nest build or npm run build, and when it's done, open the folder automatically generated named dist on top of your others folders in the root directory of your NestTs app, in that folder (dist) is listed all the files and folders you have in your root directory and some of those files has extension js, then try to find a file named main.js, and write down it's location like (dist/src/main.js or dist/main.js) and put that location in your package.json under script in start:prod value.

    ...
"scripts": {
"start:prod": "node dist/main.js", /*here where you should add the
loction of main.js don't forget to add the extension .js*/
},
...


问:
Compare Javascript Object field with another Object field
I have two Objects one of them has the Store Name and the other object has the Price for an item along with the Store ID on both objects. Such as;

```<code>obj1 = [
    {id: 1,name: "Store1"},
    {id: 2,name: "Store2"},
    {id: 3,name: "Store3"}
  ];

obj2= [
{ id: 1, price: 100 },
{ id: 2, price: 200 },
{ id: 3, price: 300 }
];
</code>```

What I want to achieve is that compare obj1 id with obj2 id if they are the same get the price and the store name from the same id. What is the best way to achieve this? I have been trying to use Array.map or filter but can't really make it work. Thank you!

答:
You can use map & find

const obj1 = [{
    id: 1,
    name: "Store1"
  },
  {
    id: 2,
    name: "Store2"
  },
  {
    id: 3,
    name: "Store3"
  },
  {
    id: 4,
    name: "Store3"
  }
];

const obj2 = [{
    id: 1,
    price: 100
  },
  {
    id: 2,
    price: 200
  },
  {
    id: 3,
    price: 300
  }
];

const newData = obj1.map((item, index) => {
  return {
    ...item,
    // if the item exist in obj2 then get the price else assign empty string
    price: obj2.find(elem => elem.id === item.id) ? .price || ''

  }

});
console.log(newData)```

Body:
I have two Objects one of them has the Store Name and the other object has the Price for an item along with the Store ID on both objects. Such as;

obj1 = [
    {id: 1,name: "Store1"},
    {id: 2,name: "Store2"},
    {id: 3,name: "Store3"}
  ];

obj2= [
{ id: 1, price: 100 },
{ id: 2, price: 200 },
{ id: 3, price: 300 }
];

What I want to achieve is that compare obj1 id with obj2 id if they are the same get the price and the store name from the same id. What is the best way to achieve this? I have been trying to use Array.map or filter but can't really make it work. Thank you!


问:
Redis Daemon not creating a PID file
The Redis startup script is supposed to create a pid file at startup, but I've confirmed all the settings I can find, and no pid file is ever created.

I installed redis by:

```<code>$ yum install redis
$ chkconfig redis on
$ service redis start
</code>```

In my config file (/etc/redis.conf) I checked to make sure these were enabled:

```<code>daemonize yes
pidfile /var/run/redis/redis.pid
</code>```

And in the startup script (/etc/init.d/redis) there is:

```<code>exec="/usr/sbin/$name"
pidfile="/var/run/redis/redis.pid"
REDIS_CONFIG="/etc/redis.conf"

[ -e /etc/sysconfig/redis ] && . /etc/sysconfig/redis

lockfile=/var/lock/subsys/redis

start() {
    [ -f $REDIS_CONFIG ] || exit 6
    [ -x $exec ] || exit 5
    echo -n $"Starting $name: "
    daemon --user ${REDIS_USER-redis} "$exec $REDIS_CONFIG"
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $name: "
    killproc -p $pidfile $name
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
</code>```

These are the settings that came by default with the install. Any idea why no pid file is created? I need to use it for Monit.
(The system is RHEL 6.4 btw)

答:
My default, Redis does not run as a daemon, and that is why it does not create a pid file.  If you look at /etc/redis/redis.conf, it says so explicitly under General.

```<code>#By default Redis does not run as a daemon.  Use 'yes' if you need it...
daemonize no
</code>```

So all you need to do is to change it to daemonize yes

ContentLicense: CC BY-SA 3.0

Title: Redis Daemon not creating a PID file

Body:
The Redis startup script is supposed to create a pid file at startup, but I've confirmed all the settings I can find, and no pid file is ever created.

I installed redis by:

$ yum install redis
$ chkconfig redis on
$ service redis start

In my config file (/etc/redis.conf) I checked to make sure these were enabled:

daemonize yes
pidfile /var/run/redis/redis.pid

And in the startup script (/etc/init.d/redis) there is:

exec="/usr/sbin/$name"
pidfile="/var/run/redis/redis.pid"
REDIS_CONFIG="/etc/redis.conf"

[ -e /etc/sysconfig/redis ] && . /etc/sysconfig/redis

lockfile=/var/lock/subsys/redis

start() {
    [ -f $REDIS_CONFIG ] || exit 6
    [ -x $exec ] || exit 5
    echo -n $"Starting $name: "
    daemon --user ${REDIS_USER-redis} "$exec $REDIS_CONFIG"
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $name: "
    killproc -p $pidfile $name
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

These are the settings that came by default with the install. Any idea why no pid file is created? I need to use it for Monit.
(The system is RHEL 6.4 btw)

Body:
My default, Redis does not run as a daemon, and that is why it does not create a pid file.  If you look at /etc/redis/redis.conf, it says so explicitly under General.

#By default Redis does not run as a daemon.  Use 'yes' if you need it...
daemonize no

So all you need to do is to change it to daemonize yes


问:
Is there any way to limit the step functions to run one after other?
If I have 3 state machines running how to limit them by executing only one after other

a
b
c

After initializing the state machines I want to run b once a is successful and run c once b is successful.

答:
With Step Functions you can configure a State machine to run as a next state for a previous created state, so you will able to manage this creating another Step Function to handle the three ones that you already have:

To handle these states will have different Integration patterns:

Call and continue
Step Functions calls the API, receives an HTTP response, and continues to the next step.

Wait for child execution to complete
Pause the parent execution at this state and monitor the child execution. Resume the parent execution when the child execution is complete.

Wait for callback
Pause the execution at this state until the execution receives a callback from the SendTaskSuccess or SendTaskFailure APIs with the task token

In your case the best option will use the Wait for child execution to complete integration pattern to be sure that all child states are done inside each state machine.


问:
How to route all URLs except some to a PHP file?
I'm working on a PHP project. I want to route all URLs except some (/, /index.php, /video-archive.php etc.) to a PHP file which is /article.php

Let me describe it in more detail:

Consider that I have article.php at URL https://example.com/article.php, when a client wants to reach to URL https://example.com/how-to-grow-beautiful-flowers.php or without the .php extension, I want this request to be processed by this https://example.com/article.php URL or simply article.php file. If user wants to reach https://example.com/ or https://example.com/index.php or https://example.com/video-archive.php they will reach to index.php and video-archive.php. So there will be exceptions to that route.

```<code>REQUEST URL                                            PROCESSING URL
https://example.com/                                   https://example.com/index.php
https://example.com/index.php                          https://example.com/index.php
https://example.com/index                              https://example.com/index.php
https://example.com/video-archive                      https://example.com/video-archive.php
https://example.com/video-archive.php                  https://example.com/video-archive.php
https://example.com/how-to-grow-flowers                https://example.com/article.php
https://example.com/types-of-flowers                   https://example.com/article.php
https://example.com/about-us                           https://example.com/article.php
</code>```

NOTE: I'm currently developing this project using XAMPP on my computer (localhost). But I'm planning to deploy it on a server in future. So it should be better to consider this information.

答:
You can redirect all requests to /article.php expect requests to files that actually exist. Example requests to /index.php, /video-archive.php and static files will load the actual file. Try this

Put this in a .htaccess in the root directory

```<code>RewriteEngine On

# redirect all request to article.php except existing files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ article.php [QSA,L]
</code>```

You can then get the URI in the article.php file like so

```<code>$article_url = rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php');
// when a client hits https://example.com/how-to-grow-beautiful-flowers.php
// $article_url equals '/how-to-grow-beautiful-flowers'
</code>```

Body:
I'm working on a PHP project. I want to route all URLs except some (/, /index.php, /video-archive.php etc.) to a PHP file which is /article.php

Let me describe it in more detail:

Consider that I have article.php at URL https://example.com/article.php, when a client wants to reach to URL https://example.com/how-to-grow-beautiful-flowers.php or without the .php extension, I want this request to be processed by this https://example.com/article.php URL or simply article.php file. If user wants to reach https://example.com/ or https://example.com/index.php or https://example.com/video-archive.php they will reach to index.php and video-archive.php. So there will be exceptions to that route.

REQUEST URL                                            PROCESSING URL
https://example.com/                                   https://example.com/index.php
https://example.com/index.php                          https://example.com/index.php
https://example.com/index                              https://example.com/index.php
https://example.com/video-archive                      https://example.com/video-archive.php
https://example.com/video-archive.php                  https://example.com/video-archive.php
https://example.com/how-to-grow-flowers                https://example.com/article.php
https://example.com/types-of-flowers                   https://example.com/article.php
https://example.com/about-us                           https://example.com/article.php

NOTE: I'm currently developing this project using XAMPP on my computer (localhost). But I'm planning to deploy it on a server in future. So it should be better to consider this information.

Body:
You can redirect all requests to /article.php expect requests to files that actually exist. Example requests to /index.php, /video-archive.php and static files will load the actual file. Try this

Put this in a .htaccess in the root directory

RewriteEngine On

# redirect all request to article.php except existing files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ article.php [QSA,L]

You can then get the URI in the article.php file like so

$article_url = rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php');
// when a client hits https://example.com/how-to-grow-beautiful-flowers.php
// $article_url equals '/how-to-grow-beautiful-flowers'


问:
Xamarin Forms: Image circle
I need to use a circular image with border, I already tried using the ImageCircle plugin and it is broken in the current version of Xamarin, the border appears outside the image in the iOS version, in the android version works. Also I tried to create a custom renderer but I could not make it work properly, it follows the print of the result of a custom renderer I searched in google:

Code:

```<code>private void CreateCircle()
{
    try
    {
        double min = Math.Min(Element.Width, Element.Height);
        Control.Layer.CornerRadius = (float)(min / 2.0);
        Control.Layer.MasksToBounds = false;
        Control.Layer.BorderColor = Color.Red.ToCGColor();
        Control.Layer.BorderWidth = 2;
        Control.ClipsToBounds = true;
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Unable to create circle image: " + ex);
    }
}
</code>```

The bug occurs only if you set a HeightRequest

答:
circle image(easy):</p>
```<code><Image Source="Image">
      <Image.Clip>
            <EllipseGeometry Center="30,30"
                             RadiusX="30"
                             RadiusY="30">
            </EllipseGeometry>
      </Image.Clip>
</Image>
</code>```

Title: Xamarin Forms: Image circle

Body:
I need to use a circular image with border, I already tried using the ImageCircle plugin and it is broken in the current version of Xamarin, the border appears outside the image in the iOS version, in the android version works. Also I tried to create a custom renderer but I could not make it work properly, it follows the print of the result of a custom renderer I searched in google:

Code:

private void CreateCircle()
{
    try
    {
        double min = Math.Min(Element.Width, Element.Height);
        Control.Layer.CornerRadius = (float)(min / 2.0);
        Control.Layer.MasksToBounds = false;
        Control.Layer.BorderColor = Color.Red.ToCGColor();
        Control.Layer.BorderWidth = 2;
        Control.ClipsToBounds = true;
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Unable to create circle image: " + ex);
    }
}

The bug occurs only if you set a HeightRequest

Body:
circle image(easy):

<Image Source="Image">
      <Image.Clip>
            <EllipseGeometry Center="30,30"
                             RadiusX="30"
                             RadiusY="30">
            </EllipseGeometry>
      </Image.Clip>
</Image>


问:
Visual C++ WinForms. When using marshaling occurs: Error C2731 'WinMain': function cannot be overloaded
I am creating a GUI app in Visual C++, WinForms, Visual Studio 2022

When this library in included #include <msclr\marshal_cppstd.h>

The following error appears: Error C2731   'WinMain': function cannot be overloaded

The library itself is included for the opportunity to convert from System::String^ type of a variable into std::string
The following solution of string conversion was taken from the user "z05DSL3A" (the answer is at the end of the page).

The problem is that it requires the #include <msclr\marshal_cppstd.h> which produces the error

Here's the example of the code where the string conversion is used

```<code>    #pragma once
    #include <string>

    #include <msclr\marshal_cppstd.h> //The library which causes the error

    using namespace System;

    namespace WebBrowser {
/* ... */

    private: System::Void buttonNavigate_Click(System::Object^ sender, System::EventArgs^ e)
{

    std::string dot; //Vanialla string

    System::String^ systemString = textNavigate->Text; //Object string

    msclr::interop::marshal_context context;
    std::string standardString = context.marshal_as<std::string>(systemString);

    dot = standardString;

    int occurrence = 0;

    for (int i = 0; i < dot.size(); i++) {
        if (dot[i] == '.') { occurrence++; }
    }

    if (occurrence > 0) {

        webBrowser->Navigate(textNavigate->Text);

    }
    else {
        textNavigate->Text = "Inavlid URL";

    }  }
</code>```

The project mainly consists of 2 files. Here's the full code of these files:

MyForm.cpp:

```<code>#include "MyForm.h" //Name of the form

using namespace WebBrowser; // Name of the project

[STAThread]
// int WinMain() - compiler returns 0
// void WinMain() - void does not return anything
// WinMain() – entry point for Windows GUI app
int WinMain() {
    //Enable visual elements for the app
    Application::EnableVisualStyles();
    // Establishing compatability with .NET Framework
    Application::SetCompatibleTextRenderingDefault(false);
    //Start the app with the form
    Application::Run(gcnew MyForm()); //in cirle brackets () also type the name of the form
    // Application::Run(gcnew Project1::MyForm);
}
</code>```

MyForm.h:

```<code>  #pragma once
#include <string>

//#include <msclr\marshal_cppstd.h>

using namespace System;

namespace WebBrowser {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for MyForm
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^ buttonBack;
    private: System::Windows::Forms::Button^ buttonForward;
    private: System::Windows::Forms::TextBox^ textNavigate;
    protected:

    private: System::Windows::Forms::Button^ buttonNavigate;
    private: System::Windows::Forms::WebBrowser^ webBrowser;
    private: System::Windows::Forms::Button^ buttonRefresh;

    protected:

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->buttonBack = (gcnew System::Windows::Forms::Button());
            this->buttonForward = (gcnew System::Windows::Forms::Button());
            this->textNavigate = (gcnew System::Windows::Forms::TextBox());
            this->buttonNavigate = (gcnew System::Windows::Forms::Button());
            this->webBrowser = (gcnew System::Windows::Forms::WebBrowser());
            this->buttonRefresh = (gcnew System::Windows::Forms::Button());
            this->SuspendLayout();
            //
            // buttonBack
            //
            this->buttonBack->Font = (gcnew System::Drawing::Font(L"Verdana", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonBack->Location = System::Drawing::Point(4, 6);
            this->buttonBack->Name = L"buttonBack";
            this->buttonBack->Size = System::Drawing::Size(25, 25);
            this->buttonBack->TabIndex = 0;
            this->buttonBack->Text = L"<";
            this->buttonBack->UseVisualStyleBackColor = true;
            this->buttonBack->Click += gcnew System::EventHandler(this, &MyForm::buttonBack_Click);
            //
            // buttonForward
            //
            this->buttonForward->Font = (gcnew System::Drawing::Font(L"Verdana", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonForward->Location = System::Drawing::Point(35, 5);
            this->buttonForward->Name = L"buttonForward";
            this->buttonForward->Size = System::Drawing::Size(25, 25);
            this->buttonForward->TabIndex = 1;
            this->buttonForward->Text = L">";
            this->buttonForward->UseVisualStyleBackColor = true;
            this->buttonForward->Click += gcnew System::EventHandler(this, &MyForm::buttonForward_Click);
            //
            // textNavigate
            //
            this->textNavigate->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left)
                | System::Windows::Forms::AnchorStyles::Right));
            this->textNavigate->Font = (gcnew System::Drawing::Font(L"Verdana", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->textNavigate->Location = System::Drawing::Point(66, 7);
            this->textNavigate->Name = L"textNavigate";
            this->textNavigate->Size = System::Drawing::Size(440, 23);
            this->textNavigate->TabIndex = 2;
            this->textNavigate->Text = L"Type a URL";
            this->textNavigate->Click += gcnew System::EventHandler(this, &MyForm::textBox1_TextChanged);
            this->textNavigate->TextChanged += gcnew System::EventHandler(this, &MyForm::textBox1_TextChanged);
            this->textNavigate->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &MyForm::textNavigate_KeyDown);
            this->textNavigate->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &MyForm::textNavigate_KeyPress);
            //
            // buttonNavigate
            //
            this->buttonNavigate->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
            this->buttonNavigate->Font = (gcnew System::Drawing::Font(L"Verdana", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonNavigate->Location = System::Drawing::Point(592, 7);
            this->buttonNavigate->Name = L"buttonNavigate";
            this->buttonNavigate->Size = System::Drawing::Size(71, 23);
            this->buttonNavigate->TabIndex = 3;
            this->buttonNavigate->Text = L"Navigate";
            this->buttonNavigate->UseVisualStyleBackColor = true;
            this->buttonNavigate->Click += gcnew System::EventHandler(this, &MyForm::buttonNavigate_Click);
            //
            // webBrowser
            //
            this->webBrowser->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
                | System::Windows::Forms::AnchorStyles::Left)
                | System::Windows::Forms::AnchorStyles::Right));
            this->webBrowser->Location = System::Drawing::Point(1, 36);
            this->webBrowser->MinimumSize = System::Drawing::Size(20, 20);
            this->webBrowser->Name = L"webBrowser";
            this->webBrowser->ScriptErrorsSuppressed = true;
            this->webBrowser->Size = System::Drawing::Size(662, 425);
            this->webBrowser->TabIndex = 4;
            this->webBrowser->Url = (gcnew System::Uri(L"https://duckduckgo.com", System::UriKind::Absolute));
            this->webBrowser->DocumentCompleted += gcnew System::Windows::Forms::WebBrowserDocumentCompletedEventHandler(this, &MyForm::webBrowser_DocumentCompleted);
            //
            // buttonRefresh
            //
            this->buttonRefresh->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
            this->buttonRefresh->Font = (gcnew System::Drawing::Font(L"Verdana", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonRefresh->Location = System::Drawing::Point(517, 7);
            this->buttonRefresh->Name = L"buttonRefresh";
            this->buttonRefresh->Size = System::Drawing::Size(65, 23);
            this->buttonRefresh->TabIndex = 5;
            this->buttonRefresh->Text = L"Refresh";
            this->buttonRefresh->UseVisualStyleBackColor = true;
            this->buttonRefresh->Click += gcnew System::EventHandler(this, &MyForm::buttonRefresh_Click);
            //
            // MyForm
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(666, 456);
            this->Controls->Add(this->buttonRefresh);
            this->Controls->Add(this->webBrowser);
            this->Controls->Add(this->buttonNavigate);
            this->Controls->Add(this->textNavigate);
            this->Controls->Add(this->buttonForward);
            this->Controls->Add(this->buttonBack);
            this->HelpButton = true;
            this->Name = L"MyForm";
            this->Text = L"FasterThings Web Browser";
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void webBrowser1_DocumentCompleted(System::Object^ sender, System::Windows::Forms::WebBrowserDocumentCompletedEventArgs^ e) {
    }
private: System::Void buttonBack_Click(System::Object^ sender, System::EventArgs^ e)
{
    webBrowser->GoBack();
}
private: System::Void buttonForward_Click(System::Object^ sender, System::EventArgs^ e)
{
    webBrowser->GoForward();
}
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e)
{
    if (textNavigate->Text == "Type a URL"|| textNavigate->Text == "Inavlid URL") {
        textNavigate->Text = "";

    }
}
private: System::Void buttonNavigate_Click(System::Object^ sender, System::EventArgs^ e)
{
    /* //This is the code that uses string conversion
    std::string dot; //Vanialla string

    System::String^ systemString = textNavigate->Text; //Object string

    msclr::interop::marshal_context context;
    std::string standardString = context.marshal_as<std::string>(systemString);

    dot = standardString;

    int occurrence = 0;

    for (int i = 0; i < dot.size(); i++) {
        if (dot[i] == '.') { occurrence++; }
    }

    if (occurrence > 0) {

        webBrowser->Navigate(textNavigate->Text);

    }
    else {
        textNavigate->Text = "Inavlid URL";

    } */

    webBrowser->Navigate(textNavigate->Text);

}
private: System::Void buttonRefresh_Click(System::Object^ sender, System::EventArgs^ e) {
    webBrowser->Refresh();

}
private: System::Void textNavigate_Leave(System::Object^ sender, System::EventArgs^ e) {
    if (textNavigate->Text == "") {

        textNavigate->Text == "Type a URL";

    }
}
private: System::Void textNavigate_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {

}
private: System::Void webBrowser_DocumentCompleted(System::Object^ sender, System::Windows::Forms::WebBrowserDocumentCompletedEventArgs^ e) {
}
private: System::Void textNavigate_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {

    if (e->KeyValue == (int)Keys::Enter)
    {

        webBrowser -> Navigate(textNavigate->Text);

    }

}
};
}
</code>```

What could be a solution to the problem?

答:
Why would you post such an incredible amount of absolutely useless code when the error tells you exactly what the problem is: Error C2731 'WinMain': function cannot be overloaded

The problem is obviously on this line:

```<code>int WinMain()
</code>```

If you read any of the extensive documentation on the topic, it should be clear that the function needs to look like this:

```<code>int WinMain(
  [in] HINSTANCE hInstance,
  [in] HINSTANCE hPrevInstance,
  [in] LPSTR     lpCmdLine,
  [in] int       nShowCmd
);
</code>```

Body:
I am creating a GUI app in Visual C++, WinForms, Visual Studio 2022

When this library in included #include <msclr\marshal_cppstd.h>

The following error appears: Error C2731   'WinMain': function cannot be overloaded

The library itself is included for the opportunity to convert from System::String^ type of a variable into std::string
The following solution of string conversion was taken from the user "z05DSL3A" (the answer is at the end of the page).

The problem is that it requires the #include <msclr\marshal_cppstd.h> which produces the error

Here's the example of the code where the string conversion is used

    #pragma once
    #include <string>

    #include <msclr\marshal_cppstd.h> //The library which causes the error

    using namespace System;

    namespace WebBrowser {
/* ... */

    private: System::Void buttonNavigate_Click(System::Object^ sender, System::EventArgs^ e)
{

    std::string dot; //Vanialla string

    System::String^ systemString = textNavigate->Text; //Object string

    msclr::interop::marshal_context context;
    std::string standardString = context.marshal_as<std::string>(systemString);

    dot = standardString;

    int occurrence = 0;

    for (int i = 0; i < dot.size(); i++) {
        if (dot[i] == '.') { occurrence++; }
    }

    if (occurrence > 0) {

        webBrowser->Navigate(textNavigate->Text);

    }
    else {
        textNavigate->Text = "Inavlid URL";

    }  }

The project mainly consists of 2 files. Here's the full code of these files:

MyForm.cpp:

#include "MyForm.h" //Name of the form

using namespace WebBrowser; // Name of the project

[STAThread]
// int WinMain() - compiler returns 0
// void WinMain() - void does not return anything
// WinMain() – entry point for Windows GUI app
int WinMain() {
    //Enable visual elements for the app
    Application::EnableVisualStyles();
    // Establishing compatability with .NET Framework
    Application::SetCompatibleTextRenderingDefault(false);
    //Start the app with the form
    Application::Run(gcnew MyForm()); //in cirle brackets () also type the name of the form
    // Application::Run(gcnew Project1::MyForm);
}

MyForm.h:

  #pragma once
#include <string>

//#include <msclr\marshal_cppstd.h>

using namespace System;

namespace WebBrowser {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    ///
    /// Summary for MyForm
    ///
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        ///
        /// Clean up any resources being used.
        ///
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^ buttonBack;
    private: System::Windows::Forms::Button^ buttonForward;
    private: System::Windows::Forms::TextBox^ textNavigate;
    protected:

    private: System::Windows::Forms::Button^ buttonNavigate;
    private: System::Windows::Forms::WebBrowser^ webBrowser;
    private: System::Windows::Forms::Button^ buttonRefresh;

    protected:

    private:
        ///
        /// Required designer variable.
        ///
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        ///
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///
        void InitializeComponent(void)
        {
            this->buttonBack = (gcnew System::Windows::Forms::Button());
            this->buttonForward = (gcnew System::Windows::Forms::Button());
            this->textNavigate = (gcnew System::Windows::Forms::TextBox());
            this->buttonNavigate = (gcnew System::Windows::Forms::Button());
            this->webBrowser = (gcnew System::Windows::Forms::WebBrowser());
            this->buttonRefresh = (gcnew System::Windows::Forms::Button());
            this->SuspendLayout();
            //
            // buttonBack
            //
            this->buttonBack->Font = (gcnew System::Drawing::Font(L"Verdana", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonBack->Location = System::Drawing::Point(4, 6);
            this->buttonBack->Name = L"buttonBack";
            this->buttonBack->Size = System::Drawing::Size(25, 25);
            this->buttonBack->TabIndex = 0;
            this->buttonBack->Text = L"<";
            this->buttonBack->UseVisualStyleBackColor = true;
            this->buttonBack->Click += gcnew System::EventHandler(this, &MyForm::buttonBack_Click);
            //
            // buttonForward
            //
            this->buttonForward->Font = (gcnew System::Drawing::Font(L"Verdana", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonForward->Location = System::Drawing::Point(35, 5);
            this->buttonForward->Name = L"buttonForward";
            this->buttonForward->Size = System::Drawing::Size(25, 25);
            this->buttonForward->TabIndex = 1;
            this->buttonForward->Text = L">";
            this->buttonForward->UseVisualStyleBackColor = true;
            this->buttonForward->Click += gcnew System::EventHandler(this, &MyForm::buttonForward_Click);
            //
            // textNavigate
            //
            this->textNavigate->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left)
                | System::Windows::Forms::AnchorStyles::Right));
            this->textNavigate->Font = (gcnew System::Drawing::Font(L"Verdana", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->textNavigate->Location = System::Drawing::Point(66, 7);
            this->textNavigate->Name = L"textNavigate";
            this->textNavigate->Size = System::Drawing::Size(440, 23);
            this->textNavigate->TabIndex = 2;
            this->textNavigate->Text = L"Type a URL";
            this->textNavigate->Click += gcnew System::EventHandler(this, &MyForm::textBox1_TextChanged);
            this->textNavigate->TextChanged += gcnew System::EventHandler(this, &MyForm::textBox1_TextChanged);
            this->textNavigate->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &MyForm::textNavigate_KeyDown);
            this->textNavigate->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &MyForm::textNavigate_KeyPress);
            //
            // buttonNavigate
            //
            this->buttonNavigate->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
            this->buttonNavigate->Font = (gcnew System::Drawing::Font(L"Verdana", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonNavigate->Location = System::Drawing::Point(592, 7);
            this->buttonNavigate->Name = L"buttonNavigate";
            this->buttonNavigate->Size = System::Drawing::Size(71, 23);
            this->buttonNavigate->TabIndex = 3;
            this->buttonNavigate->Text = L"Navigate";
            this->buttonNavigate->UseVisualStyleBackColor = true;
            this->buttonNavigate->Click += gcnew System::EventHandler(this, &MyForm::buttonNavigate_Click);
            //
            // webBrowser
            //
            this->webBrowser->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
                | System::Windows::Forms::AnchorStyles::Left)
                | System::Windows::Forms::AnchorStyles::Right));
            this->webBrowser->Location = System::Drawing::Point(1, 36);
            this->webBrowser->MinimumSize = System::Drawing::Size(20, 20);
            this->webBrowser->Name = L"webBrowser";
            this->webBrowser->ScriptErrorsSuppressed = true;
            this->webBrowser->Size = System::Drawing::Size(662, 425);
            this->webBrowser->TabIndex = 4;
            this->webBrowser->Url = (gcnew System::Uri(L"https://duckduckgo.com", System::UriKind::Absolute));
            this->webBrowser->DocumentCompleted += gcnew System::Windows::Forms::WebBrowserDocumentCompletedEventHandler(this, &MyForm::webBrowser_DocumentCompleted);
            //
            // buttonRefresh
            //
            this->buttonRefresh->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
            this->buttonRefresh->Font = (gcnew System::Drawing::Font(L"Verdana", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->buttonRefresh->Location = System::Drawing::Point(517, 7);
            this->buttonRefresh->Name = L"buttonRefresh";
            this->buttonRefresh->Size = System::Drawing::Size(65, 23);
            this->buttonRefresh->TabIndex = 5;
            this->buttonRefresh->Text = L"Refresh";
            this->buttonRefresh->UseVisualStyleBackColor = true;
            this->buttonRefresh->Click += gcnew System::EventHandler(this, &MyForm::buttonRefresh_Click);
            //
            // MyForm
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(666, 456);
            this->Controls->Add(this->buttonRefresh);
            this->Controls->Add(this->webBrowser);
            this->Controls->Add(this->buttonNavigate);
            this->Controls->Add(this->textNavigate);
            this->Controls->Add(this->buttonForward);
            this->Controls->Add(this->buttonBack);
            this->HelpButton = true;
            this->Name = L"MyForm";
            this->Text = L"FasterThings Web Browser";
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void webBrowser1_DocumentCompleted(System::Object^ sender, System::Windows::Forms::WebBrowserDocumentCompletedEventArgs^ e) {
    }
private: System::Void buttonBack_Click(System::Object^ sender, System::EventArgs^ e)
{
    webBrowser->GoBack();
}
private: System::Void buttonForward_Click(System::Object^ sender, System::EventArgs^ e)
{
    webBrowser->GoForward();
}
private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e)
{
    if (textNavigate->Text == "Type a URL"|| textNavigate->Text == "Inavlid URL") {
        textNavigate->Text = "";

    }
}
private: System::Void buttonNavigate_Click(System::Object^ sender, System::EventArgs^ e)
{
    /* //This is the code that uses string conversion
    std::string dot; //Vanialla string

    System::String^ systemString = textNavigate->Text; //Object string

    msclr::interop::marshal_context context;
    std::string standardString = context.marshal_as<std::string>(systemString);

    dot = standardString;

    int occurrence = 0;

    for (int i = 0; i < dot.size(); i++) {
        if (dot[i] == '.') { occurrence++; }
    }

    if (occurrence > 0) {

        webBrowser->Navigate(textNavigate->Text);

    }
    else {
        textNavigate->Text = "Inavlid URL";

    } */

    webBrowser->Navigate(textNavigate->Text);

}
private: System::Void buttonRefresh_Click(System::Object^ sender, System::EventArgs^ e) {
    webBrowser->Refresh();

}
private: System::Void textNavigate_Leave(System::Object^ sender, System::EventArgs^ e) {
    if (textNavigate->Text == "") {

        textNavigate->Text == "Type a URL";

    }
}
private: System::Void textNavigate_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {

}
private: System::Void webBrowser_DocumentCompleted(System::Object^ sender, System::Windows::Forms::WebBrowserDocumentCompletedEventArgs^ e) {
}
private: System::Void textNavigate_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {

    if (e->KeyValue == (int)Keys::Enter)
    {

        webBrowser -> Navigate(textNavigate->Text);

    }

}
};
}

What could be a solution to the problem?

Body:
Why would you post such an incredible amount of absolutely useless code when the error tells you exactly what the problem is: Error C2731 'WinMain': function cannot be overloaded

The problem is obviously on this line:

int WinMain()

If you read any of the extensive documentation on the topic, it should be clear that the function needs to look like this:

int WinMain(
  [in] HINSTANCE hInstance,
  [in] HINSTANCE hPrevInstance,
  [in] LPSTR     lpCmdLine,
  [in] int       nShowCmd
);


问:
Setting minimum length for auto link
I have a big paragraph which may have numbers, email addresses and links. So I have to set  setAutoLinkMask(Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS) for my textview.

The content may contain digits of varying numbers. I want to set numbers having atleast 8 digits as phone number links.(For Eg : 12345678)

Is it possible to set minimum length for Linkify.PHONE_NUMBERS ?
Is there anyway to achieve this?

答:
Yes, its possible. I researched this phenomenon :-)

To set the minimum length for a phone number, use this code:

```<code>private final Linkify.MatchFilter matchFilterForPhone = new Linkify.MatchFilter() {
    @Override
    public boolean acceptMatch(CharSequence s, int start, int end) {
        int digitCount = 0;
        for (int i = start; i < end; i++) {
            if (Character.isDigit(s.charAt(i))) {
                digitCount++;
                if (digitCount >= 6) { // HERE: number 6 is minimum
                    return true;
                }
            }
        }
        return false;
    }
};
</code>```

To properly format and link phone numbers, use:

```<code>final SpannableString s = new SpannableString(myTekst);
Linkify.addLinks(s, android.util.Patterns.PHONE, "tel:", matchFilterForPhone, Linkify.sPhoneNumberTransformFilter);
</code>```

Now place the formatted s in your TextView, and call:

```<code>findViewById(R.id.message).setLinkTextColor(Color.BLUE);
findViewById(R.id.message).setMovementMethod(LinkMovementMethod.getInstance());
</code>```

That's all. Thanks for vote.

Title: Setting minimum length for auto link

Body:
Yes, its possible. I researched this phenomenon :-)

To set the minimum length for a phone number, use this code:

private final Linkify.MatchFilter matchFilterForPhone = new Linkify.MatchFilter() {
    @Override
    public boolean acceptMatch(CharSequence s, int start, int end) {
        int digitCount = 0;
        for (int i = start; i < end; i++) {
            if (Character.isDigit(s.charAt(i))) {
                digitCount++;
                if (digitCount >= 6) { // HERE: number 6 is minimum
                    return true;
                }
            }
        }
        return false;
    }
};

To properly format and link phone numbers, use:

final SpannableString s = new SpannableString(myTekst);
Linkify.addLinks(s, android.util.Patterns.PHONE, "tel:", matchFilterForPhone, Linkify.sPhoneNumberTransformFilter);

Now place the formatted s in your TextView, and call:

findViewById(R.id.message).setLinkTextColor(Color.BLUE);
findViewById(R.id.message).setMovementMethod(LinkMovementMethod.getInstance());

That's all. Thanks for vote.


问:
Streaming HTML from Java web application
How to achieve continuous HTML streaming in a Java web application?

Like, making the page keep on loading (indicates) and push data from server.

答:
Using ajax you can call the server continuously and continue to refresh parts of the page.

Obviously you would be better using timeouts and not continuously.


问:
Extracting somewhat reliably placed substrings from a longer string in SQL
So I have a dataset that looks roughly like this:

```<code>01/02/2022, "bananas, apples and oranges", "accepted", "John"
01/05/2022, "bananas and grapes", "accepted", "Mary"
01/08/2022, "kale and bananas", "rejected", "John"
</code>```

I need to transform it into:

```<code>01/02/2022, "bananas", "accepted", "John"
01/02/2022, "apples", "accepted", "John"
01/02/2022, "oranges", "accepted", "John"
01/05/2022, "bananas, "accepted", "Mary"
</code>```

etc.

My problem is extracting the substrings for the types of fruit. The pattern is reliable in that the last delimiter is always " and ", and if there is another one before it, it's always ", ". So I can use CHARINDEX to find the position of the start of each word. But I struggle with finding the position of the end of the word. I could probably do it with a ton of CASE WHENs but is there an easier way?

(I asked this question earlier but I did a bad job of describing the problem then.)

答:
Given this data:

```<code>CREATE TABLE dbo.whatever
(
  d date,
  fruits varchar(255),
  status varchar(12),
  name   varchar(32)
 );

INSERT dbo.whatever VALUES
('20220102', 'bananas, apples and oranges', 'accepted', 'John'),
('20220105', 'bananas and grapes', 'accepted', 'Mary'),
('20220108', 'kale and bananas', 'rejected', 'John');
</code>```

You want to split strings but based on two delimiters. So before you split them, you can just replace one with the other:

```<code>SELECT w.d, fruit = LTRIM(f.value), w.status, w.name
FROM dbo.whatever AS w
CROSS APPLY
STRING_SPLIT(REPLACE(w.fruits, ' and ', ', '), ',') AS f;
</code>```

Results:

d
fruit
status
name

2022-01-02
bananas
accepted
John

2022-01-02
apples
accepted
John

2022-01-02
oranges
accepted
John

2022-01-05
bananas
accepted
Mary

2022-01-05
grapes
accepted
Mary

2022-01-08
kale
rejected
John

2022-01-08
bananas
rejected
John

Example db<>fiddle

Body:
So I have a dataset that looks roughly like this:

01/02/2022, "bananas, apples and oranges", "accepted", "John"
01/05/2022, "bananas and grapes", "accepted", "Mary"
01/08/2022, "kale and bananas", "rejected", "John"

I need to transform it into:

01/02/2022, "bananas", "accepted", "John"
01/02/2022, "apples", "accepted", "John"
01/02/2022, "oranges", "accepted", "John"
01/05/2022, "bananas, "accepted", "Mary"

etc.

My problem is extracting the substrings for the types of fruit. The pattern is reliable in that the last delimiter is always " and ", and if there is another one before it, it's always ", ". So I can use CHARINDEX to find the position of the start of each word. But I struggle with finding the position of the end of the word. I could probably do it with a ton of CASE WHENs but is there an easier way?

(I asked this question earlier but I did a bad job of describing the problem then.)

Body:
Given this data:

CREATE TABLE dbo.whatever
(
  d date,
  fruits varchar(255),
  status varchar(12),
  name   varchar(32)
 );

INSERT dbo.whatever VALUES
('20220102', 'bananas, apples and oranges', 'accepted', 'John'),
('20220105', 'bananas and grapes', 'accepted', 'Mary'),
('20220108', 'kale and bananas', 'rejected', 'John');

You want to split strings but based on two delimiters. So before you split them, you can just replace one with the other:

SELECT w.d, fruit = LTRIM(f.value), w.status, w.name
FROM dbo.whatever AS w
CROSS APPLY
STRING_SPLIT(REPLACE(w.fruits, ' and ', ', '), ',') AS f;

Results:

d
fruit
status
name

2022-01-02
bananas
accepted
John

2022-01-02
apples
accepted
John

2022-01-02
oranges
accepted
John

2022-01-05
bananas
accepted
Mary

2022-01-05
grapes
accepted
Mary

2022-01-08
kale
rejected
John

2022-01-08
bananas
rejected
John

Example db<>fiddle


问:
GCE Load Balancer Health Check Fails (Connection Refused)
My (GCE) Load Balancer health checks are failing with a connection refused error, ultimately marking my GCE Ingress as UNHEALTHY.
Now I'm wondering how to fix this issue.

For my setup I'm using a GKE Autopilot cluster. And I have teared down and restarted my setup several times, always leading to the same result.

Suppose I have a deployment configured with a pod template consisting of several containers (of which not all of them expose ports).

Side Note: For simplicity I skipped some configurations, such as config maps.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-app-deployment
spec:
  selector:
    matchLabels:
      app: some-app
  replicas: 2
  template:
    metadata:
      labels:
        app: some-app
    spec:
      restartPolicy: Always
      containers:
        - name: web-server
          image: {{some-app-image}}
          command: ['app', 'web-server']
          ports:
            - name: web-server
              containerPort: 5000
              protocol: TCP
        - name: admin-server
          image: {{some-app-image}}
          command: ['app', 'admin-server']
          ports:
            - name: admin-server
              containerPort: 5001
              protocol: TCP
        - name: worker
          image: {{some-app-image}}
          command: ['app', 'worker']
        - name: cron
          image: {{some-app-image}}
          command: ['app', 'cron']
        - name: helper
          image: {{some-app-image}}
          command: [ '/bin/bash', '-c', '--' ]
          args: [ 'while true; do sleep 30; done;' ]
```
<p>The following is the BackendConfig CRD, which supposedly defines the health check.
I chose to define the path as <code>/favicon.ico</code> because Load Balancer Health Check requires exactly <code>200 OK</code> response and the web-servers base path <code>/</code> emits a redirect <code>302</code>, hence it would faild the Health Check.
With <code>kubectl port-forward</code> I confirmed that <code>/favicon.ico</code> actually emits <code>200 OK</code> and it does.
Btw. just to exclude this from being a problem, I also tried other paths without success.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: http-hc-config
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20
</code>```

Additionally there is a custom header added to the admin endpoint.

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: x-header-config
spec:
  customRequestHeaders:
    headers:
    - "X-Client-Region:{client_region}"
```
<p>The following is the service description. It references the BackendConfig via annotations as per the documentation.
The documentation is not very specific as to how to reference the health check, so I mapped it to the relevant port.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
  name: some-app-service
  annotations:
    cloud.google.com/backend-config: '{
      "default":"http-hc-config",
      "ports":{"4001":"x-header-config"}}'
spec:
  type: NodePort
  selector:
    app: some-app
  ports:
    - name: web
      targetPort: 5000
      protocol: TCP
      port: 4000
    - name: admin
      targetPort: 5001
      protocol: TCP
      port: 4001
</code>```

I confirmed that my service is running, as I could successfully kubectl port-forward the pods and access the web-servers content.

Now the final piece of the setup is this ingress object.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: gce
spec:
  rules:
    - host: admin.example.com
      http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4001
    - http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4000
```
<p>EDIT #1 & #2:
Performing a <code>gcloud compute health-checks describe {{HEALTH_DEF_ID}}</code> I receive the following output for the health check on <code>port 4001</code>, which seems to be out-of-sync with the defined BackendConfig CRD:</p>
<pre class="lang-yaml prettyprint-override"><code>checkIntervalSec: 15
creationTimestamp: '2022-02-07T11:30:50.059-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  portSpecification: USE_SERVING_PORT
  proxyHeader: NONE
  requestPath: /
id: {{REDACTED}}
kind: compute#healthCheck
logConfig:
  enable: true
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2
</code>```

And the following for port 4000, which surprisingly contains the right path and port configuration:

checkIntervalSec: 20
creationTimestamp: '2022-02-07T12:12:59.248-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  port: 5000
  portSpecification: USE_FIXED_PORT
  proxyHeader: NONE
  requestPath: /favicon.ico
id: {{REDACTED}}
kind: compute#healthCheck
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2
```
<p>Either there's something wrong with my setup, or the BackendConfig is not equally applied for all services in the rules section of the Ingress.</p>
<p>Edit #3:</p>
<p>The Healt Check log entry for <code>port 4000</code> shows:</p>
<pre class="lang-json prettyprint-override"><code>healthCheckProbeResult: {
detailedHealthState: "TIMEOUT"
healthCheckProtocol: "HTTP"
healthState: "UNHEALTHY"
ipAddress: "10.40.129.203"
previousDetailedHealthState: "UNKNOWN"
previousHealthState: "UNHEALTHY"
probeCompletionTimestamp: "2022-02-07T20:06:10.955412154Z"
probeRequest: "/favicon.ico"
probeResultText: "HTTP response: , Error: Connection refused"
probeSourceIp: "35.191.12.114"
responseLatency: "0.000569s"
targetIp: "10.40.129.203"
targetPort: 5000
}
</code>```

EDIT #4:
I needed to adjust the BackendConfig annotation, as my case was in fact more involved compared to what my previous definitions were showing.

答:
The problem was in the way I applied the BackendConfig annotation of the service.
My assumption was that the "default" config would be applied to both ports and the extra header config would additionally be applied to port 4001.

But this is not the case.

In case a BackendConfig deviates from the default, you'll have to define a one for each case where it deviates from the HTTP ports.
BackendConfigs will not get merged and you can not add multiple configs per port.

---
apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: config-4000
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20
---
apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: config-4001
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20
  headers:
    - "X-Client-Region:{client_region}"
---
apiVersion: v1
kind: Service
metadata:
  name: some-app-service
  annotations:
    cloud.google.com/backend-config: '{"ports":{
       "4000":"config-4000",
       "4001":"config-4001"
    }}'
spec:
  type: NodePort
  selector:
    app: some-app
  ports:
    - name: web
      targetPort: 5000
      protocol: TCP
      port: 4000
    - name: admin
      targetPort: 5001
      protocol: TCP
      port: 4001
```

EDIT #1:

An additional issue (resulting in the Connection Error) was in my project config:

The server was configured to bind to 127.0.0.1 instead of 0.0.0.0

Body:
My (GCE) Load Balancer health checks are failing with a connection refused error, ultimately marking my GCE Ingress as UNHEALTHY.
Now I'm wondering how to fix this issue.

For my setup I'm using a GKE Autopilot cluster. And I have teared down and restarted my setup several times, always leading to the same result.

Suppose I have a deployment configured with a pod template consisting of several containers (of which not all of them expose ports).

Side Note: For simplicity I skipped some configurations, such as config maps.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: some-app-deployment
spec:
  selector:
    matchLabels:
      app: some-app
  replicas: 2
  template:
    metadata:
      labels:
        app: some-app
    spec:
      restartPolicy: Always
      containers:
        - name: web-server
          image: {{some-app-image}}
          command: ['app', 'web-server']
          ports:
            - name: web-server
              containerPort: 5000
              protocol: TCP
        - name: admin-server
          image: {{some-app-image}}
          command: ['app', 'admin-server']
          ports:
            - name: admin-server
              containerPort: 5001
              protocol: TCP
        - name: worker
          image: {{some-app-image}}
          command: ['app', 'worker']
        - name: cron
          image: {{some-app-image}}
          command: ['app', 'cron']
        - name: helper
          image: {{some-app-image}}
          command: [ '/bin/bash', '-c', '--' ]
          args: [ 'while true; do sleep 30; done;' ]

The following is the BackendConfig CRD, which supposedly defines the health check.
I chose to define the path as /favicon.ico because Load Balancer Health Check requires exactly 200 OK response and the web-servers base path / emits a redirect 302, hence it would faild the Health Check.
With kubectl port-forward I confirmed that /favicon.ico actually emits 200 OK and it does.
Btw. just to exclude this from being a problem, I also tried other paths without success.

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: http-hc-config
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20

Additionally there is a custom header added to the admin endpoint.

apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: x-header-config
spec:
  customRequestHeaders:
    headers:
    - "X-Client-Region:{client_region}"

The following is the service description. It references the BackendConfig via annotations as per the documentation.
The documentation is not very specific as to how to reference the health check, so I mapped it to the relevant port.

apiVersion: v1
kind: Service
metadata:
  name: some-app-service
  annotations:
    cloud.google.com/backend-config: '{
      "default":"http-hc-config",
      "ports":{"4001":"x-header-config"}}'
spec:
  type: NodePort
  selector:
    app: some-app
  ports:
    - name: web
      targetPort: 5000
      protocol: TCP
      port: 4000
    - name: admin
      targetPort: 5001
      protocol: TCP
      port: 4001

I confirmed that my service is running, as I could successfully kubectl port-forward the pods and access the web-servers content.

Now the final piece of the setup is this ingress object.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: gce
spec:
  rules:
    - host: admin.example.com
      http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4001
    - http:
        paths:
        - path: /*
          pathType: ImplementationSpecific
          backend:
            service:
              name: some-app-service
              port:
                number: 4000

EDIT #1 & #2:
Performing a gcloud compute health-checks describe {{HEALTH_DEF_ID}} I receive the following output for the health check on port 4001, which seems to be out-of-sync with the defined BackendConfig CRD:

checkIntervalSec: 15
creationTimestamp: '2022-02-07T11:30:50.059-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  portSpecification: USE_SERVING_PORT
  proxyHeader: NONE
  requestPath: /
id: {{REDACTED}}
kind: compute#healthCheck
logConfig:
  enable: true
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2

And the following for port 4000, which surprisingly contains the right path and port configuration:

checkIntervalSec: 20
creationTimestamp: '2022-02-07T12:12:59.248-08:00'
description: Default kubernetes L7 Loadbalancing health check for NEG.
healthyThreshold: 1
httpHealthCheck:
  port: 5000
  portSpecification: USE_FIXED_PORT
  proxyHeader: NONE
  requestPath: /favicon.ico
id: {{REDACTED}}
kind: compute#healthCheck
name: k8s1-4622dadc-{{REDACTED}}
selfLink: https://www.googleapis.com/compute/v1/projects/{{REDACTED}}
timeoutSec: 15
type: HTTP
unhealthyThreshold: 2

Either there's something wrong with my setup, or the BackendConfig is not equally applied for all services in the rules section of the Ingress.

Edit #3:

The Healt Check log entry for port 4000 shows:

healthCheckProbeResult: {
detailedHealthState: "TIMEOUT"
healthCheckProtocol: "HTTP"
healthState: "UNHEALTHY"
ipAddress: "10.40.129.203"
previousDetailedHealthState: "UNKNOWN"
previousHealthState: "UNHEALTHY"
probeCompletionTimestamp: "2022-02-07T20:06:10.955412154Z"
probeRequest: "/favicon.ico"
probeResultText: "HTTP response: , Error: Connection refused"
probeSourceIp: "35.191.12.114"
responseLatency: "0.000569s"
targetIp: "10.40.129.203"
targetPort: 5000
}

EDIT #4:
I needed to adjust the BackendConfig annotation, as my case was in fact more involved compared to what my previous definitions were showing.

Body:
The problem was in the way I applied the BackendConfig annotation of the service.
My assumption was that the "default" config would be applied to both ports and the extra header config would additionally be applied to port 4001.

But this is not the case.

In case a BackendConfig deviates from the default, you'll have to define a one for each case where it deviates from the HTTP ports.
BackendConfigs will not get merged and you can not add multiple configs per port.

---
apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: config-4000
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20
---
apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: config-4001
spec:
  healthCheck:
    type: HTTP
    port: 5000
    requestPath: "/favicon.ico"
    checkIntervalSec: 20
  headers:
    - "X-Client-Region:{client_region}"
---
apiVersion: v1
kind: Service
metadata:
  name: some-app-service
  annotations:
    cloud.google.com/backend-config: '{"ports":{
       "4000":"config-4000",
       "4001":"config-4001"
    }}'
spec:
  type: NodePort
  selector:
    app: some-app
  ports:
    - name: web
      targetPort: 5000
      protocol: TCP
      port: 4000
    - name: admin
      targetPort: 5001
      protocol: TCP
      port: 4001

EDIT #1:

An additional issue (resulting in the Connection Error) was in my project config:

The server was configured to bind to 127.0.0.1 instead of 0.0.0.0


问:
How to download all files in a directory in ASP.NET using C#
I am currently learning uploading / downloading / deleting files in C# asp.net. I figured out how to delete every file in a folder with code like this:

```<code>protected void DeleteAllFiles(object sender, EventArgs e)
{
    System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Output"));

    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete();
    }

    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true);
    }

    Response.Redirect("~/Outputs.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString()));
}
</code>```

But I can't find anything on how to download all files in a directory. I figured out how to download individual files but I am having trouble with a button that downloads all files in a directory. Surely there is an easy way to do this? I can't find it anywhere else so this is probably a dumb question to ask but any help is appreciated.

答: It's not possible to send multiple files in a single HTTP request. However, you can create a zip archive of multiple files and send that instead. See this answer for an example.</p>

Body:
I am currently learning uploading / downloading / deleting files in C# asp.net. I figured out how to delete every file in a folder with code like this:

protected void DeleteAllFiles(object sender, EventArgs e)
{
    System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Output"));

    foreach (FileInfo file in di.GetFiles())
    {
        file.Delete();
    }

    foreach (DirectoryInfo dir in di.GetDirectories())
    {
        dir.Delete(true);
    }

    Response.Redirect("~/Outputs.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString()));
}

But I can't find anything on how to download all files in a directory. I figured out how to download individual files but I am having trouble with a button that downloads all files in a directory. Surely there is an easy way to do this? I can't find it anywhere else so this is probably a dumb question to ask but any help is appreciated.


问:
Display data from db on HTML using Node.js
I am trying to get a webpage to display data from my database and display it on a html page in a table and be able to scroll down on the table by rendering it in ejs. I based my code from this site https://www.tutsmake.com/node-js-fetch-and-display-data-from-mysql-database-in-html-list/

i'm not really sure what I'm doing wrong, the db is connecting just fine, and I have the ejs file in my views folder. I'm guessing the issue is coming from the ejs file but I'm not sure. I've just started coding again so this is basically all new to me.

when I go to localhost:3000/test I'm getting a 404 error and when I look at the terminal it says  GET/TEST 404 20.377ms -1153, I think I might be pulling to much data at once since the there are 75 rows for this, I've tried to limit the amount of rows but it still wont load the page and for some reason this code can't even find my ejs file.

From what I've read online there are a million different ways to do this and I don't know where to start to get this working. I'm using mssql as my database and using visual studio to build everything.

this is my server.js

```<code>var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');

var sql = require("mssql/msnodesqlv8");
var connection = require('./lib/db');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
   secret: '123456cat',
   resave: false,
   saveUninitialized: true,
   cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use(expressValidator());

app.use('/', indexRouter);
app.use('/index', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
   next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
   // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};
   // render the error page
   res.status(err.status || 500);
   res.render('error');
});
module.exports = app;
</code>```

this is my dbaCon.js

```<code>const sql = require("mssql/msnodesqlv8");

var conn = new sql.ConnectionPool({
    server: 'DESKTOP-BA7Q2HM',
    port: 1433,
    driver: 'msnodesqlv8',
    database: "tempdb",
    domain: 'DNAME',
    requestTimeout: 3600000,
    options: {
        trustedConnection: true,
        enableArtithAbort: true
    },
    debug: true,
    parseJSON: true
});

conn.connect(function (err) {
    if (err) throw err;
    console.log('Database is connected successfully!');
});
module.exports = conn;
</code>```

this is my users.js

```<code>var express = require('express');
var router = express.Router();
var connection = require('../dbaCon.js');

/* GET home page. */
router.get('/', function (req, res, next) {

    connection.query('SELECT id, status, type, Date, Review * FROM [dba].[table] ', function (err, rows) {

        if (err) {
            req.flash('error', err);
            res.render('index', { page_title: "test - Node.js", data: '' });
        } else {

            res.render('index', { page_title: "test - Node.js", data: rows });
        }

    });
});

module.exports = router;
</code>```

this is my index.ejs file

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Display Active Loan info to Client</title>
</head>
<body>
    <% if (messages.error) { %>
    <p style="color:red"><%- messages.error %></p>
    <% } %>
    <% if (messages.success) { %>
    <p class="alert alert-success mt-4"><%- messages.success %></p>
    <% } %>
    <br>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">id</th>
                <th scope="col">status</th>
                <th scope="col">type</th>
                <th scope="col">date</th>
                <th scope="col">review</th>

            </tr>
        </thead>
        <tbody>
            <% if(data.length){
            for(var i = 0; i< data.length; i++) {%>
            <tr>
                <th scope="row"><%= (i+1) %></th>
                <td><%= data[i].id%></td>
                <td><%= data[i].status%></td>
                <td><%= data[i].type%></td>
                <td><%= data[i].date%></td>
                <td><%= data[i].review%></td>
            </tr>
            <% }
            }else{ %>
            <tr>
                <td colspan="3">No Data Availed</td>
            </tr>
            <% } %>
        </tbody>
    </table>
</body>
</html>
</code>```

答:
you do not have a route for "/test".

you have these routes that points to '/WHAT_YOU_HAVE_ON_indexRouter' and '/index/WHAT_YOU_HAVE_ON_userRouter'

app.use('/', indexRouter);
app.use('/index', usersRouter);

on your userRouter you dont have a '/test' route, you need to add it.

you reach the 404 because the app cant find any route related to '/test'

Body:
I am trying to get a webpage to display data from my database and display it on a html page in a table and be able to scroll down on the table by rendering it in ejs. I based my code from this site https://www.tutsmake.com/node-js-fetch-and-display-data-from-mysql-database-in-html-list/

i'm not really sure what I'm doing wrong, the db is connecting just fine, and I have the ejs file in my views folder. I'm guessing the issue is coming from the ejs file but I'm not sure. I've just started coding again so this is basically all new to me.

when I go to localhost:3000/test I'm getting a 404 error and when I look at the terminal it says  GET/TEST 404 20.377ms -1153, I think I might be pulling to much data at once since the there are 75 rows for this, I've tried to limit the amount of rows but it still wont load the page and for some reason this code can't even find my ejs file.

From what I've read online there are a million different ways to do this and I don't know where to start to get this working. I'm using mssql as my database and using visual studio to build everything.

this is my server.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');

var sql = require("mssql/msnodesqlv8");
var connection = require('./lib/db');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
   secret: '123456cat',
   resave: false,
   saveUninitialized: true,
   cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use(expressValidator());

app.use('/', indexRouter);
app.use('/index', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
   next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
   // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};
   // render the error page
   res.status(err.status || 500);
   res.render('error');
});
module.exports = app;

this is my dbaCon.js

const sql = require("mssql/msnodesqlv8");

var conn = new sql.ConnectionPool({
    server: 'DESKTOP-BA7Q2HM',
    port: 1433,
    driver: 'msnodesqlv8',
    database: "tempdb",
    domain: 'DNAME',
    requestTimeout: 3600000,
    options: {
        trustedConnection: true,
        enableArtithAbort: true
    },
    debug: true,
    parseJSON: true
});

conn.connect(function (err) {
    if (err) throw err;
    console.log('Database is connected successfully!');
});
module.exports = conn;

this is my users.js

var express = require('express');
var router = express.Router();
var connection = require('../dbaCon.js');

/* GET home page. */
router.get('/', function (req, res, next) {

    connection.query('SELECT id, status, type, Date, Review * FROM [dba].[table] ', function (err, rows) {

        if (err) {
            req.flash('error', err);
            res.render('index', { page_title: "test - Node.js", data: '' });
        } else {

            res.render('index', { page_title: "test - Node.js", data: rows });
        }

    });
});

module.exports = router;

this is my index.ejs file

<!DOCTYPE html>

    <title>Display Active Loan info to Client</title>

    <% if (messages.error) { %>

<%- messages.error %>

    <% } %>
    <% if (messages.success) { %>

<%- messages.success %>

    <% } %>

                id
                status
                type
                date
                review

            <% if(data.length){
            for(var i = 0; i< data.length; i++) {%>

                <%= (i+1) %>
                <%= data[i].id%>
                <%= data[i].status%>
                <%= data[i].type%>
                <%= data[i].date%>
                <%= data[i].review%>

            <% }
            }else{ %>

                No Data Availed

            <% } %>


问:
Where should I put DataGrip database driver on linux?
Need to install Postgre database driver on my PC for DataGrip, my PC has no internet.

I has this jar file on my PC desktop, but in what place should I put this jar file?

So on Windows, it was ~\.DataGrip2019.2\config\jdbc-drivers, but what directory on Linux?

答: In Data source & Drivers dialog switch to Drivers tab, select target driver, on driver files pane remove current entry, then click (+) -> Custom JARs -> select your file and that's it.</p>


问:
c# Collection of Dictionary
how would I create and then access a collection of a (Sorted)Dictionary?
It could be a Series<SortedDictionary<double, MyClass>> or a Dictionary<int, SortedDictionary<double, MyClass>> for example.

```<code>Series[0] = sortedDict;
Dict.Add(myInt, sortedDict);
</code>```

For some reason, when doing it like this, the Dictionary is empty, when accessing values with a loop and the series seems to be empty as well.

```<code>for (int i = 0; i < Dict.Count; i++)
{
   SortedDictionary<double, MyClass> sortedDictPair = Dict.ElementAt(i).Value;
   foreach (var item in sortedDictPair)
   {
        Print(item.Key);
        MyClass myClass= item.Value;
        Print(myClass.classMember);
    }
}

SortedDictionary<double, MyClass> sortedDictPair = Series[0];
for (int j = 0; j < sortedDictPair.Count; j++)
    {
        MyClass myClass = sortedDictPair.ElementAt(j).Value;
        Print(myClass.classMember);
    }
 }
</code>```

Is there something I am overseeing?
Edit: when I let it print the sortedDict before aissgning it, it is full of entries.

答:
Can you try them in two foreach loops?

```<code>Dictionary<int, SortedDictionary<double, MyClass>> dictionary = new Dictionary<int, SortedDictionary<double, MyClass>>()
    {
        { 1, new SortedDictionary<double,MyClass>(){ {2, new MyClass{ Score=1 } }, { 3, new MyClass { Score = 1 } } } },
        { 2, new SortedDictionary<double,MyClass>()}
    };
    foreach (var item1 in dictionary)
    {
        foreach (var item2 in item1.Value)
        {
            Console.WriteLine(item2.Key);
            MyClass myClass = item2.Value;
            Console.WriteLine(myClass.Score);
        }
    }
</code>```

Title: c# Collection of Dictionary

Body:
how would I create and then access a collection of a (Sorted)Dictionary?
It could be a Series<SortedDictionary<double, MyClass>> or a Dictionary<int, SortedDictionary<double, MyClass>> for example.

Series[0] = sortedDict;
Dict.Add(myInt, sortedDict);

For some reason, when doing it like this, the Dictionary is empty, when accessing values with a loop and the series seems to be empty as well.

for (int i = 0; i < Dict.Count; i++)
{
   SortedDictionary<double, MyClass> sortedDictPair = Dict.ElementAt(i).Value;
   foreach (var item in sortedDictPair)
   {
        Print(item.Key);
        MyClass myClass= item.Value;
        Print(myClass.classMember);
    }
}

SortedDictionary<double, MyClass> sortedDictPair = Series[0];
for (int j = 0; j < sortedDictPair.Count; j++)
    {
        MyClass myClass = sortedDictPair.ElementAt(j).Value;
        Print(myClass.classMember);
    }
 }

Is there something I am overseeing?
Edit: when I let it print the sortedDict before aissgning it, it is full of entries.

Body:
Can you try them in two foreach loops?

Dictionary<int, SortedDictionary<double, MyClass>> dictionary = new Dictionary<int, SortedDictionary<double, MyClass>>()
    {
        { 1, new SortedDictionary<double,MyClass>(){ {2, new MyClass{ Score=1 } }, { 3, new MyClass { Score = 1 } } } },
        { 2, new SortedDictionary<double,MyClass>()}
    };
    foreach (var item1 in dictionary)
    {
        foreach (var item2 in item1.Value)
        {
            Console.WriteLine(item2.Key);
            MyClass myClass = item2.Value;
            Console.WriteLine(myClass.Score);
        }
    }


问:
xpath expression not working in Logic Apps
I have the following XML response from a SOAP call

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Body>
        <GetContractStatusesResponse xmlns="http://www.proactis.com/xml/xml-ns/">
            <GetContractStatusesResult>
                <Message>Successful</Message>
                <Code>1</Code>
                <InterfaceLanguage>de</InterfaceLanguage>
                <GetContractStatusesData xmlns="http://schemas.proactis.com/p4/contractmanagement/2013/02">
                    <ContractStatus code="DRFT" typeId="3581">Draft</ContractStatus>
                    <ContractStatus code="BAPR" typeId="3582">Being Approved</ContractStatus>
                    <ContractStatus code="RJCT" typeId="3583">Rejected</ContractStatus>
                    <ContractStatus code="CNCL" typeId="3584">Cancelled</ContractStatus>
                    <ContractStatus code="APPR" typeId="3585">Approved</ContractStatus>
                    <ContractStatus code="ACPE" typeId="3586">Activation Pending</ContractStatus>
                    <ContractStatus code="ACTV" typeId="3587">Active</ContractStatus>
                    <ContractStatus code="SUSP" typeId="3588">Suspended</ContractStatus>
                    <ContractStatus code="COMP" typeId="3589">Completed</ContractStatus>
                    <ContractStatus code="NOV" typeId="3783">Novated</ContractStatus>
                    <ContractStatus code="DEF" typeId="3853">In Defects Period</ContractStatus>
                </GetContractStatusesData>
            </GetContractStatusesResult>
        </GetContractStatusesResponse>
    </soap:Body>
</soap:Envelope>
</code>```

I am trying to create an xpath reference to retrieve an array of GetContractStatusesData so that i can then loop through each ContractStatus to use the value and also the associated code as well

I have tried various online xpath generators but they dont seem to work properly when imported into Logic Apps, and even to try something more simpler like getting the message value.

These are the ones i have tried by setting a logic app variable

```<code>xpath(xml(variables('Payload')), '//ContractStatus[1]/@code')
xpath(xml(variables('Payload')), '//ContractStatus[1]/text()[1]')
</code>```

The result I typically get back is []

答:
Namespaces come into play.  Try the following:

```<code>//*[local-name()="GetContractStatusesData"]/*[local-name()="ContractStatus"]/text()
</code>```

As for using concat, for some reason Logic Apps doesn't work with it.

Body:
I have the following XML response from a SOAP call

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Body>
        <GetContractStatusesResponse xmlns="http://www.proactis.com/xml/xml-ns/">
            <GetContractStatusesResult>
                <Message>Successful</Message>
                1
                <InterfaceLanguage>de</InterfaceLanguage>
                <GetContractStatusesData xmlns="http://schemas.proactis.com/p4/contractmanagement/2013/02">
                    <ContractStatus code="DRFT" typeId="3581">Draft</ContractStatus>
                    <ContractStatus code="BAPR" typeId="3582">Being Approved</ContractStatus>
                    <ContractStatus code="RJCT" typeId="3583">Rejected</ContractStatus>
                    <ContractStatus code="CNCL" typeId="3584">Cancelled</ContractStatus>
                    <ContractStatus code="APPR" typeId="3585">Approved</ContractStatus>
                    <ContractStatus code="ACPE" typeId="3586">Activation Pending</ContractStatus>
                    <ContractStatus code="ACTV" typeId="3587">Active</ContractStatus>
                    <ContractStatus code="SUSP" typeId="3588">Suspended</ContractStatus>
                    <ContractStatus code="COMP" typeId="3589">Completed</ContractStatus>
                    <ContractStatus code="NOV" typeId="3783">Novated</ContractStatus>
                    <ContractStatus code="DEF" typeId="3853">In Defects Period</ContractStatus>
                </GetContractStatusesData>
            </GetContractStatusesResult>
        </GetContractStatusesResponse>
    </soap:Body>
</soap:Envelope>

I am trying to create an xpath reference to retrieve an array of GetContractStatusesData so that i can then loop through each ContractStatus to use the value and also the associated code as well

I have tried various online xpath generators but they dont seem to work properly when imported into Logic Apps, and even to try something more simpler like getting the message value.

These are the ones i have tried by setting a logic app variable

xpath(xml(variables('Payload')), '//ContractStatus[1]/@code')
xpath(xml(variables('Payload')), '//ContractStatus[1]/text()[1]')

The result I typically get back is []

Body:
Namespaces come into play.  Try the following:

//*[local-name()="GetContractStatusesData"]/*[local-name()="ContractStatus"]/text()

As for using concat, for some reason Logic Apps doesn't work with it.


问:
Using TABLOCK with merge SQL Server
I have a merge query similar to the one below:

```<code>MERGE [Unshipped] u
USING [Order] or ON or.ID = u.ID

WHEN MATCHED AND u.Date <> or.Date
   THEN
      UPDATE
      SET u.Date = or.Date

WHEN NOT MATCHED
    THEN
       INSERT (ID, FK, Date)
       VALUES (or.ID, or.FK, or.Date)
</code>```

If i am to add TABLOCK where is the best place for it? I would have assumed i would put it like below - wrap the whole merge statement:

```<code>     MERGE [Unshipped] u WITH (TABLOCK)
     USING [Order] order or ON or.ID = u.ID
</code>```

or is it more suitable for it to go with the insert statement?

答:
You only need:

```<code> MERGE [Unshipped] WITH (TABLOCK) AS u
 USING [Order] or ON or.ID = u.ID
</code>```

Rest of the MERGE statement is unchanged.

Title: Using TABLOCK with merge SQL Server

Body:
I have a merge query similar to the one below:

MERGE [Unshipped] u
USING [Order] or ON or.ID = u.ID

WHEN MATCHED AND u.Date <> or.Date
   THEN
      UPDATE
      SET u.Date = or.Date

WHEN NOT MATCHED
    THEN
       INSERT (ID, FK, Date)
       VALUES (or.ID, or.FK, or.Date)

If i am to add TABLOCK where is the best place for it? I would have assumed i would put it like below - wrap the whole merge statement:

     MERGE [Unshipped] u WITH (TABLOCK)
     USING [Order] order or ON or.ID = u.ID

or is it more suitable for it to go with the insert statement?

Body:
You only need:

 MERGE [Unshipped] WITH (TABLOCK) AS u
 USING [Order] or ON or.ID = u.ID

Rest of the MERGE statement is unchanged.


答:
when I go to localhost:3000/test I'm getting a 404 error

You didn't setup any route with the endpoint /test, at least not on the code you posted, that's why you get an 404 not found error.

I think I might be pulling to much data at once since the there are 75 rows for this

No, 75 rows are no close to much data. You should edit your question to clarify each problem.

Title: Display data from db on HTML using Node.js


问:
How to include libgmp to xeus-cling?
I am trying to run the following code:

#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>
```
<p>and I get following errors:</p>
```In file included from input_line_8:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
In file included from /usr/include/limits.h:26:
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h:56:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT) || __GLIBC_USE (ISOC2X)
    ^
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h:73:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_FUNCS_EXT) || __GLIBC_USE (ISOC2X)
    ^
In file included from input_line_8:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
/usr/include/limits.h:145:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT_C2X)
    ^
```
<hr />
<p>I am trying to include <code><limits.h></code> firstly:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <limits.h>
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>
</code>```

but I still get the error

```<code>In file included from input_line_9:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
/usr/include/limits.h:145:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT_C2X)
    ^
</code>```

How to make <libgmpxx.h> use <limits.h> from xeus-cling, not from /usr/include?

答:
in jupyter:

#include <stddef.h>    /* for size_t */
#include <limits.h>
#define __xeus_cling__
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>
```
<p>and
in <code>/usr/include/x86_64-linux-gnu/gmp.h</code></p>
<pre class="lang-cpp prettyprint-override"><code>  #include <stddef.h>    /* for size_t */
  #include <limits.h>
</code>```

replace with

```<code>#ifndef __xeus_cling__
  #include <stddef.h>    /* for size_t */
  #include <limits.h>
#endif
</code>```

Title: How to include libgmp to xeus-cling?

Body:
I am trying to run the following code:

#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>

and I get following errors:

In file included from input_line_8:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
In file included from /usr/include/limits.h:26:
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h:56:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT) || __GLIBC_USE (ISOC2X)
    ^
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h:73:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_FUNCS_EXT) || __GLIBC_USE (ISOC2X)
    ^
In file included from input_line_8:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
/usr/include/limits.h:145:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT_C2X)
    ^

I am trying to include <limits.h> firstly:

#include <limits.h>
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>

but I still get the error

In file included from input_line_9:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
/usr/include/limits.h:145:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT_C2X)
    ^

How to make <libgmpxx.h> use <limits.h> from xeus-cling, not from /usr/include?

Body:
in jupyter:

#include <stddef.h>    /* for size_t */
#include <limits.h>
#define __xeus_cling__
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>

and
in /usr/include/x86_64-linux-gnu/gmp.h

  #include <stddef.h>    /* for size_t */
  #include <limits.h>

replace with

#ifndef __xeus_cling__
  #include <stddef.h>    /* for size_t */
  #include <limits.h>
#endif