问:
Do destructors affect performance?
I have added a destructor to one of my base classes which I use to help hunt for memory leaks like so:

```<code>#if DEBUG
~BaseViewModel()
{
    Debug.WriteLine("View Model Disposed");
}
#endif
</code>```

Even removing the Debug.WriteLine code

Will having the destructor present affect performance for a debug build?

答:
According to Microsoft Documentation

Empty finalizers should not be used. When a class contains a
  finalizer, an entry is created in the Finalize queue. When the
  finalizer is called, the garbage collector is invoked to process the
  queue. An empty finalizer just causes a needless loss of performance.

You need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose. Otherwise it will cause your objects resides in memory for longer, because they will be added to the finalizer queue. (Note: Read how Finalization works).

Title: Do destructors affect performance?

Body:
I have added a destructor to one of my base classes which I use to help hunt for memory leaks like so:

#if DEBUG
~BaseViewModel()
{
    Debug.WriteLine("View Model Disposed");
}
#endif

Even removing the Debug.WriteLine code

Will having the destructor present affect performance for a debug build?


来源: stackexchange

问:
Can the time to live (TTL) for a memcached key be set to infinite?
I have implemented memcache in my PHP-MySQL based app and it gets updated regularly from a backend process.

Due to this some data is conflicting with the expiration time and other backend processes, so I came up with a solution but for that I would have to make the TTL = infinite.

答:
Easy - just write 0 there.

expire

Expiration time of the item. If it's
  equal to zero, the item will never
  expire. You can also use Unix
  timestamp or a number of seconds
  starting from current time, but in the
  latter case the number of seconds may
  not exceed 2592000 (30 days).

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
.NET Model item shows up in Input box but not in link
I have a Url that I want to generate like this:

```<code>@Html.HiddenFor(m=>m.Id)
@Html.TextBoxFor(x=>x.Id)
@{ var cancel = Url.Action("Index", "KeySetting", new { area = "Document"})+"&Id="+@Model.Id; }
</code>```

However, when I load the page, my TextBox is not empty but my url.action is missing the Model.Id value.

I have also tried this:

```<code>@Html.ActionLink("Cancel", "Index", "KeySetting", new { area = "Document", Id = @Model.Id }, new { @class = "btn btn-outline-secondary" })
</code>```

But my Id doesn't appear as well. Why?

EDIT: Route Settings

```<code>        app.UseMvc(routes =>
        {
            routes.MapRoute(
              name: "areas",
              template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            );
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

        });
</code>```

答:
No idea why this is not working but this is the best I could come up with. Its not pretty but it works for now. If anyone has a better idea I'll change the tick over to them.

This is what I did:

```<code><script>
    $(document).ready(function (e) {
        var link = $("#@Html.IdFor(x=>x.Id)").val();
        $("#cancel").attr("href", "@Url.Action("Index", "KeySetting", new { area = "Document" })?Id=" + link);
    })
</script>
<a class="btn btn-outline-secondary" id="cancel" href="#">Cancel</a>
</code>```

Body:
I have a Url that I want to generate like this:

@Html.HiddenFor(m=>m.Id)
@Html.TextBoxFor(x=>x.Id)
@{ var cancel = Url.Action("Index", "KeySetting", new { area = "Document"})+"&Id="+@Model.Id; }

However, when I load the page, my TextBox is not empty but my url.action is missing the Model.Id value.

I have also tried this:

@Html.ActionLink("Cancel", "Index", "KeySetting", new { area = "Document", Id = @Model.Id }, new { @class = "btn btn-outline-secondary" })

But my Id doesn't appear as well. Why?

EDIT: Route Settings

        app.UseMvc(routes =>
        {
            routes.MapRoute(
              name: "areas",
              template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            );
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

        });

Body:
No idea why this is not working but this is the best I could come up with. Its not pretty but it works for now. If anyone has a better idea I'll change the tick over to them.

This is what I did:

<script>
    $(document).ready(function (e) {
        var link = $("#@Html.IdFor(x=>x.Id)").val();
        $("#cancel").attr("href", "@Url.Action("Index", "KeySetting", new { area = "Document" })?Id=" + link);
    })
</script>
<a class="btn btn-outline-secondary" id="cancel" href="#">Cancel</a>


问:
Cakephp: How to get a list of the database table names using Twig
I am creating a bake template using Twig for a cakePHP project. All what I want is to access the tables names of the database and their fields using twig to generate code based on these tables and fields.

I could easily access the tables names using (BUT THIS IS NOT WHAT I WANT)

```<code>use Cake\Datasource\ConnectionManager;

$db = ConnectionManager::get('default');
$collection = $db->getSchemaCollection();
$listTables = $collection->listTables();
</code>```

I want to write something like that

```<code>{% set db = ConnectionManager.get('default') %}
{% set collection = db.getSchemaCollection() %}
{% set listTables = collection.listTables() %}
</code>```

答:
You can't use PHP Class or functions in twig directly. Also it's not best practice to use it this way.

Best solutions are:

Recommended: Put your login into the controller and pass the variable into the twig file. See passing variable section in the documentation here.

Another way you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too. Refer to this answer here.

Body:
I am creating a bake template using Twig for a cakePHP project. All what I want is to access the tables names of the database and their fields using twig to generate code based on these tables and fields.

I could easily access the tables names using (BUT THIS IS NOT WHAT I WANT)

use Cake\Datasource\ConnectionManager;

$db = ConnectionManager::get('default');
$collection = $db->getSchemaCollection();
$listTables = $collection->listTables();

I want to write something like that

{% set db = ConnectionManager.get('default') %}
{% set collection = db.getSchemaCollection() %}
{% set listTables = collection.listTables() %}


问:
Citrus Framework - echo action does not "echo"
I am attempting to debug/trace an integration test written with the Citrus Framework. Among the various test "actions" that can be taken, there is an echo action which is supposed to do what you might expect: echo something to the console log. The problem is: it does not echo.

When I run the integration test (via Maven failsafe plugin), errors from the test failing appear on the console, but nothing else.

What am I missing?

UPDATE:

This appears to only be a problem when running the integration tests as part of a maven build. When the test is run from eclipse, the complete console log appears.

答:
This may be an issue with your test names. Failsafe Maven plugin by default has a naming convention and only runs those tests that follow this convention. So your test names must match a pattern.

Please review the default naming pattern in failsafe plugin and see if this fixes your issue.


问:
Show space, tab, CRLF characters in editor of Visual Studio
Where are the settings to show a space, tab, paragraph, CRLF, etc. (extended) characters?

答:
For Visual Studio for mac, you can find it under Visual Studio -> Preferences -> Text Editor -> Markers and Rulers -> Show invisible characters

Please note you may need to restart Visual Studio for the changes to take effect


问:
Flutter & Redis client
I have (Chat) Flutter mobile app which uses Lumen as backend. However, I want to cache some things and would like to use Redis for this purpose. Is there a way how Flutter app can speak with Redis? Should I install some package for this or make HTTP request for every caching?

My goal is to store last conversation message.

On backend side I can do something like this:

```<code>Redis::hSet('chat1', 'message', 'hello');
</code>```

But I am not sure how this is going to affect performance... Therefore it would be better to have Redis client on Frontend side (Flutter).

答:
You can use package https://pub.dev/packages/redis

This package is Redis client for Dart

code snippet

```<code>import 'package:redis/redis.dart';
...
RedisConnection conn = new RedisConnection();
conn.connect('localhost',6379).then((Command command){
    command.send_object(["SET","key","0"]).then((var response)
        print(response);
    )
}
</code>```

Title: Flutter & Redis client

Body:
I have (Chat) Flutter mobile app which uses Lumen as backend. However, I want to cache some things and would like to use Redis for this purpose. Is there a way how Flutter app can speak with Redis? Should I install some package for this or make HTTP request for every caching?

My goal is to store last conversation message.

On backend side I can do something like this:

Redis::hSet('chat1', 'message', 'hello');

But I am not sure how this is going to affect performance... Therefore it would be better to have Redis client on Frontend side (Flutter).

Body:
You can use package https://pub.dev/packages/redis

This package is Redis client for Dart

code snippet

import 'package:redis/redis.dart';
...
RedisConnection conn = new RedisConnection();
conn.connect('localhost',6379).then((Command command){
    command.send_object(["SET","key","0"]).then((var response)
        print(response);
    )
}


问:
Javascript get status from service
I develop a web application that is getting user updates from a web service (that is in another domain) I want to get the updates every 10 seconds.

For calling the service for the first time I dynamically insert a script in the page. The service is JSONP. Then I would like to define a trigger that insert a script from 10 to 10 seconds to get the updates. Is this correct? Can I do that without affecting the user experience on the website? I mean the site performance ... it will be great if I could do the call async and when I have the results I will update the status.

Is there any better solution for accessing the remote services. Is there an efficient way of dynamically reusing the same script using a trigger? I am pretty new to Javascript. Can you give me a short sample how can I define a trigger that calls a remote web service? ... or if there is a better solution.

答:
I suggest that in your AJAX callback, when you get the result, you schedule a timer (window.setTimeout(ex, t)) so that your updating script is called again.

The reason to set the time in the AJAX callback is that you don't know exactly how long it will take for the AJAX call to complete. In this way, you ensure a smooth 10 sec delay between successive updates.

About performance, you will have to check that. It depends on the amount of data and the kind of processing you do of it (and the rest of your page)... but you can try it and check processor usage...

Title: Javascript get status from service


问:
Jest - ReferenceError: imported function is not defined
I have been at this for 2 hours now, but couldn't figure out what I am doing wrong. I have following jest+puppeteer test:

import {convert} from '../__helpers__/number';

const getAmount = async (page) => {
  const element = await page.waitForSelector('.my-element');

  return element.evaluate((node) => convert(node.innerText));
}
```

<p>which is very simple and straight forward. But it keeps failing with following error:</p>

```Error: Evaluation failed: ReferenceError: _number is not defined
          at __puppeteer_evaluation_script__:2:15
          at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/ExecutionContext.js:122:13)
        -- ASYNC --
          at ExecutionContext.<anonymous> (node_modules/puppeteer/lib/helper.js:111:15)
          at ElementHandle.evaluate (node_modules/puppeteer/lib/JSHandle.js:55:42)
          at ElementHandle.evaluate (node_modules/puppeteer/lib/helper.js:112:23)
          at _callee$ (__tests__/e2e/test.spec.js:13:27)
          at tryCatch (node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:45:40)
          at Generator.invoke [as _invoke] (node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:271:22)
          at Generator.prototype.(anonymous function) [as next] (node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:97:21)
          at asyncGeneratorStep (__tests__/e2e/test.spec.js:30:103)
          at _next (__tests__/e2e/test.spec.js:32:194)
```

<p>The above line number don't match with the source code .. and from the error it looked like it is failing from the transpiled code. So I went to the <code>jest-transform-cache</code> location and looked at the file, and the line numbers don't match that either; they are all off by 1. The transpiled code also had the updated output and had following line:</p>

```var _number = require('../__helpers__/number');
```

<p>I tried debugging in all the ways I could think of:</p>

<ul>
<li>cleared cache</li>
<li>tried renaming the file</li>
<li>restarted the system</li>
<li>ran the test in different system</li>
<li>running jest with no cache etc</li>
</ul>

<p>Also tried this:</p>

<pre class="lang-js prettyprint-override"><code>// import {convert} from '../__helpers__/number';

const convert = (text) => magic(text); // for simplicity's sake

const getAmount = async (page) => {
  const element = await page.waitForSelector('.my-element');

  return element.evaluate((node) => convert(node.innerText));
}
</code>```

Now it fails with following error:

```<code>Evaluation failed: ReferenceError: convert is not defined

      at __puppeteer_evaluation_script__:2:15
      at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/ExecutionContext.js:122:13)
.
:
</code>```

Thought I would throw it here to see if anyone else run into this weirdness. It shouldn't fail by any norms, and I can't figure it out at all. Please help me! Any ideas/direction would be greatly appreciated.

Thank you!

答:
you need to pass convert function in as parameter of elementHandle.evaluate(pageFunction[, ...args]) like this: </p>

```<code>import {convert} from '../__helpers__/number';

const getAmount = async (page) => {
  const element = await page.waitForSelector('.my-element');

return element.evaluate((node, convert) => convert(node.innerText), convert);
}
</code>```

Body:
I have been at this for 2 hours now, but couldn't figure out what I am doing wrong. I have following jest+puppeteer test:

import {convert} from '../__helpers__/number';

const getAmount = async (page) => {
  const element = await page.waitForSelector('.my-element');

  return element.evaluate((node) => convert(node.innerText));
}

which is very simple and straight forward. But it keeps failing with following error:

Error: Evaluation failed: ReferenceError: _number is not defined
          at __puppeteer_evaluation_script__:2:15
          at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/ExecutionContext.js:122:13)
        -- ASYNC --
          at ExecutionContext.<anonymous> (node_modules/puppeteer/lib/helper.js:111:15)
          at ElementHandle.evaluate (node_modules/puppeteer/lib/JSHandle.js:55:42)
          at ElementHandle.evaluate (node_modules/puppeteer/lib/helper.js:112:23)
          at _callee$ (__tests__/e2e/test.spec.js:13:27)
          at tryCatch (node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:45:40)
          at Generator.invoke [as _invoke] (node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:271:22)
          at Generator.prototype.(anonymous function) [as next] (node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:97:21)
          at asyncGeneratorStep (__tests__/e2e/test.spec.js:30:103)
          at _next (__tests__/e2e/test.spec.js:32:194)

The above line number don't match with the source code .. and from the error it looked like it is failing from the transpiled code. So I went to the jest-transform-cache location and looked at the file, and the line numbers don't match that either; they are all off by 1. The transpiled code also had the updated output and had following line:

var _number = require('../__helpers__/number');

I tried debugging in all the ways I could think of:

cleared cache

tried renaming the file

restarted the system

ran the test in different system

running jest with no cache etc

Also tried this:

// import {convert} from '../__helpers__/number';

const convert = (text) => magic(text); // for simplicity's sake

const getAmount = async (page) => {
  const element = await page.waitForSelector('.my-element');

  return element.evaluate((node) => convert(node.innerText));
}

Now it fails with following error:

Evaluation failed: ReferenceError: convert is not defined

      at __puppeteer_evaluation_script__:2:15
      at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/ExecutionContext.js:122:13)
.
:

Thought I would throw it here to see if anyone else run into this weirdness. It shouldn't fail by any norms, and I can't figure it out at all. Please help me! Any ideas/direction would be greatly appreciated.

Thank you!

Body:
you need to pass convert function in as parameter of elementHandle.evaluate(pageFunction[, ...args]) like this:

import {convert} from '../__helpers__/number';

const getAmount = async (page) => {
  const element = await page.waitForSelector('.my-element');

return element.evaluate((node, convert) => convert(node.innerText), convert);
}


问:
is it possible to create this dashboard in power BI?
I am just starting out with Power BI. So far it has been easy to learn. My goal is to create a dashboard like this:

https://dc-js.github.io/dc.js/

I am just wondering if someone knows an interactive power bi sample like this. Is it even possible to create such reports in power BI?

Thanks.

答: Yes, it is possible to create dashboards like this. See for example Power BI Embedded Playground or Microsoft Sales & Returns report (download or view in browser):


问:
axios get function not working in Reactjs
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

```<code>app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

</code>```

and I call the API in my reactjs page component

```<code>class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList
</code>```

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

答:
Error in destructuring, missed curly brace const { enduser_tbl }

```<code>render() {
        const { enduser_tbl = [] } = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
</code>```

For safe side:

```<code>const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( { data: enduser_tbl = [] } => {
            console.log(data)
            this.setState({
                enduser_tbl
            })
        })
</code>```

Body:
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

and I call the API in my reactjs page component

class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

Body:
Error in destructuring, missed curly brace const { enduser_tbl }

render() {
        const { enduser_tbl = [] } = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }

For safe side:

const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( { data: enduser_tbl = [] } => {
            console.log(data)
            this.setState({
                enduser_tbl
            })
        })


问:
Python - If/Elif statement (loops)
Can someone tell me why I'm getting 4 as the outcome? Should 3 be printing instead because the code is satisfied in the If section.</p>

```<code>a = 15

if a&5  == 0:
    print('3')
elif a% 5 == 0:
    print('4')

else:
    print('5')
</code>```

答:
The "&" operator is a Bitwise AND so in your code it is like:

```<code>1111 & 0101 = 0101
</code>```

That means

```<code>15 and 5 = 5
</code>```

So the first condition can not be true and you'll get 4 in output because the reminder of 15/5 is 0.

Title: Python - If/Elif statement (loops)

Body:
Can someone tell me why I'm getting 4 as the outcome? Should 3 be printing instead because the code is satisfied in the If section.

a = 15

if a&5  == 0:
    print('3')
elif a% 5 == 0:
    print('4')

else:
    print('5')

Body:
The "&" operator is a Bitwise AND so in your code it is like:

1111 & 0101 = 0101

That means

15 and 5 = 5

So the first condition can not be true and you'll get 4 in output because the reminder of 15/5 is 0.


问:
Angular 9 - The pipe 'keyvalue' could not be found
The pipe 'keyvalue' could not be found. in angular 9</p>

```<code>"@angular/animations": "^9.0.1",
    "@angular/common": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",

 <div *ngFor="let item of faqData | keyvalue; let i=index">
            {{item.key}}:{{item.value}}
          </div>
          <p>Map</p>
          <div *ngFor="let item of map | keyvalue">
            {{item.key}}:{{item.value}}
          </div>

 faqData = { id: 1, name: "Abdul Rafay" };
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);
</code>```

答:
It works fine with Angular9 and it should work fine with all versions of app using angular 6+.

However if you also can try the alternate way.

```<code> <div *ngFor="let prop of key">
          <div>key: {{prop}}</div>
          <div>value: {{faqData [prop]}}<div>
 </div>
</code>```

and then in TS

```<code> get key(){
    return Object.keys(this.faqData );
 }
</code>```

FIX:
OP found that he was missing CommonModule under the imports

Body:
The pipe 'keyvalue' could not be found. in angular 9

"@angular/animations": "^9.0.1",
    "@angular/common": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",

            {{item.key}}:{{item.value}}

Map

            {{item.key}}:{{item.value}}

 faqData = { id: 1, name: "Abdul Rafay" };
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);

Body:
It works fine with Angular9 and it should work fine with all versions of app using angular 6+.

However if you also can try the alternate way.

 <div *ngFor="let prop of key">
          <div>key: {{prop}}</div>
          <div>value: {{faqData [prop]}}<div>
 </div>

and then in TS

 get key(){
    return Object.keys(this.faqData );
 }

FIX:
OP found that he was missing CommonModule under the imports


问:
Finding out when an NSThread has finished
I have a few functions that I need to call when I press a button. I use [self getamountofdatacenters]; to call these functions. When I press the button, the simulator gets stuck until its done with all the functions, and this takes 5-7 seconds, so I'm trying to use NSThread:

```<code>[NSThread detachNewThreadSelector:@selector(GETAMOUNTDATACENTERS)
                         toTarget:self
                       withObject:nil];
</code>```

I'm doing this three times with different functions, but I want to find out what the progress is of an NSThread and to catch it when it's actually done. How can I do this? Thank you.

答:
Forget about explicit threads and use GCD:</p>

```<code>dispatch_async(dispatch_get_global_queue(0, NULL), ^{
    [self getNumberOfDataCenters];
    dispatch_sync(dispatch_get_main_queue(), ^{
        // The work is done, do whatever you need.
        // This code is executed on the main thread,
        // so that you can update the UI.
    });
});
</code>```

Body:
I have a few functions that I need to call when I press a button. I use [self getamountofdatacenters]; to call these functions. When I press the button, the simulator gets stuck until its done with all the functions, and this takes 5-7 seconds, so I'm trying to use NSThread:

[NSThread detachNewThreadSelector:@selector(GETAMOUNTDATACENTERS)
                         toTarget:self
                       withObject:nil];

I'm doing this three times with different functions, but I want to find out what the progress is of an NSThread and to catch it when it's actually done. How can I do this? Thank you.

Body:
Forget about explicit threads and use GCD:

dispatch_async(dispatch_get_global_queue(0, NULL), ^{
    [self getNumberOfDataCenters];
    dispatch_sync(dispatch_get_main_queue(), ^{
        // The work is done, do whatever you need.
        // This code is executed on the main thread,
        // so that you can update the UI.
    });
});


问:
Python: changing .py file to .exe
I need some help with changing .py file to .exe file. I am trying to do it with cx_Freeze module, i managed to do the setup.py file, the only problem is, i dont know what should i put in my command prompt?

setup.py file looks like this:

```<code>import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"include_files": ["postevanka.ui,beep.wav,gang.wav"]}

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "Poštevanka",
        version = "0.1",
        description = "Postevanka",
        options = {"build_exe": build_exe_options},
        executables = [Executable("postevanka.py", base=base)])
</code>```

答:
try using pyinstaller

in command window, cd to the folder where your python file is located and simply type the following command by replacing 'myscript.py' with the name of your python file

```<code>pyinstaller --onefile --windowed myscript.py
</code>```

this will create a new folder named "dist" in the current directory. This folder will contain the newly created exe file with the same name as your .py file

another option is to use the following command in the command window

```<code>pyinstaller myscript.py
</code>```

this will create a folder named after your python file inside the dist folder. the new folder will contain the exe file along with copies of all the modules and libraries you have used in your code and some additional files needed for the exe to run.

i suggest to use the first method which creates a single file which can be shared without any hassles.

refer https://pyinstaller.readthedocs.io/en/stable/operating-mode.html if you need more information regarding that.

Hope it helps!!

Title: Python: changing .py file to .exe

Body:
I need some help with changing .py file to .exe file. I am trying to do it with cx_Freeze module, i managed to do the setup.py file, the only problem is, i dont know what should i put in my command prompt?

setup.py file looks like this:

import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"include_files": ["postevanka.ui,beep.wav,gang.wav"]}

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "Poštevanka",
        version = "0.1",
        description = "Postevanka",
        options = {"build_exe": build_exe_options},
        executables = [Executable("postevanka.py", base=base)])

Body:
try using pyinstaller

in command window, cd to the folder where your python file is located and simply type the following command by replacing 'myscript.py' with the name of your python file

pyinstaller --onefile --windowed myscript.py

this will create a new folder named "dist" in the current directory. This folder will contain the newly created exe file with the same name as your .py file

another option is to use the following command in the command window

pyinstaller myscript.py

this will create a folder named after your python file inside the dist folder. the new folder will contain the exe file along with copies of all the modules and libraries you have used in your code and some additional files needed for the exe to run.

i suggest to use the first method which creates a single file which can be shared without any hassles.

refer https://pyinstaller.readthedocs.io/en/stable/operating-mode.html if you need more information regarding that.

Hope it helps!!


问:
String.replace(x,x,count => 1) in Python
I am new to python and learning it. In my project code I saw in the replace function the count is given in this format. When I run in Python editor it gives this error.

```<code>"Bharath..Bharath..Bharath".replace("..", ".", count => 1)
</code>```

SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/py_compile.py", line 147, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 1

    x="Bharath..Bharath..Bharath".replace("..", ".", count => 1)

                                                            ^
SyntaxError: invalid syntax
```

Can anyone tell me what this count => 1 means i understand that the last parameter is the no of occurrences to replace.

Thanks

答:
In Python this can be done very easily String.replace(StringToReplace, ReplaceWith, Count)

For your example

x="Bharath..Bharath..Bharath".replace("..", ".", 1)should work. Keywords like "count" dont work here.

So you were close to the solution. :)

Body:
I am new to python and learning it. In my project code I saw in the replace function the count is given in this format. When I run in Python editor it gives this error.

"Bharath..Bharath..Bharath".replace("..", ".", count => 1)

SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/py_compile.py", line 147, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 1

    x="Bharath..Bharath..Bharath".replace("..", ".", count => 1)

                                                            ^
SyntaxError: invalid syntax

Can anyone tell me what this count => 1 means i understand that the last parameter is the no of occurrences to replace.

Thanks


问:
Using imported interceptor on controller not working in nestjs
I like to organise my project along feature lines with different modules for cross cutting concerns eg: configuration, authentication, etc. However when importing an Interceptor into a feature module for use with a Controller Nest doesn't seem to reuse the existing instance.

controllers.module.ts

@Module({
  imports: [
    // ConfigService is exported from this module.
    ConfigModule
  ],
  providers: [
    // For debugging purposes I used a factory so I could place a breakpoint and see
    // when the Interceptor is being created.
    {
      provide: MyInterceptor,
      useFactory: (config: ConfigService) => new MyInterceptor(config),
      inject: [
        ConfigService
      ]
    }
  ],
  exports: [
    MyInterceptor
  ]
})
export class ControllersModule {

}
```

<p><strong><code>customer.module.ts</code></strong></p>

<pre class="lang-js prettyprint-override"><code>@Module({
  imports: [
    ControllersModule
  ],
  controllers: [
    CustomerController
  ],
  providers: [
    CustomerService
  ]
})
export class CustomerModule {

}
</code>```

customer.controller.ts

@Controller("/customers")
@UseInterceptors(MyInterceptor)
export class CustomerController {
  constructor(private readonly customerService: CustomerService) {

  }

  @Get()
  customers() {
    return this.customerService.findAll();
  }
}
```

<p>When the application starts up, I can see the <code>MyInterceptor</code> provider factory being called, with an instance of <code>ConfigService</code>. However then I see the following error on the console</p>

```error: [ExceptionHandler] Nest can't resolve dependencies of the MyInterceptor (?). Please make sure that the argument ConfigService at index [0] is available in the CustomerModule context.

Potential solutions:
- If ConfigService is a provider, is it part of the current CustomerModule?
- If ConfigService is exported from a separate @Module, is that module imported within CustomerModule?
  @Module({
    imports: [ /* the Module containing ConfigService */ ]
  })
```

Now maybe there's something about how Nest instantiates/uses Interceptors that I'm not understanding but I thought that given that MyInteceptor had been created, and the ControllersModule imported by CustomerModule that the bean would have been available and applied to CustomerController.

Is there something I'm missing here?

答:
Interceptors (along with other request lifecycle classes) are kinda like pseudoproviders in that that are @Injectable() but they aren't added to a providers array for binding. You can bind then via the providers array, (APP_INTERCEPTOR) but that will cause it to be bound globally.

Because interceptors can't be added to a providers array the way you are trying, you need to instead add the ConfigModule to whatever module uses the interceptor.

Body:
I like to organise my project along feature lines with different modules for cross cutting concerns eg: configuration, authentication, etc. However when importing an Interceptor into a feature module for use with a Controller Nest doesn't seem to reuse the existing instance.

controllers.module.ts

@Module({
  imports: [
    // ConfigService is exported from this module.
    ConfigModule
  ],
  providers: [
    // For debugging purposes I used a factory so I could place a breakpoint and see
    // when the Interceptor is being created.
    {
      provide: MyInterceptor,
      useFactory: (config: ConfigService) => new MyInterceptor(config),
      inject: [
        ConfigService
      ]
    }
  ],
  exports: [
    MyInterceptor
  ]
})
export class ControllersModule {

}

customer.module.ts

@Module({
  imports: [
    ControllersModule
  ],
  controllers: [
    CustomerController
  ],
  providers: [
    CustomerService
  ]
})
export class CustomerModule {

}

customer.controller.ts

@Controller("/customers")
@UseInterceptors(MyInterceptor)
export class CustomerController {
  constructor(private readonly customerService: CustomerService) {

  }

  @Get()
  customers() {
    return this.customerService.findAll();
  }
}

When the application starts up, I can see the MyInterceptor provider factory being called, with an instance of ConfigService. However then I see the following error on the console

error: [ExceptionHandler] Nest can't resolve dependencies of the MyInterceptor (?). Please make sure that the argument ConfigService at index [0] is available in the CustomerModule context.

Potential solutions:
- If ConfigService is a provider, is it part of the current CustomerModule?
- If ConfigService is exported from a separate @Module, is that module imported within CustomerModule?
  @Module({
    imports: [ /* the Module containing ConfigService */ ]
  })

Now maybe there's something about how Nest instantiates/uses Interceptors that I'm not understanding but I thought that given that MyInteceptor had been created, and the ControllersModule imported by CustomerModule that the bean would have been available and applied to CustomerController.

Is there something I'm missing here?


问:
How does Interval keyword work in Oracle?
I have 2 queries :

```<code>SELECT 300*interval '1' HOUR FROM DUAL  --   0 5:0:0.0 (Output)

SELECT 300* interval '1' minute FROM DUAL -- 12 12:0:0.0(Output)
</code>```

I am unable to get how is the interval Keyword working and what is the format of the Output produced ?

答:
It is the best to always know all of your participants of multiplication or any other math operation to undesrstand it.

'1' HOUR

```<code>select interval '1' HOUR from dual;
</code>```

will return 1 hour, then you multiple it with number 300 and you will get:

```<code>+000000012 12:00:00.000000000
</code>```

Because (300 * 1) / 24 = 12.5. or 12 days and 12 hours.

'1' minute

The same thing happend with minutes where your result is 5 hours. This query :

```<code>select interval '1' minute FROM DUAL
</code>```

will return 1 minute and then you multiple it with number 300 to get this:

```<code>+000000000 05:00:00.000000000
</code>```

Because (300 * 1) / 60 = 5 or 5 hours.
Here is a demo

P.S.

Depending on the tool you use you can see this results as:

+12 12:00:00.000000

+00 05:00:00.000000

Body:
I have 2 queries :

SELECT 300*interval '1' HOUR FROM DUAL  --   0 5:0:0.0 (Output)

SELECT 300* interval '1' minute FROM DUAL -- 12 12:0:0.0(Output)

I am unable to get how is the interval Keyword working and what is the format of the Output produced ?

Body:
It is the best to always know all of your participants of multiplication or any other math operation to undesrstand it.

'1' HOUR

select interval '1' HOUR from dual;

will return 1 hour, then you multiple it with number 300 and you will get:

+000000012 12:00:00.000000000

Because (300 * 1) / 24 = 12.5. or 12 days and 12 hours.

'1' minute

The same thing happend with minutes where your result is 5 hours. This query :

select interval '1' minute FROM DUAL

will return 1 minute and then you multiple it with number 300 to get this:

+000000000 05:00:00.000000000

Because (300 * 1) / 60 = 5 or 5 hours.
Here is a demo

P.S.

Depending on the tool you use you can see this results as:

+12 12:00:00.000000

+00 05:00:00.000000


问:
React js Nested Loop array
Hi I need nelp for following json array loop.it likes that instagram or facebook post. I have a json nested array. I tried below code but it is not helped me. I need the view like that instagram post Below attached image.

I want get Profile,Likes,Comments,Post details separately through loop

Output:(for ex. If loop through Record1 means it get all nested item like (profile,Post..etc)).It print output like below image

Records1 :
     Profile
     Post
     likedetails
     commentdetails

Records2 :
     Profile
     Post
     likedetails
     commentdetails

Records3 :
     Profile
     Post
     likedetails
     commentdetails

Records4 :
     Profile
     Post
     likedetails
     commentdetails

Records5 :
     Profile
     Post
     likedetails
     commentdetails

```<code>render() {
  var Json={
     "AllPost":[
        {
           "User_Id":1,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"1",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"1",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"1"
                 }],
                 "likedetails":[{
                    "Post_Id":"1",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":2,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"2",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"2",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"2"
                 }],
                 "likedetails":[{
                    "Post_Id":"12",
                    "LikeCount":"3452"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":3,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"3",
                    "UserImage":"",
                    "Fullname":"Test3",
                    "Username":"te3"
                 }],
                 "Post":[{
                    "Post_Id":"3",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"3"
                 }],
                 "likedetails":[{
                    "Post_Id":"3",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":4,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"4",
                    "UserImage":"",
                    "Fullname":"Test4",
                    "Username":"te4"
                 }],
                 "Post":[{
                    "Post_Id":"4",
                    "UploadFile":"",
                    "Post_Caption":"Test4",
                    "User_Id":"4"
                 }],
                 "likedetails":[{
                    "Post_Id":"4",
                    "LikeCount":"3454"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":5,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"5",
                    "UserImage":"",
                    "Fullname":"Test5",
                    "Username":"te5"
                 }],
                 "Post":[{
                    "Post_Id":"5",
                    "UploadFile":"",
                    "Post_Caption":"Test5",
                    "User_Id":"5"
                 }],
                 "likedetails":[{
                    "Post_Id":"5",
                    "LikeCount":"3455"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        }
     ]
  }

let arr=[];
Object.keys(Json.AllPost).forEach((records, index) => {

        Json.AllPost[records].forEach((obj, idx) => {
           arr.push(obj);
           console.log(arr);
        })
    });
</code>```

ex:
codepen:https://codepen.io/dotnet345/pen/oNXBxBM

答:
Ok.

you can follow this code

```<code>    state={
    instagramPost: [],
}

componentDidMount() {
    const BASE_URL = 'https://www.instagram.com/'userName'/?__a=1';
    Axios.get(BASE_URL)
        .then((res) => {
            console.log(res.data.graphql.user.edge_owner_to_timeline_media.edges[0].node.edge_media_to_caption.edges[0].node)
            this.setState({d: res.data.graphql.user.edge_owner_to_timeline_media.edges})
        });
        }

render() {
    const { instagramPost } = this.state;
    return (
        <React.Fragment>
            {
    instagramPost && instagramPost.map((user, i) => (
    <div key={i}>
    <img alt="" src={user.node.edge_media_to_caption.edges[0].node.text}/>
    <div>{user.node.edge_media_to_caption.edges[0].node.text}</div>
                               </div>
    ))
            }
        </React.Fragment>
    )
}
</code>```

Title: React js Nested Loop array

Body:
Hi I need nelp for following json array loop.it likes that instagram or facebook post. I have a json nested array. I tried below code but it is not helped me. I need the view like that instagram post Below attached image.

I want get Profile,Likes,Comments,Post details separately through loop

Output:(for ex. If loop through Record1 means it get all nested item like (profile,Post..etc)).It print output like below image

Records1 :
     Profile
     Post
     likedetails
     commentdetails

Records2 :
     Profile
     Post
     likedetails
     commentdetails

Records3 :
     Profile
     Post
     likedetails
     commentdetails

Records4 :
     Profile
     Post
     likedetails
     commentdetails

Records5 :
     Profile
     Post
     likedetails
     commentdetails

render() {
  var Json={
     "AllPost":[
        {
           "User_Id":1,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"1",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"1",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"1"
                 }],
                 "likedetails":[{
                    "Post_Id":"1",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":2,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"2",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"2",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"2"
                 }],
                 "likedetails":[{
                    "Post_Id":"12",
                    "LikeCount":"3452"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":3,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"3",
                    "UserImage":"",
                    "Fullname":"Test3",
                    "Username":"te3"
                 }],
                 "Post":[{
                    "Post_Id":"3",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"3"
                 }],
                 "likedetails":[{
                    "Post_Id":"3",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":4,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"4",
                    "UserImage":"",
                    "Fullname":"Test4",
                    "Username":"te4"
                 }],
                 "Post":[{
                    "Post_Id":"4",
                    "UploadFile":"",
                    "Post_Caption":"Test4",
                    "User_Id":"4"
                 }],
                 "likedetails":[{
                    "Post_Id":"4",
                    "LikeCount":"3454"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":5,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"5",
                    "UserImage":"",
                    "Fullname":"Test5",
                    "Username":"te5"
                 }],
                 "Post":[{
                    "Post_Id":"5",
                    "UploadFile":"",
                    "Post_Caption":"Test5",
                    "User_Id":"5"
                 }],
                 "likedetails":[{
                    "Post_Id":"5",
                    "LikeCount":"3455"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        }
     ]
  }

let arr=[];
Object.keys(Json.AllPost).forEach((records, index) => {

        Json.AllPost[records].forEach((obj, idx) => {
           arr.push(obj);
           console.log(arr);
        })
    });

ex:
codepen:https://codepen.io/dotnet345/pen/oNXBxBM

Body:
Ok.

you can follow this code

    state={
    instagramPost: [],
}

componentDidMount() {
    const BASE_URL = 'https://www.instagram.com/'userName'/?__a=1';
    Axios.get(BASE_URL)
        .then((res) => {
            console.log(res.data.graphql.user.edge_owner_to_timeline_media.edges[0].node.edge_media_to_caption.edges[0].node)
            this.setState({d: res.data.graphql.user.edge_owner_to_timeline_media.edges})
        });
        }

render() {
    const { instagramPost } = this.state;
    return (
        <React.Fragment>
            {
    instagramPost && instagramPost.map((user, i) => (
    <div key={i}>
    <img alt="" src={user.node.edge_media_to_caption.edges[0].node.text}/>
    <div>{user.node.edge_media_to_caption.edges[0].node.text}</div>
                               </div>
    ))
            }
        </React.Fragment>
    )
}


问:
onPanResponderRelease is not working on Android
Can anyone please look at my code. I also tried with onPanResponderEnd, is this a issue yet to fixed or i'm doing it wrongly.

//animation

```<code>const [anim] = useState(new Animated.ValueXY())
</code>```

//panresponder

```<code>const [pan] =    useState(PanResponder.create({
                        onStartShouldSetPanResponder: (evt, gestureState) => true,
                        onPanResponderMove: (event,gesture)=>{

                    console.log("move")

      },onPanResponderRelease: (evt, gestureState) => {
       console.log("release")
       },

     }))
</code>```

//passing animated view to flat list

```<code>       return (forYouNews.length==0?<SkeletonLoading /> :
       <Animated.View    {...pan.panHandlers} style={anim.getLayout()}>
       <FlatList style={{backgroundColor:"white"}} keyExtractor={(list)=>list.title} data={forYouNews}
       renderItem={({item,index })=>{
  return <Card>    <View style={styles.textView}>    <Text style={{fontSize:12,color:"rgb(29, 132, 242)"}}>{index+1 +".    "}</Text>
  </View>    <View>
<Image style={styles.img} source={{uri:item.urlToImage==null?oimageicon:item.urlToImage}}></Image>
</View>
   </View>     </Card>

    }}
     > </FlatList>  </Animated.View>
   ) }
</code>```

答:
NOTE :

Before posting any question on stackoverflow please be more nice. First of all give more information about your question. After that post the affected or issue having codebase only. Do not put all the code of your file including stylesheet. It will be more easy to answer your question rather than this. :)

SOLUTION :

To get it working properly use onPanResponderEnd instead of onPanResponderRelease.

Also if we still want to use onPanResponderRelease then we should allow termination request by:

```<code>onPanResponderTerminationRequest: () => true
</code>```

Body:
Can anyone please look at my code. I also tried with onPanResponderEnd, is this a issue yet to fixed or i'm doing it wrongly.

//animation

const [anim] = useState(new Animated.ValueXY())

//panresponder

const [pan] =    useState(PanResponder.create({
                        onStartShouldSetPanResponder: (evt, gestureState) => true,
                        onPanResponderMove: (event,gesture)=>{

                    console.log("move")

      },onPanResponderRelease: (evt, gestureState) => {
       console.log("release")
       },

     }))

//passing animated view to flat list

       return (forYouNews.length==0?<SkeletonLoading /> :
       <Animated.View    {...pan.panHandlers} style={anim.getLayout()}>
       <FlatList style={{backgroundColor:"white"}} keyExtractor={(list)=>list.title} data={forYouNews}
       renderItem={({item,index })=>{
  return <Card>    <View style={styles.textView}>    <Text style={{fontSize:12,color:"rgb(29, 132, 242)"}}>{index+1 +".    "}</Text>
  </View>    <View>
<Image style={styles.img} source={{uri:item.urlToImage==null?oimageicon:item.urlToImage}}></Image>
</View>
   </View>     </Card>

    }}
     > </FlatList>  </Animated.View>
   ) }

Body:
NOTE :

Before posting any question on stackoverflow please be more nice. First of all give more information about your question. After that post the affected or issue having codebase only. Do not put all the code of your file including stylesheet. It will be more easy to answer your question rather than this. :)

SOLUTION :

To get it working properly use onPanResponderEnd instead of onPanResponderRelease.

Also if we still want to use onPanResponderRelease then we should allow termination request by:

onPanResponderTerminationRequest: () => true


问:
Consider special charecter into .csv File
I am working on application, in it I have to consider all special characters.I am using  below code but in it I also want to consider "space and comma" but in it, when trigger space it make split at that place and make new fild for it..so friends is there any solutions to consider special characters.If you have any idea then please suggest me.Thanks</p>

```<code>   arrCsv=[[NSArray alloc]initWithObjects:@"Hello",@"Hi",@"traun  testdata",@"Hi,fine",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fileName = [NSString stringWithFormat:@"%@/try.csv", documentsDirectory];

[[arrCsv componentsJoinedByString:@","] writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];
</code>```

答:
Writing your own CSV parsing routines in a simplistic fashion is both error-prone and needlessly time-consuming. I highly recommend you use Dave DeLong's excellent CHCSV library.

If you wanted to use this library, you could do something along the following lines to write two rows to a file:

```<code>NSArray *row1 = [NSArray arrayWithObjects:@"Field One", @"Field Two", @"Field, three", nil];
NSArray *row2 = [NSArray arrayWithObjects:@"Field' One", @"Field,, Two", @"Field\" three", nil];
NSArray *rows = [NSArray arrayWithObjects:row1, row2, nil];

NSError *error = nil;
[rows writeToCSVFile:@"path/to/file.csv" atomically:YES error:&error];
if (error) {
    // do something with error
}
</code>```

Body:
I am working on application, in it I have to consider all special characters.I am using  below code but in it I also want to consider "space and comma" but in it, when trigger space it make split at that place and make new fild for it..so friends is there any solutions to consider special characters.If you have any idea then please suggest me.Thanks

   arrCsv=[[NSArray alloc]initWithObjects:@"Hello",@"Hi",@"traun  testdata",@"Hi,fine",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fileName = [NSString stringWithFormat:@"%@/try.csv", documentsDirectory];

[[arrCsv componentsJoinedByString:@","] writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];

Body:
Writing your own CSV parsing routines in a simplistic fashion is both error-prone and needlessly time-consuming. I highly recommend you use Dave DeLong's excellent CHCSV library.

If you wanted to use this library, you could do something along the following lines to write two rows to a file:

NSArray *row1 = [NSArray arrayWithObjects:@"Field One", @"Field Two", @"Field, three", nil];
NSArray *row2 = [NSArray arrayWithObjects:@"Field' One", @"Field,, Two", @"Field\" three", nil];
NSArray *rows = [NSArray arrayWithObjects:row1, row2, nil];

NSError *error = nil;
[rows writeToCSVFile:@"path/to/file.csv" atomically:YES error:&error];
if (error) {
    // do something with error
}


答:
Replace method does not take keyword arguments so, just update your code with following code.</p>

```<code>"Bharath..Bharath..Bharath".replace("..", ".", 1)
</code>```

Title: String.replace(x,x,count => 1) in Python

Body:
Replace method does not take keyword arguments so, just update your code with following code.

"Bharath..Bharath..Bharath".replace("..", ".", 1)


问:
Calling `QQuickPaintedItem::updateImage(const QImage& image)` in a thread safe way (no QThread)
I'm reading this answer about creating a custom QQuickPaintedItem in C++ How to paint sequential image in efficient way in QQuickPaintedItem

and I want to write code that is not Qt-dependent. That is, I don't want to rely on QThread. I just want to call CameraView::updateImage(const QImage& image) from a std::thread, not q QThread. Is it possible?

I thougth of simply creating a thread, passing the CameraView instance to it, and calling it from the thread. However, this is not thread safe.

How can I call CameraView::updateImage(const QImage& image) in a thread safe manner?

答:
You can, of course, use the C++ Standard Library classes in your code. For example, use std::mutex to update image as follows:

```<code>void CameraView::updateImage(const QImage& image) {
    std::unique_lock<std::mutex> lock(mutex); // std::mutex object is located elsewhere
    // ... the rest of the code as before ...
}
</code>```

You can also leave CameraView code unchanged and call the updateImage function from external code. Just make sure that the image is updated using the same mutex in all threads:

```<code>void functionInAnotherThread(CameraView& cameraView) {
    std::unique_lock<std::mutex> lock(mutex); // std::mutex object is located elsewhere

    // ... the rest of the code ...

    cameraView.updateImage(image);

    // ... the rest of the code ...
}
</code>```

Let's try to implement this approach. Let's change the header file a bit:

```<code>class CameraView : public QQuickPaintedItem {
    Q_OBJECT
    Q_DISABLE_COPY(CameraView)

public:
    CameraView(QQuickItem* parent = nullptr);

public slots:
    void updateImage(const QImage&);
    void scheduleUpdate();

protected:
    QImage image_;
};
</code>```

Now, write the definitions of the methods:

```<code>void CameraView::updateImage(const QImage& image) {
    image_ = image.copy(); // Does deep copy of image data.
}

void CameraView::scheduleUpdate() {
    update();
}

void CameraView::paint(QPainter* painter) {
    painter->drawImage(this->boundingRect(), image_);
}
</code>```

Finally, we write the function of updating the picture and scheduling redrawing:

```<code>void functionInAnotherThread(CameraView& cameraView) {
    std::unique_lock<std::mutex> lock(mutex); // std::mutex object is located elsewhere

    cameraView.updateImage(image);

    lock.unlock(); // Unlock the mutex as we have already updated the image.

    QMetaObject::invokeMethod(&cameraView, "scheduleUpdate",
        Qt::QueuedConnection); // Call slot through the queued connection.
}
</code>```

With Qt::QueuedConnection, the slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread. Thus, we can schedule the widget to be redrawn from another thread. Try using other types of connections if this does not work.

Body:
You can, of course, use the C++ Standard Library classes in your code. For example, use std::mutex to update image as follows:

void CameraView::updateImage(const QImage& image) {
    std::unique_lock<std::mutex> lock(mutex); // std::mutex object is located elsewhere
    // ... the rest of the code as before ...
}

You can also leave CameraView code unchanged and call the updateImage function from external code. Just make sure that the image is updated using the same mutex in all threads:

void functionInAnotherThread(CameraView& cameraView) {
    std::unique_lock<std::mutex> lock(mutex); // std::mutex object is located elsewhere

    // ... the rest of the code ...

    cameraView.updateImage(image);

    // ... the rest of the code ...
}

Let's try to implement this approach. Let's change the header file a bit:

class CameraView : public QQuickPaintedItem {
    Q_OBJECT
    Q_DISABLE_COPY(CameraView)

public:
    CameraView(QQuickItem* parent = nullptr);

public slots:
    void updateImage(const QImage&);
    void scheduleUpdate();

protected:
    QImage image_;
};

Now, write the definitions of the methods:

void CameraView::updateImage(const QImage& image) {
    image_ = image.copy(); // Does deep copy of image data.
}

void CameraView::scheduleUpdate() {
    update();
}

void CameraView::paint(QPainter* painter) {
    painter->drawImage(this->boundingRect(), image_);
}

Finally, we write the function of updating the picture and scheduling redrawing:

void functionInAnotherThread(CameraView& cameraView) {
    std::unique_lock<std::mutex> lock(mutex); // std::mutex object is located elsewhere

    cameraView.updateImage(image);

    lock.unlock(); // Unlock the mutex as we have already updated the image.

    QMetaObject::invokeMethod(&cameraView, "scheduleUpdate",
        Qt::QueuedConnection); // Call slot through the queued connection.
}

With Qt::QueuedConnection, the slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread. Thus, we can schedule the widget to be redrawn from another thread. Try using other types of connections if this does not work.


问:
DUPLICATES IN LEFT JOIN MYSQL QUERY
please help, how can i remove duplicates

whenever i have more than two rows on each table they duplicate

The (getter_tbl) result keeps on duplicating on whenever the (helper) table rows increases

```<code>SELECT DISTINCT h.status as h_status, h.ph_amount as h_ph_amount, h.help_id as h_help_id, h.h_unique_id as h_h_unique_id, h.user_id as h_user_id, h.ph_date as h_ph_date, h.ph_commitment as h_ph_commitment, h.ph_type as h_ph_type,
g.status as g_status, g.user_id as g_user_id, g.getter_tbl_id as g_getter_tbl_id, g.gh_committment as g_gh_committment, g.gh_type as g_gh_type, g.status as g_status, g.method as g_method, g.amount as g_amount,
u.nickname as u_nickname, u.user_id as u_user_id
FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = g.user_id
LEFT JOIN user AS u ON u.user_id = '{$user_id}'
WHERE h.user_id = '{$user_id}' AND g.user_id='{$user_id}' AND h.status='open' OR g.status='open'
GROUP BY h.help_id, g.getter_tbl_id, u.user_id
</code>```

this my code

```<code>foreach($query as $queryRows){
    if($queryRows['g_status'] == 'open'){
      print '
        <div class="block-content block-content-full text-left text-black" style="padding: 10px 15px 1px; ">
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Amount:</strong> '.number_format($queryRows['g_gh_committment'], 0).'</div>
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Balance:</strong> '.number_format($queryRows['g_gh_committment'], 0).'</div>

      ';
    }
    if($queryRows['h_status'] == 'open'){
      print '
        <div class="block-content block-content-full text-left text-black" style="padding: 10px 15px 1px; ">
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Amount:</strong> '.number_format($queryRows['h_ph_amount'], 0).'</div>
        <div class="font-size-sm text-black-op" style=" color: black !important; "><strong>Balance:</strong> '.number_format($queryRows['h_ph_commitment'], 0).'</div>

      ';
    }
}
</code>```

答:
It was getting really hard to be clear in a comment -- so I'm offering a potential answer.

You duplicate your user_id several times. Perhaps that is the reason you are duplicating your results.

Also your SQL syntax likely has a bug. I'm assuming your WHERE clause should be AND (h.status=open OR g.status=open). In that, you want to get the user when either of those status are open.

Does this work?

```<code>SELECT DISTINCT

h.status as h_status,
h.ph_amount as h_ph_amount,
h.help_id as h_help_id,
h.h_unique_id as h_h_unique_id,
h.ph_date as h_ph_date,
h.ph_commitment as h_ph_commitment,
h.ph_type as h_ph_type,
g.status as g_status,
g.getter_tbl_id as g_getter_tbl_id,
g.gh_committment as g_gh_committment,
g.gh_type as g_gh_type,
g.status as g_status,
g.method as g_method,
g.amount as g_amount,
u.nickname as u_nickname,
u.user_id as u_user_id

FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = g.user_id
LEFT JOIN user AS u ON u.user_id = h.user_id

WHERE
u.user_id = '{$user_id}' AND
(h.status='open' OR g.status='open')

GROUP BY h.help_id, g.getter_tbl_id, u.user_id
</code>```

NOTE: It will only return u_user_id (and not the same id in 3 different variables)

Title: DUPLICATES IN LEFT JOIN MYSQL QUERY

Body:
please help, how can i remove duplicates

whenever i have more than two rows on each table they duplicate

The (getter_tbl) result keeps on duplicating on whenever the (helper) table rows increases

SELECT DISTINCT h.status as h_status, h.ph_amount as h_ph_amount, h.help_id as h_help_id, h.h_unique_id as h_h_unique_id, h.user_id as h_user_id, h.ph_date as h_ph_date, h.ph_commitment as h_ph_commitment, h.ph_type as h_ph_type,
g.status as g_status, g.user_id as g_user_id, g.getter_tbl_id as g_getter_tbl_id, g.gh_committment as g_gh_committment, g.gh_type as g_gh_type, g.status as g_status, g.method as g_method, g.amount as g_amount,
u.nickname as u_nickname, u.user_id as u_user_id
FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = g.user_id
LEFT JOIN user AS u ON u.user_id = '{$user_id}'
WHERE h.user_id = '{$user_id}' AND g.user_id='{$user_id}' AND h.status='open' OR g.status='open'
GROUP BY h.help_id, g.getter_tbl_id, u.user_id

this my code

foreach($query as $queryRows){
    if($queryRows['g_status'] == 'open'){
      print '

Amount: '.number_format($queryRows['g_gh_committment'], 0).'

Balance: '.number_format($queryRows['g_gh_committment'], 0).'

      ';
    }
    if($queryRows['h_status'] == 'open'){
      print '

Amount: '.number_format($queryRows['h_ph_amount'], 0).'

Balance: '.number_format($queryRows['h_ph_commitment'], 0).'

      ';
    }
}

Body:
It was getting really hard to be clear in a comment -- so I'm offering a potential answer.

You duplicate your user_id several times. Perhaps that is the reason you are duplicating your results.

Also your SQL syntax likely has a bug. I'm assuming your WHERE clause should be AND (h.status=open OR g.status=open). In that, you want to get the user when either of those status are open.

Does this work?

SELECT DISTINCT

h.status as h_status,
h.ph_amount as h_ph_amount,
h.help_id as h_help_id,
h.h_unique_id as h_h_unique_id,
h.ph_date as h_ph_date,
h.ph_commitment as h_ph_commitment,
h.ph_type as h_ph_type,
g.status as g_status,
g.getter_tbl_id as g_getter_tbl_id,
g.gh_committment as g_gh_committment,
g.gh_type as g_gh_type,
g.status as g_status,
g.method as g_method,
g.amount as g_amount,
u.nickname as u_nickname,
u.user_id as u_user_id

FROM helper AS h
LEFT JOIN getter_tbl AS g ON h.user_id = g.user_id
LEFT JOIN user AS u ON u.user_id = h.user_id

WHERE
u.user_id = '{$user_id}' AND
(h.status='open' OR g.status='open')

GROUP BY h.help_id, g.getter_tbl_id, u.user_id

NOTE: It will only return u_user_id (and not the same id in 3 different variables)


问:
ERROR: Sonar server 'http://localhost:9000' can not be reached
when running the following command:
cmd /c C:\sonar-runner-2.4\bin\sonar-runner.bat

(sonar runner is installed on the build machine)
i get the following errors:

ERROR: Sonar server 'http://localhost:9000' can not be reached

ERROR: Error during Sonar runner execution

ERROR: java.net.ConnectException: Connection refused: connect

ERROR: Caused by: Connection refused: connect

what can cause these errors?

Hi dinesh,

this is my sonar-runner.properties file:

```<code>sonar.projectKey=NDM
sonar.projectName=NDM
sonar.projectVersion=1.0

sonar.visualstudio.solution=NDM.sln

#sonar.sourceEncoding=UTF-8
sonar.web.host:sonarqube
sonar.web.port=9000

# Enable the Visual Studio bootstrapper
sonar.visualstudio.enable=true

# Unit Test Results
sonar.cs.vstest.reportsPaths=TestResults/*.trx

# Required only when using SonarQube < 4.2
sonar.language=cs

sonar.sources=.
</code>```

As you can see i set the sonar.web.host:sonarqube
sonar.web.port=9000 but when i run sonar-runner.bat i still get the

ERROR: Sonar server 'http://localhost:9000' can not be reached - why is it still looking for localhost:9000

and not sonarqube:9000 as i set?

i saw that in the log of sonar-runner.bat there the following line:
INFO: Work directory: D:\sTFS\26091\Sources\NDM\Source..sonar

while my solution is in D:\sTFS\26091\Sources\NDM\Source\

could this be the problem?

thanks,
Guy

答: Please check if postgres(or any other database service) is running properly.</p>

Body:
when running the following command:
cmd /c C:\sonar-runner-2.4\bin\sonar-runner.bat

(sonar runner is installed on the build machine)
i get the following errors:

ERROR: Sonar server 'http://localhost:9000' can not be reached

ERROR: Error during Sonar runner execution

ERROR: java.net.ConnectException: Connection refused: connect

ERROR: Caused by: Connection refused: connect

what can cause these errors?

Hi dinesh,

this is my sonar-runner.properties file:

sonar.projectKey=NDM
sonar.projectName=NDM
sonar.projectVersion=1.0

sonar.visualstudio.solution=NDM.sln

#sonar.sourceEncoding=UTF-8
sonar.web.host:sonarqube
sonar.web.port=9000

# Enable the Visual Studio bootstrapper
sonar.visualstudio.enable=true

# Unit Test Results
sonar.cs.vstest.reportsPaths=TestResults/*.trx

# Required only when using SonarQube < 4.2
sonar.language=cs

sonar.sources=.

As you can see i set the sonar.web.host:sonarqube
sonar.web.port=9000 but when i run sonar-runner.bat i still get the

ERROR: Sonar server 'http://localhost:9000' can not be reached - why is it still looking for localhost:9000

and not sonarqube:9000 as i set?

i saw that in the log of sonar-runner.bat there the following line:
INFO: Work directory: D:\sTFS\26091\Sources\NDM\Source..sonar

while my solution is in D:\sTFS\26091\Sources\NDM\Source\

could this be the problem?

thanks,
Guy


问:
How to get byte[] from float number
How to get byte[] from float number? I need to create message where for data I have four bytes, datum can be unsigned int( it is easy to get byte[] from int), binary and float ( but I don't know how to get four bytes from float ). Any solution ?</p>

答:
Without any math involved, you can do that by writing the value via a DataOutputStream and then fetch the resulting output:

```<code>ByteArrayOutputStream bos = new ByteArrayOutputStream(4);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeFloat(yourFloat);
byte[] bytes = bos.toByteArray();
// at this point, your bytes will contain the 4-byte representation of the float.
</code>```

Title: How to get byte[] from float number

Body:
Without any math involved, you can do that by writing the value via a DataOutputStream and then fetch the resulting output:

ByteArrayOutputStream bos = new ByteArrayOutputStream(4);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeFloat(yourFloat);
byte[] bytes = bos.toByteArray();
// at this point, your bytes will contain the 4-byte representation of the float.


问:
Need to parse a Json object and append it to a table
```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function myFunction() {
            var abc, obj, i, j;
            abc = {
                "cars": [
                    '{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
                    '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
                    '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
                ]
            }
            var obj = JSON.parse(abc);
            var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
            document.getElementById("dtable").appendChild(theader);
            var x;
            for (i = 0; i < abc.cars.length; i++) {
                x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors + "</td><td>" + obj.cars[i].lol[0] + "</td></tr>";
                document.getElementById("dtable").appendChild(x);
            }
        };
    </script>
</head>
<body>
    <div class="container" ,id="dsjson">
        <button type="button" onclick="myFunction()">display json</button>
        <br><br>
        <table id="dtable"></table>
    </div>
</body>
</html>
</code>```

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

答:
I think you are a bit confused with appendChild and innerHTML.

If you want to use appendChild you will need to provide an HTML element, however, if you just want to add HTML text, use innerHTML.

abc is already a JSON object, so you don't need to parse it again, however, you will want to parse the lol prop inside.

Here are those changes and some small improvements, using object destructuring to clean some things up a little.

<!DOCTYPE html>

    <button type="button" onclick="myFunction()">display json</button>

```

Body:
<!DOCTYPE html>

        <button type="button" onclick="myFunction()">display json</button>

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

Body:
I think you are a bit confused with appendChild and innerHTML.

If you want to use appendChild you will need to provide an HTML element, however, if you just want to add HTML text, use innerHTML.

abc is already a JSON object, so you don't need to parse it again, however, you will want to parse the lol prop inside.

Here are those changes and some small improvements, using object destructuring to clean some things up a little.

<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    function myFunction() {
      var abc, obj, i, j;
      abc = {
        "cars": [
          '{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
          '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
          '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
        ]
      }

      var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
      document.getElementById("dtable").innerHTML = (theader);
      var x = "";
      for (i = 0; i < abc.cars.length; i++) {
        const car = JSON.parse(abc.cars[i])
        const { model, doors, lol } = car
        x += "<tr><td>" + model + "</td><td>" + doors + "</td><td>" + lol[0] + "</td></tr>";
      }
      document.getElementById("dtable").innerHTML += x;
    };
  </script>
</head>

<body>
  <div class="container" ,id="dsjson">
    <button type="button" onclick="myFunction()">display json</button>
    <br><br>
    <table id="dtable"></table>
  </div>
</body>

</html>


问:
Make a DIV fill an entire table cell
I've seen this question and googled a bit, but nothing so far has worked. I figure it's 2010 now (those questions/answers are old and, well, unanswered) and we have CSS3! Is there any way to get a div to fill an entire table cell's width and height using CSS?

I don't know what the width and/or height of the cell will be ahead of time, and setting the div's width and height to 100% does not work.

Also, the reason I need the div is because I need to absolutely position some elements outside of the cell, and position: relative does not apply to tds, so I need a wrapper div.

答:
This is probably not recommended.

I figured out a workaround which works if your div doesn't contain text and has an uniform background.

```<code>display: 'list-item'
</code>```

gives the div the desired height and width, but with the big downside of having a list item bullet. Since the div has a homogeneous background-color I got rid of the bullet with those styles:

```<code>list-style-position: 'inside',
color: *background-color*,
</code>```

ContentLicense: CC BY-SA 2.5

Title: Make a DIV fill an entire table cell

Body:
This is probably not recommended.

I figured out a workaround which works if your div doesn't contain text and has an uniform background.

display: 'list-item'

gives the div the desired height and width, but with the big downside of having a list item bullet. Since the div has a homogeneous background-color I got rid of the bullet with those styles:

list-style-position: 'inside',
color: *background-color*,


问:
How to find which parts of C# code may throw exceptions
Is there a way to make Visual Studio tell me which parts of my code may throw exceptions? Something like the compiler warnings that can be suppressed, but instead it warns me that some line may throw an exception if it isn't surrounded by a try and catch.

答:
ReSharper usually does that. It adds some warnings for possible exceptions.
If you don't want to use it search for similar products.</p>


问:
RecursionError: maximum recursion depth exceeded - Binary Tree
While implementing add_node and search methods for a binary tree, Im getting a RecursionError: maximum recursion depth exceeded

Code:

```<code>class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    def add_node(self, node, value):
        node = self.root
        if node is not None:
            if not node.value:
                node.value = value
            elif not node.left:
                node.left = value
            elif not node.right:
                node.right = value
            else:
                node.left = self.add_node(node.left, value)
        else:
            self.root = TreeNode(value)

    def search(self, value):
        node = self.root
        found = False
        while node is not None:
            if node.value == value:
                found = True
            if node.left:
                found = node.left.search(value)
            if node.right:
                found = found or node.left.search(value)
        return found

def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(binary_tree.root, 200)
    binary_tree.add_node(binary_tree.root, 300)
    binary_tree.add_node(binary_tree.root, 100)
    binary_tree.add_node(binary_tree.root, 30)
    binary_tree.traverse_inorder(binary_tree.root)
    print(binary_tree.search(200))

if __name__ == '__main__':
    main()
</code>```

Error:

```<code>Traceback (most recent call last):
  File ".\binary_tree_test20.py", line 51, in <module>
    main()
  File ".\binary_tree_test20.py", line 45, in main
    binary_tree.add_node(binary_tree.root, 30)
  File ".\binary_tree_test20.py", line 22, in add_node
    node.left = self.add_node(node.left, value)
  File ".\binary_tree_test20.py", line 22, in add_node
    node.left = self.add_node(node.left, value)
  File ".\binary_tree_test20.py", line 22, in add_node
    node.left = self.add_node(node.left, value)
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
</code>```

答:
This is a remedy I can give you.

```<code>class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def _add_node(node, value):
    if not node.value:
        node.value = value
    elif not node.left:
        node.left = TreeNode(value)
    elif not node.right:
        node.right = TreeNode(value)
    else:
        _add_node(node.left, value)

class BinaryTree:
    # ...

    def add_node(self, value):
        node = self.root
        if node is not None:
            _add_node(node, value)
        else:
            self.root = TreeNode(value)

    # ...

def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(200)
    binary_tree.add_node(300)
    binary_tree.add_node(100)
    binary_tree.add_node(30)
</code>```

Although I recommend only extending TreeNode definition without defining BinaryTree.

Body:
While implementing add_node and search methods for a binary tree, Im getting a RecursionError: maximum recursion depth exceeded

Code:

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    def add_node(self, node, value):
        node = self.root
        if node is not None:
            if not node.value:
                node.value = value
            elif not node.left:
                node.left = value
            elif not node.right:
                node.right = value
            else:
                node.left = self.add_node(node.left, value)
        else:
            self.root = TreeNode(value)

    def search(self, value):
        node = self.root
        found = False
        while node is not None:
            if node.value == value:
                found = True
            if node.left:
                found = node.left.search(value)
            if node.right:
                found = found or node.left.search(value)
        return found

def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(binary_tree.root, 200)
    binary_tree.add_node(binary_tree.root, 300)
    binary_tree.add_node(binary_tree.root, 100)
    binary_tree.add_node(binary_tree.root, 30)
    binary_tree.traverse_inorder(binary_tree.root)
    print(binary_tree.search(200))

if __name__ == '__main__':
    main()

Error:

Traceback (most recent call last):
  File ".\binary_tree_test20.py", line 51, in <module>
    main()
  File ".\binary_tree_test20.py", line 45, in main
    binary_tree.add_node(binary_tree.root, 30)
  File ".\binary_tree_test20.py", line 22, in add_node
    node.left = self.add_node(node.left, value)
  File ".\binary_tree_test20.py", line 22, in add_node
    node.left = self.add_node(node.left, value)
  File ".\binary_tree_test20.py", line 22, in add_node
    node.left = self.add_node(node.left, value)
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded

Body:
This is a remedy I can give you.

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def _add_node(node, value):
    if not node.value:
        node.value = value
    elif not node.left:
        node.left = TreeNode(value)
    elif not node.right:
        node.right = TreeNode(value)
    else:
        _add_node(node.left, value)

class BinaryTree:
    # ...

    def add_node(self, value):
        node = self.root
        if node is not None:
            _add_node(node, value)
        else:
            self.root = TreeNode(value)

    # ...

def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(200)
    binary_tree.add_node(300)
    binary_tree.add_node(100)
    binary_tree.add_node(30)

Although I recommend only extending TreeNode definition without defining BinaryTree.


答:
You're getting infinite recursion because you're not using the node parameter, you're replacing it with self.root. So when you recurse, you start at the root again each time, and never end.

Also, the line node.left = self.add_node(node.left, value) expects add_node to return the new node, but your method doesn't return anything. When it's updating an existing node it should just return the modified node; if it's creating a new node, it returns that node.

```<code>    def add_node(self, node, value):
        if node is not None:
            if not node.value:
                node.value = value
            elif not node.left:
                node.left = value
            elif not node.right:
                node.right = value
            else:
                node.left = self.add_node(node.left, value)
            return node
        else:
            return TreeNode(value)
</code>```

You would call this method like this:

```<code>binary_tree.root = binary_tree.add_node(binary_tree.root, 30)
</code>```

Title: RecursionError: maximum recursion depth exceeded - Binary Tree

Body:
You're getting infinite recursion because you're not using the node parameter, you're replacing it with self.root. So when you recurse, you start at the root again each time, and never end.

Also, the line node.left = self.add_node(node.left, value) expects add_node to return the new node, but your method doesn't return anything. When it's updating an existing node it should just return the modified node; if it's creating a new node, it returns that node.

    def add_node(self, node, value):
        if node is not None:
            if not node.value:
                node.value = value
            elif not node.left:
                node.left = value
            elif not node.right:
                node.right = value
            else:
                node.left = self.add_node(node.left, value)
            return node
        else:
            return TreeNode(value)

You would call this method like this:

binary_tree.root = binary_tree.add_node(binary_tree.root, 30)