问:
How to solve Pymodbus exception when Master requests for holding registry values of the Arduino Slave
I currently trying to receive data from my Arduino slave to my computer. I am successful in creating an Arduino slave. However, when I am trying to receive the data from my computer using the Pymodbus library, my code fails to receive the data from the Arduino and raises a ModbusIOException. For the specifications of my project, I am trying to build a Modbus RTU with the Arduino to simulate a sensor with random numbers as readings. The Arduino code uses the Modbus-Arduino library of Andre Sarmento.

https://github.com/andresarmento/modbus-arduino

I already checked my Arduino slave if it is working. I tried reading the data through a Modbus Master emulator (QModMaster), and it worked just fine. This might prove that the problem itself is from the code for the Master. Furthermore, the serial connection seems to work fine, since the self.client.connect() returns True.

These are the screenshots of the QModMaster configurations.

Slave configurations
Serial Port configurations

Python code for the master:

```<code>class ModbusRTU:
    def __init__(self, graph_name, port, baudrate=9600,
                 stopbits=1, bytesize=8, parity='N',
                 timeout=1):
        self.graph_name = graph_name
        self.client = ModbusSerialClient(method='rtu',
                                         port=port,
                                         baudrate=baudrate,
                                         parity=parity,
                                         timeout=timeout)
        self.connection = self.client.connect()
        result = self.client.read_holding_registers(address=0,
                                                  count=2,
                                                  unit=1)
        print(result.registers)

if __name__ == '__main__':
    modbus = ModbusRTU(graph_name='/dev/ttyACM0',
                       port='/dev/ttyACM0', baudrate=9600,
                       stopbits=1, bytesize=8, parity='N',
                       timeout=1)
    print(modbus.check_connection())
</code>```

Arduino code for the simulated slave and sensor:

```<code>#include <Modbus.h>
#include <ModbusSerial.h>

ModbusSerial mb;
const int READING = 0;
const int DECIMAL = 1;

void setup() {
  mb.config(&Serial, 9600, SERIAL_8N1);
  mb.setSlaveId(1);
  mb.addHreg(READING);
  mb.addHreg(DECIMAL);
}

void loop() {
  mb.task();
  mb.Hreg(READING, random(1, 201));
  mb.Hreg(DECIMAL, random(0, 4));
}
</code>```

Upon printing the results.registers, it is supposedly a list of integers. However, it just raises a ModbusIOException with a message of:

```<code>'ModbusIOException' object has no attribute 'registers'
  File "/home/kebaranas/PythonProjects/ThirsyWell/tools/utilities.py", line 21, in __init__
    print(result.registers)
  File "/home/kebaranas/PythonProjects/ThirsyWell/tools/utilities.py", line 29, in <module>
    timeout=1)
</code>```

It also gives this message as well.

```<code>Modbus Error: [Input/Output] Modbus Error: [Invalid Message] Incomplete message received, expected at least 2 bytes (0 received)
</code>```

答:
Before print(result.registers) try the following code snippet:

```<code>if not result.isError():
    print(result.registers)
else:
    print("error: {}".format(result))
</code>```

Also, fill in other ModbusSerialClient() argument.

Here is updated of your code snippet:

```<code>from pymodbus.client.sync import ModbusSerialClient

class ModbusRTU:
    def __init__(self, graph_name, port, baudrate=9600,
                 stopbits=1, bytesize=8, parity='N',
                 timeout=1):
        self.graph_name = graph_name
        self.client = ModbusSerialClient(
            method='rtu',
            port=port,
            baudrate=baudrate,
            parity=parity,
            timeout=timeout,
            stopbits=stopbits,
            bytesize=bytesize
        )
        self.connection = self.client.connect()
        result = self.client.read_input_registers(address=1,
                                                  count=2,
                                                  unit=1)
        if not result.isError():
            print(result.registers)
        else:
            print("error: {}".format(result))

if __name__ == '__main__':
    modbus = ModbusRTU(
        graph_name='/dev/ttyACM0',
        port='/dev/ttyACM0', baudrate=9600,
        stopbits=1, bytesize=8, parity='N',
        timeout=1
    )
</code>```

Body:
I currently trying to receive data from my Arduino slave to my computer. I am successful in creating an Arduino slave. However, when I am trying to receive the data from my computer using the Pymodbus library, my code fails to receive the data from the Arduino and raises a ModbusIOException. For the specifications of my project, I am trying to build a Modbus RTU with the Arduino to simulate a sensor with random numbers as readings. The Arduino code uses the Modbus-Arduino library of Andre Sarmento.

https://github.com/andresarmento/modbus-arduino

I already checked my Arduino slave if it is working. I tried reading the data through a Modbus Master emulator (QModMaster), and it worked just fine. This might prove that the problem itself is from the code for the Master. Furthermore, the serial connection seems to work fine, since the self.client.connect() returns True.

These are the screenshots of the QModMaster configurations.

Slave configurations
Serial Port configurations

Python code for the master:

class ModbusRTU:
    def __init__(self, graph_name, port, baudrate=9600,
                 stopbits=1, bytesize=8, parity='N',
                 timeout=1):
        self.graph_name = graph_name
        self.client = ModbusSerialClient(method='rtu',
                                         port=port,
                                         baudrate=baudrate,
                                         parity=parity,
                                         timeout=timeout)
        self.connection = self.client.connect()
        result = self.client.read_holding_registers(address=0,
                                                  count=2,
                                                  unit=1)
        print(result.registers)

if __name__ == '__main__':
    modbus = ModbusRTU(graph_name='/dev/ttyACM0',
                       port='/dev/ttyACM0', baudrate=9600,
                       stopbits=1, bytesize=8, parity='N',
                       timeout=1)
    print(modbus.check_connection())

Arduino code for the simulated slave and sensor:

#include <Modbus.h>
#include <ModbusSerial.h>

ModbusSerial mb;
const int READING = 0;
const int DECIMAL = 1;

void setup() {
  mb.config(&Serial, 9600, SERIAL_8N1);
  mb.setSlaveId(1);
  mb.addHreg(READING);
  mb.addHreg(DECIMAL);
}

void loop() {
  mb.task();
  mb.Hreg(READING, random(1, 201));
  mb.Hreg(DECIMAL, random(0, 4));
}

Upon printing the results.registers, it is supposedly a list of integers. However, it just raises a ModbusIOException with a message of:

'ModbusIOException' object has no attribute 'registers'
  File "/home/kebaranas/PythonProjects/ThirsyWell/tools/utilities.py", line 21, in __init__
    print(result.registers)
  File "/home/kebaranas/PythonProjects/ThirsyWell/tools/utilities.py", line 29, in <module>
    timeout=1)

It also gives this message as well.

Modbus Error: [Input/Output] Modbus Error: [Invalid Message] Incomplete message received, expected at least 2 bytes (0 received)

Body:
Before print(result.registers) try the following code snippet:

if not result.isError():
    print(result.registers)
else:
    print("error: {}".format(result))

Also, fill in other ModbusSerialClient() argument.

Here is updated of your code snippet:

from pymodbus.client.sync import ModbusSerialClient

class ModbusRTU:
    def __init__(self, graph_name, port, baudrate=9600,
                 stopbits=1, bytesize=8, parity='N',
                 timeout=1):
        self.graph_name = graph_name
        self.client = ModbusSerialClient(
            method='rtu',
            port=port,
            baudrate=baudrate,
            parity=parity,
            timeout=timeout,
            stopbits=stopbits,
            bytesize=bytesize
        )
        self.connection = self.client.connect()
        result = self.client.read_input_registers(address=1,
                                                  count=2,
                                                  unit=1)
        if not result.isError():
            print(result.registers)
        else:
            print("error: {}".format(result))

if __name__ == '__main__':
    modbus = ModbusRTU(
        graph_name='/dev/ttyACM0',
        port='/dev/ttyACM0', baudrate=9600,
        stopbits=1, bytesize=8, parity='N',
        timeout=1
    )


来源: stackexchange

问:
Is there any difference between native-base <View/> and react-native <View/>?
I know native-base in a wrapper on react-native library but there are some components which we can import from react-native as well as from native-base also eg., View, Text, etc., Is there any difference between these two imported components. I am new to react native just want to know.</p>

答:
I diagnosed more in this and got chain react and kitchen slink which gives more clarity about every component

https://github.com/GeekyAnts/NativeBase

ContentLicense: CC BY-SA 4.0


问:
Deleting Resource from Kubernetes Using Weaveworks Flux
Flux sync git state with cluster state but If I want to delete a resource from Kubernetes in a scenerio where all resources are managed through git, what is the best way to delete a resource (deplyment, service, ingress etc) with flux ?</p>

答:
Flux has an experimental (but quite mature) garbage collection feature that can be enabled by setting the --sync-garbage-collection flag as an argument on the Flux daemon deployment (or by setting syncGarbageCollection.enabled to true in your values.yaml in case you are deploying Flux using the Helm chart).

With the garbage collection feature enabled, Flux will remove resources from Kubernetes when they are removed from git.

You can find in depth information about the garbage collection feature in the documentation.


问:
Why is my CSS selector not working with beautifulsoup but works fine as a chrome console query?
I have a css selector that works fine when executing it in the chrome JS Console, but does not work when running it through beautifulsoup on one example, yet works on another (I'm unable to discern the difference between the two).

```<code>url_1 = 'https://www.amazon.com/s?k=bacopa&page=1'
url_2 = 'https://www.amazon.com/s?k=acorus+calamus&page=1'
</code>```

The following query works fine on both when executing it in the chrome console.

```<code>document.querySelectorAll('div.s-result-item')
</code>```

Then running the two urls through beautifulsoup, this is the output I get.

url_1 (works)

```<code>headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_1, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup .select('div.s-result-item')
print(len(listings))
</code>```

output: 53 (correct)

url_2 (does not work)

```<code>headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_2, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup.select('div.s-result-item')
print(len(listings))
</code>```

output: 0 (incorrect - expected: 49)

Does anyone know what might be going on here and how I can get the css selector to work with beautifulsoup?

答:
I think it is the html. Change the parser to 'lxml'. You can also shorten your css selector to just class and re-use connection with Session object for efficiency.

```<code>import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.amazon.com/s?k=bacopa&page=1','https://www.amazon.com/s?k=acorus+calamus&page=1']

with requests.Session() as s:
    for url in urls:
        r = s.get(url, headers = {'User-Agent' : 'Mozilla/5.0'})
        soup = bs(r.content, 'lxml')
        listings = soup.select('.s-result-item')
        print(len(listings))
</code>```

Body:
I have a css selector that works fine when executing it in the chrome JS Console, but does not work when running it through beautifulsoup on one example, yet works on another (I'm unable to discern the difference between the two).

url_1 = 'https://www.amazon.com/s?k=bacopa&page=1'
url_2 = 'https://www.amazon.com/s?k=acorus+calamus&page=1'

The following query works fine on both when executing it in the chrome console.

document.querySelectorAll('div.s-result-item')

Then running the two urls through beautifulsoup, this is the output I get.

url_1 (works)

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_1, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup .select('div.s-result-item')
print(len(listings))

output: 53 (correct)

url_2 (does not work)

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
r = requests.get(url_2, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
listings = soup.select('div.s-result-item')
print(len(listings))

output: 0 (incorrect - expected: 49)

Does anyone know what might be going on here and how I can get the css selector to work with beautifulsoup?

Body:
I think it is the html. Change the parser to 'lxml'. You can also shorten your css selector to just class and re-use connection with Session object for efficiency.

import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.amazon.com/s?k=bacopa&page=1','https://www.amazon.com/s?k=acorus+calamus&page=1']

with requests.Session() as s:
    for url in urls:
        r = s.get(url, headers = {'User-Agent' : 'Mozilla/5.0'})
        soup = bs(r.content, 'lxml')
        listings = soup.select('.s-result-item')
        print(len(listings))


问:
How to make faster large data (5,000,000) in Django with Datatables No django-datatables-view No Rest Framework
I want to take large data (examples 5 000,000) with datatables in Django .But Proccessing is slowly (Page Load is 12 seconds).Users login to webpage. Then Click to Test .html. Backend procces run to test_json in Views. Views call taking db data with to_dict_json.  On Models.py. This method in Views return Json response objects.
How to make faster large data in Django with datatables

Models.py

```<code>class SysTest(models.Model):

class Meta:
    db_table = 'sysTest'

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Tip = models.ForeignKey(SysRefTip, on_delete=models.CASCADE)
Kod = models.CharField(_("Kod"), max_length=20, blank=False, null=False)
Aciklama1 = models.CharField(_("Açıklama 1"), max_length=100,blank=True, null=True)
Aciklama2 = models.CharField(_("Açıklama 2"), max_length=100,blank=True, null=True)
GrupKod = models.CharField(_("Grup Kodu"), max_length=20,blank=True, null=True)
SayKod = models.FloatField(_("Sayısal Değer"),blank=True, null=True)

def to_dict_json(self):

    return{
        'Id':self.id,
        'Kod':self.Kod,
        'Aciklama1':self.Aciklama1,
        'Aciklama2':self.Aciklama2,
        'GrupKod':self.GrupKod,
        'SayKod':self.SayKod,
    }
</code>```

View.py

```<code>def test_json(request):
    persons  = SysTest.objects.all()
    data = [person.to_dict_json() for person in persons ]
    response = {'data': data}
   return JsonResponse(response,safe=False,content_type="application/json")
</code>```

Urls.py

```<code>from django.urls import path, include
from Referans.Views import testView
from django.conf.urls.i18n import i18n_patterns
app_name ="Test"

urlpatterns = [
    path('', testView.test_listele , name="test"),
    path('test/json/', testView.test_json, name='test_json'),

]
</code>```

test.html

```<code>            <div class="card-body">

                <table id="myTable2" class="table datatable-responsive-control-right">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Kod</th>
                        <th>Açıklama1</th>
                        <th>Açıklama2</th>
                        <th>SayKod</th>
                        <th>GrupKod</th>
                    </tr>
                    </thead>
                </table>

                </div>

            {% block js%}
            <script>

            $(document).ready( function () {
            var t0 = performance.now();
            degerleriGetir('test/json')
            var t1 = performance.now();

            });

            function degerleriGetir(data){

                table =$('#myTable2').DataTable({
                        Serverside:true,
                        Processing: true,
                        orderClasses: false,
                        bSortClasses:false,
                        bDeferRender: true,
                        scrollCollapse: true,
                        scrollY: 500,
                        stateSave: true,
                        scroller: {
                            loadingIndicator: true
                        },
                        ajax:{
                        url:('test/json'),
                        processing:true,
                        },
                        destroy:true,
                        columns: [
                        {'data': 'Id'},
                        {'data': 'Kod'},
                        {'data': 'Aciklama1'},
                        {'data': 'Aciklama2'},
                        {'data': 'GrupKod'},
                        {'data': 'SayKod'}
                        ]
                    });
            };

            </script>

            {% endblock js  %}
</code>```

答:
Asyncronous loading is made with ajax request, for example. The javascript controls which pages the user wants to see, making a request to django "view_url+?page=X". Then, get the info (usually in json) and loads the content into html. I never used DataTable, so i can't tell you exactly what you have to do. What I am telling you is what you can do to achieve this asynchronous loading. Other option is paginating normally, loading the page each time for each page (so much easier to implement by hand). Take a look to django ListView model to make your implementation easier and faster!

Good luck!

Body:
I want to take large data (examples 5 000,000) with datatables in Django .But Proccessing is slowly (Page Load is 12 seconds).Users login to webpage. Then Click to Test .html. Backend procces run to test_json in Views. Views call taking db data with to_dict_json.  On Models.py. This method in Views return Json response objects.
How to make faster large data in Django with datatables

Models.py

class SysTest(models.Model):

class Meta:
    db_table = 'sysTest'

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Tip = models.ForeignKey(SysRefTip, on_delete=models.CASCADE)
Kod = models.CharField(_("Kod"), max_length=20, blank=False, null=False)
Aciklama1 = models.CharField(_("Açıklama 1"), max_length=100,blank=True, null=True)
Aciklama2 = models.CharField(_("Açıklama 2"), max_length=100,blank=True, null=True)
GrupKod = models.CharField(_("Grup Kodu"), max_length=20,blank=True, null=True)
SayKod = models.FloatField(_("Sayısal Değer"),blank=True, null=True)

def to_dict_json(self):

    return{
        'Id':self.id,
        'Kod':self.Kod,
        'Aciklama1':self.Aciklama1,
        'Aciklama2':self.Aciklama2,
        'GrupKod':self.GrupKod,
        'SayKod':self.SayKod,
    }

View.py

def test_json(request):
    persons  = SysTest.objects.all()
    data = [person.to_dict_json() for person in persons ]
    response = {'data': data}
   return JsonResponse(response,safe=False,content_type="application/json")

Urls.py

from django.urls import path, include
from Referans.Views import testView
from django.conf.urls.i18n import i18n_patterns
app_name ="Test"

urlpatterns = [
    path('', testView.test_listele , name="test"),
    path('test/json/', testView.test_json, name='test_json'),

]

test.html

                        Id
                        Kod
                        Açıklama1
                        Açıklama2
                        SayKod
                        GrupKod

            {% block js%}

            {% endblock js  %}


问:
Page navigation menu is hidding on the top of the page after scroll up on iOS
I want to make a navigation menu that hiddes after scrolling down and appears back after scrolling up. Everything is working fine on desktop and Android browsers. Problem occours on iOS devices. When you scroll up to the top of the page and release menu hides.

I only found old answers to problem with menu not showing at all on scrolling up, but that should not be a problem with newer versions of Safari.

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;

  if (prevScrollpos > currentScrollPos) {
    document.getElementById("main-header").style.top = "0";
  } else {
    document.getElementById("main-header").style.top = "-90px";
  }
    prevScrollpos = currentScrollPos;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="main-header container-fluid menu-on-top" id="main-header">
  <div class="row">
    <div class="container fixposition">
      <nav class="navbar navbar-toggleable-lg navbar-light bg-faded navbar-expand-xl ">
        <button id="button-nav" class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#menu-nawigacyjne" aria-controls="menu-nawigacyjne" aria-expanded="false" aria-label="Toggle navigation">

  ">

  <div class="collapse navbar-collapse primary-menu m-auto" id="menu-nawigacyjne">
   <?php if ( has_nav_menu( 'primary' ) ) : ?>
       <?php
       wp_nav_menu( array(
        'theme_location' => 'primary',
        'items_wrap' => '<ul class="nav navbar-nav m-auto">%3$s</ul>'
       ) );
       ?>
      <?php endif; ?>
     </div>
    </nav>
   </div>
  </div>
 </header></code>```

                    <button id="button-nav"  class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#menu-nawigacyjne" aria-controls="menu-nawigacyjne" aria-expanded="false" aria-label="Toggle navigation">

                    ">

                        <?php if ( has_nav_menu( 'primary' ) ) : ?>
                            <?php
                            wp_nav_menu( array(
                                'theme_location' => 'primary',
                                'items_wrap' => '
%3$s
'
                            ) );
                            ?>
                        <?php endif; ?>

```

答: I managed to resolve this by adding a top: 0; to a class "menu-on-top" that was added every time page was on the top of the screen.</p>

Body:
I want to make a navigation menu that hiddes after scrolling down and appears back after scrolling up. Everything is working fine on desktop and Android browsers. Problem occours on iOS devices. When you scroll up to the top of the page and release menu hides.

I only found old answers to problem with menu not showing at all on scrolling up, but that should not be a problem with newer versions of Safari.

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;

  if (prevScrollpos > currentScrollPos) {
    document.getElementById("main-header").style.top = "0";
  } else {
    document.getElementById("main-header").style.top = "-90px";
  }
    prevScrollpos = currentScrollPos;
};

        <button id="button-nav" class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#menu-nawigacyjne" aria-controls="menu-nawigacyjne" aria-expanded="false" aria-label="Toggle navigation">

  <a class="navbar-brand d-flex align-items-center" href="<?php echo esc_url( home_url( '/' ) ); ?>">

   <?php if ( has_nav_menu( 'primary' ) ) : ?>
       <?php
       wp_nav_menu( array(
        'theme_location' => 'primary',
        'items_wrap' => '
%3$s
'
       ) );
       ?>
      <?php endif; ?>

                    <button id="button-nav"  class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#menu-nawigacyjne" aria-controls="menu-nawigacyjne" aria-expanded="false" aria-label="Toggle navigation">

                    <a class="navbar-brand d-flex align-items-center" href="<?php echo esc_url( home_url( '/' ) ); ?>">

                        <?php if ( has_nav_menu( 'primary' ) ) : ?>
                            <?php
                            wp_nav_menu( array(
                                'theme_location' => 'primary',
                                'items_wrap' => '
%3$s
'
                            ) );
                            ?>
                        <?php endif; ?>


问:
Adding array into an array item
I am populating a json file and I have an array like this

```<code>[{ name: name, address: address, age: age }]

[{ name2: name2, address2: address2, age2: age2 }]
</code>```

Now, I want to merge these two arrays and I'm expecting a result like this

```<code>[
    { name: name, address: address, age: age },
    { name2: name2, address2: address2, age2: age2 }
]
</code>```

答:
Another option...</p>

```<code>var array1 = [{ name: name, address: address, age: age }]
var array2 = [{ name2: name2, address2: address2, age2: age2 }]

var merged = array1.concat(array2)
</code>```

Title: Adding array into an array item

Body:
I am populating a json file and I have an array like this

[{ name: name, address: address, age: age }]

[{ name2: name2, address2: address2, age2: age2 }]

Now, I want to merge these two arrays and I'm expecting a result like this

[
    { name: name, address: address, age: age },
    { name2: name2, address2: address2, age2: age2 }
]

Body:
Another option...

var array1 = [{ name: name, address: address, age: age }]
var array2 = [{ name2: name2, address2: address2, age2: age2 }]

var merged = array1.concat(array2)


问:
Setting active tab in ASP.NET Ajax TabContainer causes entire container to disappear
I have an ASP.NET page that uses the ASP.NET Ajax Control Toolkit TabContainer. In the Page_Load event, I am hiding some of the tabs based on the data given to the page. I then want to make one of the tabs active based on the value of an (optional) query string parameter.

So I have:

```<code>protected void Page_Load ( object sender, EventArgs e )
{
    if ( !this.IsPostBack )
    {
        // Tabs with no data are hidden in here
        LoadDataIntoTabs();

        PreselectCorrectTab();
    }
}

private void PreselectCorrectTab ()
{
    if ( ctlTabContainer.Visible )
    {
        if ( !string.IsNullOrEmpty( Request.QueryString[ "tabIndex" ] ) )
        {
            int tabIndex = 0;

            if ( int.TryParse( Request.QueryString[ "tabIndex" ], out tabIndex ) )
            {
                if ( ( ctlTabContainer.Tabs.Count > tabIndex ) && ctlTabContainer.Tabs[ tabIndex ].Visible )
                {
                    ctlTabContainer.ActiveTabIndex = tabIndex;
                }
            }
        }
    }
}
</code>```

If I hit the page with the tabIndex query string parameter set, the entire tab container disappears.

The strange thing is that if I change LoadDataIntoTabs() to not hide tabs that contain no data, everything works as you would expect (i.e. the correct tab is selected when the page renders).

Any ideas?

EDIT

As requested, here are more details:

```<code>private void LoadDataIntoTabs ()
{
    LoadPendingWidgetsTab();
    LoadDataIntoTab2();
    LoadDataIntoTab3();
    // etc...
}

private void LoadPendingWidgetsTab ()
{
    IList<Widget> pendingWidgets = GetAllPendingWidgets();

    if ( ( pendingWidgets != null ) && ( pendingWidgets.Count > 0 ) )
    {
        tbpPendingWidgets.Visible = true;
        tbpPendingWidgets.HeaderText = String.Format( "Pending Widgets ({0})", pendingWidgets.Count );

        grdPendingWidgets.DataSource = pendingWidgets;
        grdPendingWidgets.DataBind();
    }
    else
    {
        tbpPendingWidgets.Visible = false;
    }
}
</code>```

答:
This worked for me:

Manually resetting the index, the visibility and the active tab.

```<code> tabcontainer.ActiveTab = tabname
 tabcontainer.Visible = True
 tabcontainer.ActiveTabIndex = 2
</code>```

In another situation where I was not trying to set the active tab, I had to reset  tabcontainer.ActiveTabIndex = 0.

So I put the two together and it worked.

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET page that uses the ASP.NET Ajax Control Toolkit TabContainer. In the Page_Load event, I am hiding some of the tabs based on the data given to the page. I then want to make one of the tabs active based on the value of an (optional) query string parameter.

So I have:

protected void Page_Load ( object sender, EventArgs e )
{
    if ( !this.IsPostBack )
    {
        // Tabs with no data are hidden in here
        LoadDataIntoTabs();

        PreselectCorrectTab();
    }
}

private void PreselectCorrectTab ()
{
    if ( ctlTabContainer.Visible )
    {
        if ( !string.IsNullOrEmpty( Request.QueryString[ "tabIndex" ] ) )
        {
            int tabIndex = 0;

            if ( int.TryParse( Request.QueryString[ "tabIndex" ], out tabIndex ) )
            {
                if ( ( ctlTabContainer.Tabs.Count > tabIndex ) && ctlTabContainer.Tabs[ tabIndex ].Visible )
                {
                    ctlTabContainer.ActiveTabIndex = tabIndex;
                }
            }
        }
    }
}

If I hit the page with the tabIndex query string parameter set, the entire tab container disappears.

The strange thing is that if I change LoadDataIntoTabs() to not hide tabs that contain no data, everything works as you would expect (i.e. the correct tab is selected when the page renders).

Any ideas?

EDIT

As requested, here are more details:

private void LoadDataIntoTabs ()
{
    LoadPendingWidgetsTab();
    LoadDataIntoTab2();
    LoadDataIntoTab3();
    // etc...
}

private void LoadPendingWidgetsTab ()
{
    IList<Widget> pendingWidgets = GetAllPendingWidgets();

    if ( ( pendingWidgets != null ) && ( pendingWidgets.Count > 0 ) )
    {
        tbpPendingWidgets.Visible = true;
        tbpPendingWidgets.HeaderText = String.Format( "Pending Widgets ({0})", pendingWidgets.Count );

        grdPendingWidgets.DataSource = pendingWidgets;
        grdPendingWidgets.DataBind();
    }
    else
    {
        tbpPendingWidgets.Visible = false;
    }
}

Body:
This worked for me:

Manually resetting the index, the visibility and the active tab.

 tabcontainer.ActiveTab = tabname
 tabcontainer.Visible = True
 tabcontainer.ActiveTabIndex = 2

In another situation where I was not trying to set the active tab, I had to reset  tabcontainer.ActiveTabIndex = 0.

So I put the two together and it worked.

ContentLicense: CC BY-SA 3.0


问:
Why does it always return true?
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

```<code>if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}
</code>```

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

答:
Order of Precedence decides

In each programming language, symbols are processed in order of their precedence order.

In Short:

AS the others already explained, your assignment

```<code>firstSymbol === "A" || "a" || "D" || "d"
</code>```

would be processed as

```<code>(firstSymbol === "A") || ("a") || ("D") || ("d")
</code>```

Link to how logical operators are processed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Title: Why does it always return true?

Body:
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

Body:
Order of Precedence decides

In each programming language, symbols are processed in order of their precedence order.

In Short:

AS the others already explained, your assignment

firstSymbol === "A" || "a" || "D" || "d"

would be processed as

(firstSymbol === "A") || ("a") || ("D") || ("d")

Link to how logical operators are processed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence


问:
Dynamic modal content with multiple variables
I realise that this has been asked a number of ways already, but for the life of me I cant find one that is similar to my issue....
I have the adapted the 'recognised' code in the documentation for showing dynamic content in a modal to the following.

Pulling my hair out, and sure I am just doing something silly.......

HTML for the call

```<code>                                <div class="row">
                                    <?php $option=array_column($options, 'name', 'id');?>
                                    <div class="col-5 col-md-6 col-lg-2 clickable" data-toggle="modal" data-target="#Engine1Modal" data-thing1="<?php echo $option[$vesseldata['Engine1Type']];?>" data-thing2="<?php echo $vesseldata['Engine1Number'];?>" title="Update Engine 1">Engine 1</div>
                                    <div class="col-7 col-md-6 col-lg-4">
                                        <a href="#" data-toggle="modal" data-target="#Engine1Modal" data-thing1="<?php echo $option[$vesseldata['Engine1Type']];?>" data-thing2="<?php echo $vesseldata['Engine1Number'];?>" title="Update Engine 1">
                                            <?php echo $option[$vesseldata['Engine1Type']];?>
                                        </a>
                                    </div>
                                    <div class="col-5 col-md-6 col-lg-2>Engine 1 Serial</div><div class="col-7 col-md-6 col-lg-4"><?php echo $vesseldata['Engine1Number'];?></div>
                                </div>

</code>```

Then the script is just embedded in the page at the moment to try and make life easy.

```<code>                <script>
                        $('#Engine2Modal').on('show.bs.modal', function (event) {
                          var trigger = $(event.relatedTarget); // Button that triggered the modal
                          var thing1 = trigger.data('thing1'); // Extract info from data-* attributes
                          var thing2 = trigger.data('thing2'); // Extract info from data-* attributes
                          // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                          // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                          var modal = $(this);
                          modal.find('.modal-title').text(thing1 + '<br>Serial # ' + thing2);
                          });
                                      </script>

</code>```

Then the Modal html is here

```<code><div class="modal right fade in" id="Engine2Modal" tabindex="-1" role="dialog"  aria-labelledby="ModalLabel" aria-hidden="true">
    <form id="service_form"  method="get">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="ModalLabel">New message</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>

                    <div class="modal-body">
                        <div class="row">
                            <label class="control-label col-xs-4 col-md-3" for="DesignRef">Design Reference</label>
                            <div class="col-xs-8  col-md-7">
                            <input type="text" class="form-control" name="DesignRef" id="DesignRef" placeholder="Design Reference" value=""/>
                            <?php if(!empty($registration_error['DesignRef'])) { ?>
                                    <br/>
                                    <div class="alert alert-danger" role="alert"><?php echo $registration_error['DesignRef']; ?></div>
                            <?php } ?>
                            </div>
                        </div>
                    </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </form>
</div>

</code>```

答:
Finally found it......

Found an article that explains that the text method is not actually the right one to use if you want to parse HTML.  And in fact there is an HTML method in jQuery... :-)

```<code>                        modal.find('.modal-title1').html(item);
</code>```

works.

Body:
I realise that this has been asked a number of ways already, but for the life of me I cant find one that is similar to my issue....
I have the adapted the 'recognised' code in the documentation for showing dynamic content in a modal to the following.

Pulling my hair out, and sure I am just doing something silly.......

HTML for the call

                                    <?php $option=array_column($options, 'name', 'id');?>
                                    <div class="col-5 col-md-6 col-lg-2 clickable" data-toggle="modal" data-target="#Engine1Modal" data-thing1="<?php echo $option[$vesseldata['Engine1Type']];?>" data-thing2="<?php echo $vesseldata['Engine1Number'];?>" title="Update Engine 1">Engine 1

                                        <a href="#" data-toggle="modal" data-target="#Engine1Modal" data-thing1="<?php echo $option[$vesseldata['Engine1Type']];?>" data-thing2="<?php echo $vesseldata['Engine1Number'];?>" title="Update Engine 1">
                                            <?php echo $option[$vesseldata['Engine1Type']];?>

Engine 1 Serial

<?php echo $vesseldata['Engine1Number'];?>

Then the script is just embedded in the page at the moment to try and make life easy.

Then the Modal html is here

    <form id="service_form"  method="get">

New message

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            ×
                        </button>

                            Design Reference

                            <input type="text" class="form-control" name="DesignRef" id="DesignRef" placeholder="Design Reference" value=""/>
                            <?php if(!empty($registration_error['DesignRef'])) { ?>

<?php echo $registration_error['DesignRef']; ?>

                            <?php } ?>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

    </form>

Body:
Finally found it......

Found an article that explains that the text method is not actually the right one to use if you want to parse HTML.  And in fact there is an HTML method in jQuery... :-)

                        modal.find('.modal-title1').html(item);

works.


问:
How Mapper and Reducer works together "without" sorting?
I know how the map reduces works and what steps I have:

Mapping

Shuffle and sorting

Reducing

Off course I have Partitioning, Combiners but that's not important right now.

The interesting is that when I run map reduce jobs, looks like mappers and reducers work in parallel:

So I don't understand how it is possible.

Question  1.
If I have multiple nodes that are doing mapping operation, how reducer can start working? Because Reducer can't start working without sorting right? (The input must be sorted for Reducer - if the mapper is still working, input can't be sorted).

Question 2.
If I have multiple reducers, how the final data will be merged together? In other words, final results should be sorted right? It means we spend additional O( n*Log n) time to merge "multiple reducer results?"

答:
Reducers can start copying results from mappers as soon as they become available. It is called copy phase of the reduce task (see Hadoop the Definitive Guide, Chapter 7 How MapReduce Works).

Also from there:

...When all the map outputs have been copied, the reduce task moves into
  the sort phase (which should properly be called the merge phase, as
  the sorting was carried out on the map side), which merges the map
  outputs, maintaining their sort ordering. This is done in rounds...


问:
mongodb spring connection lost overnight
I'm using azure cosmosdb with mongoAPI (spring data, mongoRepository)
Each morning, first request to fetch data from mongo causes exception:

Following requests succeed without doing any actions.

Any idea what might be causing this?
Is there a way to have spring automatically recover connections without failing request?

Thanks

The exception:

```<code>org.springframework.data.mongodb.UncategorizedMongoDbException: Exception sending message; nested exception is com.mongodb.MongoSocketWriteException: Exception sending message
        at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:107)
        at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1978)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1784)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1767)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:641)
        at org.springframework.data.mongodb.repository.query.MongoQueryExecution$CollectionExecution.execute(MongoQueryExecution.java:79)
        at org.springframework.data.mongodb.repository.query.MongoQueryExecution$ResultProcessingExecution.execute(MongoQueryExecution.java:411)
        at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:94)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
...
Caused by: com.mongodb.MongoSocketWriteException: Exception sending message
        at com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:465)
        at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:208)
        at com.mongodb.connection.UsageTrackingInternalConnection.sendMessage(UsageTrackingInternalConnection.java:90)
        at com.mongodb.connection.DefaultConnectionPool$PooledConnection.sendMessage(DefaultConnectionPool.java:429)
        at com.mongodb.connection.CommandProtocol.sendMessage(CommandProtocol.java:189)
        at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:111)
        at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168)
        at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289)
        at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:176)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:216)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:207)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:113)
        at com.mongodb.operation.FindOperation$1.call(FindOperation.java:516)
        at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510)
        at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431)
        at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:510)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:81)
        at com.mongodb.Mongo.execute(Mongo.java:836)
        at com.mongodb.Mongo$2.execute(Mongo.java:823)
        at com.mongodb.DBCursor.initializeCursor(DBCursor.java:870)
        at com.mongodb.DBCursor.hasNext(DBCursor.java:142)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1964)
        ... 129 common frames omitted
Caused by: java.net.SocketException: Broken pipe (Write failed)
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
        at sun.security.ssl.OutputRecord.writeBuffer(OutputRecord.java:431)
        at sun.security.ssl.OutputRecord.write(OutputRecord.java:417)
        at sun.security.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:886)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:857)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
        at com.mongodb.connection.SocketStream.write(SocketStream.java:75)
        at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204)
        ... 150 common frames omitted
</code>```

答:
It closes the connection because of passing the maximum connection idle time.

You will need to set this property according to your requirement.

```<code>maxConnectionIdleTime
</code>```

This can be set either on your Mongo configuration or application profile.

Good luck.

Body:
I'm using azure cosmosdb with mongoAPI (spring data, mongoRepository)
Each morning, first request to fetch data from mongo causes exception:

Following requests succeed without doing any actions.

Any idea what might be causing this?
Is there a way to have spring automatically recover connections without failing request?

Thanks

The exception:

org.springframework.data.mongodb.UncategorizedMongoDbException: Exception sending message; nested exception is com.mongodb.MongoSocketWriteException: Exception sending message
        at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:107)
        at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1978)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1784)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1767)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:641)
        at org.springframework.data.mongodb.repository.query.MongoQueryExecution$CollectionExecution.execute(MongoQueryExecution.java:79)
        at org.springframework.data.mongodb.repository.query.MongoQueryExecution$ResultProcessingExecution.execute(MongoQueryExecution.java:411)
        at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:94)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
...
Caused by: com.mongodb.MongoSocketWriteException: Exception sending message
        at com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:465)
        at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:208)
        at com.mongodb.connection.UsageTrackingInternalConnection.sendMessage(UsageTrackingInternalConnection.java:90)
        at com.mongodb.connection.DefaultConnectionPool$PooledConnection.sendMessage(DefaultConnectionPool.java:429)
        at com.mongodb.connection.CommandProtocol.sendMessage(CommandProtocol.java:189)
        at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:111)
        at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168)
        at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289)
        at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:176)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:216)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:207)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:113)
        at com.mongodb.operation.FindOperation$1.call(FindOperation.java:516)
        at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510)
        at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431)
        at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:510)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:81)
        at com.mongodb.Mongo.execute(Mongo.java:836)
        at com.mongodb.Mongo$2.execute(Mongo.java:823)
        at com.mongodb.DBCursor.initializeCursor(DBCursor.java:870)
        at com.mongodb.DBCursor.hasNext(DBCursor.java:142)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1964)
        ... 129 common frames omitted
Caused by: java.net.SocketException: Broken pipe (Write failed)
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
        at sun.security.ssl.OutputRecord.writeBuffer(OutputRecord.java:431)
        at sun.security.ssl.OutputRecord.write(OutputRecord.java:417)
        at sun.security.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:886)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:857)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
        at com.mongodb.connection.SocketStream.write(SocketStream.java:75)
        at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204)
        ... 150 common frames omitted

Body:
It closes the connection because of passing the maximum connection idle time.

You will need to set this property according to your requirement.

maxConnectionIdleTime

This can be set either on your Mongo configuration or application profile.

Good luck.


问:
Find the name(s) of students who have secured maximum marks in each subject
Write a query to display subject names and student name who have secured maximum marks in each subject ordered by subject_name in ascending order. The solution has to be implemented in subquery.

I have used below query :

```<code> select subject_name, student_name
 from subject s
 inner join mark m
 on s.subject_id=m.subject_id
 inner join student s1
  on m.student_id=s1.student_id
  where student_id in  (select student_id
                          from mark
                         having max(value)
                          group by s.subject_id)
  order by s.subject_name;
</code>```

But this code gives an error at the 10th line of invalid relational operator

PLEASE HELP!!

答:
The clause HAVING must be used to add conditions when you use aggregation functions, because the where clause does not allow it,the sintaxys is:

```<code>**SELECT columns FROM table_name WHERE condition GROUP BY columns HAVING condition**
</code>```

Where HAVING condition is for example:  max(value) > 1000

Your subquery should look like this:

```<code>SELECT student_id, max(value)
FROM   mark
WHERE  student_id = s.subject_id
GROUP BY student_id
HAVING  MAX(value) > 1000;
</code>```

Regards!

Body:
Write a query to display subject names and student name who have secured maximum marks in each subject ordered by subject_name in ascending order. The solution has to be implemented in subquery.

I have used below query :

 select subject_name, student_name
 from subject s
 inner join mark m
 on s.subject_id=m.subject_id
 inner join student s1
  on m.student_id=s1.student_id
  where student_id in  (select student_id
                          from mark
                         having max(value)
                          group by s.subject_id)
  order by s.subject_name;

But this code gives an error at the 10th line of invalid relational operator

PLEASE HELP!!

Body:
The clause HAVING must be used to add conditions when you use aggregation functions, because the where clause does not allow it,the sintaxys is:

**SELECT columns FROM table_name WHERE condition GROUP BY columns HAVING condition**

Where HAVING condition is for example:  max(value) > 1000

Your subquery should look like this:

SELECT student_id, max(value)
FROM   mark
WHERE  student_id = s.subject_id
GROUP BY student_id
HAVING  MAX(value) > 1000;

Regards!


问:
protected destructor with unique_ptr
I am trying to call APIs from a third party library.

There is a trouble when I want to use unique_ptr with a class having protected destructor.

Here is the example,

```<code>#include <memory>
#include <iostream>

using namespace std;

class Parent {
  public:
    Parent () //Constructor
    {
        cout << "\n Parent constructor called\n" << endl;
    }
  protected:
    ~ Parent() //Dtor
    {
        cout << "\n Parent destructor called\n" << endl;
    }
};

class Child : public Parent
{
  public:
    Child () //Ctor
    {
        cout << "\nChild constructor called\n" << endl;
    }
    ~Child() //dtor
    {
        cout << "\nChild destructor called\n" << endl;
    }
};

Parent* get() {
  return new Child();
}

int main(int argc, char const* argv[])
{
  Parent * p1 = get(); // this is ok
  std::unique_ptr<Parent> p2(get()); // this is not ok
  return 0;
}
</code>```

I am trying to use unique_ptr with Parent class. But the compiler threw the errors

```<code>/usr/include/c++/5/bits/unique_ptr.h: In instantiation
of ‘void std::default_delete<_Tp>::operator()(_Tp*) const
[with _Tp = Parent]’:
/usr/include/c++/5/bits/unique_ptr.h:236:17:   required
from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp
= Parent; _Dp = std::default_delete<Parent>]’
main.cpp:38:35:   required from here
main.cpp:12:5: error: ‘Parent::~Parent()’ is protected
 ~ Parent() //Dtor
 ^
In file included from /usr/include/c++/5/memory:81:0,
             from main.cpp:2:
/usr/include/c++/5/bits/unique_ptr.h:76:2: error: within
this context
  delete __ptr;
</code>```

Any idea about getting rid of this issue? I can't hack Parent and Child class since they are the classes of the third party library.

答:
Unfortunately, the real way to get rid of this issue is to not derive classes from Parent, and to not manage the lifetime of Parent objects (or any derived classes) using std::unique_ptr<Parent>.

In other words, you need to redesign your classes.

The reasons I say this are

If someone has gone to the trouble of giving Parent a protected non-virtual destructor, the intent is most likely to avoid having a Parent * which actually points at an instance of a derived class and is released using operator delete.  A library designer will not (normally) do this without good reason.

Your code can be forced to compile as is (e.g. by making std::default_delete<Parent> a friend of Parent).   However, std::default_delete is used by unique_ptr to release the managed object.   And it uses operator delete.   That gives undefined behaviour if the object being managed by the unique_ptr<Parent> is of a type derived from Parent.

So, in short, you're working around the intent of (whoever designed) your third party library and, if you force the code to compile anyway, your reward will be undefined behaviour.

Title: protected destructor with unique_ptr

Body:
I am trying to call APIs from a third party library.

There is a trouble when I want to use unique_ptr with a class having protected destructor.

Here is the example,

#include <memory>
#include <iostream>

using namespace std;

class Parent {
  public:
    Parent () //Constructor
    {
        cout << "\n Parent constructor called\n" << endl;
    }
  protected:
    ~ Parent() //Dtor
    {
        cout << "\n Parent destructor called\n" << endl;
    }
};

class Child : public Parent
{
  public:
    Child () //Ctor
    {
        cout << "\nChild constructor called\n" << endl;
    }
    ~Child() //dtor
    {
        cout << "\nChild destructor called\n" << endl;
    }
};

Parent* get() {
  return new Child();
}

int main(int argc, char const* argv[])
{
  Parent * p1 = get(); // this is ok
  std::unique_ptr<Parent> p2(get()); // this is not ok
  return 0;
}

I am trying to use unique_ptr with Parent class. But the compiler threw the errors

/usr/include/c++/5/bits/unique_ptr.h: In instantiation
of ‘void std::default_delete<_Tp>::operator()(_Tp*) const
[with _Tp = Parent]’:
/usr/include/c++/5/bits/unique_ptr.h:236:17:   required
from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp
= Parent; _Dp = std::default_delete<Parent>]’
main.cpp:38:35:   required from here
main.cpp:12:5: error: ‘Parent::~Parent()’ is protected
 ~ Parent() //Dtor
 ^
In file included from /usr/include/c++/5/memory:81:0,
             from main.cpp:2:
/usr/include/c++/5/bits/unique_ptr.h:76:2: error: within
this context
  delete __ptr;

Any idea about getting rid of this issue? I can't hack Parent and Child class since they are the classes of the third party library.


问:
Filter a one to many relation record result
I need to filter the results given from a one to many relation directly from the model object, but I cant find the right way.
Here, the relations:

I have a User model that can subscript to many companies (company model), and a company can have many users subscripted to it, so, is a many to many relation.

In every company, this user has a personal info, so, every user, could have many profiles (profile model) one for each company that is subscripted to.
So It is a one to many relation.

Imagine I want to retrieve the company that a user is currently viewing directly from the model, this, Im achieving by filtering the many to many relation:

```<code>class User extends Authenticatable
{
///
 public function obtainLoggedOnCompany()
 {
   return $this->belongsToMany('app\Company', 'user_company', 'id', 'company_id')->withPivot('selected')->wherePivot('selected', 1)
 }
</code>```

Then, if I want to return the selected company in a blade view I just call:

Auth::user()->obtainLoggedOnCompany->first();

All thanks to the withPivot and wherePivot clause.

Different is the case when I want to retrieve the registered profile of a currently selected company, I tried:

```<code>public function obtainSelectedProfile()
{
$SelectedCompany= $this->obtainLoggedOnCompany->first();

return $this->hasMany('app\Profile','user_id')->where('company_id', '=', $SelectedCompany->company_id);
}
</code>```

But it throws a Trying to get property of non object Exception.
Is there another way to filter one to many relations directly in the model relation function?

Iam using Laravel 5.2

答:
actually, this sentence works perfectly!:

```<code>public function obtainSelectedProfile()
{
$SelectedCompany= $this->obtainLoggedOnCompany->first();

return $this->hasMany('app\Profile','user_id')->where('company_id', '=',
$SelectedCompany->company_id);
}
</code>```

My error was elswhere on my view!

Though I think Its a better practice to prepare the data on the controller before passing it to the view, because I would have to query to server every single time I want to get data from the user profile on the fly in the view.

Body:
I need to filter the results given from a one to many relation directly from the model object, but I cant find the right way.
Here, the relations:

I have a User model that can subscript to many companies (company model), and a company can have many users subscripted to it, so, is a many to many relation.

In every company, this user has a personal info, so, every user, could have many profiles (profile model) one for each company that is subscripted to.
So It is a one to many relation.

Imagine I want to retrieve the company that a user is currently viewing directly from the model, this, Im achieving by filtering the many to many relation:

class User extends Authenticatable
{
///
 public function obtainLoggedOnCompany()
 {
   return $this->belongsToMany('app\Company', 'user_company', 'id', 'company_id')->withPivot('selected')->wherePivot('selected', 1)
 }

Then, if I want to return the selected company in a blade view I just call:

Auth::user()->obtainLoggedOnCompany->first();

All thanks to the withPivot and wherePivot clause.

Different is the case when I want to retrieve the registered profile of a currently selected company, I tried:

public function obtainSelectedProfile()
{
$SelectedCompany= $this->obtainLoggedOnCompany->first();

return $this->hasMany('app\Profile','user_id')->where('company_id', '=', $SelectedCompany->company_id);
}

But it throws a Trying to get property of non object Exception.
Is there another way to filter one to many relations directly in the model relation function?

Iam using Laravel 5.2

Body:
actually, this sentence works perfectly!:

public function obtainSelectedProfile()
{
$SelectedCompany= $this->obtainLoggedOnCompany->first();

return $this->hasMany('app\Profile','user_id')->where('company_id', '=',
$SelectedCompany->company_id);
}

My error was elswhere on my view!

Though I think Its a better practice to prepare the data on the controller before passing it to the view, because I would have to query to server every single time I want to get data from the user profile on the fly in the view.


问:
How Do I Write Data To A SQLite Database Using Adobe Air?
I'm absolutely struggling with this. I am building an application using Adobe Air that will allow us to vote on calls we receive (such as is the call a sales call, complaint, or a query about a product) and save these votes for viewing later on.

I've built the interface with all the radio buttons, and it has compiled successfully, but that is as far as I've managed to get. I don't know if it is loading the database that I have provided and even if I knew this I don't know how to get it to write the data to the database.

I've used Google and a lot of websites it lists don't go over how to insert and retrieve data using Adobe Air with SQLite (even though I'm lead to believe this is the database Adobe have packaged with it).

Any help on this I would be very grateful for.

Cheers

答:
Have a look on the following:
https://stackoverflow.com/questions/2883989/basic-crud-in-adobe-air-flex

http://www.12robots.com/index.cfm/2009/7/14/Using-SQLite-Databases-with-AIR--Series-Introduction

http://devworks.thinkdigit.com/Features/Using-an-SQLite-database-in-an-AIR_6471.html


问:
How do I get the average of each similar column value?
Say I have this:

```<code>     tag     value

1    apple    3

2    banana   5

3    apple    4

4    banana   2
</code>```

How can I have a query get the average of each value with respect to the tags?

So like:

```<code>    tag      value

1   apple    3.5

2   banana   3.5
</code>```

I can get the average of the whole column easily with an inner select, but have no idea how to do so with respect to the tag.

答:
You can simply use group by and avg():

```<code>select
     tag
    ,avg(value)
from yourTable
group by tag
</code>```

Body:
Say I have this:

     tag     value

1    apple    3

2    banana   5

3    apple    4

4    banana   2

How can I have a query get the average of each value with respect to the tags?

So like:

    tag      value

1   apple    3.5

2   banana   3.5

I can get the average of the whole column easily with an inner select, but have no idea how to do so with respect to the tag.

Body:
You can simply use group by and avg():

select
     tag
    ,avg(value)
from yourTable
group by tag


问:
Failed to load resource: Request timed out on Safari in my wordpress site
I have wordpress site. Recently we have getting issue in ajax request.
In website,  we have open popup for register when I click on register and call ajax it's getting "Failed to load resource: Request timed out. "  on safari browser only

I tried with async:true, timeout and also setTimeout for solve this issue but no one working.

```<code>var request = $.ajax({
                url: jobifySettings.homeurl,
                data: data,
                type: 'POST',
                cache: false
            }).done(function(response) {
                form.find( $( '.woocommerce-error' ) ).remove();

                var $response = $( '#ajax-response' );
                var html = $.parseHTML(response);

                console.log( response );

                $response.append(html);
                error = $response.find( $( '.woocommerce-error' ) );

                if ( error.length > 0 ) {
                    form.prepend( error.clone() );
                    $response.html('');

                    e.preventDefault();
                }
            });
</code>```

答:
Firstly I would say to keep async set to true in your ajax settings (which you said you tried), as this will make Safari hold the connection open until you get a response back (and then close it).

However, if this is not working on it's own for you, you could try adding a cross-origin 'CORS' header (Header set Access-Control-Allow-Methods: "*") in your htaccess file. If you have issues with CORS, this troubleshooting link may help.

Quote from link: (in case it breaks in future)

```<code><ifmodule mod_headers.c="">
   SetEnvIf Origin "^(.*\.domain\.com)$" ORIGIN_SUB_DOMAIN=$1
   Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
   Header set Access-Control-Allow-Methods: "*"
   Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</ifmodule>
</code>```

Body:
I have wordpress site. Recently we have getting issue in ajax request.
In website,  we have open popup for register when I click on register and call ajax it's getting "Failed to load resource: Request timed out. "  on safari browser only

I tried with async:true, timeout and also setTimeout for solve this issue but no one working.

var request = $.ajax({
                url: jobifySettings.homeurl,
                data: data,
                type: 'POST',
                cache: false
            }).done(function(response) {
                form.find( $( '.woocommerce-error' ) ).remove();

                var $response = $( '#ajax-response' );
                var html = $.parseHTML(response);

                console.log( response );

                $response.append(html);
                error = $response.find( $( '.woocommerce-error' ) );

                if ( error.length > 0 ) {
                    form.prepend( error.clone() );
                    $response.html('');

                    e.preventDefault();
                }
            });

Body:
Firstly I would say to keep async set to true in your ajax settings (which you said you tried), as this will make Safari hold the connection open until you get a response back (and then close it).

However, if this is not working on it's own for you, you could try adding a cross-origin 'CORS' header (Header set Access-Control-Allow-Methods: "*") in your htaccess file. If you have issues with CORS, this troubleshooting link may help.

Quote from link: (in case it breaks in future)

<ifmodule mod_headers.c="">
   SetEnvIf Origin "^(.*\.domain\.com)$" ORIGIN_SUB_DOMAIN=$1
   Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
   Header set Access-Control-Allow-Methods: "*"
   Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</ifmodule>


问:
Use SQLCMD to execute script return Invalid object name
I have to insert a very large amount of data in sql, the operation did not work via SQL Management Studio therefore I was investigating the insert via sqlcmd. so what I did was the following:

create a file.sql that contains the following query (multiple times):

```<code>IF NOT EXISTS (SELECT * FROM [dbo].[tblAccount]
               WHERE [AccountID] = 117242 AND
                     [TimeStamp] = CAST(N'2013-01-16 05:53:50.490' AS DateTime))
BEGIN
    INSERT INTO
        [dbo].[tblAccount] ([AccountID]
                           ,[Name]
                           ,[Comment]
                           ,[IsMachine]
                           ,[UserID]
                           ,[Prefix]
                           ,[Action]
                           ,[Initials]
                           ,[Name]
                           ,[TimeStamp]
                           ,[Reason]
                           ,[Iscal])
                    VALUES (117242
                           ,'blabla'
                           ,'The users project)'
                           ,1
                           ,'val'
                           ,39
                           ,'val'
                           ,'blabla'
                           ,'blabla'
                           ,CAST(N'2013-01-16 05:53:50.490' AS DateTime)
                           ,'NORMAL'
                           ,'0')
END
</code>```

I saved the file into a folder and then from the command line I do the following:

```<code>C:\>sqlcmd -S pc_name\MSSQLEXPRESS -i"C:\Users\name\Desktop\OutPut\Result tblAccount.sql"
</code>```

I get the following error:

Msg 208, Level 16, State 1, Server pc_name\MSSQLEXPRESS, Line 1

Invalid object name 'dbo.tblAccount'.

I'm not sure if it is related to the syntax of the sql or in the way I write the sqlcmd.

答:
I know it's an over a year ago question, but in case somebody run into the same issue, make sure to provide credentials. I just ran into same issue and without providing credentials, sqlcmd issues that error. I don't know what's happening behind the scene, but seems that it connects to some sort of default db when authentication fails and couldn't find the table as a result. </p>

```<code> sqlcmd -S <computer name> -U <username> -P <password> -i  <absolute path to your script>
</code>```

Body:
I have to insert a very large amount of data in sql, the operation did not work via SQL Management Studio therefore I was investigating the insert via sqlcmd. so what I did was the following:

create a file.sql that contains the following query (multiple times):

IF NOT EXISTS (SELECT * FROM [dbo].[tblAccount]
               WHERE [AccountID] = 117242 AND
                     [TimeStamp] = CAST(N'2013-01-16 05:53:50.490' AS DateTime))
BEGIN
    INSERT INTO
        [dbo].[tblAccount] ([AccountID]
                           ,[Name]
                           ,[Comment]
                           ,[IsMachine]
                           ,[UserID]
                           ,[Prefix]
                           ,[Action]
                           ,[Initials]
                           ,[Name]
                           ,[TimeStamp]
                           ,[Reason]
                           ,[Iscal])
                    VALUES (117242
                           ,'blabla'
                           ,'The users project)'
                           ,1
                           ,'val'
                           ,39
                           ,'val'
                           ,'blabla'
                           ,'blabla'
                           ,CAST(N'2013-01-16 05:53:50.490' AS DateTime)
                           ,'NORMAL'
                           ,'0')
END

I saved the file into a folder and then from the command line I do the following:

C:\>sqlcmd -S pc_name\MSSQLEXPRESS -i"C:\Users\name\Desktop\OutPut\Result tblAccount.sql"

I get the following error:

Msg 208, Level 16, State 1, Server pc_name\MSSQLEXPRESS, Line 1

Invalid object name 'dbo.tblAccount'.

I'm not sure if it is related to the syntax of the sql or in the way I write the sqlcmd.

Body:
I know it's an over a year ago question, but in case somebody run into the same issue, make sure to provide credentials. I just ran into same issue and without providing credentials, sqlcmd issues that error. I don't know what's happening behind the scene, but seems that it connects to some sort of default db when authentication fails and couldn't find the table as a result.

 sqlcmd -S <computer name> -U <username> -P <password> -i  <absolute path to your script>


问:
How to group arrays in array by first element object key
Got an array of arrays like this:

```<code>    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]
</code>```

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

```<code>  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]
</code>```

I tried to use reduce function, but the result was totally different.

```<code>let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }
</code>```

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?

答:
Create the object of keys along with its count. Then you can filter the keys which are present more than once i:e (count >= 2). Then iterate over your input array using reduce and see it is present within the filtered array keys, if yes then push in separate array and other is accu. Then merge the two arrays into one.

let input = [
    [
      {"key":2, "other":123},
      {"key":2, "other":222}
    ],
    [
      {"key":3, "other":0}
    ],
    [
      {"key":1, "other":11},
      {"key":1, "other":23}
    ],
    [
      {"key":1, "other":22}
    ]
];

// keys with unique key and its count. filter whose count are greater than two.

const groupByArrKeysOccurence = input.reduce((accu, arr) => {
    const key = arr[0].key;
    accu[key] = (accu[key] || 0) + 1;
    return accu;
}, {});

const filteredKeys = Object.entries(groupByArrKeysOccurence).filter(([_, val]) => val > 1).map(([key, _]) => Number(key));

const multipleArrOccurenceKeys = [];

const singleArrOccurenceKeys = input.reduce((accu, arr) => {
    const isKey = arr.some(({key}) => filteredKeys.includes(key));
    if(isKey) {
        multipleArrOccurenceKeys.push(arr);
    } else {
        accu.push(arr);
    }
    return accu;
}, []);

console.log([...singleArrOccurenceKeys, multipleArrOccurenceKeys]);```

Body:
Got an array of arrays like this:

    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]

I tried to use reduce function, but the result was totally different.

let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?


问:
How to define a function that calculates the BMI from dataframe(Python)
I need to define a function that will calculate and return out of dataframe that includes columns "Height" and "Weight", the BMI of each row.
Here is the code that i wrote:

```<code>import pandas as pd
def BMI(DataFrame):
    df=pd.DataFrame
    return df['Weight']/df['Height']^2
</code>```

But when I try to run that function with:

```<code>data.apply(BMI,axis=1)
</code>```

when "data" is my dataframe,

the result is an error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\frame.py", line 6487, in apply
    return op.get_result()
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 151, in get_result
    return self.apply_standard()
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 257, in apply_standard
    self.apply_series_generator()
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 286, in apply_series_generator
    results[i] = self.f(v)
  File "<input>", line 3, in BMI
TypeError: ("'type' object is not subscriptable", 'occurred at index 0')

What went wrong with my code?

答:
You have a few syntax errors,

first ^2 does not work in python, is **2, and Why are you defining a DataFrame inside your function?

This should work:

```<code>p = pd.DataFrame({'H': [183, 180], 'W': [70, 80]})
p.apply(lambda x: (x.W/x.H)**2, axis=1)

Out[17]:
0    0.146317
1    0.197531
dtype: float64
</code>```

Body:
I need to define a function that will calculate and return out of dataframe that includes columns "Height" and "Weight", the BMI of each row.
Here is the code that i wrote:

import pandas as pd
def BMI(DataFrame):
    df=pd.DataFrame
    return df['Weight']/df['Height']^2

But when I try to run that function with:

data.apply(BMI,axis=1)

when "data" is my dataframe,

the result is an error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\frame.py", line 6487, in apply
    return op.get_result()
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 151, in get_result
    return self.apply_standard()
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 257, in apply_standard
    self.apply_series_generator()
  File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 286, in apply_series_generator
    results[i] = self.f(v)
  File "<input>", line 3, in BMI
TypeError: ("'type' object is not subscriptable", 'occurred at index 0')

What went wrong with my code?

Body:
You have a few syntax errors,

first ^2 does not work in python, is **2, and Why are you defining a DataFrame inside your function?

This should work:

p = pd.DataFrame({'H': [183, 180], 'W': [70, 80]})
p.apply(lambda x: (x.W/x.H)**2, axis=1)

Out[17]:
0    0.146317
1    0.197531
dtype: float64


问:
CardView to make a circle background, show oval background
I followed this post

and tried to make a transparent circle background around my X verctor Image.

```<code>  <android.support.design.card.MaterialCardView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:innerRadius="0dp"
      android:shape="ring"
      android:thicknessRatio="0"
      app:cardCornerRadius="24dp"
      card_view:cardElevation="0dp"
      card_view:cardMaxElevation="0dp">
    <ImageView
        android:id="@+id/close_button"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="top|end"
        android:padding="@dimen/account_menu_close_button_padding"
        android:alpha="0"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/og_close_icon_a11y"
        android:focusable="true"
        android:theme="@style/myStyle"
        android:visibility="gone"
        app:srcCompat="@drawable/quantum_gm_ic_close_vd_theme_24"
        />
  </android.support.design.card.MaterialCardView>
</code>```

However I keep on getting:
1) oval shape
2) thing white border

How can I fix these both?

答:
Try this way

```<code><com.google.android.material.card.MaterialCardView
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_gravity="center"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="0"
    app:cardBackgroundColor="@color/colorAccent"
    app:cardCornerRadius="24dp"
    app:cardElevation="0dp"
    card_view:cardMaxElevation="0dp">

    <ImageView
        android:id="@+id/close_button"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="top|end"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/app_name"
        android:focusable="true"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_close" />

</com.google.android.material.card.MaterialCardView>
</code>```

OUTPUT

OUTPUT in device

Body:
I followed this post

and tried to make a transparent circle background around my X verctor Image.

  <android.support.design.card.MaterialCardView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:innerRadius="0dp"
      android:shape="ring"
      android:thicknessRatio="0"
      app:cardCornerRadius="24dp"
      card_view:cardElevation="0dp"
      card_view:cardMaxElevation="0dp">
    <ImageView
        android:id="@+id/close_button"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="top|end"
        android:padding="@dimen/account_menu_close_button_padding"
        android:alpha="0"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/og_close_icon_a11y"
        android:focusable="true"
        android:theme="@style/myStyle"
        android:visibility="gone"
        app:srcCompat="@drawable/quantum_gm_ic_close_vd_theme_24"
        />
  </android.support.design.card.MaterialCardView>

However I keep on getting:
1) oval shape
2) thing white border

How can I fix these both?

Body:
Try this way

<com.google.android.material.card.MaterialCardView
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_gravity="center"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="0"
    app:cardBackgroundColor="@color/colorAccent"
    app:cardCornerRadius="24dp"
    app:cardElevation="0dp"
    card_view:cardMaxElevation="0dp">

    <ImageView
        android:id="@+id/close_button"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="top|end"
        android:background="?attr/selectableItemBackground"
        android:contentDescription="@string/app_name"
        android:focusable="true"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_close" />

</com.google.android.material.card.MaterialCardView>

OUTPUT

OUTPUT in device


问:
How to call this function?
I have a function in Saves.java class and i want to call this function in the other Import.java class, how doing it ?
Here is the code of the function:

```<code>public void updatelv(Activity activity) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String fileName = getResources().getString(R.string.fileName);
        fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
        list = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
        ListView L = (ListView) findViewById(R.id.lv);

        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item, list);
        L.setAdapter(adapter);
        }
</code>```

I think that i have to do this :  Saves save=new Saves();
And after, how to call the updatelv(activity) function ?

Thank you.

the import.java class called when pressed in a menu Import" button(in Saves.java class):

```<code>case R.id.importer:
  Import myImport = new Import(this);
  myImport.transfer();
</code>```

答:
You need to have an object of type Activity ready and then:

```<code>  save.updatelv(activityObj);
</code>```

should do it.

Title: How to call this function?

Body:
I have a function in Saves.java class and i want to call this function in the other Import.java class, how doing it ?
Here is the code of the function:

public void updatelv(Activity activity) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String fileName = getResources().getString(R.string.fileName);
        fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
        list = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
        ListView L = (ListView) findViewById(R.id.lv);

        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item, list);
        L.setAdapter(adapter);
        }

I think that i have to do this :  Saves save=new Saves();
And after, how to call the updatelv(activity) function ?

Thank you.

the import.java class called when pressed in a menu Import" button(in Saves.java class):

case R.id.importer:
  Import myImport = new Import(this);
  myImport.transfer();

Body:
You need to have an object of type Activity ready and then:

  save.updatelv(activityObj);

should do it.


问:
Function returns an error (ESLint) move function to body root
I have the following function.the code does what i need it to do,however its not structured correctly because of the declarations therefore it gives "(ESLint) move function to body root" error :

This is my code:

```<code>function onSuccess(result) {

            if (result) {
                 function GetTotal(result) {

                    var totBal = 0;
                    var str = 'R';
                    for (var i = 0; i < result.length; i++) {
                        totBal += result[i].Price;
                    }
                    str += totBal.toFixed(2);
                    return str;
                }
                var span = document.getElementById("Total");
                span.innerHTML = GetTotal(result);
            }
        }
</code>```

This is what i tried:

```<code>function onSuccess(result) {
        var fn;
        if (result) {
          fn=function GetTotal(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }
</code>```

the "(ESLint) move function to body root" gets solved But with the above it returns an error saying "getTotal is not defined"

答:
You can just move the function to the body root as suggested by ESLint like so

```<code>function onSuccess(result) {
  function GetTotal(result) {
    var totBal = 0;
    var str = 'R';
    for (var i = 0; i < result.length; i++) {
      totBal += result[i].Price;
    }
    str += totBal.toFixed(2);
    return str;
  }

  if (result) {
    var span = document.getElementById("Total");
    span.innerHTML = GetTotal(result);
  }
}
</code>```

Or just get rid of the function as it's inside of a function anyway and you don't seem to be using it again.

```<code>function onSuccess(result) {
  if (result) {
    var totBal = 0;
    var str = 'R';
    for (var i = 0; i < result.length; i++) {
      totBal += result[i].Price;
    }
    str += totBal.toFixed(2);
    var span = document.getElementById("Total");
    span.innerHTML = str
  }
}
</code>```

Body:
I have the following function.the code does what i need it to do,however its not structured correctly because of the declarations therefore it gives "(ESLint) move function to body root" error :

This is my code:

function onSuccess(result) {

            if (result) {
                 function GetTotal(result) {

                    var totBal = 0;
                    var str = 'R';
                    for (var i = 0; i < result.length; i++) {
                        totBal += result[i].Price;
                    }
                    str += totBal.toFixed(2);
                    return str;
                }
                var span = document.getElementById("Total");
                span.innerHTML = GetTotal(result);
            }
        }

This is what i tried:

function onSuccess(result) {
        var fn;
        if (result) {
          fn=function GetTotal(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }

the "(ESLint) move function to body root" gets solved But with the above it returns an error saying "getTotal is not defined"

Body:
You can just move the function to the body root as suggested by ESLint like so

function onSuccess(result) {
  function GetTotal(result) {
    var totBal = 0;
    var str = 'R';
    for (var i = 0; i < result.length; i++) {
      totBal += result[i].Price;
    }
    str += totBal.toFixed(2);
    return str;
  }

  if (result) {
    var span = document.getElementById("Total");
    span.innerHTML = GetTotal(result);
  }
}

Or just get rid of the function as it's inside of a function anyway and you don't seem to be using it again.

function onSuccess(result) {
  if (result) {
    var totBal = 0;
    var str = 'R';
    for (var i = 0; i < result.length; i++) {
      totBal += result[i].Price;
    }
    str += totBal.toFixed(2);
    var span = document.getElementById("Total");
    span.innerHTML = str
  }
}