问:
Android activity crashes when a breakpoint is set
I have a strange issue I'm experiencing when developing an app for Android. I'm trying to debug my application using my phone (a Oneplus One), Android Studio and ADB. Everything works as normal except that when I start an activity that already has a breakpoint set in Android Studio, it crashes with no log output. This happens both when the activity is the launch activity and when I'm starting one with an intent.

As you can imagine, this is incredibly irritating since I have a bug in my onCreate() method that I want to break in.

I have tried adding the line Debug.waitForDebugger() to the bit of code above the breakpoints but this doesn't help.

I haven't added any code to this question because this error is independent of the code. It happens with multiple projects and Activities. I don't have another Android phone to test it on so can't check that. Has anyone else experienced this and/or found a fix?

Thanks in advance.

EDIT:
Added an example of code. This code does not crash when a breakpoint is not set, neither does the breakpoint need to be in this bit of code for the crash to occur. This is just the code I'm trying to debug, behaviour of which would be impossible to fix without knowledge of my server back-end, so I'm not asking for help with that.

```<code>protected void onCreate(Bundle savedInstanceState) {
    //Create activity
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Check for play services
    if (!checkPlayServices()){
        //Exit and notify user that play services are required
        Toast.makeText(this, "Google Play Services must be installed for Insty to work", Toast.LENGTH_LONG).show();
        System.exit(1);
        }

    //Get token. If null, push to login screen
    SharedPreferences sp = getBaseContext().getSharedPreferences(NetService.SP_APP, Context.MODE_PRIVATE);
    if (!sp.contains(NetService.SP_TOKEN)){
        //Token doesn't exist - push to login screen
        startActivity(new Intent(MainActivity.this, LoginActivity.class));
        MainActivity.this.finish();
        return;
    }

    //Setup action bar
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    //Populate navigation drawer
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)findViewById(R.id.left_drawer);
    String[] menuItems = getResources().getStringArray(R.array.menu_items);
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, menuItems));
    //Set an on click listener
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    //Add to action bar
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_drawer, R.string.close_drawer){
        @Override
        public void onDrawerClosed(View view){
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View view){
            invalidateOptionsMenu();
        }
    };

    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    //Start a token verification
    ResultReceiver receiver = new ResultReceiver(new Handler()){
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            VerifyResult result = VerifyResult.values()[resultData.getInt(NetService.RESULT_VERIFY)];
            switch (result){
                case VALID:
                    //Do nothing
                    break;

                case INVALID:
                    //Push back to login screen
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    MainActivity.this.finish();
                    break;

                case BAD_NETWORK:
                    //Toast to let user know network is down
                    Toast.makeText(MainActivity.this, R.string.bad_network, Toast.LENGTH_LONG).show();
                    break;

                case ERROR:
                    //Toast to show error
                    Toast.makeText(MainActivity.this, R.string.generic_error, Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
    //Start verify
    NetService.startActionVerify(this, receiver, sp.getString(NetService.SP_TOKEN, ""));

    //Open on chats fragment
    FragmentManager fragMgr = getFragmentManager();
    fragMgr.beginTransaction().replace(R.id.content_frame, new ChatsFragment()).commit();

}
</code>```

答: Test on another device with newer SDK. Had the same problem on Nexus 5X API 27 while on Pixel XL API 32 works fine.</p>

Body:
I have a strange issue I'm experiencing when developing an app for Android. I'm trying to debug my application using my phone (a Oneplus One), Android Studio and ADB. Everything works as normal except that when I start an activity that already has a breakpoint set in Android Studio, it crashes with no log output. This happens both when the activity is the launch activity and when I'm starting one with an intent.

As you can imagine, this is incredibly irritating since I have a bug in my onCreate() method that I want to break in.

I have tried adding the line Debug.waitForDebugger() to the bit of code above the breakpoints but this doesn't help.

I haven't added any code to this question because this error is independent of the code. It happens with multiple projects and Activities. I don't have another Android phone to test it on so can't check that. Has anyone else experienced this and/or found a fix?

Thanks in advance.

EDIT:
Added an example of code. This code does not crash when a breakpoint is not set, neither does the breakpoint need to be in this bit of code for the crash to occur. This is just the code I'm trying to debug, behaviour of which would be impossible to fix without knowledge of my server back-end, so I'm not asking for help with that.

protected void onCreate(Bundle savedInstanceState) {
    //Create activity
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Check for play services
    if (!checkPlayServices()){
        //Exit and notify user that play services are required
        Toast.makeText(this, "Google Play Services must be installed for Insty to work", Toast.LENGTH_LONG).show();
        System.exit(1);
        }

    //Get token. If null, push to login screen
    SharedPreferences sp = getBaseContext().getSharedPreferences(NetService.SP_APP, Context.MODE_PRIVATE);
    if (!sp.contains(NetService.SP_TOKEN)){
        //Token doesn't exist - push to login screen
        startActivity(new Intent(MainActivity.this, LoginActivity.class));
        MainActivity.this.finish();
        return;
    }

    //Setup action bar
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    //Populate navigation drawer
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)findViewById(R.id.left_drawer);
    String[] menuItems = getResources().getStringArray(R.array.menu_items);
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, menuItems));
    //Set an on click listener
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    //Add to action bar
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_drawer, R.string.close_drawer){
        @Override
        public void onDrawerClosed(View view){
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View view){
            invalidateOptionsMenu();
        }
    };

    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    //Start a token verification
    ResultReceiver receiver = new ResultReceiver(new Handler()){
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            VerifyResult result = VerifyResult.values()[resultData.getInt(NetService.RESULT_VERIFY)];
            switch (result){
                case VALID:
                    //Do nothing
                    break;

                case INVALID:
                    //Push back to login screen
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    MainActivity.this.finish();
                    break;

                case BAD_NETWORK:
                    //Toast to let user know network is down
                    Toast.makeText(MainActivity.this, R.string.bad_network, Toast.LENGTH_LONG).show();
                    break;

                case ERROR:
                    //Toast to show error
                    Toast.makeText(MainActivity.this, R.string.generic_error, Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
    //Start verify
    NetService.startActionVerify(this, receiver, sp.getString(NetService.SP_TOKEN, ""));

    //Open on chats fragment
    FragmentManager fragMgr = getFragmentManager();
    fragMgr.beginTransaction().replace(R.id.content_frame, new ChatsFragment()).commit();

}


来源: stackexchange

问:
how to tackle the python set object operations in C?
I want to introduce C code in Python and the C code has the following statements:

test.h

```<code>#include<Python.h>

PyObject *getFeature(wchar_t *text,
                     PyObject *unigram);
// where the unigram is a Set Object with type 'PySetObject'
</code>```

test.c

```<code>#include<test.h>

PyObject *getFeature(wchar_t *text,
                     PyObject *unigram)
{
    int ret = -1;
    PyObject *featureList = PyList_New(0);

    PyObject *curString = PyUnicode_FromWideChar(text, 2);
    ret = PySet_Contains(unigram, curString);
    printf("## res: `nc`, %d.\n", ret);
    ret = PyList_Append(featureList, curString);

    return featureList;
}

</code>```

and then I compiled it and get a shared lib called libtest.so. So I can import this C .so file into the python code with ctypes like below:

test.py

```<code>import ctypes

dir_path = 'path/to/the/libtest.so'
feature_extractor = ctypes.cdll.LoadLibrary(
    os.path.join(dir_path, 'libtest.so'))
get_feature_c = feature_extractor.getFeature
get_feature_c.argtypes = [
    ctypes.c_wchar_p, ctypes.py_object]
get_feature_c.restype = ctypes.py_object

unigram = {'据','nc', 'kls'}
print(hash('据'))
print(hash('nc'))
print(hash('kls'))
res = get_feature_c('nc', unigram)

</code>```

execute this test.py file and I can get the following fault:

```<code>6875335301337518411
6875335301337518411
-5567445891360670268
Segmentation fault
</code>```

I know the bug is caused by the confliction of different string nc and 据, which have the same hash value 6875335301337518411.
Python use a secondary level hashtable to tackle the confliction of strings with same hash value.

So how to solve this problem and import the secondary confliction hashtable to the C code?

答:
The hash match is a red herring.  The problem is not using PyDLL so the GIL is held when using the CPython APIs.

test.c

#include <Python.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API PyObject *getFeature(wchar_t *text, PyObject *unigram)
{
    int ret = -1;
    PyObject *featureList = PyList_New(0);

    PyObject *curString = PyUnicode_FromWideChar(text, 2);
    ret = PySet_Contains(unigram, curString);
    printf("## res: `nc`, %d.\n", ret);
    ret = PyList_Append(featureList, curString);
    Py_DECREF(curString); // fix reference leak
    return featureList;
}
```
<p><strong>test.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import ctypes as ct

dll = ct.PyDLL('./test') # Use PyDLL so GIL is held
dll.getFeature.argtypes = ct.c_wchar_p, ct.py_object
dll.getFeature.restype = ct.py_object

unigram = {'据','nc', 'kls'}
print(hash('据'))
print(hash('nc'))
print(hash('kls'))
print(dll.getFeature('nc', unigram))
</code>```

Output:

5393181648594783828
5393181648594783828
-5015907635941537187
## res: `nc`, 1.
['nc']
```

ContentLicense: CC BY-SA 4.0

Body:
I want to introduce C code in Python and the C code has the following statements:

test.h

#include<Python.h>

PyObject *getFeature(wchar_t *text,
                     PyObject *unigram);
// where the unigram is a Set Object with type 'PySetObject'

test.c

#include<test.h>

PyObject *getFeature(wchar_t *text,
                     PyObject *unigram)
{
    int ret = -1;
    PyObject *featureList = PyList_New(0);

    PyObject *curString = PyUnicode_FromWideChar(text, 2);
    ret = PySet_Contains(unigram, curString);
    printf("## res: `nc`, %d.\n", ret);
    ret = PyList_Append(featureList, curString);

    return featureList;
}

and then I compiled it and get a shared lib called libtest.so. So I can import this C .so file into the python code with ctypes like below:

test.py

import ctypes

dir_path = 'path/to/the/libtest.so'
feature_extractor = ctypes.cdll.LoadLibrary(
    os.path.join(dir_path, 'libtest.so'))
get_feature_c = feature_extractor.getFeature
get_feature_c.argtypes = [
    ctypes.c_wchar_p, ctypes.py_object]
get_feature_c.restype = ctypes.py_object

unigram = {'据','nc', 'kls'}
print(hash('据'))
print(hash('nc'))
print(hash('kls'))
res = get_feature_c('nc', unigram)

execute this test.py file and I can get the following fault:

6875335301337518411
6875335301337518411
-5567445891360670268
Segmentation fault

I know the bug is caused by the confliction of different string nc and 据, which have the same hash value 6875335301337518411.
Python use a secondary level hashtable to tackle the confliction of strings with same hash value.

So how to solve this problem and import the secondary confliction hashtable to the C code?

Body:
The hash match is a red herring.  The problem is not using PyDLL so the GIL is held when using the CPython APIs.

test.c

#include <Python.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API PyObject *getFeature(wchar_t *text, PyObject *unigram)
{
    int ret = -1;
    PyObject *featureList = PyList_New(0);

    PyObject *curString = PyUnicode_FromWideChar(text, 2);
    ret = PySet_Contains(unigram, curString);
    printf("## res: `nc`, %d.\n", ret);
    ret = PyList_Append(featureList, curString);
    Py_DECREF(curString); // fix reference leak
    return featureList;
}

test.py

import ctypes as ct

dll = ct.PyDLL('./test') # Use PyDLL so GIL is held
dll.getFeature.argtypes = ct.c_wchar_p, ct.py_object
dll.getFeature.restype = ct.py_object

unigram = {'据','nc', 'kls'}
print(hash('据'))
print(hash('nc'))
print(hash('kls'))
print(dll.getFeature('nc', unigram))

Output:

5393181648594783828
5393181648594783828
-5015907635941537187
## res: `nc`, 1.
['nc']


问:
Tomcat and JDBC
I am trying to configure the following on Tomcat.

```<code>Resource auth="Container" name="jdbc/yourDataSourceName"
         driverClassName="oracle.jdbc.OracleDriver"
         factory="oracle.jdbc.pool.OracleDataSourceFactory"
         type="oracle.jdbc.pool.OracleDataSource"
         connectionCacheProperties="{}"
         connectionCachingEnabled="true"
         user="foo"
         password="bar"
         url="jdbc:oracle:thin:@foo.bar.com:1521:foobar"
</code>```

When I put the following in my app META-INF/context.xml file, I get the following error:

```<code>java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to oracle.jdbc.pool.OracleDataSource
</code>```

When I move this to $TOMCAT_HOME/conf/context.xml, it works fine. It is not letting me configure specific to the app. Any ideas?

I have ojdbc6.jar in $TOMCAT_HOME/lib as well as in WEB-INF/lib of my application  folder. Please advise. Am I missing something? Thanks for your time.

答:
You can try not to use specific Oracle classes such as "OracleDataSourceFactory" in your datasource configuration. It seems that Oracle Conn.pool is not compatible with DBCP.
Define driverClass only.

You can try something like this:

```<code><Resource
name="jdbc/yourDataSourceName" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@foo.bar.com:1521:foobar"
user="foo"
password="bar"
maxActive="5" maxIdle="1" maxWait="-1"/>
</code>```

Hope it will help

ContentLicense: CC BY-SA 3.0

Title: Tomcat and JDBC

Body:
I am trying to configure the following on Tomcat.

Resource auth="Container" name="jdbc/yourDataSourceName"
         driverClassName="oracle.jdbc.OracleDriver"
         factory="oracle.jdbc.pool.OracleDataSourceFactory"
         type="oracle.jdbc.pool.OracleDataSource"
         connectionCacheProperties="{}"
         connectionCachingEnabled="true"
         user="foo"
         password="bar"
         url="jdbc:oracle:thin:@foo.bar.com:1521:foobar"

When I put the following in my app META-INF/context.xml file, I get the following error:

java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to oracle.jdbc.pool.OracleDataSource

When I move this to $TOMCAT_HOME/conf/context.xml, it works fine. It is not letting me configure specific to the app. Any ideas?

I have ojdbc6.jar in $TOMCAT_HOME/lib as well as in WEB-INF/lib of my application  folder. Please advise. Am I missing something? Thanks for your time.

Body:
You can try not to use specific Oracle classes such as "OracleDataSourceFactory" in your datasource configuration. It seems that Oracle Conn.pool is not compatible with DBCP.
Define driverClass only.

You can try something like this:

<Resource
name="jdbc/yourDataSourceName" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@foo.bar.com:1521:foobar"
user="foo"
password="bar"
maxActive="5" maxIdle="1" maxWait="-1"/>

Hope it will help


问:
UIButton - How to set Minimum Font Size?
My question is simple. Is there any way to set a minimum font size for UIButton like this can be easily set up with UILabel?

答: Teetz's answer works like a charm. In case if you want to add margin between titleLabel of UIButton edges after it adjustsFontSizeToFitWidth, you can add few spaces before first character & after last character. So, that it looks neat.


问:
Azure Devops - Release Pipeline when re-running failed tests azure devops shows failure status even if re-run succeeded
I use Specflow with SpecRunner+ I am using the Deafult.srprofile to to re-run failed tests 3 times in visual studio it shows 2passed 1 failed but the status of the test is a failure, the same goes for azure devops if a re-ran test passes the outcome of the run is a failure. The Failures are sometimes caused by locator timeouts or server timeouts not often but saw it happen few time thats why we decided to implement a re-run.

Could anyone help on this?

```<code>022-02-09T12:40:13.8607507Z Test Run Failed.
2022-02-09T12:40:13.8608607Z Total tests: 37
2022-02-09T12:40:13.8609271Z      Passed: 36
2022-02-09T12:40:13.8609858Z      Failed: 1
2022-02-09T12:40:13.8617476Z  Total time: 7.4559 Minutes
2022-02-09T12:40:13.9226929Z ##[warning]Vstest failed with error. Check logs for failures. There might be failed tests.
2022-02-09T12:40:14.0075402Z ##[error]Error: The process 'D:\Microsoft_Visual_Studio\2019\Common7\IDE\Extensions\TestPlatform\vstest.console.exe' failed with exit code 1
2022-02-09T12:40:14.8164576Z ##[error]VsTest task failed.
</code>```

But then the report states that it was retried 3 times which 2 of the retries were seccusefull but still a failure status on the azure devops run.

答:
The behavior of the report is the correct one and sadly this can't be configured to be changed.

What you can do is to adjust how the results are reported back to Azure DevOps.
You can configure it via the VSTest element in the srProfile- File.

This example means, that at least one retry has to be passing:

<VSTest testRetryResults="Unified" passRateAbsolute="1"/>
```

Docs: https://docs.specflow.org/projects/specflow-runner/en/latest/Profile/VSTest.html

Be aware that we have stopped the development of the SpecFlow+ Runner. More details here: https://specflow.org/using-specflow/the-retirement-of-specflow-runner/

Body:
I use Specflow with SpecRunner+ I am using the Deafult.srprofile to to re-run failed tests 3 times in visual studio it shows 2passed 1 failed but the status of the test is a failure, the same goes for azure devops if a re-ran test passes the outcome of the run is a failure. The Failures are sometimes caused by locator timeouts or server timeouts not often but saw it happen few time thats why we decided to implement a re-run.

Could anyone help on this?

022-02-09T12:40:13.8607507Z Test Run Failed.
2022-02-09T12:40:13.8608607Z Total tests: 37
2022-02-09T12:40:13.8609271Z      Passed: 36
2022-02-09T12:40:13.8609858Z      Failed: 1
2022-02-09T12:40:13.8617476Z  Total time: 7.4559 Minutes
2022-02-09T12:40:13.9226929Z ##[warning]Vstest failed with error. Check logs for failures. There might be failed tests.
2022-02-09T12:40:14.0075402Z ##[error]Error: The process 'D:\Microsoft_Visual_Studio\2019\Common7\IDE\Extensions\TestPlatform\vstest.console.exe' failed with exit code 1
2022-02-09T12:40:14.8164576Z ##[error]VsTest task failed.

But then the report states that it was retried 3 times which 2 of the retries were seccusefull but still a failure status on the azure devops run.

Body:
The behavior of the report is the correct one and sadly this can't be configured to be changed.

What you can do is to adjust how the results are reported back to Azure DevOps.
You can configure it via the VSTest element in the srProfile- File.

This example means, that at least one retry has to be passing:

<VSTest testRetryResults="Unified" passRateAbsolute="1"/>

Docs: https://docs.specflow.org/projects/specflow-runner/en/latest/Profile/VSTest.html

Be aware that we have stopped the development of the SpecFlow+ Runner. More details here: https://specflow.org/using-specflow/the-retirement-of-specflow-runner/


问:
Running order of multiple scripts in an HTML document?
I have an HTML page that i ship to the browser and it contains a couple of script tag.

This is my index.html file:

```<code>  <body>
    <div id="app"></div>

    <script src="src/index.js"></script>

    <script>
      window.test = true;
    </script>
  </body>
</html>

</code>```

And this is my src/index.js file:

```<code><script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};

test();
</script>
</code>```

In the HTML file, i define window.test after i run the src/index.js.
src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.

What is the order in which these scripts will run?
Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?

CodeSandbox:
https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

答:
to guarantee that test function is only call after variable is setted why not use a custom event

```<code><script src="src/index.js"></script>

<script>
  window.test = true;
  const event = new Event('test-setted');
  document.dispatchEvent(event);

</script>
</code>```

and in index.js

```<code><script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};
document.addEventListener('test-setted', function (e) {
    test();
}, false);

</script>
</code>```

Body:
I have an HTML page that i ship to the browser and it contains a couple of script tag.

This is my index.html file:

And this is my src/index.js file:

In the HTML file, i define window.test after i run the src/index.js.
src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.

What is the order in which these scripts will run?
Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?

CodeSandbox:
https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

Body:
to guarantee that test function is only call after variable is setted why not use a custom event

<script src="src/index.js"></script>

<script>
  window.test = true;
  const event = new Event('test-setted');
  document.dispatchEvent(event);

</script>

and in index.js

<script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};
document.addEventListener('test-setted', function (e) {
    test();
}, false);

</script>


问:
AWS not showing whole webiste with CloudFront
To keep it short, i setup CloudFront to "fix" my problem that when i went onto my AWS website it showed my Social header but nothing else: AWS Website

but when i tried to use CloudFront:  CloudFront Website it still looks the same... when i test my code in VSC it shows me the whole website like its supposed to What its Supposed to look like

I set it up with the tutorial from Amazon, its redirected to the right website yet it still doesnt show... its HTTPS so it isn't that... any suggestions?

```<code><html>
<title>Future Company Design</title>
<head><link rel="shortcut icon" type="image/x-icon" href="file:///C:/Users/LNGM/OneDrive%20-%20System%20Industrie%20Electronic%20GmbH/Bilder/favicon.ico" /></head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {margin:0;height:2000px;}
body,h1 {font-family: "Raleway", sans-serif}
body, html {height: 100%}
.bgimg {
  background-image: url('file:///C:/Users/LNGM/Downloads/website.jpg');
  min-height: 100%;
  background-position: center;
  background-size: cover;
}

.icon-bar {
 position: absolute;
  right: -720;
  top: -50;
}

.icon-bar a {
  display:flex;
  text-align: left;
  padding: 16px;
  transition: all 0.3s ease;
  color: white;
  font-size: 20px;
}

.icon-bar a:hover {
  background-color: rgb(196, 44, 44);
}

.Twitch {
  background: #6441a5;
  color: white;
}

.twitter {
  background: #55ACEE;
  color: white;
}

.instagram {
  background: #125688;
  color: white;
}

.linkedin {
  background: #007bb5;
  color: white;
}

</style>
<body>

<script>
var countDownDate = new Date("Dec 23, 2022 08:00:00").getTime();

var x = setInterval(function() {

  var now = new Date().getTime();

  var distance = countDownDate - now;

  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "Website going Live in only a Couple of Minutes";
  }
}, 1000);

</script>

<div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
  <div class="w3-display-topleft w3-padding-large w3-xlarge">
    <img src="file:///C:/Users/LNGM/Downloads/rsz_logo_small.png">
  </div>
  <div class="w3-display-middle">
    <h1 class="w3-jumbo w3-animate-top">Work in Progress</h1>
    <hr class="w3-border-grey" style="margin:auto;width:40%">
    <p id="demo" class="w3-large w3-center"></p>

    <div class="icon-bar">
      <a href="https://twitter.com/MaaxyBaxy" target="_blank" class="twitter"><i class="fa fa-twitter"></i></a>
      <a href="https://www.instagram.com/lurinoxii/" target="_blank" class="instagram"><i class="fa fa-instagram"></i></a>
      <a href="https://www.linkedin.com/in/matteo-lang-620881201/" target="_blank" class="linkedin"><i class="fa fa-linkedin"></i></a>
      <a href="https://Twitch.tv/Lurinoxi" target="_blank" class="Twitch"><i class="fa fa-Twitch"></i></a>

</body>
</html>
</code>```

答: Would propose to use relative path when referencing other static assets in your website. This will prevent broken linkages when you deploy in S3. EG. file:///C:/Users/LNGM/Downloads/website.jpg don't exists in S3, its a reference to a specific path in your PC

Body:
To keep it short, i setup CloudFront to "fix" my problem that when i went onto my AWS website it showed my Social header but nothing else: AWS Website

but when i tried to use CloudFront:  CloudFront Website it still looks the same... when i test my code in VSC it shows me the whole website like its supposed to What its Supposed to look like

I set it up with the tutorial from Amazon, its redirected to the right website yet it still doesnt show... its HTTPS so it isn't that... any suggestions?

<title>Future Company Design</title>
<link rel="shortcut icon" type="image/x-icon" href="file:///C:/Users/LNGM/OneDrive%20-%20System%20Industrie%20Electronic%20GmbH/Bilder/favicon.ico" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Work in Progress


问:
Filtering search results by operating hour with elasticsearch
I'm using elasticsearch to index and search locations, and I'm running into 1 particular issue with filtering by operating hour which I don't know how to work out

Basically, each location will have operating hour (for every day of the week) and each day may have more than 1 "sets" of operating hour (we use 2 for now).

For example:
Monday:
open 9am / close 12pm
open 1pm / close 9pm

Given the current time and the current day of the week, I need to search for the "open" locations.

I don't know how should I index these operating hour together with the location details, and how to use them to filter out the results yet, any help, suggestion would be really appreciated

Regards

答:
The simplest way to do it is by naming and indexing time slots when a location is open. First, you need to come up with a schema that assigns a name to each time slot when location can be open. For example, thu17 may represent 5PM on Thursday. The location in your example should then be indexed with several fields "open" containing the following values: mon09, mon10, mon11, mon13, mon14, mon15, mon16, mon17, mon18, mon19, mon20, tue09, tue10 and so on. To show only locations that are open on Thursday 7AM, you just need add this filter to your query:  open:thu07.

You don't have to use this particular naming schema. You can, for example, just count the number of hours from the beginning of the week. In this case, 9 AM on Monday would be 9, 11PM on Monday - 23, 2AM on Tuesday - 26 and so on.


问:
ActionBarDrawerToggle doesn't accept String as parameter
the Red line is under "Open navigation drawer" and "Close navigation drawer"

```<code>import androidx.appcompat.app.ActionBarDrawerToggle;
setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Menu");
    setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this,
                drawer,
                toolbar ,
                "Open navigation drawer",
                "Close navigation drawer"

                );
        drawer.setDrawerListener(toogle);
        toogle.syncState();
</code>```

This picture shows the problem

答:
If you check constructor signature as you can see it accepts string resource, int, not String

```<code>public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
        Toolbar toolbar, @StringRes int openDrawerContentDescRes,
        @StringRes int closeDrawerContentDescRes) {
    this(activity, toolbar, drawerLayout, null, openDrawerContentDescRes,
            closeDrawerContentDescRes);
}
</code>```

You need to change both from String to string resource such as R.string.YOUR_STRING that located in strings.xml file.

Body:
the Red line is under "Open navigation drawer" and "Close navigation drawer"

import androidx.appcompat.app.ActionBarDrawerToggle;
setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Menu");
    setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this,
                drawer,
                toolbar ,
                "Open navigation drawer",
                "Close navigation drawer"

                );
        drawer.setDrawerListener(toogle);
        toogle.syncState();

This picture shows the problem

Body:
If you check constructor signature as you can see it accepts string resource, int, not String

public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
        Toolbar toolbar, @StringRes int openDrawerContentDescRes,
        @StringRes int closeDrawerContentDescRes) {
    this(activity, toolbar, drawerLayout, null, openDrawerContentDescRes,
            closeDrawerContentDescRes);
}

You need to change both from String to string resource such as R.string.YOUR_STRING that located in strings.xml file.


问:
Send RestClient through Function Azure VS Code
I am trying to make a post request with c# through the Azure HttpTrigger function. Only that when executing it sends me thousands of errors.
Can someone help me here?

This is my code:

```<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Admin
{
    public static class addTimbres
    {
        public static readonly string url = "https://dev.facturacfdi.mx:8083/admindigital/WSDistribuidoresServices?wsdl";

        [FunctionName("addTimbres")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
        {
            string username = "distribuidor1";
            string pass = "r*6Og80*2";
            string id = req.Query["id"];
            string cantidad = req.Query["cantidad"];
            string precio = req.Query["precio"];
            string tipo = req.Query["tipoServicio"];

            var client = new RestClient("https://dev.facturacfdi.mx:8083/admindigital/WSDistribuidoresServices?wsdl");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "text/xml");
            request.AddHeader("Cookie", "AWSELB=9967379D183B464F07472AD23944C79D1D256893C16F7531AC9AEC11DFCF25BB286EED0AA8BE0779B4925DB1440897B768AE03876F852C644560C840DC57CFDF50A6CA647F; AWSELBCORS=9967379D183B464F07472AD23944C79D1D256893C16F7531AC9AEC11DFCF25BB286EED0AA8BE0779B4925DB1440897B768AE03876F852C644560C840DC57CFDF50A6CA647F");
            var body =
            @"<Envelope xmlns=""http://schemas.xmlsoap.org/soap/envelope/"">
            " + "\n" +
            @"    <Body>
            " + "\n" +
            @"        <getUsuarios xmlns=""http://servicios.ws.distribuidores.forsedi.mx/"">
            " + "\n" +
            @"            <username xmlns="""">distribuidor1</username>
            " + "\n" +
            @"            <password xmlns="""">r*6Og80*2</password>
            " + "\n" +
            @"        </getUsuarios>
            " + "\n" +
            @"    </Body>
            " + "\n" +
            @"</Envelope>";
            request.AddParameter("text/xml", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

        }

    }
}

</code>```

I understand that RestClient is used for this case, but I can't find out how it is implemented with Azure Functions.

Thanks.

答:
You need to add a reference to the RestSharp NuGet package to your project. And also, at the top of your .cs file, need to refer the namespace.

```<code> using RestSharp;
</code>```

Also, you are sending xml as request body, check out the documentation, it is more appropriate to use the AddXmlBody method.

Body:
I am trying to make a post request with c# through the Azure HttpTrigger function. Only that when executing it sends me thousands of errors.
Can someone help me here?

This is my code:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Admin
{
    public static class addTimbres
    {
        public static readonly string url = "https://dev.facturacfdi.mx:8083/admindigital/WSDistribuidoresServices?wsdl";

        [FunctionName("addTimbres")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
        {
            string username = "distribuidor1";
            string pass = "r*6Og80*2";
            string id = req.Query["id"];
            string cantidad = req.Query["cantidad"];
            string precio = req.Query["precio"];
            string tipo = req.Query["tipoServicio"];

            var client = new RestClient("https://dev.facturacfdi.mx:8083/admindigital/WSDistribuidoresServices?wsdl");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "text/xml");
            request.AddHeader("Cookie", "AWSELB=9967379D183B464F07472AD23944C79D1D256893C16F7531AC9AEC11DFCF25BB286EED0AA8BE0779B4925DB1440897B768AE03876F852C644560C840DC57CFDF50A6CA647F; AWSELBCORS=9967379D183B464F07472AD23944C79D1D256893C16F7531AC9AEC11DFCF25BB286EED0AA8BE0779B4925DB1440897B768AE03876F852C644560C840DC57CFDF50A6CA647F");
            var body =
            @"<Envelope xmlns=""http://schemas.xmlsoap.org/soap/envelope/"">
            " + "\n" +
            @"
            " + "\n" +
            @"        <getUsuarios xmlns=""http://servicios.ws.distribuidores.forsedi.mx/"">
            " + "\n" +
            @"            <username xmlns="""">distribuidor1</username>
            " + "\n" +
            @"            <password xmlns="""">r*6Og80*2</password>
            " + "\n" +
            @"        </getUsuarios>
            " + "\n" +
            @"
            " + "\n" +
            @"</Envelope>";
            request.AddParameter("text/xml", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

        }

    }
}

I understand that RestClient is used for this case, but I can't find out how it is implemented with Azure Functions.

Thanks.

Body:
You need to add a reference to the RestSharp NuGet package to your project. And also, at the top of your .cs file, need to refer the namespace.

 using RestSharp;

Also, you are sending xml as request body, check out the documentation, it is more appropriate to use the AddXmlBody method.


问:
How to use the useState() with specific strings ("this" | "that")
I am trying to use the useState in React-native with TypeScript and want to use specific strings that can be used in a component. How can I do this?

I have this:

```<code>                                             |
                                             \/
const [getViewState, setViewState] = useState();
                 |
                 \/
<Icon name={getViewState} size={25} color={COLORS.light_gray}></Icon>

</code>```
```<code>type props = {
  style?: StyleProp<ImageStyle>;
  name: "add" | "check" | "down" | "home" | "lock" | "right" | "search" | "settings" | "user" | "grid" | "list";
  size: number;
  color: string;
  onPress?: Function;
};```
```

答:
```<code>const [viewState, setViewState] = useState("myDefaultStateString")

<Icon name={viewState} size={25} color={COLORS.light_gray}></Icon>

// change state
const someFunciton = () => {
  setViewState("someOtherString")
}
</code>```

Body:
I am trying to use the useState in React-native with TypeScript and want to use specific strings that can be used in a component. How can I do this?

I have this:

                                             |
                                             \/
const [getViewState, setViewState] = useState();
                 |
                 \/
<Icon name={getViewState} size={25} color={COLORS.light_gray}></Icon>

type props = {
  style?: StyleProp<ImageStyle>;
  name: "add" | "check" | "down" | "home" | "lock" | "right" | "search" | "settings" | "user" | "grid" | "list";
  size: number;
  color: string;
  onPress?: Function;
};```


问:
Nextjs/Vercel error: only absolute URLs are supported. Where is the '.json' in my route params coming from?
The Problem:
I'm new to Next.js (1 month) and Vercel (1 day), and between them something appears to be inserting .json in my urls on the search route, causing them to fail with error:

```<code>[GET] /_next/data/9MJcw6afNEM1L-eax6OWi/search/hand.json?term=hand
10:21:52:87
Function Status:None
Edge Status:500
Duration:292.66 ms
Init Duration: 448.12 ms
Memory Used:88 MB
ID:fra1:fra1::ldzhz-1644484912454-0a30b71b6c90
User Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0

TypeError: Only absolute URLs are supported
at getNodeRequestOptions (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:61917)
at /var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:63448
at new Promise (<anonymous>)
at Function.fetch [as default] (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:63382)
at fetchWithAgent (/var/task/node_modules/next/dist/server/node-polyfill-fetch.js:38:39)
at getServerSideProps (/var/task/.next/server/chunks/730.js:238:28)
at Object.renderToHTML (/var/task/node_modules/next/dist/server/render.js:566:26)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async doRender (/var/task/node_modules/next/dist/server/base-server.js:855:38)
at async /var/task/node_modules/next/dist/server/base-
server.js:950:28

2022-02-10T09:21:53.788Z    994c9544-0bbe-4a68-af83-f0e4c322151e    ERROR
Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?
at Object.renderToHTML (/var/task/node_modules/next/dist/server/render.js:592:19)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async doRender (/var/task/node_modules/next/dist/server/base-server.js:855:38)
at async /var/task/node_modules/next/dist/server/base-server.js:950:28
at async /var/task/node_modules/next/dist/server/response-cache.js:63:36 {  page: '/search/[term]'}

RequestId: 994c9544-0bbe-4a68-af83-f0e4c322151e Error: Runtime exited with error: exit status 1
Runtime.ExitError
</code>```

Though the browser says https://.../search/hand as it should.
No such thing is happening on my local server build though, and it works perfectly well.

Background/Code Snippets:
The search route is the only route that uses SSR, and is also the only route with this issue. It is a dynamic route, so it seems either next in production or vercel expects some kind of json for it -presumably pre-rendered content-, and is replacing the route URL with json.

Also I have had to use the VERCEL_URL environment variable to prepare a URL for fetch requests, so this may also be messing up the URL, but the .json in the error message makes me think otherwise, since search should not be pre-rendered.

The Page Structure For the Search Route (Index imports the component in [term] and defines its own getServerSide props to accommodate a search route without a param):

```<code>|-Search
  |- [term].js
  |- Index.js
</code>```

The Code For [term].js:

```<code>...
export default function Search({results, currentSearch}){
...
}

export async function getServerSideProps(req) {
  const { criteria, page } = req.query;
  const { term } = req.params || { term: '' };
  try {
    const data = await fetch(`${process.env.VERCEL_URL}/api/search/${term}?criteria=${criteria || 'name'}&page=${page}`);
    const searchRes = await data.json();
    return {
      props: {
        results: searchRes.data,
        currentSearch: searchRes.query
      }
    }
  } catch (e) {
    console.log(e)
  }
}
</code>```

Index.js is similar:

```<code>import Search from "./[term]";
export default Search;

export async function getServerSideProps(req) {
  const { criteria, page } = req.query;
  const { term } = req.params || { term: '' };
  if(!term){
    return {
      props: {
        results: [],
        currentSearch: {}
      }
    }
  }
  try {
    const data = await fetch(`${process.env.VERCEL_URL}/api/search/${term}?criteria=${criteria || 'name'}&page=${page}`);
    const searchRes = await data.json();
    return {
      props: {
        results: searchRes.data,
        currentSearch: searchRes.query
      }
    }
  } catch (e) {
    console.log(e)
  }
}
</code>```

The API I'm trying to fetch from is confirmed to be working, so this problem is strictly regarding pages, or .json being provided to the fetch method from router params.

答:
It would turn out that VERCEL_URL is actually an absolute URL (It does not include a protocol). I had to deploy console.log statements to find this. A little embarrassed that I missed it in the docs.

The .json was not actually in the query or params, and therefore not in the fetch request. The fetch failed because the url had no protocol.

The .json in the page url must be from Next's internal operations, and does not mean the page is being built ahead of time. Yes it is being rendered using some json, but my thinking that the json indicates a pre-rendered page(SSG/ISR) was wrong. This must mean Server Side Rendering will also make use of such json, but only at runtime, when the request is made.

The use of .json after the params slug in the GET requests for a page has no bearing on the internal flow of your app, provided it has worked correctly. If you see it in error messages, know that it is from Next and examine other parts of the code at the point of failure.

The page structure I attempted ([param].js + index.js in the same
directory) is fine, which is why my local build could work properly.

I want to delete this question because the solution is essentially one that a thorough look in the docs would have revealed, but at the same time I think the mistake itself is an easily made one and that some of the conclusions listed above(particularly the one about json being used in all next routes) could save time spent debugging for some new users of Next/Vercel.

Body:
The Problem:
I'm new to Next.js (1 month) and Vercel (1 day), and between them something appears to be inserting .json in my urls on the search route, causing them to fail with error:

[GET] /_next/data/9MJcw6afNEM1L-eax6OWi/search/hand.json?term=hand
10:21:52:87
Function Status:None
Edge Status:500
Duration:292.66 ms
Init Duration: 448.12 ms
Memory Used:88 MB
ID:fra1:fra1::ldzhz-1644484912454-0a30b71b6c90
User Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0

TypeError: Only absolute URLs are supported
at getNodeRequestOptions (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:61917)
at /var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:63448
at new Promise (<anonymous>)
at Function.fetch [as default] (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:63382)
at fetchWithAgent (/var/task/node_modules/next/dist/server/node-polyfill-fetch.js:38:39)
at getServerSideProps (/var/task/.next/server/chunks/730.js:238:28)
at Object.renderToHTML (/var/task/node_modules/next/dist/server/render.js:566:26)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async doRender (/var/task/node_modules/next/dist/server/base-server.js:855:38)
at async /var/task/node_modules/next/dist/server/base-
server.js:950:28

2022-02-10T09:21:53.788Z    994c9544-0bbe-4a68-af83-f0e4c322151e    ERROR
Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?
at Object.renderToHTML (/var/task/node_modules/next/dist/server/render.js:592:19)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async doRender (/var/task/node_modules/next/dist/server/base-server.js:855:38)
at async /var/task/node_modules/next/dist/server/base-server.js:950:28
at async /var/task/node_modules/next/dist/server/response-cache.js:63:36 {  page: '/search/[term]'}

RequestId: 994c9544-0bbe-4a68-af83-f0e4c322151e Error: Runtime exited with error: exit status 1
Runtime.ExitError

Though the browser says https://.../search/hand as it should.
No such thing is happening on my local server build though, and it works perfectly well.

Background/Code Snippets:
The search route is the only route that uses SSR, and is also the only route with this issue. It is a dynamic route, so it seems either next in production or vercel expects some kind of json for it -presumably pre-rendered content-, and is replacing the route URL with json.

Also I have had to use the VERCEL_URL environment variable to prepare a URL for fetch requests, so this may also be messing up the URL, but the .json in the error message makes me think otherwise, since search should not be pre-rendered.

The Page Structure For the Search Route (Index imports the component in [term] and defines its own getServerSide props to accommodate a search route without a param):

|-Search
  |- [term].js
  |- Index.js

The Code For [term].js:

...
export default function Search({results, currentSearch}){
...
}

export async function getServerSideProps(req) {
  const { criteria, page } = req.query;
  const { term } = req.params || { term: '' };
  try {
    const data = await fetch(`${process.env.VERCEL_URL}/api/search/${term}?criteria=${criteria || 'name'}&page=${page}`);
    const searchRes = await data.json();
    return {
      props: {
        results: searchRes.data,
        currentSearch: searchRes.query
      }
    }
  } catch (e) {
    console.log(e)
  }
}

Index.js is similar:

import Search from "./[term]";
export default Search;

export async function getServerSideProps(req) {
  const { criteria, page } = req.query;
  const { term } = req.params || { term: '' };
  if(!term){
    return {
      props: {
        results: [],
        currentSearch: {}
      }
    }
  }
  try {
    const data = await fetch(`${process.env.VERCEL_URL}/api/search/${term}?criteria=${criteria || 'name'}&page=${page}`);
    const searchRes = await data.json();
    return {
      props: {
        results: searchRes.data,
        currentSearch: searchRes.query
      }
    }
  } catch (e) {
    console.log(e)
  }
}

The API I'm trying to fetch from is confirmed to be working, so this problem is strictly regarding pages, or .json being provided to the fetch method from router params.


问:
Virtual column names in ClickHouse
ClickHouse documentation says:

Virtual column is an integral table engine attribute that is defined in the engine source code. You shouldn't specify virtual columns in the CREATE TABLE query and you can't see them in SHOW CREATE TABLE and DESCRIBE TABLE query results. Virtual columns are also read-only, so you can't insert data into virtual columns.

But I cannot find a list of virtual column names. Could you please point out, what are their names? How do I select their values and data types?

答:
Do you mean MergeTree engine or file or HDFS or what?

MergeTree

```<code>_part  -- name of a part
_part_index -- sequential index of the part in the query result
_partition_id -- name of a partition
_part_uuid -- unique part identifier, if enabled `MergeTree` setting `assign_part_uuids` (Part movement between shards)
_partition_value -- values (tuple) of a `partition by` expression
_sample_factor -- sample_factor from the query
</code>```

Title: Virtual column names in ClickHouse

Body:
Do you mean MergeTree engine or file or HDFS or what?

MergeTree

_part  -- name of a part
_part_index -- sequential index of the part in the query result
_partition_id -- name of a partition
_part_uuid -- unique part identifier, if enabled `MergeTree` setting `assign_part_uuids` (Part movement between shards)
_partition_value -- values (tuple) of a `partition by` expression
_sample_factor -- sample_factor from the query


问:
Mongodb : An error occurred while loading navigation: Invalid UTF-8 string in BSON document
I installed MongoDB Compass, and I get error message “An error occurred while loading navigation: Invalid UTF-8 string in BSON document”. I can't visualize my data.

Version MongoDB 5.0.3(current)

Windows 10

I tried reinstalling a different version of MongoDB but it didn't help.

I download it on another other computer of the same configuration, everything seems to work.
What could have happened?

P.S. Console commands work without problem.
This is what I see after i click on connect

答:
I fixed this problem with the same MongoDB Compass version shared by Wlogz (1.21.2).
The link is in the previous comment...</p>


问:
SSIS error: delimiter for column "columnX" is not found
This question was asked here before but the solutions proposed don't seem to be working for me.

I'm trying to import a text file pipe delimited text qualifier ". The SSIS package is returning the error message

delimiter for column "columnX" is not found

where column X is the last field in the file.

In the connection manager advanced tab, I have set up the column delimiter for columnX to {LF} while all the other fields are set to vertical |.

I have verified the file and there are no missing fields. There are some null values but all the fields are there.

I can't point out what is causing this. Your help would be greatly appreciated.

答: This has happened to me on several occasions.  Each time it has been caused by someone adding a column to the csv file. The error happens when it gets to the end of the last column and expects a carriage return line feed cr/lf, but finds only the carriage return because there is an added column.</p>


问:
reusable UI in android app
I am working on android app where I am thinking to develop reusable UI interface. How it can be developed and included in my .xml's

Here I want to develop a progress bar with my image and it will be display on some .xml's.
Please provide any code help.

I am a new in this field.

答: I think you need to use styles and themes. Check this out.</p>

Title: reusable UI in android app


问:
understaing nested for loop
I am just testing a code that i have written but cant figure out why theloop is getting executed twice for the 3 and 4 th value in the array and  4 times for the 5 and 6th value.

My code is as follow

```<code>Angry=["irritated","annoying"]
Sad=["upset","scared"]
Happy=["awsome","excited"]
a=[]
a.extend(Angry)
a.extend(Sad)
a.extend(Happy)

name=input("what is your name")
age=input("whai is your age")
m=input(f"how do you feel today ? choose from the list above {print(a)}")

for i in Angry:
    for j in Sad:
        for k in Happy:
#             print("m is:", m)
#             print("i is:", i)
#             print("j is:", j)
#             print("k is:", k)
            if (m == k):
                print(name,"is feeling HAPPY")
                break
            else:
                continue
        if m == j:
            print(name,"mood is SAD")
            print("m",m)
            print("i",m)
            print("j",m)
            print("k",m)
            break
        else:
            continue
    if m == i:
        print(name,"mood is ANGRY")
        break
</code>```

答:
Because break only applies to the inmost loop and not the outer ones. In case of m == k you find that name is happy 2 times 2 times, because you don't break the outer loops.

The nested for loops does this:

For each value in Angry, check each value in Sad and for each value in Sad check each value in Happy:

irritated -> upset -> awesome -> excited -> scared -> awesome -> excited -> annoying -> upset -> awesome -> excited -> scared -> awesome -> excited

Which means each value in Happy is checked 4 times, each value in Sad is checked two times and each value in Angry is checked once.

I take it this was a case study for nested loops, but here's an approach to solve your task differently:

```<code>if m in Angry:
    print(name, "mood is ANGRY")
elif m in Sad:
    print(name, "mood is SAD")
elif m in Happy:
    print(name, "is feeling HAPPY")
else:
    print('Unknown feeling?!')
</code>```

m in Angry checks, well, if m is equal to any element in Angry. The chained if/elif/else cases make sure that m is only found once.

Edit:

If want to keep the nested for loops, you need to break out of outer loops either with a return statement after putting the loop inside a function

def get_message():
    for i in Angry:
        for j in Sad:
            for k in Happy:
                if m == k:
                    print(name, "is feeling HAPPY")
                    return
            if m == j:
                print(name, "mood is SAD")
                return
        if m == i:
            print(name, "mood is ANGRY")
            return

get_message()
```
<p>or you need to maintain a variable that gets passed as break condition through the loops:</p>
<pre class="lang-py prettyprint-override"><code>found = False
for i in Angry:
    for j in Sad:
        for k in Happy:
            if m == k:
                print(name, "is feeling HAPPY")
                found = True
            if found:
                break
        if m == j:
            print(name, "mood is SAD")
            found = True
        if found:
            break
    if m == i:
        print(name, "mood is ANGRY")
        found = True
    if found:
        break
</code>```

Title: understaing nested for loop

Body:
I am just testing a code that i have written but cant figure out why theloop is getting executed twice for the 3 and 4 th value in the array and  4 times for the 5 and 6th value.

My code is as follow

Angry=["irritated","annoying"]
Sad=["upset","scared"]
Happy=["awsome","excited"]
a=[]
a.extend(Angry)
a.extend(Sad)
a.extend(Happy)

name=input("what is your name")
age=input("whai is your age")
m=input(f"how do you feel today ? choose from the list above {print(a)}")

for i in Angry:
    for j in Sad:
        for k in Happy:
#             print("m is:", m)
#             print("i is:", i)
#             print("j is:", j)
#             print("k is:", k)
            if (m == k):
                print(name,"is feeling HAPPY")
                break
            else:
                continue
        if m == j:
            print(name,"mood is SAD")
            print("m",m)
            print("i",m)
            print("j",m)
            print("k",m)
            break
        else:
            continue
    if m == i:
        print(name,"mood is ANGRY")
        break

Body:
Because break only applies to the inmost loop and not the outer ones. In case of m == k you find that name is happy 2 times 2 times, because you don't break the outer loops.

The nested for loops does this:

For each value in Angry, check each value in Sad and for each value in Sad check each value in Happy:

irritated -> upset -> awesome -> excited -> scared -> awesome -> excited -> annoying -> upset -> awesome -> excited -> scared -> awesome -> excited

Which means each value in Happy is checked 4 times, each value in Sad is checked two times and each value in Angry is checked once.

I take it this was a case study for nested loops, but here's an approach to solve your task differently:

if m in Angry:
    print(name, "mood is ANGRY")
elif m in Sad:
    print(name, "mood is SAD")
elif m in Happy:
    print(name, "is feeling HAPPY")
else:
    print('Unknown feeling?!')

m in Angry checks, well, if m is equal to any element in Angry. The chained if/elif/else cases make sure that m is only found once.

Edit:

If want to keep the nested for loops, you need to break out of outer loops either with a return statement after putting the loop inside a function

def get_message():
    for i in Angry:
        for j in Sad:
            for k in Happy:
                if m == k:
                    print(name, "is feeling HAPPY")
                    return
            if m == j:
                print(name, "mood is SAD")
                return
        if m == i:
            print(name, "mood is ANGRY")
            return

get_message()

or you need to maintain a variable that gets passed as break condition through the loops:

found = False
for i in Angry:
    for j in Sad:
        for k in Happy:
            if m == k:
                print(name, "is feeling HAPPY")
                found = True
            if found:
                break
        if m == j:
            print(name, "mood is SAD")
            found = True
        if found:
            break
    if m == i:
        print(name, "mood is ANGRY")
        found = True
    if found:
        break


问:
I have a Route working fine with a GET and doing ERROR 404 for UPDATE and DELETE. What can I do?
Follow the code below, everything is working fine with other collections that I am using exactly the same code and handlerFactory as well with the GET call for this one but when I try to delete and update it is getting a 404 error, it is not a typo because GET is working well and the same in the handlerFactory.js as all CRUD operations are working fine with this same code and other collection:

app.js

```<code>var userRouter = require('./routes/userRoutes');
// Routes Definitions
app.use('/', viewRouter);
app.use('/api/v1/aircraft', aircraftRouter);
app.use('/api/v1/users', userRouter);
</code>```

UserRoutes.js

```<code>const express = require('express');
const userController = require('../controllers/userController');

const router = express.Router();

router.get('/', userController.getAllUsers);

router
  .get('/:id', userController.getUser)
  .delete(userController.deleteUser)
  .patch(userController.UpdateUser);

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

UserController.js

```<code>const user = require('../models/userModel');
const factory = require('./handlerFactory');

exports.getAllUsers = factory.getAll(user);
exports.getUser = factory.getOne(user);
exports.deleteUser = factory.deleteOne(user)
exports.UpdateUser = factory.updateOne(user);
</code>```

handlerfactory.js

```<code>const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');
const APIFeatures = require('../utils/apiFeatures');

exports.deleteOne = (Model) =>
catchAsync(async (req, res, next) => {
const doc = await Model.findByIdAndDelete(req.params.id);

if (!doc) {
  return next(new AppError('No document found with that ID', 401));
  console.log('No document found with that ID');
}

res.status(204).json({
  status: 'success',
  data: null,
});
});

exports.updateOne = (Model) =>
catchAsync(async (req, res, next) => {
const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
  new: true,
  runValidators: true,
});

if (!doc) {
  return next(new AppError('No document found with that ID', 404));
}

res.status(200).json({
  status: 'success',
  data: {
    data: doc,
  },
});
});
</code>```

答:
I will answers my own question here because Daniel just come to my attention a silly mistake that I was making but I think it can still be useful to others.

If you just wanna one route per line use:

```<code>router.update('/:id', userController.updateOne);
</code>```

If you are trying to use multiple routes in the same line do not forget to use .route like in the code below:

```<code>router.route('/:id').get(userController.getUser)
.delete(userController.deleteUser)
.patch(userController.UpdateUser);
</code>```

Thank you very much, it may be silly but silly things happen with code every day.

Thank you all!

Body:
Follow the code below, everything is working fine with other collections that I am using exactly the same code and handlerFactory as well with the GET call for this one but when I try to delete and update it is getting a 404 error, it is not a typo because GET is working well and the same in the handlerFactory.js as all CRUD operations are working fine with this same code and other collection:

app.js

var userRouter = require('./routes/userRoutes');
// Routes Definitions
app.use('/', viewRouter);
app.use('/api/v1/aircraft', aircraftRouter);
app.use('/api/v1/users', userRouter);

UserRoutes.js

const express = require('express');
const userController = require('../controllers/userController');

const router = express.Router();

router.get('/', userController.getAllUsers);

router
  .get('/:id', userController.getUser)
  .delete(userController.deleteUser)
  .patch(userController.UpdateUser);

module.exports = router;

UserController.js

const user = require('../models/userModel');
const factory = require('./handlerFactory');

exports.getAllUsers = factory.getAll(user);
exports.getUser = factory.getOne(user);
exports.deleteUser = factory.deleteOne(user)
exports.UpdateUser = factory.updateOne(user);

handlerfactory.js

const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');
const APIFeatures = require('../utils/apiFeatures');

exports.deleteOne = (Model) =>
catchAsync(async (req, res, next) => {
const doc = await Model.findByIdAndDelete(req.params.id);

if (!doc) {
  return next(new AppError('No document found with that ID', 401));
  console.log('No document found with that ID');
}

res.status(204).json({
  status: 'success',
  data: null,
});
});

exports.updateOne = (Model) =>
catchAsync(async (req, res, next) => {
const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
  new: true,
  runValidators: true,
});

if (!doc) {
  return next(new AppError('No document found with that ID', 404));
}

res.status(200).json({
  status: 'success',
  data: {
    data: doc,
  },
});
});

Body:
I will answers my own question here because Daniel just come to my attention a silly mistake that I was making but I think it can still be useful to others.

If you just wanna one route per line use:

router.update('/:id', userController.updateOne);

If you are trying to use multiple routes in the same line do not forget to use .route like in the code below:

router.route('/:id').get(userController.getUser)
.delete(userController.deleteUser)
.patch(userController.UpdateUser);

Thank you very much, it may be silly but silly things happen with code every day.

Thank you all!


问:
Cannot change directory in psql on windows 10. PostgreSQL 11
I downloaded local PosgreSQL 11 on Windows 10.

I try to change directory in psql on command line window to c:\Program Files\PostgreSQL\11\bin>

I get either invalid command or directory does not exist

I tried following with

```<code>postgres=# cd c:\Program Files\PostgreSQL\11\bin
Invalid command \Program. Try \? for help.
postgres-# \cd c:\Program Files\PostgreSQL\11\bin
Invalid command \Program. Try \? for help.
postgres-# \cd..
Invalid command \cd... Try \? for help.
postgres-# \cd ..
postgres-# \cd Program Files
\cd: could not change directory to "Program": No such file or directory
</code>```

I'm not even sure about current directory as pwd is not recognized:

```<code>postgres-# \! pwd
'pwd' is not recognized as an internal or external command,
operable program or batch file.
</code>```

many thanks in advance

UPADATE: Figured out how to check current directory \! cd

Tried to run command this way \! C:\>cd C:\Program Files\PostgreSQL\11\bin

I get:

```<code>postgres-# \! C:\>cd C:\Program Files\PostgreSQL\11\bin
Access is denied.
</code>```

答:
You could try</p>
```<code>postgres=# \cd 'c:\\Program Files\\PostgreSQL\\11\\bin'
</code>```

Body:
I downloaded local PosgreSQL 11 on Windows 10.

I try to change directory in psql on command line window to c:\Program Files\PostgreSQL\11\bin>

I get either invalid command or directory does not exist

I tried following with

postgres=# cd c:\Program Files\PostgreSQL\11\bin
Invalid command \Program. Try \? for help.
postgres-# \cd c:\Program Files\PostgreSQL\11\bin
Invalid command \Program. Try \? for help.
postgres-# \cd..
Invalid command \cd... Try \? for help.
postgres-# \cd ..
postgres-# \cd Program Files
\cd: could not change directory to "Program": No such file or directory

I'm not even sure about current directory as pwd is not recognized:

postgres-# \! pwd
'pwd' is not recognized as an internal or external command,
operable program or batch file.

many thanks in advance

UPADATE: Figured out how to check current directory \! cd

Tried to run command this way \! C:\>cd C:\Program Files\PostgreSQL\11\bin

I get:

postgres-# \! C:\>cd C:\Program Files\PostgreSQL\11\bin
Access is denied.

Body:
You could try

postgres=# \cd 'c:\\Program Files\\PostgreSQL\\11\\bin'


问:
Getting System.InvalidOperationException: Operation is not valid due to the current state of the object while consuming Service Bus message
I am getting the below exception stacktrace while deployed to env, it's working fine in my local:

```<code>servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive

servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive
 [INFO] System.InvalidOperationException: Operation is not valid due to the current state of the object.
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.OnReceiveAsync(Int32 maxMessageCount, TimeSpan serverWaitTime)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.<>c_DisplayClass64_0.<<ReceiveAsync>b_0>d.MoveNext()
 [INFO] — End of stack trace from previous location —
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(Int32 maxMessageCount, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.MessageReceivePump.<MessagePumpTaskAsync>b__11_0()
</code>```

My project is in .Net5.0 and downgrading is something I don't wanna do unless no options.like suggestedhere
Any suggestion/gudance will be highly appretiated.

Thanks in advance.

答:
From the error details, I believe this is due to a bug in the version of Microsoft.Azure.Amqp that is referenced by the legacy Service Bus package. (details can be found in #165)

Adding a direct reference to the Microsoft.Azure.Amqp package in your project should hoist the version and work around the issue.

It is worth noting that the Microsoft.Azure.ServiceBus package has been officially deprecated and is not advised for new development. It will continue to be supported for the foreseeable future, but will no longer be receiving enhancements or non-critical fixes.

If possible, we recommend moving to Azure.Messaging.ServiceBus.

Body:
I am getting the below exception stacktrace while deployed to env, it's working fine in my local:

servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive

servicebus.windows.net/poc.enterprisebus.contracts.events/updatedevent/Subscriptions/poc.Test.Worker during Receive
 [INFO] System.InvalidOperationException: Operation is not valid due to the current state of the object.
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.OnReceiveAsync(Int32 maxMessageCount, TimeSpan serverWaitTime)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.<>c_DisplayClass64_0.<<ReceiveAsync>b_0>d.MoveNext()
 [INFO] — End of stack trace from previous location —
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(Int32 maxMessageCount, TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.Core.MessageReceiver.ReceiveAsync(TimeSpan operationTimeout)
 [INFO]    at Microsoft.Azure.ServiceBus.MessageReceivePump.<MessagePumpTaskAsync>b__11_0()

My project is in .Net5.0 and downgrading is something I don't wanna do unless no options.like suggestedhere
Any suggestion/gudance will be highly appretiated.

Thanks in advance.


问:
User is loged/signed in but the screen does not change
I am working with Firebase authentication and lately was not able to do anything because of the following error. When I enter the user's credentials, it gets authenticated on the Firebase console, but my app's screen does not change. What's more, the following error appears in debug console.

2 I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false
I/SurfaceControl(26261): nativeRelease nativeObject
s[-5476376676702711408] I/SurfaceControl(26261): nativeRelease
nativeObject e[-5476376676702711408] W/System  (26261): Ignoring
header X-Firebase-Locale because its value was null. 2
I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false

```<code>void authUser(
      String email, String password, String conPassword, bool isLogin) async {
    UserCredential authResult;
    setState(() {
      isLoading = true;
    });
    FocusScope.of(context).unfocus();
    try {
      if (password != conPassword && isLogin == false) {
        showDialog(
          context: context,
          builder: (_) => const AlertDialog(
            title: Text('Passwords don\'t match'),
            content: Text('Please check if your passwords match'),
          ),
        );
      }

      if (isLogin == false) {
        authResult = await firebaseAuth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await firebaseAuth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      }

      setState(() {
        isLoading = false;
      });
    } catch (e) {
      rethrow;
    }
  }
</code>```

...

```<code>TextFormField(
                  key: const ValueKey('email'),
                  keyboardType: TextInputType.emailAddress,
                  decoration: const InputDecoration(
                    label: Text('Email adress'),
                  ),
                  onSaved: (newValue) {
                    email = newValue!;
                    FocusScope.of(context).requestFocus(_passwordNode);
                  },
                ),
                TextFormField(
                  key: const ValueKey('password'),
                  focusNode: _passwordNode,
                  obscureText: true,
                  onSaved: (newValue) {
                    password = newValue!;
                    FocusScope.of(context).requestFocus(_conPasswordNode);
                  },
                  decoration: const InputDecoration(
                    label: Text('Password'),
                  ),
                ),
                if (isLogin == false)
                  TextFormField(
                    key: const ValueKey('conPassword'),
                    focusNode: _conPasswordNode,
                    obscureText: true,
                    decoration: const InputDecoration(
                      label: Text('Confirm password'),
                    ),
                    onSaved: (newValue) {
                      conPassword = newValue!;
                    },
                  ),
                Expanded(
                  child: Container(),
                ),
                widget.isLoading == true
                    ? const Center(
                        child: CircularProgressIndicator(),
                      )
                    : ButtonBar(
                        alignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              setState(() {
                                isLogin = !isLogin;
                              });
                            },
                            child: Text(isLogin == true ? 'SignUp' : 'Login'),
                          ),
                          ElevatedButton(
                            onPressed: _trySubmit,
                            child: const Text('Done'),
                          ),
                        ],
                      ),

   ...
    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: Firebase.initializeApp(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              }
              return MultiProvider(
                providers: [
                  ChangeNotifierProvider(
                    create: (ctx) => RecipeProvider(),
                  ),

  ],
            child: MaterialApp ...
             home: StreamBuilder<User?>(
                  stream: FirebaseAuth.instance.authStateChanges(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const CircularProgressIndicator();
                    }
                    if (snapshot.hasData) {
                      return AllRecipesScreen();
                    }
                    return AuthScreen();
                  }),
              routes: {
                AllRecipesScreen.routeName: (ctx) => AllRecipesScreen(),
                RecipeDetailScreen.routeName: (ctx) => RecipeDetailScreen(),
                AddRecipeScreen.routeName: (ctx) => AddRecipeScreen(),
                AuthScreen.routeName: (ctx) => AuthScreen(),
              },
            ),
          );
        });
  }
}
</code>```

答:
The code seems to be quite incomplete to conclude anything out of it.
And as much as I know the logs that you have provided are not errors , it is just that way and are printed every-time. I don't think your main issue seems to be firebase authentication. It may be an issue of navigation(or a wrapper if you're using one).

Body:
I am working with Firebase authentication and lately was not able to do anything because of the following error. When I enter the user's credentials, it gets authenticated on the Firebase console, but my app's screen does not change. What's more, the following error appears in debug console.

2 I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false
I/SurfaceControl(26261): nativeRelease nativeObject
s[-5476376676702711408] I/SurfaceControl(26261): nativeRelease
nativeObject e[-5476376676702711408] W/System  (26261): Ignoring
header X-Firebase-Locale because its value was null. 2
I/System.out(26261): (HTTPLog)-Static: isSBSettingEnabled false

void authUser(
      String email, String password, String conPassword, bool isLogin) async {
    UserCredential authResult;
    setState(() {
      isLoading = true;
    });
    FocusScope.of(context).unfocus();
    try {
      if (password != conPassword && isLogin == false) {
        showDialog(
          context: context,
          builder: (_) => const AlertDialog(
            title: Text('Passwords don\'t match'),
            content: Text('Please check if your passwords match'),
          ),
        );
      }

      if (isLogin == false) {
        authResult = await firebaseAuth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await firebaseAuth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      }

      setState(() {
        isLoading = false;
      });
    } catch (e) {
      rethrow;
    }
  }

...

TextFormField(
                  key: const ValueKey('email'),
                  keyboardType: TextInputType.emailAddress,
                  decoration: const InputDecoration(
                    label: Text('Email adress'),
                  ),
                  onSaved: (newValue) {
                    email = newValue!;
                    FocusScope.of(context).requestFocus(_passwordNode);
                  },
                ),
                TextFormField(
                  key: const ValueKey('password'),
                  focusNode: _passwordNode,
                  obscureText: true,
                  onSaved: (newValue) {
                    password = newValue!;
                    FocusScope.of(context).requestFocus(_conPasswordNode);
                  },
                  decoration: const InputDecoration(
                    label: Text('Password'),
                  ),
                ),
                if (isLogin == false)
                  TextFormField(
                    key: const ValueKey('conPassword'),
                    focusNode: _conPasswordNode,
                    obscureText: true,
                    decoration: const InputDecoration(
                      label: Text('Confirm password'),
                    ),
                    onSaved: (newValue) {
                      conPassword = newValue!;
                    },
                  ),
                Expanded(
                  child: Container(),
                ),
                widget.isLoading == true
                    ? const Center(
                        child: CircularProgressIndicator(),
                      )
                    : ButtonBar(
                        alignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              setState(() {
                                isLogin = !isLogin;
                              });
                            },
                            child: Text(isLogin == true ? 'SignUp' : 'Login'),
                          ),
                          ElevatedButton(
                            onPressed: _trySubmit,
                            child: const Text('Done'),
                          ),
                        ],
                      ),

   ...
    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: Firebase.initializeApp(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              }
              return MultiProvider(
                providers: [
                  ChangeNotifierProvider(
                    create: (ctx) => RecipeProvider(),
                  ),

  ],
            child: MaterialApp ...
             home: StreamBuilder<User?>(
                  stream: FirebaseAuth.instance.authStateChanges(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const CircularProgressIndicator();
                    }
                    if (snapshot.hasData) {
                      return AllRecipesScreen();
                    }
                    return AuthScreen();
                  }),
              routes: {
                AllRecipesScreen.routeName: (ctx) => AllRecipesScreen(),
                RecipeDetailScreen.routeName: (ctx) => RecipeDetailScreen(),
                AddRecipeScreen.routeName: (ctx) => AddRecipeScreen(),
                AuthScreen.routeName: (ctx) => AuthScreen(),
              },
            ),
          );
        });
  }
}


问:
angular - displaying details in mat-table - problem creating multiple tables in multiple records
I have a code structure in angular html as follows.
It creates more than one table when more than one record arrives, how can I prevent this?

```<code>  <div *ngFor="let item of materialsDetails" >
    <ng-container *ngFor="let subItem of item.materialDemandDetails">
      <table mat-table [dataSource]="materialsDetails" class="mat-elevation-z8">

        <ng-container matColumnDef="id">
          <th mat-header-cell *matHeaderCellDef> Id </th>
          <td mat-cell *matCellDef="let element"> {{subItem.id}}</td>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
    </ng-container>
  </div>
</code>```

I get the data, I transfer it to the table, but more than one "ID" field occurs as in the bottom picture, how can I prevent this?

I want to show data in material Demand Details in table. but too many columns occur

```<code>[
  {
    "description": "Ram demand.",
    "createdUserId": "12345",
    "createdUserName": "creater",
    "status": "idle",
    "companyId": 2,
    "materialDemandId": 0,
    "materialDemandDetails": [
      {
        "stockName": "Ram 12 gb products",
        "totalDemand": 2,
        "materialDemandId": 1,
        "productId": 2,
        "id": 1,
        "createdDate": "2022-02-08T14:29:11.1763481",
        "updatedDate": "2022-02-08T11:28:42.409",
        "totalCount": 0,
        "companyId": 0
      },
      {
        "stockName": "Ram 2 gb products",
        "totalDemand": 2,
        "materialDemandId": 1,
        "productId": 1,
        "id": 3,
        "createdDate": "2022-02-08T14:32:09.7305862",
        "updatedDate": "2022-02-08T11:28:42.409",
        "totalCount": 0,
        "companyId": 0
      }
    ],
    "id": 1,
    "createdDate": "2022-02-08T14:28:33.0658772",
    "updatedDate": "2022-02-08T11:27:46.939",
    "totalCount": 0
  }
]
</code>```

A json data is coming as below

Master json

details

mat-table view

Models .

```<code>import {MaterialDemandDetailsModel} from "./material-demand-details-model/material-demand-details-model";

export class MaterialDemandWithDetailModel {
  id: number | undefined;
  description: string | undefined;
  createdUserId: string | undefined;
  createdUserName: string | undefined;
  status: string | undefined;
  companyId: string | undefined;
  totalCount: number | undefined;

  materialDemandDetails: MaterialDemandDetailsModel[] | any; //MaterialDemandDetailsModel[] | undefined;
}

export class MaterialDemandDetailsModel {
  id: number | undefined;
  totalDemand: number | undefined;
  stockName: string | undefined;
  materialDemandId: number | undefined;
  productId: number | undefined;
  createdDate:Date | undefined;
  updatedDate: Date | undefined;
}
</code>```

答:
Remove the second *ngFor and change data source to materialDemandDetails instead of materialsDetails. Change subItem.id also to element.id.
You don't have to iterate through materialDemandDetails array, but give this array as data source for your table as:

```<code><div *ngFor="let item of materialsDetails" >
      <table mat-table [dataSource]="item.materialDemandDetails" class="mat-elevation-z8">

        <ng-container matColumnDef="id">
          <th mat-header-cell *matHeaderCellDef> Id </th>
          <td mat-cell *matCellDef="let element"> {{element.id}}</td>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
  </div>
</code>```

stackblitz link: https://stackblitz.com/edit/material-table-responsive-zepz3z?file=src%2Fapp%2Ftable-basic-example.html

Body:
I have a code structure in angular html as follows.
It creates more than one table when more than one record arrives, how can I prevent this?

    <ng-container *ngFor="let subItem of item.materialDemandDetails">

        <ng-container matColumnDef="id">
           Id
           {{subItem.id}}
        </ng-container>

    </ng-container>

I get the data, I transfer it to the table, but more than one "ID" field occurs as in the bottom picture, how can I prevent this?

I want to show data in material Demand Details in table. but too many columns occur

[
  {
    "description": "Ram demand.",
    "createdUserId": "12345",
    "createdUserName": "creater",
    "status": "idle",
    "companyId": 2,
    "materialDemandId": 0,
    "materialDemandDetails": [
      {
        "stockName": "Ram 12 gb products",
        "totalDemand": 2,
        "materialDemandId": 1,
        "productId": 2,
        "id": 1,
        "createdDate": "2022-02-08T14:29:11.1763481",
        "updatedDate": "2022-02-08T11:28:42.409",
        "totalCount": 0,
        "companyId": 0
      },
      {
        "stockName": "Ram 2 gb products",
        "totalDemand": 2,
        "materialDemandId": 1,
        "productId": 1,
        "id": 3,
        "createdDate": "2022-02-08T14:32:09.7305862",
        "updatedDate": "2022-02-08T11:28:42.409",
        "totalCount": 0,
        "companyId": 0
      }
    ],
    "id": 1,
    "createdDate": "2022-02-08T14:28:33.0658772",
    "updatedDate": "2022-02-08T11:27:46.939",
    "totalCount": 0
  }
]

A json data is coming as below

Master json

details

mat-table view

Models .

import {MaterialDemandDetailsModel} from "./material-demand-details-model/material-demand-details-model";

export class MaterialDemandWithDetailModel {
  id: number | undefined;
  description: string | undefined;
  createdUserId: string | undefined;
  createdUserName: string | undefined;
  status: string | undefined;
  companyId: string | undefined;
  totalCount: number | undefined;

  materialDemandDetails: MaterialDemandDetailsModel[] | any; //MaterialDemandDetailsModel[] | undefined;
}

export class MaterialDemandDetailsModel {
  id: number | undefined;
  totalDemand: number | undefined;
  stockName: string | undefined;
  materialDemandId: number | undefined;
  productId: number | undefined;
  createdDate:Date | undefined;
  updatedDate: Date | undefined;
}

Body:
Remove the second *ngFor and change data source to materialDemandDetails instead of materialsDetails. Change subItem.id also to element.id.
You don't have to iterate through materialDemandDetails array, but give this array as data source for your table as:

<div *ngFor="let item of materialsDetails" >
      <table mat-table [dataSource]="item.materialDemandDetails" class="mat-elevation-z8">

        <ng-container matColumnDef="id">
          <th mat-header-cell *matHeaderCellDef> Id </th>
          <td mat-cell *matCellDef="let element"> {{element.id}}</td>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
  </div>

stackblitz link: https://stackblitz.com/edit/material-table-responsive-zepz3z?file=src%2Fapp%2Ftable-basic-example.html


问:
UTF-8 to Unicode Code Points
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

```<code>function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}
</code>```

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032

答: I once created a function called _convert() which encodes safely everything to UTF-8.</p>

Title: UTF-8 to Unicode Code Points

Body:
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032


问:
What HTTP code do you get if an SSL has expired?
I have a custom monitor code setup. I need to check if the specified URL has its SSL certificate expired. Is there a specific HTTP code for this? For example:

(async() => {
    const res = await fetch('http://example.com');
    // Or `statusText`
    if (res.status == some_ssl_expiryCode) {
        console.log('SSL expired!');
    }
})();
```

Is there a way to do this in javascript?

答: The client application receives an HTTP 400 - Bad request response with the message "The SSL certificate error".</p>

Body:
I have a custom monitor code setup. I need to check if the specified URL has its SSL certificate expired. Is there a specific HTTP code for this? For example:

(async() => {
    const res = await fetch('http://example.com');
    // Or `statusText`
    if (res.status == some_ssl_expiryCode) {
        console.log('SSL expired!');
    }
})();

Is there a way to do this in javascript?


问:
SQL Dynamic Exchange Rate
I'm trying to create a stored procedure that provided the exchange rate based on the users selection.

When I simply type this query, it works fine:

```<code>SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = 'GBP'
</code>```

However when I try to transfer this into a stored procedure:

```<code>ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS
BEGIN

    SET NOCOUNT ON;

EXEC('

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = ' + @CCY + '

    ')

END
</code>```

I get the following error message and I can't work out why.

答:
You don't need Dynamic SQL at all here, the reason you are getting the error is because you are. As you have confirmed that the statement you have is literally all you have (there isn't a hidden requirement) just use your non-dynamic statement in your procedure:

ALTER PROCEDURE [dbo].[TEST] (@CCY char(3)) AS
BEGIN

    SET NOCOUNT ON;

    SELECT RATE
    FROM USERCONFIG.dbo.curr
    WHERE CODE = @CCY;

END;
```

Title: SQL Dynamic Exchange Rate

Body:
I'm trying to create a stored procedure that provided the exchange rate based on the users selection.

When I simply type this query, it works fine:

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = 'GBP'

However when I try to transfer this into a stored procedure:

ALTER PROCEDURE [dbo].[TEST] (@CCY char(3))

AS
BEGIN

    SET NOCOUNT ON;

EXEC('

SELECT RATE

FROM USERCONFIG.dbo.curr

WHERE CODE = ' + @CCY + '

    ')

END

I get the following error message and I can't work out why.