问:
Geo distance query with regex query in elastic search
I want to make a query with a keyword and show only the posts 150km around me within the queried keyword my query below is working but shows all the posts

```<code>{
    "query": {
        "regexp": {
            "title": {
                "value": ".*h.*",
                "flags": "ALL",
                "max_determinized_states": 10000,
                "rewrite": "constant_score"
            }
        }
    },
     "sort": [{
        "date": {
            "order": "desc"
        }
    }]
}
</code>```

but when I add the filter query like follows I am receiving parsing error

```<code>"filter": {
              "geo_distance": {
                   "distance": "150km",
                        "location": {
                         "lat": \(latitude),
                         "lon": \(longitude)
                         }
                   }
          }
</code>```

Any one can help please

答:
Here is the query you should be using, which combines both the regexp query and the geo_distance query using a bool/filter query:

```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "geo_distance": {
            "distance": "150km",
            "location": {
               "lat": \(latitude),
               "lon": \(longitude)
            }
          }
        },
        {
          "regexp": {
            "title": {
              "value": ".*h.*",
              "flags": "ALL",
              "max_determinized_states": 10000,
              "rewrite": "constant_score"
            }
          }
        }
      ]
    }
  },
  "sort": [
    {
      "date": {
        "order": "desc"
      }
    }
  ]
}
</code>```

Body:
I want to make a query with a keyword and show only the posts 150km around me within the queried keyword my query below is working but shows all the posts

{
    "query": {
        "regexp": {
            "title": {
                "value": ".*h.*",
                "flags": "ALL",
                "max_determinized_states": 10000,
                "rewrite": "constant_score"
            }
        }
    },
     "sort": [{
        "date": {
            "order": "desc"
        }
    }]
}

but when I add the filter query like follows I am receiving parsing error

"filter": {
              "geo_distance": {
                   "distance": "150km",
                        "location": {
                         "lat": \(latitude),
                         "lon": \(longitude)
                         }
                   }
          }

Any one can help please

Body:
Here is the query you should be using, which combines both the regexp query and the geo_distance query using a bool/filter query:

{
  "query": {
    "bool": {
      "filter": [
        {
          "geo_distance": {
            "distance": "150km",
            "location": {
               "lat": \(latitude),
               "lon": \(longitude)
            }
          }
        },
        {
          "regexp": {
            "title": {
              "value": ".*h.*",
              "flags": "ALL",
              "max_determinized_states": 10000,
              "rewrite": "constant_score"
            }
          }
        }
      ]
    }
  },
  "sort": [
    {
      "date": {
        "order": "desc"
      }
    }
  ]
}


来源: stackexchange

问:
how I make object value as key of another object of array?
I'm getting data in form of array of objects like this...

```<code> let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
</code>```

I want this this array in this form please anyone help...

```<code> let arrayIWant = [
                    {
                      2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
                      5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
                    }
                  ]
</code>```

Please help

答:
Iterate through all the items in the array.

For each item:

If the serviceId does not exist as a prop of the object, set the prop's serviceId key with an array containing the item.

If it exists, add the item to that array.

ContentLicense: CC BY-SA 4.0

Body:
I'm getting data in form of array of objects like this...

 let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];

I want this this array in this form please anyone help...

 let arrayIWant = [
                    {
                      2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
                      5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
                    }
                  ]

Please help


问:
How Can I Solve Permission Denied in React Native Project?
anyone faced this issue after a run

```<code>react-native run-android/ios
</code>```

android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java
  (Permission denied)

when i write sudo before any command like npm install/yarn add etc it's work very well

otherways i got errors related to Permission

答:
You might check the permissions on android/gradlew

They should be 755 not 644

Run chmod 755 android/gradlew inside your app root folder
then run react-native run-android

And it should work again

Finally remove the node modules and re-install using rm -rf node_modules && npm install

Body:
anyone faced this issue after a run

react-native run-android/ios

android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java
  (Permission denied)

when i write sudo before any command like npm install/yarn add etc it's work very well

otherways i got errors related to Permission


问:
Pyinstaller excluding SubModules while Compiling
I have developed the UI using the PyQt5, now i am converting the code into standalone application using Pyinstaller, but the problem is the file size is coming huge (nearly 250MB). Can i reduce the size of my file but excluding the unnecessary imports of PyQt5.
Following the libraries i have used -

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import os,sys
from mat4py import loadmat
from matplotlib import pyplot as plt
</code>```

PyQt5 library has following many sub modules (QtCore, QtGui, QtWidgets, QtMultimedia, QtBluetooth, QtNetwork, QtPositioning, Enginio, QtWebSockets, QtWebKit, QtWebKitWidgets, QtXml, QtSvg, QtSql, QtTest) in which i am using only QtCore, QtGui and QtWidgets.

Similarly, library matplotlib many modules in which i am using pyplot.

I want to skip the modules which the program doesn't using, so that i can reduce the size of the executable file.

My Spec file of pyinstaller -

```<code>import sys
sys.setrecursionlimit(3000)

block_cipher = None

a = Analysis(['ReadMAT.py'],
             pathex=['C:\\Users\\Sekhar\\Documents\\PythonScripts\\RXP\\ReadMAT'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='ReadMAT',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False, icon='ReadMAT.ico')
</code>```

How to skip the submodules which will not get into the compilation process. How can i reduce the file size of the executable ?

答:
PyInstaller has a hook mechanism for each package and it handles the binaries needed for the packages.

For some well-known libraries like Qt, it implements an efficient hook file that only retrieves the necessary binaries. But if you want to exclude some parts you need to do it by yourself either by using exclude command or manipulating the hook file:

By excluding the unnecessary modules with --exclude-module. Usually, this would be enough.

By modifying the specific hook file and remove the binaries you don't need.

For example, in Qt's hook file (<Pyinstaller_path>/utils/hooks/qt.py), there is a variable called _qt_dynamic_dependencies_dict and has all the binaries which located in <qt_installation_path>/Qt/bin so you can remove each one you don't need.

Later in a function called get_qt_binaries which bundles other Qt binaries, you can remove each one you don't need like opengl32sw.dll.

For example:

```<code>_qt_dynamic_dependencies_dict = {
    ## "lib_name":              (.hiddenimports,           translations_base,  zero or more plugins...)
    # I've removed qt5bluetooth with commenting below line
    #"qt5bluetooth":             (".QtBluetooth",           None,               ),  # noqa: E241,E202
    "qt5concurrent":            (None,                     "qtbase",           ),
    ...
}
...

def get_qt_binaries(qt_library_info):
    binaries = []
    angle_files = ['libEGL.dll', 'libGLESv2.dll', 'd3dcompiler_??.dll']
    binaries += find_all_or_none(angle_files, 3, qt_library_info)

    # comment the following two lines to exclude the `opengl32sw.dll`
    # opengl_software_renderer = ['opengl32sw.dll']
    # binaries += find_all_or_none(opengl_software_renderer, 1, qt_library_info)

    # Include ICU files, if they exist.
    # See the "Deployment approach" section in ``PyInstaller/utils/hooks/qt.py``.
    icu_files = ['icudt??.dll', 'icuin??.dll', 'icuuc??.dll']
    binaries += find_all_or_none(icu_files, 3, qt_library_info)

    return binaries
</code>```

Body:
I have developed the UI using the PyQt5, now i am converting the code into standalone application using Pyinstaller, but the problem is the file size is coming huge (nearly 250MB). Can i reduce the size of my file but excluding the unnecessary imports of PyQt5.
Following the libraries i have used -

from PyQt5 import QtCore, QtGui, QtWidgets
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import os,sys
from mat4py import loadmat
from matplotlib import pyplot as plt

PyQt5 library has following many sub modules (QtCore, QtGui, QtWidgets, QtMultimedia, QtBluetooth, QtNetwork, QtPositioning, Enginio, QtWebSockets, QtWebKit, QtWebKitWidgets, QtXml, QtSvg, QtSql, QtTest) in which i am using only QtCore, QtGui and QtWidgets.

Similarly, library matplotlib many modules in which i am using pyplot.

I want to skip the modules which the program doesn't using, so that i can reduce the size of the executable file.

My Spec file of pyinstaller -

import sys
sys.setrecursionlimit(3000)

block_cipher = None

a = Analysis(['ReadMAT.py'],
             pathex=['C:\\Users\\Sekhar\\Documents\\PythonScripts\\RXP\\ReadMAT'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='ReadMAT',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False, icon='ReadMAT.ico')

How to skip the submodules which will not get into the compilation process. How can i reduce the file size of the executable ?

Body:
PyInstaller has a hook mechanism for each package and it handles the binaries needed for the packages.

For some well-known libraries like Qt, it implements an efficient hook file that only retrieves the necessary binaries. But if you want to exclude some parts you need to do it by yourself either by using exclude command or manipulating the hook file:

By excluding the unnecessary modules with --exclude-module. Usually, this would be enough.

By modifying the specific hook file and remove the binaries you don't need.

For example, in Qt's hook file (<Pyinstaller_path>/utils/hooks/qt.py), there is a variable called _qt_dynamic_dependencies_dict and has all the binaries which located in <qt_installation_path>/Qt/bin so you can remove each one you don't need.

Later in a function called get_qt_binaries which bundles other Qt binaries, you can remove each one you don't need like opengl32sw.dll.

For example:

_qt_dynamic_dependencies_dict = {
    ## "lib_name":              (.hiddenimports,           translations_base,  zero or more plugins...)
    # I've removed qt5bluetooth with commenting below line
    #"qt5bluetooth":             (".QtBluetooth",           None,               ),  # noqa: E241,E202
    "qt5concurrent":            (None,                     "qtbase",           ),
    ...
}
...

def get_qt_binaries(qt_library_info):
    binaries = []
    angle_files = ['libEGL.dll', 'libGLESv2.dll', 'd3dcompiler_??.dll']
    binaries += find_all_or_none(angle_files, 3, qt_library_info)

    # comment the following two lines to exclude the `opengl32sw.dll`
    # opengl_software_renderer = ['opengl32sw.dll']
    # binaries += find_all_or_none(opengl_software_renderer, 1, qt_library_info)

    # Include ICU files, if they exist.
    # See the "Deployment approach" section in ``PyInstaller/utils/hooks/qt.py``.
    icu_files = ['icudt??.dll', 'icuin??.dll', 'icuuc??.dll']
    binaries += find_all_or_none(icu_files, 3, qt_library_info)

    return binaries


问:
Self hosted VPN with PiHole on AWS
I'm trying to create a setup where all of my (mobile and home) traffic is encrypted and ad-blocked. The idea is to use this setup:

wherein all of my traffic when using the VPN client on my phone or PC is routed through a custom OpenVPN setup running on a AWS EC2 instance. On its way out of the EC2 instance towards the public internet, I want to have a PiHole or equivalent DNS sinkhole filtering requests for blacklisted sites.

It's important that this is configured in such a way that I'm not allowing for a public/open DNS resolver - only traffic coming from through the OpenVPN (and therefore coming from an OpenVPN client that is using one of my keys) should be allowed.

Is this possible? Am I correctly understanding the functionality of all the parts?

How do I set this up? What concepts do I need to understand to make this work?

答: This tutorial seems like a good place to start. This is using lightsail not EC2, but if you aren't planning to scale this up much that might be simpler and cheaper.</p>

Title: Self hosted VPN with PiHole on AWS


问:
Append two pandas dataframe with different shapes and in for loop using python or pandasql
I have two dataframe such as:

df1:

```<code>     id  A  B  C  D

     1   a  b  c  d
     1   e  f  g  h
     1   i  j  k  l
</code>```

df2:

```<code>     id  A  C  D

     2   x  y  z
     2   u  v  w
</code>```

The final outcome should be:

```<code>    id  A   B  C  D

    1   a  b  c  d
    1   e  f  g  h
    1   i  j  k  l
    2   x     y  z
    2   u     v  w
</code>```

These tables are generated using for loop from json files. So have to keep on appending these tables one below another.

Note: Two dataframes 'id' column is always different.

My approach:

data is a dataframe in which column 'X' has json data and has and "id" column also.

```<code>          df1=pd.DataFrame()
          for i, row1 in data.head(2).iterrows():

             df2= pd.io.json.json_normalize(row1["X"])
             df2.columns = df2.columns.map(lambda x: x.split(".")[-1])
             df2["id"]=[row1["id"] for i in range(df2.shape[0])]

             if len(df1)==0:
                df1=df2.copy()

             df1=pd.concat((df1,df2), ignore_index=True)

      Error: AssertionError: Number of manager items must equal union of block items # manager items: 46, # tot_items: 49
</code>```

How to solve this using python or pandas sql.

答:
You can use pd.concat to concatenate two dataframes like

```<code>>>> pd.concat((df,df1), ignore_index=True)
   id  A    B  C  D
0   1  a    b  c  d
1   1  e    f  g  h
2   1  i    j  k  l
3   2  x  NaN  y  z
4   2  u  NaN  v  w
</code>```

Body:
I have two dataframe such as:

df1:

     id  A  B  C  D

     1   a  b  c  d
     1   e  f  g  h
     1   i  j  k  l

df2:

     id  A  C  D

     2   x  y  z
     2   u  v  w

The final outcome should be:

    id  A   B  C  D

    1   a  b  c  d
    1   e  f  g  h
    1   i  j  k  l
    2   x     y  z
    2   u     v  w

These tables are generated using for loop from json files. So have to keep on appending these tables one below another.

Note: Two dataframes 'id' column is always different.

My approach:

data is a dataframe in which column 'X' has json data and has and "id" column also.

          df1=pd.DataFrame()
          for i, row1 in data.head(2).iterrows():

             df2= pd.io.json.json_normalize(row1["X"])
             df2.columns = df2.columns.map(lambda x: x.split(".")[-1])
             df2["id"]=[row1["id"] for i in range(df2.shape[0])]

             if len(df1)==0:
                df1=df2.copy()

             df1=pd.concat((df1,df2), ignore_index=True)

      Error: AssertionError: Number of manager items must equal union of block items # manager items: 46, # tot_items: 49

How to solve this using python or pandas sql.

Body:
You can use pd.concat to concatenate two dataframes like

>>> pd.concat((df,df1), ignore_index=True)
   id  A    B  C  D
0   1  a    b  c  d
1   1  e    f  g  h
2   1  i    j  k  l
3   2  x  NaN  y  z
4   2  u  NaN  v  w


问:
How to run multiple select query at once in sequelize using single await
Have to run both codes at a single time. Don't want to wait and then fire next query but wait for both query execution complete.</p>

```<code>products = await Product.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

variationProducts = await VariationProduct.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});
</code>```

答:
```<code>const products = Product.findAll();
const variationProducts = VariationProduct.findAll();

const productsPromise = await products;
const variationProductsPromise = await variationProducts;
</code>```

Body:
Have to run both codes at a single time. Don't want to wait and then fire next query but wait for both query execution complete.

products = await Product.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

variationProducts = await VariationProduct.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});


问:
Update SVN credentials in jenkins
We have upgraded our instances of Jenkins(new .WAR) and it’s Subversion Plugin.
and then we come to know that it is behaving differently in the new setup.

every job must have its SVN credentials established.
In this scenario we are updating SVN credentials for each and every job for instance.

Is there any way to upgrade our SVN credentials one time for every project and for every job??

答:
You could change actual SVN credentials. It will affect all jobs that use it. The page with credentials is located here:
https://:/credentials/

I tried to find the page via menu in Jenkins configuration, but I couldn't find actual path to it.

ContentLicense: CC BY-SA 3.0

Title: Update SVN credentials in jenkins


问:
When should copy-local be set to true and when should it not?
I am wondering if there are any heuristics for when to set copy-local=true for references?

If referenced types are only used internally can I set copy-local to true but if referenced types are exposed as parameters or return values I set copy-local to false and indicate that a specific version of the dependency should be referenced when my library should be used?

Can anyone clarify this for me?

答:
Copy local is important for deployment scenarios and tools.  As a general rule you should use CopyLocal=True if the reference is not contained within the GAC.

Copy Local essentially means I must manually deploy this DLL in order for my application to work.  When it's false it essentially means "I depend on another component which must be installed separately or chained, the DLL will just be there already".

OwnerDisplayName: Fadeproof

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: JaredPar


问:
UDPClient Async BeginReceive is very slow
I am using UDPClient to send multicast request and receive response from various clients on the network.  I am able to send request and also getting response, but response that I get is very slow. It take 2-3 minutes to get response from all the clients. On send request on the network I checked in the WireShark, there I am seeing response in milliseconds from all the clients only in test program. It is taking lot of time. Can anyone guide what mistake I might be doing? Following is the code. Please guide me on this.  I have been stuck on this issue for the  last 2 days.

```<code>public class Trinity_WSDiscovery : IDiscoveryService
{
        #region IDiscoveryService Members
        public event EventHandler FoundNewDevice;
        public event EventHandler EndOfDiscovery;
        DeviceBinding m_DeviceBinding;
        bool IsFindComplete = false;
        Thread receiveThread;
        UdpClient sock ;
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(System.Net.IPAddress.Any, 0);
        IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse("239.255.255.250"), 3702);
        UdpState udpState = new UdpState();
        XmlDocument xmlDoc = new XmlDocument();

    public void Start()
    {
        //Need to create new object every time we start discovery because
        //every time udp buffer needs to be flushed and restarted
        sock = new UdpClient();
        string str = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:wsadis=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:dn=\"http://www.onvif.org/ver10/network/wsdl\"><soap:Header><wsadis:MessageID>uuid:" + System.Guid.NewGuid().ToString() + "</wsadis:MessageID><wsadis:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsadis:To><wsadis:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsadis:Action></soap:Header><soap:Body><d:Probe><d:Types /> <d:Scopes/></d:Probe></soap:Body></soap:Envelope>";
        byte[] data = Encoding.ASCII.GetBytes(str);
        sock.Send(data, data.Length, iep);
        sock.JoinMulticastGroup(System.Net.IPAddress.Parse("239.255.255.250"));
        IPEndPoint iep1 = new IPEndPoint(System.Net.IPAddress.Any, 0);
        udpState.ipEndpt = RemoteIpEndPoint;
        udpState.udpClient = sock;
        BeginReceive();
    }

    public void BeginReceive()
    {
        Thread.Sleep(100);
        if (sock.Available > 0)
        {
            sock.BeginReceive(new AsyncCallback(ReceiveCallback), udpState);
        }
        else
        {
            FindComplete();
        }
    }

    public void ReceiveCallback(IAsyncResult ar)
    {
        UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
        IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
        Byte[] receiveBytes = udpClient.EndReceive(ar, ref ipEndpt);
        string receiveString = Encoding.ASCII.GetString(receiveBytes);
        if (receiveString.Contains("NetworkVideoTransmitter"))
        {
            xmlDoc.LoadXml(receiveString);
            XmlNodeList list = xmlDoc.GetElementsByTagName("XAddrs", "http://schemas.xmlsoap.org/ws/2005/04/discovery");
            XmlNode node = list[0];
            string strEndPoints = node.FirstChild.Value;
            string[] strEndPointList = Regex.Split(strEndPoints, " ");
            OnFoundDevice(strEndPointList);
        }
        BeginReceive();
    }
</code>```

}`

答:
Why do you need Thread.Sleep?

It might cause the delays.

Body:
I am using UDPClient to send multicast request and receive response from various clients on the network.  I am able to send request and also getting response, but response that I get is very slow. It take 2-3 minutes to get response from all the clients. On send request on the network I checked in the WireShark, there I am seeing response in milliseconds from all the clients only in test program. It is taking lot of time. Can anyone guide what mistake I might be doing? Following is the code. Please guide me on this.  I have been stuck on this issue for the  last 2 days.

public class Trinity_WSDiscovery : IDiscoveryService
{
        #region IDiscoveryService Members
        public event EventHandler FoundNewDevice;
        public event EventHandler EndOfDiscovery;
        DeviceBinding m_DeviceBinding;
        bool IsFindComplete = false;
        Thread receiveThread;
        UdpClient sock ;
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(System.Net.IPAddress.Any, 0);
        IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse("239.255.255.250"), 3702);
        UdpState udpState = new UdpState();
        XmlDocument xmlDoc = new XmlDocument();

    public void Start()
    {
        //Need to create new object every time we start discovery because
        //every time udp buffer needs to be flushed and restarted
        sock = new UdpClient();
        string str = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:wsadis=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:dn=\"http://www.onvif.org/ver10/network/wsdl\"><soap:Header><wsadis:MessageID>uuid:" + System.Guid.NewGuid().ToString() + "</wsadis:MessageID><wsadis:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsadis:To><wsadis:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsadis:Action></soap:Header><soap:Body><d:Probe><d:Types /> <d:Scopes/></d:Probe></soap:Body></soap:Envelope>";
        byte[] data = Encoding.ASCII.GetBytes(str);
        sock.Send(data, data.Length, iep);
        sock.JoinMulticastGroup(System.Net.IPAddress.Parse("239.255.255.250"));
        IPEndPoint iep1 = new IPEndPoint(System.Net.IPAddress.Any, 0);
        udpState.ipEndpt = RemoteIpEndPoint;
        udpState.udpClient = sock;
        BeginReceive();
    }

    public void BeginReceive()
    {
        Thread.Sleep(100);
        if (sock.Available > 0)
        {
            sock.BeginReceive(new AsyncCallback(ReceiveCallback), udpState);
        }
        else
        {
            FindComplete();
        }
    }

    public void ReceiveCallback(IAsyncResult ar)
    {
        UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
        IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
        Byte[] receiveBytes = udpClient.EndReceive(ar, ref ipEndpt);
        string receiveString = Encoding.ASCII.GetString(receiveBytes);
        if (receiveString.Contains("NetworkVideoTransmitter"))
        {
            xmlDoc.LoadXml(receiveString);
            XmlNodeList list = xmlDoc.GetElementsByTagName("XAddrs", "http://schemas.xmlsoap.org/ws/2005/04/discovery");
            XmlNode node = list[0];
            string strEndPoints = node.FirstChild.Value;
            string[] strEndPointList = Regex.Split(strEndPoints, " ");
            OnFoundDevice(strEndPointList);
        }
        BeginReceive();
    }

}`


问:
Why do we put a main() function in python instead of just putting the code directly inside the "name == main" clause?
It is said to be a good practice to write the following block of code in your python modules:

```<code>if __name__ == '__main__':
  # execute only if run as a script
  main()
</code>```

This prevents executing statements when you want to import this module into another program.

However, the curious thing over here is that main() function. We also need to put our code into an actual main method as follows:

```<code>def main()
    # All code goes here
    print("Inside main")
</code>```

I feel that this is a roundabout way. Are there any benefits to creating a separate main() function and then calling it inside the if-clause?

Instead what is the harm in writing the code directly inside the if-clause?

```<code>if __name__ == '__main__':
    # All code goes here
    print("Inside main")
</code>```

答:
However, the curious thing over here is that main() function. We also need to put our code into an actual main method as follows:

Well, you dont need to do so. Actually if all you want is a plain script (something that's not going to be used as a module), you don't even "need" any function at all, you could as well put all your code directly at the top-level. BUT this will not make for clean, maintainable, testable code.

I feel that this is a roundabout way. Are there any benefits to creating a separate main() function and then calling it inside the if-clause

Quite simply the same benefits as you get from using functions (and modules and classes) to organize your code: clean, readable, testable, maintainable code. Just ask yourself how you are going to test your main function if you don't have a main function ?

Body:
It is said to be a good practice to write the following block of code in your python modules:

if __name__ == '__main__':
  # execute only if run as a script
  main()

This prevents executing statements when you want to import this module into another program.

However, the curious thing over here is that main() function. We also need to put our code into an actual main method as follows:

def main()
    # All code goes here
    print("Inside main")

I feel that this is a roundabout way. Are there any benefits to creating a separate main() function and then calling it inside the if-clause?

Instead what is the harm in writing the code directly inside the if-clause?

if __name__ == '__main__':
    # All code goes here
    print("Inside main")


问:
C++ move semantics and code duplication as a result of method overloading
Before I begin, I didn't find anything that completely explains my question in an other stackoverflow post so I decided to create my own. Apologies if it is already answered somewhere else(kindly point me to the existing post if it does exist).

Lets say we have the following two methods inside of a class:

```<code>int do_stuff(Thing& thing){ /* Do stuff... */} // L-value version
int do_stuff(Thing&& thing){ /* Do stuff... */} // R-value version
</code>```

From what I have read, modern C++ has pretty much abandoned this kind of logic and it is recommending to just pass the Thing by value and let the compiler do it's magic. My question is, If I want to have two separate methods that explicitly handles L-values/R-values and avoid code duplication, which of the following is best(performance wise and as in best practice)?

```<code>int do_stuff(Thing& thing){ return do_stuff(std::move(thing)); } // The L-value version uses the R-value one
</code>```

Or

```<code>int do_stuff(Thing&& thing){ return do_stuff(thing); } // The R-value version uses the L-value one since text is an L-value inside the scope of do_stuff(Thing&&)
</code>```

Edit: The purpose of the question is for me to understand this simple case of move semantics and not to create a valid C++ API.

Edit #2: The print and std::string parts of the question are used as an example. They can be anything.

Edit #3: Renamed the example code. The methods do modify the Thing object.

答:
Passing an argument by value does not mean it can't be an rvalue reference. The && just means that the parameter has to be an rvalue reference. Not having && doesn't mean the parameter can't be an rvalue reference.

When the argument is only used by the function, and with that, I mean if it's not modified, the best way to declare your function is:

```<code>int do_stuff(const Thing& thing);
</code>```

That way, it is very clear to the reader that thing won't be modified. For most of the other cases, you should simply declare your function as:

```<code>int do_stuff(Thing thing);
</code>```

passing the parameter by value, and not by reference or rvalue reference.

It used to be common to write code like this:

```<code>int do_stuff(Thing& thing)
{
    /* change thing so that the caller can use the changed thing */
    return success; // where success is an int
}
</code>```

However, nowadays, it is often preferred to return the modified thing:

```<code>Thing do_stuff(Thing thing) { /* return modified thing */ }
</code>```

In the example above:

```<code>int do_stuff(Thing thing);
</code>```

the caller decides whether or not thing should be a copy:

```<code>do_stuff(my_thing); // copy - I need the original my_thing
do_stuff(std::move(thing)); // no copy - I don't need the original my_thing
</code>```

Note that this declaration of do_stuff covers both of your versions:

```<code>int do_stuff(Thing&);
int do_stuff(Thing&&);
</code>```

That said, you almost never need functions like:

```<code>int do_stuff(Thing&&);
</code>```

unless for objects which cannot be copied like stream objects.

Body:
Before I begin, I didn't find anything that completely explains my question in an other stackoverflow post so I decided to create my own. Apologies if it is already answered somewhere else(kindly point me to the existing post if it does exist).

Lets say we have the following two methods inside of a class:

int do_stuff(Thing& thing){ /* Do stuff... */} // L-value version
int do_stuff(Thing&& thing){ /* Do stuff... */} // R-value version

From what I have read, modern C++ has pretty much abandoned this kind of logic and it is recommending to just pass the Thing by value and let the compiler do it's magic. My question is, If I want to have two separate methods that explicitly handles L-values/R-values and avoid code duplication, which of the following is best(performance wise and as in best practice)?

int do_stuff(Thing& thing){ return do_stuff(std::move(thing)); } // The L-value version uses the R-value one

Or

int do_stuff(Thing&& thing){ return do_stuff(thing); } // The R-value version uses the L-value one since text is an L-value inside the scope of do_stuff(Thing&&)

Edit: The purpose of the question is for me to understand this simple case of move semantics and not to create a valid C++ API.

Edit #2: The print and std::string parts of the question are used as an example. They can be anything.

Edit #3: Renamed the example code. The methods do modify the Thing object.

Body:
Passing an argument by value does not mean it can't be an rvalue reference. The && just means that the parameter has to be an rvalue reference. Not having && doesn't mean the parameter can't be an rvalue reference.

When the argument is only used by the function, and with that, I mean if it's not modified, the best way to declare your function is:

int do_stuff(const Thing& thing);

That way, it is very clear to the reader that thing won't be modified. For most of the other cases, you should simply declare your function as:

int do_stuff(Thing thing);

passing the parameter by value, and not by reference or rvalue reference.

It used to be common to write code like this:

int do_stuff(Thing& thing)
{
    /* change thing so that the caller can use the changed thing */
    return success; // where success is an int
}

However, nowadays, it is often preferred to return the modified thing:

Thing do_stuff(Thing thing) { /* return modified thing */ }

In the example above:

int do_stuff(Thing thing);

the caller decides whether or not thing should be a copy:

do_stuff(my_thing); // copy - I need the original my_thing
do_stuff(std::move(thing)); // no copy - I don't need the original my_thing

Note that this declaration of do_stuff covers both of your versions:

int do_stuff(Thing&);
int do_stuff(Thing&&);

That said, you almost never need functions like:

int do_stuff(Thing&&);

unless for objects which cannot be copied like stream objects.


问:
Date range issue
I have shifted our live server to a new server configuration Windows 2008 server and sql server 2008.

But  I am having following exception while adding date field data :

2011-05-15 18:00:44,263 ERROR Error
  caught : the details of the error are
  System.Data.SqlTypes.SqlTypeException:
  SqlDateTime overflow. Must be between
  1/1/1753 12:00:00 AM and 12/31/9999
  11:59:59 PM.  at
  System.Data.SqlTypes.SqlDateTime.FromTimeSpan(TimeSpan
  value)

But the same code is working fine on local machine and was also working fine on old server.

I have even changed the date field explicitly into "mm/dd/yy" format.
But still not found the solution.
Can anyone provide me the solution.

答:
Yes this happens because of server time format changed from your local system.

You should convert to dd/MMM/yyyy hh:mm:ss  which should work in all the systems.

Posting your code may suggest you with the modified code for you.

Title: Date range issue


问:
How do I validate if a start date is after an end date with Yup?
I have a form that creates an event using Formik library. I need to check to see if the start date overlaps the end date and vice-versa. I have two date pickers that choose the date and time. How can I use Yup to validate this and show an error message if they do overlap?

Thanks for the help in advance

```<code>const validationSchema = Yup.object().shape({
    eventName: Yup.string()
        .min(1, "Must have a character")
        .max(10, "Must be shorter than 255")
        .required("Must enter an event name"),

    email: Yup.string()
        .email("Must be a valid email address")
        .max(255, "Must be shorter than 255")
        .required("Must enter an email"),

    eventStartDate: Yup.date()
        .required("Must enter start date"),

    eventEndDate: Yup.date()
        .required("Must enter end date")

})

var defaultValue = new Date().toDateString

export default function EventForm(){

    return (
        <Formik
        initialValues={{eventName: "", email: "", }}
        validationSchema={validationSchema}
        onSubmit={(values, {setSubmitting, resetForm}) => {
            setTimeout(() => {

        }}
        >
            { ({
                values,
                errors,
                touched,
                handleChange,
                handleBlur,
                handleSubmit,
                isSubmitting
            }) => (
                <form onSubmit={handleSubmit}>
                <div className="input-row">
                    <TextField
                        id="eventName"
                        label="Event Name"
                        margin="normal"
                        variant="filled"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.eventName}
                        className={touched.eventName && errors.eventName ? "has-error" : null}
                        />
                    <Error touched={touched.eventName} message={errors.eventName}/>
                </div>

                <div className="dateHolder">
                    <div className="startDate">
                            <TextField
                                id="eventStartDate"
                                label="Event Start Date"
                                type="datetime-local"
                                InputLabelProps={{
                                    shrink: true
                                }}
                                format="yyy-dd-mm HH:MM:ss"
                                onChange={handleChange}
                                onBlur={handleBlur}
                                value={values.eventStartDate}
                            />
                            <Error touched={touched.eventStartDate} message={errors.eventStartDate}/>
                    </div>

                    <div className="endDate">
                    <TextField
                                id="eventEndDate"
                                label="Event End Date"
                                type="datetime-local"
                                InputLabelProps={{
                                    shrink: true
                                }}
                                format="yyy-dd-mm HH:MM:ss"
                                onChange={handleChange}
                                onBlur={handleBlur}
                                value={values.eventEndDate}
                            />
                            <Error touched={touched.eventEndDate} message={errors.eventEndDate}/>
                    </div>
                </div>

                <div className="input-row">
                <button type="submit" disabled={isSubmitting} >
                    Submit
                </button>
          </div>

            </form>
            )}
        </Formik>
    )

}
</code>```

答:
You can use when condition:

```<code>eventStartDate: yup.date().default(() => new Date()),
eventEndDate: yup
        .date()
        .when(
            "eventStartDate",
            (eventStartDate, schema) => eventStartDate && schema.min(eventStartDate))
</code>```

Body:
I have a form that creates an event using Formik library. I need to check to see if the start date overlaps the end date and vice-versa. I have two date pickers that choose the date and time. How can I use Yup to validate this and show an error message if they do overlap?

Thanks for the help in advance

const validationSchema = Yup.object().shape({
    eventName: Yup.string()
        .min(1, "Must have a character")
        .max(10, "Must be shorter than 255")
        .required("Must enter an event name"),

    email: Yup.string()
        .email("Must be a valid email address")
        .max(255, "Must be shorter than 255")
        .required("Must enter an email"),

    eventStartDate: Yup.date()
        .required("Must enter start date"),

    eventEndDate: Yup.date()
        .required("Must enter end date")

})

var defaultValue = new Date().toDateString

export default function EventForm(){

    return (
        <Formik
        initialValues={{eventName: "", email: "", }}
        validationSchema={validationSchema}
        onSubmit={(values, {setSubmitting, resetForm}) => {
            setTimeout(() => {

        }}
        >
            { ({
                values,
                errors,
                touched,
                handleChange,
                handleBlur,
                handleSubmit,
                isSubmitting
            }) => (
                <form onSubmit={handleSubmit}>

                    <TextField
                        id="eventName"
                        label="Event Name"
                        margin="normal"
                        variant="filled"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.eventName}
                        className={touched.eventName && errors.eventName ? "has-error" : null}
                        />
                    <Error touched={touched.eventName} message={errors.eventName}/>

                            <TextField
                                id="eventStartDate"
                                label="Event Start Date"
                                type="datetime-local"
                                InputLabelProps={{
                                    shrink: true
                                }}
                                format="yyy-dd-mm HH:MM:ss"
                                onChange={handleChange}
                                onBlur={handleBlur}
                                value={values.eventStartDate}
                            />
                            <Error touched={touched.eventStartDate} message={errors.eventStartDate}/>

                    <TextField
                                id="eventEndDate"
                                label="Event End Date"
                                type="datetime-local"
                                InputLabelProps={{
                                    shrink: true
                                }}
                                format="yyy-dd-mm HH:MM:ss"
                                onChange={handleChange}
                                onBlur={handleBlur}
                                value={values.eventEndDate}
                            />
                            <Error touched={touched.eventEndDate} message={errors.eventEndDate}/>

                <button type="submit" disabled={isSubmitting} >
                    Submit
                </button>

            </form>
            )}
        </Formik>
    )

}

Body:
You can use when condition:

eventStartDate: yup.date().default(() => new Date()),
eventEndDate: yup
        .date()
        .when(
            "eventStartDate",
            (eventStartDate, schema) => eventStartDate && schema.min(eventStartDate))


答:
You can do it like this:</p>

```<code>Promise.all([Product.findAll(), VariationProduct.findAll()]).then(data => {
    // data [0] is products
    // data [1] is variationProducts
}).catch(error => {
    // oops some error
});
</code>```

Title: How to run multiple select query at once in sequelize using single await

Body:
You can do it like this:

Promise.all([Product.findAll(), VariationProduct.findAll()]).then(data => {
    // data [0] is products
    // data [1] is variationProducts
}).catch(error => {
    // oops some error
});


问:
SignalR client CORS error when using Windows authentication
I am implementing Windows authentication on an ASP.NET Core 2.2 server application, and everything is working fine except SignalR in Angular 8 app. The error I am receiving is the following one:

Access to XMLHttpRequest at 'http://localhost:2110/api/aircrafts/hub/negotiate' from origin 'http://localhost:2302' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

localhost:2302 is the client part running Angular 8 with @aspnet/signalr@1.1.4 and localhost:2110 is the server part. Here is my server code:

Startup.cs Configure Method

```<code>app.UseCors("CORS");
app.UseAuthentication();
var relativeUri = webSettings.SignalRAircraftsUri.ToString();
app.UseSignalR(hubs => { hubs.MapHub<AircraftsHub>(relativeUri); });
</code>```

Startup.cs ConfigureServices method

```<code>services.AddCors(options =>
        {
            options.AddPolicy("CORS", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins(webSettings.AllowedHosts.ToArray())
                    .AllowCredentials();
            });
        });

        services.AddSignalR();
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
</code>```

webSettings.AllowedHosts contains localhost:2302.

launchsettings.json:

```<code>  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:2110",
      "sslPort": 0
    }
  },
</code>```

And this is the Angular code:

```<code>const signalRConnection = new signalR.HubConnectionBuilder().withUrl(url).build();
signalRConnection.start();
</code>```

where url is localhost:2110/api/aircrafts/hub

Any help would be greatly appreciated.

答:
First of all, you should not use the package @aspnet/signalr@1.1.4 because it is abandoned and migrated by microsoft to the package @microsoft/signalr and it is already on version 3.1.0, as you can see in this documentation.

About CORS, you should configure your CORS like:

services.AddCors(options =>
{
    options.AddPolicy(CorsPolicy, builder => builder.WithOrigins(webSettings.AllowedHosts.ToArray())
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});
```

Body:
I am implementing Windows authentication on an ASP.NET Core 2.2 server application, and everything is working fine except SignalR in Angular 8 app. The error I am receiving is the following one:

Access to XMLHttpRequest at 'http://localhost:2110/api/aircrafts/hub/negotiate' from origin 'http://localhost:2302' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

localhost:2302 is the client part running Angular 8 with @aspnet/signalr@1.1.4 and localhost:2110 is the server part. Here is my server code:

Startup.cs Configure Method

app.UseCors("CORS");
app.UseAuthentication();
var relativeUri = webSettings.SignalRAircraftsUri.ToString();
app.UseSignalR(hubs => { hubs.MapHub<AircraftsHub>(relativeUri); });

Startup.cs ConfigureServices method

services.AddCors(options =>
        {
            options.AddPolicy("CORS", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins(webSettings.AllowedHosts.ToArray())
                    .AllowCredentials();
            });
        });

        services.AddSignalR();
        services.AddAuthentication(IISDefaults.AuthenticationScheme);

webSettings.AllowedHosts contains localhost:2302.

launchsettings.json:

  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:2110",
      "sslPort": 0
    }
  },

And this is the Angular code:

const signalRConnection = new signalR.HubConnectionBuilder().withUrl(url).build();
signalRConnection.start();

where url is localhost:2110/api/aircrafts/hub

Any help would be greatly appreciated.


问:
Mips Assembly Finding the maximum value of a user-created array
I am a couple of weeks into my CS-250 Computer Organization and Architecture class and we are currently studying the MIPS Assembly language. I am trying to take a user inputted array and find the maximum number in that array. I do not quite understand how to use the slt keyword in this context, as this is what our professor would like us to do. </p>

<p>Here is my current code. If you have any suggestions I am super open to the ideas. The only blank spot I currently have is the function for finding the maximum value of the array. </p>

```<code>.globl main

.data
array: .space 2000
prompt: .asciiz "Enter the number of integers you would like to input: "
input: .asciiz "Enter an intger: "
Max: .asciiz "Maxiumum Value is: "

.text

main:
    #Loading array into $t5
    la $t5, array

    li $s0, 0

    li $v0, 4
    la $a0, prompt
    syscall

    li $v0, 5
    syscall
    move $s1, $v0

Loop:
    #Asking the user for input
    li $v0, 4
    la $a0, input
    syscall

    #Storing user input in array address in $t5
    li $v0, 5
    syscall
    sw $v0, 0($t5)

    #Counting iterations for the loop as well as the array address
    addi $s0, $s0, 1
    addi $t5, $t5, 4

    #Loop Exit
    beq $s0, $s1, Maximum
    j Loop

 Maximum:

 Exit:
    li $v0, 10
    syscall
</code>```

答:
This should do the job:

```<code>.globl main

.data
array: .space 2000
prompt: .asciiz "Enter the number of integers you would like to input: "
input: .asciiz "Enter an intger: "
Max: .asciiz "Maxiumum Value is: "

.text
main:
    #Loading array into $t5
    la $t5, array

    li $s0, 0

    li $v0, 4
    la $a0, prompt
    syscall

    li $v0, 5
    syscall
    move $s1, $v0

Loop:
    #Asking the user for input
    li $v0, 4
    la $a0, input
    syscall

    #Storing user input in array address in $t5
    li $v0, 5
    syscall
    sw $v0, 0($t5)

    #Counting iterations for the loop as well as the array address
    addi $s0, $s0, 1
    addi $t5, $t5, 4

    #Loop Exit
    beq $s0, $s1, Maximum
    j Loop

Maximum:
    la $t5, array # load the array start address
    lw $t2, 0($t5) # max = first element
    li $s0, 0 # i = 0

Max_loop:
    lw $t3, 0($t5) # temp = actual array element
    slt $t4, $t2, $t3 # max < temp ?
    bne $t4, 1, Else # jump to else branch if it condition is false
    move $t2, $t3 # condition was true let max = temp

Else:
    addi $s0, $s0, 1 # i++
    addi $t5, $t5, 4 # array += 4
    beq $s0, $s1, Exit # i < num
    j Max_loop

Exit:
    li $v0, 10
    syscall
</code>```

Everything seems to work correctly with MARS 4.5 MIPS simulator. The result is in $t2 on exit. You could easily add the code to print its value if you want to.

The slt $t1, $t2, $t3 will bascially do this in C like code:

```<code>if ($t2 < $t3)
  $t1 = 1
else
  $t1 = 0
</code>```

So based on it you could achieve conditional branching using it result.

Note that the code I provided not necessary optimal and could be problematic if the user input less than 1, but this should be checked in the input stage anyway.

Body:
I am a couple of weeks into my CS-250 Computer Organization and Architecture class and we are currently studying the MIPS Assembly language. I am trying to take a user inputted array and find the maximum number in that array. I do not quite understand how to use the slt keyword in this context, as this is what our professor would like us to do.

Here is my current code. If you have any suggestions I am super open to the ideas. The only blank spot I currently have is the function for finding the maximum value of the array.

.globl main

.data
array: .space 2000
prompt: .asciiz "Enter the number of integers you would like to input: "
input: .asciiz "Enter an intger: "
Max: .asciiz "Maxiumum Value is: "

.text

main:
    #Loading array into $t5
    la $t5, array

    li $s0, 0

    li $v0, 4
    la $a0, prompt
    syscall

    li $v0, 5
    syscall
    move $s1, $v0

Loop:
    #Asking the user for input
    li $v0, 4
    la $a0, input
    syscall

    #Storing user input in array address in $t5
    li $v0, 5
    syscall
    sw $v0, 0($t5)

    #Counting iterations for the loop as well as the array address
    addi $s0, $s0, 1
    addi $t5, $t5, 4

    #Loop Exit
    beq $s0, $s1, Maximum
    j Loop

 Maximum:

 Exit:
    li $v0, 10
    syscall

Body:
This should do the job:

.globl main

.data
array: .space 2000
prompt: .asciiz "Enter the number of integers you would like to input: "
input: .asciiz "Enter an intger: "
Max: .asciiz "Maxiumum Value is: "

.text
main:
    #Loading array into $t5
    la $t5, array

    li $s0, 0

    li $v0, 4
    la $a0, prompt
    syscall

    li $v0, 5
    syscall
    move $s1, $v0

Loop:
    #Asking the user for input
    li $v0, 4
    la $a0, input
    syscall

    #Storing user input in array address in $t5
    li $v0, 5
    syscall
    sw $v0, 0($t5)

    #Counting iterations for the loop as well as the array address
    addi $s0, $s0, 1
    addi $t5, $t5, 4

    #Loop Exit
    beq $s0, $s1, Maximum
    j Loop

Maximum:
    la $t5, array # load the array start address
    lw $t2, 0($t5) # max = first element
    li $s0, 0 # i = 0

Max_loop:
    lw $t3, 0($t5) # temp = actual array element
    slt $t4, $t2, $t3 # max < temp ?
    bne $t4, 1, Else # jump to else branch if it condition is false
    move $t2, $t3 # condition was true let max = temp

Else:
    addi $s0, $s0, 1 # i++
    addi $t5, $t5, 4 # array += 4
    beq $s0, $s1, Exit # i < num
    j Max_loop

Exit:
    li $v0, 10
    syscall

Everything seems to work correctly with MARS 4.5 MIPS simulator. The result is in $t2 on exit. You could easily add the code to print its value if you want to.

The slt $t1, $t2, $t3 will bascially do this in C like code:

if ($t2 < $t3)
  $t1 = 1
else
  $t1 = 0

So based on it you could achieve conditional branching using it result.

Note that the code I provided not necessary optimal and could be problematic if the user input less than 1, but this should be checked in the input stage anyway.


问:
Why is typename necessary in return type? C++
Given a template class Queue with a nested Node struct.

Why is typename needed in the return type here?

```<code>template<typename T>
typename Queue<T>::Node* Queue<T>::test() {}
</code>```

The nested struct Node in the template class Queue would be in the scope of Queue<T>:: without typename.

According to Where and why do I have to put the "template" and "typename" keywords?:

We decide how the compiler should parse this. If t::x is a dependent
  name, then we need to prefix it by typename to tell the compiler to
  parse it in a certain way.

But I don't see why it justifies using typename?

答:
StoryTeller's answer is correct. I would like to add another perspective.

While parsing Queue<T>::Node* in the classical function form (like in your example) you don't know yet what you are parsing, you don't know you are parsing the return type of a function, that's why you need to explicitly specify you have a type. (well, as shown in the link posted by StoryTeller Down with typename you could know, but it requires a more complex parsing i.e. you need to scan ahead to determine you are in a function declaration).

But in the suffix return type when you reach Queue<T>::Node* you already determined you are parsing the declaration of a function and now a return type is expected.

Body:
Given a template class Queue with a nested Node struct.

Why is typename needed in the return type here?

template<typename T>
typename Queue<T>::Node* Queue<T>::test() {}

The nested struct Node in the template class Queue would be in the scope of Queue<T>:: without typename.

According to Where and why do I have to put the "template" and "typename" keywords?:

We decide how the compiler should parse this. If t::x is a dependent
  name, then we need to prefix it by typename to tell the compiler to
  parse it in a certain way.

But I don't see why it justifies using typename?


问:
Why does MonoTouch crash on this simple code?
I totally do NOT understand why MonoTouch is crashing on this code. Let me outline my steps to get to this point:

New Project

New > iPhone View with Controller (called TestScreen)

In Main.cs, added: window.AddSubview(new TestScreen().View);

Added button to the TestScreen UIView, and added an outlet called testButton on 'File's Owner' (which should be my TestScreen controller), and linked up the button to that outlet.

Then, I added the following code:

```<code>public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            this.testButton.SetTitle("Test", UIControlState.Normal); // this works!
            this.testButton.TouchUpInside += HandleTestButtonhandleTouchUpInside;
        }

        int i = 0;
        void HandleTestButtonhandleTouchUpInside (object sender, EventArgs e)
        {
            i += 1;
            this.testButton.SetTitle("Testing " + i.ToString(), UIControlState.Normal); // this crashes!
        }
</code>```

Question is: Why does the this.testButton.SetTitle() method cause a crash?

Here's the application output at time of crash:

Stacktrace:

at (wrapper managed-to-native)
  MonoTouch.UIKit.UIApplication.UIApplicationMain
  (int,string[],intptr,intptr)    at
  MonoTouch.UIKit.UIApplication.Main (string[],string,string) [0x00038]
  in /Users/plasma/Source/iphone/monotouch/UIKit/UIApplication.cs:26

  at MonoTouch.UIKit.UIApplication.Main (string[]) [0x00000] in
  /Users/plasma/Source/iphone/monotouch/UIKit/UIApplication.cs:31   at
  MyApp.Application.Main (string[]) [0x00000] in
  /Users/username/Projects/MyApp/MyApp/Main.cs:14   at (wrapper
  runtime-invoke) .runtime_invoke_void_object
  (object,intptr,intptr,intptr)

Native stacktrace:

```<code>0   MyApp               0x000d1965 mono_handle_native_sigsegv + 343
1   MyApp               0x0000ffb4 mono_sigsegv_signal_handler + 322
2   libSystem.B.dylib                   0x9476845b _sigtramp + 43
3   ???                                 0xffffffff 0x0 + 4294967295
4   UIKit                               0x01c981b5 -[UIControl sendAction:to:forEvent:] + 67
5   UIKit                               0x01c9a647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
6   UIKit                               0x01c991f4 -[UIControl touchesEnded:withEvent:] + 458
7   UIKit                               0x01c2e0d1 -[UIWindow _sendTouchesForEvent:] + 567
8   UIKit                               0x01c0f37a -[UIApplication sendEvent:] + 447
9   UIKit                               0x01c14732 _UIApplicationHandleEvent + 7576
10  GraphicsServices                    0x03edfa36 PurpleEventCallback + 1550
11  CoreFoundation                      0x00e21064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
12  CoreFoundation                      0x00d816f7 __CFRunLoopDoSource1 + 215
13  CoreFoundation                      0x00d7e983 __CFRunLoopRun + 979
14  CoreFoundation                      0x00d7e240 CFRunLoopRunSpecific + 208
15  CoreFoundation                      0x00d7e161 CFRunLoopRunInMode + 97
16  GraphicsServices                    0x03ede268 GSEventRunModal + 217
17  GraphicsServices                    0x03ede32d GSEventRun + 115
18  UIKit                               0x01c1842e UIApplicationMain + 1160
19  ???                                 0x09a7714b 0x0 + 161968459
20  ???                                 0x09a76f1c 0x0 + 161967900
21  ???                                 0x09a7651c 0x0 + 161965340
22  ???                                 0x09a76374 0x0 + 161964916
23  ???                                 0x09a764c6 0x0 + 161965254
24  MyApp               0x0000fd6f mono_jit_runtime_invoke + 1332
25  MyApp               0x001ee239 mono_runtime_invoke + 137
26  MyApp               0x001f0920 mono_runtime_exec_main + 669
27  MyApp               0x001efd0a mono_runtime_run_main + 843
28  MyApp               0x000a3c62 mono_jit_exec + 200
29  MyApp               0x002a25eb main + 3838
30  MyApp               0x000030c9 _start + 208
31  MyApp               0x00002ff8 start + 40
</code>```

Debug info from gdb:

/tmp/mono-gdb-commands.DGcT7h:1: Error in sourced command file: unable
  to debug self

================================================================= Got a SIGSEGV while executing native code. This usually indicates a fatal
  error in the mono runtime or one of the native libraries used by your
  application.

答:
Try to cast the sender to a UIButton. I hope that helps.</p>

```<code>void HandleTestButtonhandleTouchUpInside (object sender, EventArgs e)
    {
        i += 1;
        ((UIButton) sender).SetTitle("Testing " + i.ToString(), UIControlState.Normal);
    }
</code>```

Body:
I totally do NOT understand why MonoTouch is crashing on this code. Let me outline my steps to get to this point:

New Project

New > iPhone View with Controller (called TestScreen)

In Main.cs, added: window.AddSubview(new TestScreen().View);

Added button to the TestScreen UIView, and added an outlet called testButton on 'File's Owner' (which should be my TestScreen controller), and linked up the button to that outlet.

Then, I added the following code:

public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            this.testButton.SetTitle("Test", UIControlState.Normal); // this works!
            this.testButton.TouchUpInside += HandleTestButtonhandleTouchUpInside;
        }

        int i = 0;
        void HandleTestButtonhandleTouchUpInside (object sender, EventArgs e)
        {
            i += 1;
            this.testButton.SetTitle("Testing " + i.ToString(), UIControlState.Normal); // this crashes!
        }

Question is: Why does the this.testButton.SetTitle() method cause a crash?

Here's the application output at time of crash:

Stacktrace:

at (wrapper managed-to-native)
  MonoTouch.UIKit.UIApplication.UIApplicationMain
  (int,string[],intptr,intptr)    at
  MonoTouch.UIKit.UIApplication.Main (string[],string,string) [0x00038]
  in /Users/plasma/Source/iphone/monotouch/UIKit/UIApplication.cs:26

  at MonoTouch.UIKit.UIApplication.Main (string[]) [0x00000] in
  /Users/plasma/Source/iphone/monotouch/UIKit/UIApplication.cs:31   at
  MyApp.Application.Main (string[]) [0x00000] in
  /Users/username/Projects/MyApp/MyApp/Main.cs:14   at (wrapper
  runtime-invoke) .runtime_invoke_void_object
  (object,intptr,intptr,intptr)

Native stacktrace:

0   MyApp               0x000d1965 mono_handle_native_sigsegv + 343
1   MyApp               0x0000ffb4 mono_sigsegv_signal_handler + 322
2   libSystem.B.dylib                   0x9476845b _sigtramp + 43
3   ???                                 0xffffffff 0x0 + 4294967295
4   UIKit                               0x01c981b5 -[UIControl sendAction:to:forEvent:] + 67
5   UIKit                               0x01c9a647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
6   UIKit                               0x01c991f4 -[UIControl touchesEnded:withEvent:] + 458
7   UIKit                               0x01c2e0d1 -[UIWindow _sendTouchesForEvent:] + 567
8   UIKit                               0x01c0f37a -[UIApplication sendEvent:] + 447
9   UIKit                               0x01c14732 _UIApplicationHandleEvent + 7576
10  GraphicsServices                    0x03edfa36 PurpleEventCallback + 1550
11  CoreFoundation                      0x00e21064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
12  CoreFoundation                      0x00d816f7 __CFRunLoopDoSource1 + 215
13  CoreFoundation                      0x00d7e983 __CFRunLoopRun + 979
14  CoreFoundation                      0x00d7e240 CFRunLoopRunSpecific + 208
15  CoreFoundation                      0x00d7e161 CFRunLoopRunInMode + 97
16  GraphicsServices                    0x03ede268 GSEventRunModal + 217
17  GraphicsServices                    0x03ede32d GSEventRun + 115
18  UIKit                               0x01c1842e UIApplicationMain + 1160
19  ???                                 0x09a7714b 0x0 + 161968459
20  ???                                 0x09a76f1c 0x0 + 161967900
21  ???                                 0x09a7651c 0x0 + 161965340
22  ???                                 0x09a76374 0x0 + 161964916
23  ???                                 0x09a764c6 0x0 + 161965254
24  MyApp               0x0000fd6f mono_jit_runtime_invoke + 1332
25  MyApp               0x001ee239 mono_runtime_invoke + 137
26  MyApp               0x001f0920 mono_runtime_exec_main + 669
27  MyApp               0x001efd0a mono_runtime_run_main + 843
28  MyApp               0x000a3c62 mono_jit_exec + 200
29  MyApp               0x002a25eb main + 3838
30  MyApp               0x000030c9 _start + 208
31  MyApp               0x00002ff8 start + 40

Debug info from gdb:

/tmp/mono-gdb-commands.DGcT7h:1: Error in sourced command file: unable
  to debug self

================================================================= Got a SIGSEGV while executing native code. This usually indicates a fatal
  error in the mono runtime or one of the native libraries used by your
  application.

Body:
Try to cast the sender to a UIButton. I hope that helps.

void HandleTestButtonhandleTouchUpInside (object sender, EventArgs e)
    {
        i += 1;
        ((UIButton) sender).SetTitle("Testing " + i.ToString(), UIControlState.Normal);
    }


问:
Javascript: How do I use React component globally?
I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

```<code>import Progress from 'package-name'

// jsx
<Progress /> //working fine
</code>```

It's working fine.

But if I use it from CDN like unpkg, it's not working.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

// Package Script
<script src="https://unpkg.com/@delowar/react-circle-progressbar@0.0.9/lib/Progress.js"></script>

<script>
    ...react code...
    <Progress />
    ...react code...
</script>
</code>```

It's showing an error:

Progress is not defined

Can anyone please help me about this issue?

Webpack Configuration:

```<code>var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}
</code>```

Original Repo: https://github.com/delowardev/react-circle-progressbar

答:
You can't require or import modules directly from URL.

But you can import it like below.

```<code>// Package Script
<script src="https://unpkg.com/@delowar/react-circle-progressbar@0.0.9/lib/Progress.js"></script>

const Progress = window.Progress;
</code>```

Body:
I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

import Progress from 'package-name'

// jsx
<Progress /> //working fine

It's working fine.

But if I use it from CDN like unpkg, it's not working.

// Package Script

It's showing an error:

Progress is not defined

Can anyone please help me about this issue?

Webpack Configuration:

var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}

Original Repo: https://github.com/delowardev/react-circle-progressbar

Body:
You can't require or import modules directly from URL.

But you can import it like below.

// Package Script
<script src="https://unpkg.com/@delowar/react-circle-progressbar@0.0.9/lib/Progress.js"></script>

const Progress = window.Progress;


问:
"Activemq not found" error after running custom Docker image
We have a legacy application that I am trying to dockerize. The jar of the application has both the application and an activemq bundled together. (We cannot change the way it is built). And has certain installation steps. I created the following initial Dockerfile for this however I am facing an issue (mentioned after the Dockerfile) when I run the image.

The Dockerfile looks like this :

```<code>FROM registry:4000/openjdk:8-jre-alpine

RUN addgroup -S appuser && adduser -S -G appuser appuser

ADD ./fe.jar /home/appuser

RUN chmod +x /home/appuser/fe.jar \
&& chown appuser:appuser /home/appuser/fe.jar

USER appuser

RUN ["java", "-jar", "/home/appuser/fe.jar", "-i"]

WORKDIR /home/appuser/fe/activemq/bin

CMD ["/bin/sh", "-c", "activemq"]
</code>```

The RUN command extracts the application and the activemq at the location into folder called fe.

The WORKDIR seems to be setting the working directly to activemq/bin. I confirmed this by using sh script which triggers when the image is run. In the sh script I trigger an ls and pwd command to see the contents and the location.

However when I run the image which triggers the CMD command I get the error that :

```<code>/bin/sh: activemq: not found
</code>```

What can be the possible issue here?

答:
If activemq is an executable in your bin directory (and not in PATH) then you need to edit your CMD:

```<code>CMD ["/bin/sh", "-c", "./activemq"]
</code>```

Also make sure that your script is executable.

Body:
We have a legacy application that I am trying to dockerize. The jar of the application has both the application and an activemq bundled together. (We cannot change the way it is built). And has certain installation steps. I created the following initial Dockerfile for this however I am facing an issue (mentioned after the Dockerfile) when I run the image.

The Dockerfile looks like this :

FROM registry:4000/openjdk:8-jre-alpine

RUN addgroup -S appuser && adduser -S -G appuser appuser

ADD ./fe.jar /home/appuser

RUN chmod +x /home/appuser/fe.jar \
&& chown appuser:appuser /home/appuser/fe.jar

USER appuser

RUN ["java", "-jar", "/home/appuser/fe.jar", "-i"]

WORKDIR /home/appuser/fe/activemq/bin

CMD ["/bin/sh", "-c", "activemq"]

The RUN command extracts the application and the activemq at the location into folder called fe.

The WORKDIR seems to be setting the working directly to activemq/bin. I confirmed this by using sh script which triggers when the image is run. In the sh script I trigger an ls and pwd command to see the contents and the location.

However when I run the image which triggers the CMD command I get the error that :

/bin/sh: activemq: not found

What can be the possible issue here?

Body:
If activemq is an executable in your bin directory (and not in PATH) then you need to edit your CMD:

CMD ["/bin/sh", "-c", "./activemq"]

Also make sure that your script is executable.


问:
Can not load module when run Unit testcase
I am building a framework(Provider), In this framework, I used library(sdk.a).
This library is written in Objective C. My framework is in Swift so I used modulemap.
In the modulemap I name the library SDK

In code I used

```<code>import SDK //this line issue error when run unit testcase
class Manager{
    public static let shared = Manager()
    private var agent: LocalAgent? //SDK class
    public connect: Bool
    //no issue it works fine
     private func find(_ device: Device) {
        //more logical codes
        self.connect = true
    }
}
</code>```

Above code works fine when I build the framework or use the framework form another application.

Problem is when I run testConnect()from unit test case file,
Compiler issue error in Manager.swift files import SDK statement "No such module 'SDK'"

Test case file: ManagerTest.swift

```<code>@testable import SDK
@testable import Provider
func testConnect(){
    let manager = Manager.shared
    manager.find(device)
}
</code>```

答:
You need to set SDK.a target membership for ProviderTests target. Like,

Select SDK.a file

Add tick the tests target membership for that file

Then clean build and run the tests again.

Image attribution: Medium post

Body:
I am building a framework(Provider), In this framework, I used library(sdk.a).
This library is written in Objective C. My framework is in Swift so I used modulemap.
In the modulemap I name the library SDK

In code I used

import SDK //this line issue error when run unit testcase
class Manager{
    public static let shared = Manager()
    private var agent: LocalAgent? //SDK class
    public connect: Bool
    //no issue it works fine
     private func find(_ device: Device) {
        //more logical codes
        self.connect = true
    }
}

Above code works fine when I build the framework or use the framework form another application.

Problem is when I run testConnect()from unit test case file,
Compiler issue error in Manager.swift files import SDK statement "No such module 'SDK'"

Test case file: ManagerTest.swift

@testable import SDK
@testable import Provider
func testConnect(){
    let manager = Manager.shared
    manager.find(device)
}


问:
Selenium with Chromedriver only works with headless mode
I'm trying to run this in Python on Manjaro Linux.

I've written some functional tests which we'd like to see running on our screens in our office. However, the tests only work if I pass a --headless option, which we absolutely do not want. Otherwise, the constant error we get is The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.. So this error is instantly gone when I pass along the --headless argument, which is very frustrating at this point.
This is the code I'm trying with now:

```<code> options = Options()
 options.add_argument("--no-sandbox")
 options.add_argument("--window-size=1920,1080")
 options.add_argument("--disable-gpu")
 options.add_argument("--disable-extensions")
 options.add_argument("--start-maximized")
 # options.add_argument("--headless")
 driver = webdriver.Chrome("/usr/bin/chromedriver", chrome_options=options)
</code>```

Any tips are highly appreciated! Thanks!

答:
This is probably because your chrome is not installed on the default location. A detailed explanation is given here. You can specify the location that chrome is running from with the following option:</p>

```<code># chrome binary location specified here
options.binary_location = "/opt/google/chrome/google-chrome"
</code>```

Body:
I'm trying to run this in Python on Manjaro Linux.

I've written some functional tests which we'd like to see running on our screens in our office. However, the tests only work if I pass a --headless option, which we absolutely do not want. Otherwise, the constant error we get is The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.. So this error is instantly gone when I pass along the --headless argument, which is very frustrating at this point.
This is the code I'm trying with now:

 options = Options()
 options.add_argument("--no-sandbox")
 options.add_argument("--window-size=1920,1080")
 options.add_argument("--disable-gpu")
 options.add_argument("--disable-extensions")
 options.add_argument("--start-maximized")
 # options.add_argument("--headless")
 driver = webdriver.Chrome("/usr/bin/chromedriver", chrome_options=options)

Any tips are highly appreciated! Thanks!

Body:
This is probably because your chrome is not installed on the default location. A detailed explanation is given here. You can specify the location that chrome is running from with the following option:

# chrome binary location specified here
options.binary_location = "/opt/google/chrome/google-chrome"


问:
PL/SQL regex validation how to escape from '
I'm working on a fullName validation function, examples that can go are :

John Deep

JohnDeep

John-Deep

I want to use this regex:

```<code>^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$
</code>```

My validation function is :

```<code> create or replace FUNCTION is_valid_fullName (str IN VARCHAR2) RETURN VARCHAR2 AS
        bln BOOLEAN;
    begin
     if regexp_like(str, '^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$') then

            return 1;
      else
        return 0;
     end if;
     end;
</code>```

However I have a problem with syntax.

PLS-00103: Encountered the symbol "]" when ...

How can I solve this?

答:
If the examples you gave are the only things that should match then use:

  regexp_like(str, '^\p{L}+[\p{L}\p{Pd}\p{Zs}]*\p{L}+$|^\p{L}+$')

But if you want the regex to match "Jhon o' Deep" then you have to somehow escape that ' character.

Body:
I'm working on a fullName validation function, examples that can go are :

John Deep

JohnDeep

John-Deep

I want to use this regex:

^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$

My validation function is :

 create or replace FUNCTION is_valid_fullName (str IN VARCHAR2) RETURN VARCHAR2 AS
        bln BOOLEAN;
    begin
     if regexp_like(str, '^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$') then

            return 1;
      else
        return 0;
     end if;
     end;

However I have a problem with syntax.

PLS-00103: Encountered the symbol "]" when ...

How can I solve this?


问:
JAXB order respected by .Net framework service references class generator
According to

JAXB and property ordering

JAXB can define propOrder. Does the .Net framework service references class generator will respect this order? How to achieve this goal?

答:
To achieve this goal element in xsd must by defined by sequence:

Does XML care about the order of elements?


问:
issue in query params in angular 8
I have a problem with the query parameters in angular 8. This is the code:

```<code>headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }
</code>```

I also tried

```<code>let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);
</code>```

and

```<code>let params = new HttpParams().set('username', username).set('password', password);
</code>```

and

```<code>let params = new HttpParams().append('username', username).append('password', password);
</code>```

The backend server get username and password as undefined, previously I had this code that worked correctly:

```<code> login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}
</code>```

What's wrong? Thanks

答:
You should use http.get() method in case there is no body(i.e. you need to modify request method from post to get at backend).

```<code> return this.http.get<any>(this.host + 'login', options).pipe(map(data => {

            console.table(data);
            this.setSession(data);
            this.currentUserSubject.next(data.user);

        }));
</code>```

or if you want to use post method then use like (but its not a good practice.)

```<code>return this.http.post<any>(this.host + 'login', {},options).pipe(map(data => {

        console.table(data);
        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));
</code>```

Title: issue in query params in angular 8

Body:
I have a problem with the query parameters in angular 8. This is the code:

headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }

I also tried

let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);

and

let params = new HttpParams().set('username', username).set('password', password);

and

let params = new HttpParams().append('username', username).append('password', password);

The backend server get username and password as undefined, previously I had this code that worked correctly:

 login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}

What's wrong? Thanks

Body:
You should use http.get() method in case there is no body(i.e. you need to modify request method from post to get at backend).

 return this.http.get<any>(this.host + 'login', options).pipe(map(data => {

            console.table(data);
            this.setSession(data);
            this.currentUserSubject.next(data.user);

        }));

or if you want to use post method then use like (but its not a good practice.)

return this.http.post<any>(this.host + 'login', {},options).pipe(map(data => {

        console.table(data);
        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));


问:
Get Parameters Problems in Yii2
My question is that i will have the ? at the beginning of the get parameter's name.For example,
if the url is

```<code>https://example.com/path?id=2
</code>```

I will get a get parameter named ?id.How can I get the id without ? instead of using such way:

```<code>https://example.com/path?&id=2
</code>```

It's wired : )

---------------- Here is details ----------------

The url manager config:

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];
```

<p>You see, I will use the <code>lang</code> parameter to control the language version of the website.And I found Yii will handle the <code>lang</code> as a get parameter.So that's the problem.<code>lang</code> might be the first get parameter, so the php handle the the <code>?</code> as the part of the parameter's name.</p>

<p>if I print the get parameters, I will get this.</p>

```https://example.com/en/modules/controller/action?id=1
```

<p>The code goes:</p>

<pre class="lang-php prettyprint-override"><code>var_dump(\Yii::$app->request->get());
</code>```

It will print:

```<code>array(2) { ["lang"]=> string(3) "en" ["?id"]=> string(1) "1" }
</code>```

THX A LOT.

答:
Include the ID parameter in the pattern that you are matching against.

```<code>[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                // Add the id to the pattern in the following line
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];
</code>```

Changing the pattern element to the following:

```<code>'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',
</code>```

Will capture a digit after a slash and make it available to your action as the $id method parameter.

If you wanted to use a question mark, instead of a slash, to separate the action from the parameter, I guess you could use this pattern:

```<code>'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>?<id:\d+>'
</code>```

But I have not tried it.

Title: Get Parameters Problems in Yii2

Body:
My question is that i will have the ? at the beginning of the get parameter's name.For example,
if the url is

https://example.com/path?id=2

I will get a get parameter named ?id.How can I get the id without ? instead of using such way:

https://example.com/path?&id=2

It's wired : )

---------------- Here is details ----------------

The url manager config:

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];

You see, I will use the lang parameter to control the language version of the website.And I found Yii will handle the lang as a get parameter.So that's the problem.lang might be the first get parameter, so the php handle the the ? as the part of the parameter's name.

if I print the get parameters, I will get this.

https://example.com/en/modules/controller/action?id=1

The code goes:

var_dump(\Yii::$app->request->get());

It will print:

array(2) { ["lang"]=> string(3) "en" ["?id"]=> string(1) "1" }

THX A LOT.

Body:
Include the ID parameter in the pattern that you are matching against.

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                // Add the id to the pattern in the following line
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];

Changing the pattern element to the following:

'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',

Will capture a digit after a slash and make it available to your action as the $id method parameter.

If you wanted to use a question mark, instead of a slash, to separate the action from the parameter, I guess you could use this pattern:

'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>?<id:\d+>'

But I have not tried it.


问:
How to run multiple select query at once in sequelize using single await
Have to run both codes at a single time. Don't want to wait and then fire next query but wait for both query execution complete.</p>

```<code>products = await Product.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

variationProducts = await VariationProduct.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});
</code>```

答:
try {
    const [products, variationProducts] = await Promise.all([
        Product.findAll(),
        VariationProduct.findAll()
    ]);

    // Do what you need with the result;
}
catch(e) {
    console.error('Problem in getting data', e);
    throw e; // Or do what you want.
}

```

Body:
Have to run both codes at a single time. Don't want to wait and then fire next query but wait for both query execution complete.

products = await Product.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

variationProducts = await VariationProduct.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});