问:
Child elements are allowing drag/drop
I'm having a weird issue with dragging and dropping in html5.

Panel A has a list of the type of elements you can drag. Panel B is where the elements are dragged. Panel C and D are other places you can drag elements, and you can drag and rearrange elements between Panels B, C and D.

My issue is that I'm able to drag an element and drop it INSIDE of another element that's inside one of the panels, which I don't want the user to be able to do. The child elements of those panels don't have any kind of javascript or drag-related properties attached to them, and yet they are currently allowing elements to be dragged inside them.

I've tried attaching "ondrop='return false;'" and "ondragover='return false;'", but neither has worked.

Surely there is a way to turn off the 'allow dragging into' property on an element?

Here's my code:

```<code><div id="elem-002" draggable="true" ondragstart="drag(event)">content</div>
</code>```

The main panel:

```<code><div id="panel-b" ondrop="drop(event)" ondragover="allowDrop(event)">
  <div id="elem-001" draggable="true" ondragstart="drag(event)">content</div>
</div>
</code>```

The JS:

```<code>function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}
</code>```

Said another way: I'm able to drag my "elem-002" directly into "elem-001", an element that was already dragged in. This causing nesting of elements that I don't want to occur. How can I prevent this?

答:
I am using a custom drag and drop, mixing the mouse[down|move|up] of a element to be dragged with the drag[enter|over|leave] & drop on another element.  And I am using Custom Events to trigger/fire/dispatch the drop event.  That does not really make a difference to the issue at hand, just wanted to give context.

Anyhoo, I was experiencing the same type of issue, and after searching for a while, and doing some debugging, I realised that the event.[target|srcElement] is actually the element which 'sent' the event.  So what I ended up doing was to;
reject any drop where the [target|srcElement] was the not the 'this' element of the event and where 'this' did not contain the [target|srcElement] (i.e. not one of its children), only then do I allow further processing;

// Drop Event Handler
function dropEventHandler(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;

    if (this !== target && this.contains(target)) {
        // Use if not a proper/normal event, this should stop any further
        //   processing of the event
        // if (event.stopPropagation) event.stopPropagation();  // Standard model
        // else event.cancelBubble = true;                       //IE

        // Stops the default action of an element from happening
        // Use the event.isDefaultPrevented() method to check whether
        //   the preventDefault() method was called for the event
        if (event.preventDefault) event.preventDefault();   // Standard model
        else event.returnValue = false;                      //IE

        return false;
    }
    // Process drop event
}
```

Tested in Chrome, FF, Opera, IE Edge && IE 11 [emulation 7-11] on Windows 10,
also IE v8.0.7601.17514 on Windows 7 [IE7 and IE8 Compatibility] modes tested.

Title: Child elements are allowing drag/drop

Body:
I'm having a weird issue with dragging and dropping in html5.

Panel A has a list of the type of elements you can drag. Panel B is where the elements are dragged. Panel C and D are other places you can drag elements, and you can drag and rearrange elements between Panels B, C and D.

My issue is that I'm able to drag an element and drop it INSIDE of another element that's inside one of the panels, which I don't want the user to be able to do. The child elements of those panels don't have any kind of javascript or drag-related properties attached to them, and yet they are currently allowing elements to be dragged inside them.

I've tried attaching "ondrop='return false;'" and "ondragover='return false;'", but neither has worked.

Surely there is a way to turn off the 'allow dragging into' property on an element?

Here's my code:

content

The main panel:

content

The JS:

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

Said another way: I'm able to drag my "elem-002" directly into "elem-001", an element that was already dragged in. This causing nesting of elements that I don't want to occur. How can I prevent this?

Body:
I am using a custom drag and drop, mixing the mouse[down|move|up] of a element to be dragged with the drag[enter|over|leave] & drop on another element.  And I am using Custom Events to trigger/fire/dispatch the drop event.  That does not really make a difference to the issue at hand, just wanted to give context.

Anyhoo, I was experiencing the same type of issue, and after searching for a while, and doing some debugging, I realised that the event.[target|srcElement] is actually the element which 'sent' the event.  So what I ended up doing was to;
reject any drop where the [target|srcElement] was the not the 'this' element of the event and where 'this' did not contain the [target|srcElement] (i.e. not one of its children), only then do I allow further processing;

// Drop Event Handler
function dropEventHandler(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;

    if (this !== target && this.contains(target)) {
        // Use if not a proper/normal event, this should stop any further
        //   processing of the event
        // if (event.stopPropagation) event.stopPropagation();  // Standard model
        // else event.cancelBubble = true;                       //IE

        // Stops the default action of an element from happening
        // Use the event.isDefaultPrevented() method to check whether
        //   the preventDefault() method was called for the event
        if (event.preventDefault) event.preventDefault();   // Standard model
        else event.returnValue = false;                      //IE

        return false;
    }
    // Process drop event
}

Tested in Chrome, FF, Opera, IE Edge && IE 11 [emulation 7-11] on Windows 10,
also IE v8.0.7601.17514 on Windows 7 [IE7 and IE8 Compatibility] modes tested.


来源: stackexchange

问:
how do I navigate and grab infos from an Array like this
Im trying to navigate and fetch info from this array but im not having much success any tips? This is an decoded JSON from Twitter API

I tryed echo $array->statuses[0]->created_at; and it did not work, am i doing something wrong here?

```<code>Array
    (
        [statuses] => Array
            (
                [0] => stdClass Object
                    (
                        [created_at] => Thu Jul 06 04:05:06 +0000 2017
                        [id] => 882812623959584768
                        [id_str] => 882812623959584768
                        [text] => RT @blackdragonsBR: [R6] GG!! Fechamos o mapa Banco por 5x2 e conquistamos a liderança no #ALIENWARENOIGN #GOBD #Acer #Predator https://t.c…
                        [truncated] =>
                        [entities] => stdClass Object
                            (
                                [hashtags] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [text] => ALIENWARENOIGN
                                                [indices] => Array
                                                    (
                                                        [0] => 90
                                                        [1] => 105
                                                }

                                        )
                                }
                        }
                }
        }
}
</code>```

答:
You need to access the array by [] not ->. So change the access of statuses like below

```<code>$array[statuses][0]->created_at;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im trying to navigate and fetch info from this array but im not having much success any tips? This is an decoded JSON from Twitter API

I tryed echo $array->statuses[0]->created_at; and it did not work, am i doing something wrong here?

Array
    (
        [statuses] => Array
            (
                [0] => stdClass Object
                    (
                        [created_at] => Thu Jul 06 04:05:06 +0000 2017
                        [id] => 882812623959584768
                        [id_str] => 882812623959584768
                        [text] => RT @blackdragonsBR: [R6] GG!! Fechamos o mapa Banco por 5x2 e conquistamos a liderança no #ALIENWARENOIGN #GOBD #Acer #Predator https://t.c…
                        [truncated] =>
                        [entities] => stdClass Object
                            (
                                [hashtags] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [text] => ALIENWARENOIGN
                                                [indices] => Array
                                                    (
                                                        [0] => 90
                                                        [1] => 105
                                                }

                                        )
                                }
                        }
                }
        }
}

Body:
You need to access the array by [] not ->. So change the access of statuses like below

$array[statuses][0]->created_at;


问:
How to convert a number to Q format
I am working with XMC1300 MCU series from Infineon. For my application I need to find out the square root of some data.

Following are the math lib api provided by Infineon

```<code>int16_t XMC_MATH_CORDIC_Q15_Sqrt(int16_t x)
int32_t XMC_MATH_CORDIC_Q31_Sqrt(int32_t x)
</code>```

These two API accept and returns data format Q15 and Q31 i.e. It could only represent [-1,1] range.

Suppose I wanted to find out the square root of

```<code>144
200
1000
34567
50000
</code>```

How can I change these numbers in range [-1, 1].

What needs to be done for the normalization of Input and Output.

Regards,
Tinchu

答:
You can't represent 144 or 50000 directly in Q15 or Q31 format.  As you mention, those formats are fixed point representations of numbers between -1 and 1.

So the problem you are left with is a basic math problem.
We can use the fact that

sqrt(A/B) = sqrt(A) / sqrt(B)

Let's do the example where your value A = 144:

Set B to the Q31 divisor B = 0x7FFFF =  32768

```<code>A/B = 0.00439`
Sqrt(A/B) = 0.0663
Sqrt(B) = Sqrt(32768) = 181.02
Sqrt(A) = Sqrt(A/B)*Sqrt(B) = 0.0663 * 181.02 = 12.
</code>```

How to do this with Q15 numbers? All numbers are scaled by B.
So Sqrt(A/B) is simply XMC_MATH_CORDIC_Q15_Sqrt(A) //=> 2172

because 0.0663 = 2172/32768.

Sqrt(B) is 181. The final result in integer math is 181 * 2172 / 32768 = 12 *

For larger numbers you need to use the Q31 divisor:
0x7fffFFFF =  2147483647

*note: Integer math will round that answer down to 11. If you want better rounding, you'll need to examine bit 15 before you do the divide.

Title: How to convert a number to Q format

Body:
I am working with XMC1300 MCU series from Infineon. For my application I need to find out the square root of some data.

Following are the math lib api provided by Infineon

int16_t XMC_MATH_CORDIC_Q15_Sqrt(int16_t x)
int32_t XMC_MATH_CORDIC_Q31_Sqrt(int32_t x)

These two API accept and returns data format Q15 and Q31 i.e. It could only represent [-1,1] range.

Suppose I wanted to find out the square root of

144
200
1000
34567
50000

How can I change these numbers in range [-1, 1].

What needs to be done for the normalization of Input and Output.

Regards,
Tinchu

Body:
You can't represent 144 or 50000 directly in Q15 or Q31 format.  As you mention, those formats are fixed point representations of numbers between -1 and 1.

So the problem you are left with is a basic math problem.
We can use the fact that

sqrt(A/B) = sqrt(A) / sqrt(B)

Let's do the example where your value A = 144:

Set B to the Q31 divisor B = 0x7FFFF =  32768

A/B = 0.00439`
Sqrt(A/B) = 0.0663
Sqrt(B) = Sqrt(32768) = 181.02
Sqrt(A) = Sqrt(A/B)*Sqrt(B) = 0.0663 * 181.02 = 12.

How to do this with Q15 numbers? All numbers are scaled by B.
So Sqrt(A/B) is simply XMC_MATH_CORDIC_Q15_Sqrt(A) //=> 2172

because 0.0663 = 2172/32768.

Sqrt(B) is 181. The final result in integer math is 181 * 2172 / 32768 = 12 *

For larger numbers you need to use the Q31 divisor:
0x7fffFFFF =  2147483647

*note: Integer math will round that answer down to 11. If you want better rounding, you'll need to examine bit 15 before you do the divide.


问:
How to use the same name classes but in separate styles
see the example to understand:

```<code>    <!--Standard Bootstrap -->
    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <!-- Material Design Bootstrap -->
    <link href="/build/css/site/mdb.min.css" rel="stylesheet">
</code>```

so i want a thing like it:

```<code>    <div class="btn btn-danger" >Standard Bootstrap Button</div>
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</code>```

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

答:
You can't, you will allways get the last definition of the class.
This is  how style-sheets work, That's why they are called CASCADING Stylesheets. So basically what you define in mdb.min.css extends or overwrites what is definied in bootstrap.min.css And yo will get the combination of both

Let's say in bootstrap.min.css you have this :

```<code>btn-danger:{
   color:#FF0000;
   width:100px;
}
</code>```

and in mdb.min.cs you have

```<code>btn-danger:{
   background-color:#00FF00;
   width:120px;
}
</code>```

Your browser will interpret this:

```<code>btn-danger:{
   color:#FF0000;
   background-color:#00FF00;
   width:120px;
}
</code>```

The width will be overwritten by mdb.min.css because that one is added last, the later you add a stylesheet, the more precedence it has, so it will overwrite everything that was defined earlier, and extend everything that hasn't been defined earlier, and merge everything else

ContentLicense: CC BY-SA 4.0

Body:
see the example to understand:

    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <link href="/build/css/site/mdb.min.css" rel="stylesheet">

so i want a thing like it:

Standard Bootstrap Button

Material Design Bootstrap Button

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

Body:
You can't, you will allways get the last definition of the class.
This is  how style-sheets work, That's why they are called CASCADING Stylesheets. So basically what you define in mdb.min.css extends or overwrites what is definied in bootstrap.min.css And yo will get the combination of both

Let's say in bootstrap.min.css you have this :

btn-danger:{
   color:#FF0000;
   width:100px;
}

and in mdb.min.cs you have

btn-danger:{
   background-color:#00FF00;
   width:120px;
}

Your browser will interpret this:

btn-danger:{
   color:#FF0000;
   background-color:#00FF00;
   width:120px;
}

The width will be overwritten by mdb.min.css because that one is added last, the later you add a stylesheet, the more precedence it has, so it will overwrite everything that was defined earlier, and extend everything that hasn't been defined earlier, and merge everything else


问:
Echo arrays with regular text
How would I write this so I'm only using one echo? </p>

```<code>echo "<div class='post'>";
echo $row['title'];
echo "</div>";
</code>```

<p>I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank. </p>

答:
Other ways of doing the same thing:</p>

```<code>echo '<div class="post">'.$row['title'].'</div>';

echo sprintf('<div class="post">%s</div>', $row['title']);

<div class="post"><?php echo $row['title'] ?></div>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Echo arrays with regular text

Body:
How would I write this so I'm only using one echo?

echo "
";
echo $row['title'];
echo "
";

I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank.

Body:
Other ways of doing the same thing:

echo '<div class="post">'.$row['title'].'</div>';

echo sprintf('<div class="post">%s</div>', $row['title']);

<div class="post"><?php echo $row['title'] ?></div>


问:
SonarQube API - multiple metrics for all components/projects
I'd like to retrieve multiple metrics for ALL projects in SQ in one GET request. Is this possible?

It seems like GET api/measures/component can give me the XML I want, but only if given a specific componentKey (project name). The only other alternative seems to be to go one by one through each component, which wouldn't be ideal given that I have over 500 projects I would like get metrics for.

答: What you're asking for is not possible. You'll have to query the api/measures/component many times to get all measures from all projects.</p>


问:
Retrieve data from last line in vmware.log file?
I currently have a script that retrieves the last modified date of the .vmx in a VM's datastore in vCenter. I need to make changes to instead use and display the last date in the vmware.log file (located in the same datastore as the .vmx)

I'm not sure how to grab that line and convert it to a XX/XX/XXXX format. In the log file, it shows it as Dec 23 10 for example. If this is not possible, no worries. I just need to pull the last line in the log file and export it to a .csv file. Below is my current code:

```<code>add-pssnapin VMware.VimAutomation.Core

# ---------- Only modify the fields in this area -------------
$vCenter = 'qlab-copsmgr'                  #name of the vCenter
$dataCenter = 'Fly-away Kit'               #name of the DataCenter
$outputFile = $vCenter + '-LastDateUsed.csv'             #desired output file name

# ---------- No modification is needed in the below code. Do not edit   -------------
$columnName = "Name,DataStore,Date Last Used" | Out-File .\$OutputFile -Encoding ascii
Connect-VIServer $vCenter -WarningAction SilentlyContinue
$vmList = Get-VM | where { $_.PowerState -eq “PoweredOff”} | select Name
$vmList = $vmList -replace 'Name : ', '' -replace '@{Name=', '' -replace '}', ''

ForEach ($VM in $vmList)
{
    # Get configuration and path to vmx file
    $VMconfig = Get-VM $VM | Get-View | select config
    $VMXpath = $VMconfig.config.files.VMpathName

    # Remove and/or replace unwanted strings
    $VMXpath = $VMXpath -replace '\[','' -replace '\] ','\' -replace '@{Filename=','/' -replace '}','' -replace '/','\'

    # List the vmx file in the datastore
    $VMXinfo = ls vmstores:\$VCenter@443\$DataCenter\$VMXpath | Where {$_.LastWriteTime} | select -first 1 | select FolderPath, LastWriteTime

    # Remove and/or replace unwanted strings
    $VMXinfo = $VMXinfo -replace 'DatastoreFullPath=', '' -replace '@{', '' -replace '}', '' -replace ';', ',' -replace 'LastWriteTime=', ''

    # Output vmx information to .csv file
    $output = $VM + ', ' + $VMXinfo
    $output
    echo $output >> $OutputFile
}
</code>```

答:
I have made a script that checks line by line and if string is found changes it to desired format

```<code>#example input you can use get-content PATH to txt or any file and assign it to $lines variable
$lines = @"
ernfoewnfnsf
ernfoewnfnsf
Dec 23 10 sgdsgdfgsdadasd
"@ -split "\r\n"

#checks line by line and if find anything that maches start of the line, one Big letter two small, space, two digits, space, two digits, space
$lines | ForEach-Object{

    if ($_ -match "^[A-Z][a-z]{2}\s\d{2}\s\d{2}\s")
    {
        $match = [convert]::ToDateTime($matches[0])
        $_ -replace $matches[0], "$($match.ToShortDateString()) " | out-file { PATH } -APPEND
    }
    else
    {
        $_ | out-file { PATH } -APPEND
    }
}
</code>```

just change {PATH} with a filenamePAth and this should work for you

Body:
I currently have a script that retrieves the last modified date of the .vmx in a VM's datastore in vCenter. I need to make changes to instead use and display the last date in the vmware.log file (located in the same datastore as the .vmx)

I'm not sure how to grab that line and convert it to a XX/XX/XXXX format. In the log file, it shows it as Dec 23 10 for example. If this is not possible, no worries. I just need to pull the last line in the log file and export it to a .csv file. Below is my current code:

add-pssnapin VMware.VimAutomation.Core

# ---------- Only modify the fields in this area -------------
$vCenter = 'qlab-copsmgr'                  #name of the vCenter
$dataCenter = 'Fly-away Kit'               #name of the DataCenter
$outputFile = $vCenter + '-LastDateUsed.csv'             #desired output file name

# ---------- No modification is needed in the below code. Do not edit   -------------
$columnName = "Name,DataStore,Date Last Used" | Out-File .\$OutputFile -Encoding ascii
Connect-VIServer $vCenter -WarningAction SilentlyContinue
$vmList = Get-VM | where { $_.PowerState -eq “PoweredOff”} | select Name
$vmList = $vmList -replace 'Name : ', '' -replace '@{Name=', '' -replace '}', ''

ForEach ($VM in $vmList)
{
    # Get configuration and path to vmx file
    $VMconfig = Get-VM $VM | Get-View | select config
    $VMXpath = $VMconfig.config.files.VMpathName

    # Remove and/or replace unwanted strings
    $VMXpath = $VMXpath -replace '\[','' -replace '\] ','\' -replace '@{Filename=','/' -replace '}','' -replace '/','\'

    # List the vmx file in the datastore
    $VMXinfo = ls vmstores:\$VCenter@443\$DataCenter\$VMXpath | Where {$_.LastWriteTime} | select -first 1 | select FolderPath, LastWriteTime

    # Remove and/or replace unwanted strings
    $VMXinfo = $VMXinfo -replace 'DatastoreFullPath=', '' -replace '@{', '' -replace '}', '' -replace ';', ',' -replace 'LastWriteTime=', ''

    # Output vmx information to .csv file
    $output = $VM + ', ' + $VMXinfo
    $output
    echo $output >> $OutputFile
}

Body:
I have made a script that checks line by line and if string is found changes it to desired format

#example input you can use get-content PATH to txt or any file and assign it to $lines variable
$lines = @"
ernfoewnfnsf
ernfoewnfnsf
Dec 23 10 sgdsgdfgsdadasd
"@ -split "\r\n"

#checks line by line and if find anything that maches start of the line, one Big letter two small, space, two digits, space, two digits, space
$lines | ForEach-Object{

    if ($_ -match "^[A-Z][a-z]{2}\s\d{2}\s\d{2}\s")
    {
        $match = [convert]::ToDateTime($matches[0])
        $_ -replace $matches[0], "$($match.ToShortDateString()) " | out-file { PATH } -APPEND
    }
    else
    {
        $_ | out-file { PATH } -APPEND
    }
}

just change {PATH} with a filenamePAth and this should work for you


问:
Get a list of duplicates from list based on properties comparison
I have a List<Demo>

```<code>public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}
</code>```

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

```<code>List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});
</code>```

and then i am doing:

```<code>var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();
</code>```

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

答:
Hers's what you want if you have more than 1 title and names are same. Say the last object is Demo1 and A.

```<code>var duplicates = demo.GroupBy(t => new { t.Name, t.Title }).Where(t => t.Count() > 1)
                     .Select(x => new { Count = x.Count(), Values = x.Select(y => y)})
                     .ToList();
</code>```

What this does it, gives you count and all the grouped values (based on Name and Title) and their Count.

Body:
I have a List<Demo>

public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});

and then i am doing:

var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

Body:
Hers's what you want if you have more than 1 title and names are same. Say the last object is Demo1 and A.

var duplicates = demo.GroupBy(t => new { t.Name, t.Title }).Where(t => t.Count() > 1)
                     .Select(x => new { Count = x.Count(), Values = x.Select(y => y)})
                     .ToList();

What this does it, gives you count and all the grouped values (based on Name and Title) and their Count.


问:
How to count vowels
How can I count the vowels in a string ?

for example:

```<code>data: str type string  value 'steave'.
</code>```

and I want the output be:

```<code>2 --> e.
1 --> a.
</code>```

答:
Just loop through the string / char and collect the results into a statistical internal table. Use CA (contains any) operator for checking vowels. Example code:

```<code>DATA: str TYPE string VALUE 'steave',
      l_pos TYPE sy-index,
      BEGIN OF ls_stat,
        char TYPE c,
        count TYPE sy-index,
      END OF ls_stat,
      lt_stat LIKE STANDARD TABLE OF ls_stat.

DO strlen( str ) TIMES.
  l_pos = sy-index - 1 .
  IF str+l_pos(1) CA 'AaEeIiOoUu'.
    ls_stat-char = str+l_pos(1).
    ls_stat-count = 1.
    COLLECT ls_stat INTO lt_stat.
  ENDIF.
ENDDO.

SORT lt_stat BY count DESCENDING.
LOOP AT lt_stat INTO ls_stat.
  WRITE: / ls_stat-count, '->', ls_stat-char.
ENDLOOP.
</code>```

Title: How to count vowels

Body:
How can I count the vowels in a string ?

for example:

data: str type string  value 'steave'.

and I want the output be:

2 --> e.
1 --> a.

Body:
Just loop through the string / char and collect the results into a statistical internal table. Use CA (contains any) operator for checking vowels. Example code:

DATA: str TYPE string VALUE 'steave',
      l_pos TYPE sy-index,
      BEGIN OF ls_stat,
        char TYPE c,
        count TYPE sy-index,
      END OF ls_stat,
      lt_stat LIKE STANDARD TABLE OF ls_stat.

DO strlen( str ) TIMES.
  l_pos = sy-index - 1 .
  IF str+l_pos(1) CA 'AaEeIiOoUu'.
    ls_stat-char = str+l_pos(1).
    ls_stat-count = 1.
    COLLECT ls_stat INTO lt_stat.
  ENDIF.
ENDDO.

SORT lt_stat BY count DESCENDING.
LOOP AT lt_stat INTO ls_stat.
  WRITE: / ls_stat-count, '->', ls_stat-char.
ENDLOOP.


问:
How to limit EditText to input only float values in Java?
I have found answers to limit it to Integer/float in xml, I want to do it programmatically.
I can set setInputType(InputType.TYPE_CLASS_NUMBER) for integer values, but what for float values?

I want them in xxxx.xxx format.

答:
Well simply use

editText.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL)

only if you want to do it programmatically.


问:
How to expand and close the tr based on checbox click
I have 10 rows in a table. Each row first column(td) is ( + button) for expansion of new tr rows. i can expand and close any row by click the + button manyally. but i also have one common check box to expand and close the all tr at a time. This is working fine when i am doing in separate. if i click the checkbox it will click the + button using code ( $(this).click() )

but the problem is i expanded one row by clicking + button. After that i am clicking the common checkbox then it will open all the expanded row, but here it closing the row which i opened already. my requirement don't close the rows already opened by clicking the + button.

At the time of expand i am adding a new class (".shown") to the current row(tr) in which i clicked.and the + button class name is (" .details-control ").

The below code is for common checkbox code at time of click.

```<code>$('.common-checkall').on('change', function() {
    var status = this.checked;
    $(".details-control:visible").each(function(){
        $(this).click();
    });
});
</code>```

This is the code for + button expand

```<code>$(elemId+' tbody').on('click', 'td.details-control', function(){
    var tr = $(this).closest('tr');
    var row = royaltiesTable.row(tr);
    try {
        if (row.child.isShown()) {
            row.child.hide();
            tr.removeClass('shown');
        } else {
            row.child(format(row.data(), tr)).show();
            tr.addClass('shown');
        }
    } catch(err) {
        console.log("");
    }
});
</code>```

答:
You may add a checking before calling
$(this).click();
e.g.

```<code>$('.common-checkall').on('change', function() {
    var status = this.checked;
    $(".details-control:visible").each(function(){
        if((status && !$(this).hasClass('shown')) || (!status && $(this).hasClass('shown'))) {
            $(this).click();
        }
    });
});
</code>```

Body:
I have 10 rows in a table. Each row first column(td) is ( + button) for expansion of new tr rows. i can expand and close any row by click the + button manyally. but i also have one common check box to expand and close the all tr at a time. This is working fine when i am doing in separate. if i click the checkbox it will click the + button using code ( $(this).click() )

but the problem is i expanded one row by clicking + button. After that i am clicking the common checkbox then it will open all the expanded row, but here it closing the row which i opened already. my requirement don't close the rows already opened by clicking the + button.

At the time of expand i am adding a new class (".shown") to the current row(tr) in which i clicked.and the + button class name is (" .details-control ").

The below code is for common checkbox code at time of click.

$('.common-checkall').on('change', function() {
    var status = this.checked;
    $(".details-control:visible").each(function(){
        $(this).click();
    });
});

This is the code for + button expand

$(elemId+' tbody').on('click', 'td.details-control', function(){
    var tr = $(this).closest('tr');
    var row = royaltiesTable.row(tr);
    try {
        if (row.child.isShown()) {
            row.child.hide();
            tr.removeClass('shown');
        } else {
            row.child(format(row.data(), tr)).show();
            tr.addClass('shown');
        }
    } catch(err) {
        console.log("");
    }
});

Body:
You may add a checking before calling
$(this).click();
e.g.

$('.common-checkall').on('change', function() {
    var status = this.checked;
    $(".details-control:visible").each(function(){
        if((status && !$(this).hasClass('shown')) || (!status && $(this).hasClass('shown'))) {
            $(this).click();
        }
    });
});


问:
back to back or gates with object comparisons. Confusion
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)</p>

```<code>function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

答:
As others have mentioned, your functions exits out at the first if statement ergo returning false.

if (a === b) {
    return true;
  }

It is also generally considered good practice to have a single return statement within your functions. In our case, we could refactor our code to something like this:

function deepEqual(a, b) {
  var ret = false;
  if (a === b) {
    ret = true;
  } else if (a == null || typeof a != "object" ||
    b == null || typeof b != "object") {
    ret = false;
  }
  return ret;
}```

This also caters for another possible problem. There are values of a and b that would not have been caught by either if statements and would have returned undefined. e.g:

deepEqual([], {});

Body:
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true

Body:
As others have mentioned, your functions exits out at the first if statement ergo returning false.

if (a === b) {
    return true;
  }

It is also generally considered good practice to have a single return statement within your functions. In our case, we could refactor our code to something like this:

function deepEqual(a, b) {
  var ret = false;
  if (a === b) {
    ret = true;
  } else if (a == null || typeof a != "object" ||
    b == null || typeof b != "object") {
    ret = false;
  }
  return ret;
}

This also caters for another possible problem. There are values of a and b that would not have been caught by either if statements and would have returned undefined. e.g:

deepEqual([], {});


问:
Testing framework for Angular within a Rails project?
I come across Karma and Jasmine when I search for testing framework for Angular.js.

What is the best one for a medium Rails + Angular project? I am a beginner with Angular.

答:
for unit testing the application, you can use the jasmine gem. You should point it to the HEAD.

```<code>gem "jasmine", github: "pivotal/jasmine-gem"
</code>```

then run bundle install and rails g jasmine:install

For end-to-end tests, you can use the usual RSpec-rails and capybara. Remember when using this, to add js:true in the beginning of the scenario e.g.

```<code>    require "rails_helper"

RSpec.feature "new users can sign up", js: true do
  scenario "successfully" do
 #your code here
  end
end
</code>```

A good explanation on the unit testing using jasmine can be found here:
https://content.pivotal.io/blog/unit-testing-angularjs-in-a-rails-app-using-the-jasmine-gem

Body:
for unit testing the application, you can use the jasmine gem. You should point it to the HEAD.

gem "jasmine", github: "pivotal/jasmine-gem"

then run bundle install and rails g jasmine:install

For end-to-end tests, you can use the usual RSpec-rails and capybara. Remember when using this, to add js:true in the beginning of the scenario e.g.

    require "rails_helper"

RSpec.feature "new users can sign up", js: true do
  scenario "successfully" do
 #your code here
  end
end

A good explanation on the unit testing using jasmine can be found here:
https://content.pivotal.io/blog/unit-testing-angularjs-in-a-rails-app-using-the-jasmine-gem


问:
A problem connecting to a MySQL DB using JDBC
Here's how I'm trying to connect:

```<code>try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }
</code>```

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...

答:
Possibly a url issue. If your code is pointing to MySQL localhost, try changing localhost to 127.0.0.1 on your url.

E.g.:

```<code>jdbc:mysql://localhost:3306/MY_DB
</code>```

to

```<code>jdbc:mysql://127.0.0.1:3306/MY_DB
</code>```

And see if this works.

Body:
Here's how I'm trying to connect:

try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...

Body:
Possibly a url issue. If your code is pointing to MySQL localhost, try changing localhost to 127.0.0.1 on your url.

E.g.:

jdbc:mysql://localhost:3306/MY_DB

to

jdbc:mysql://127.0.0.1:3306/MY_DB

And see if this works.


问:
A function can take another function as one of its arguments
I wrote the following code in playground and try to learn from Apple doc function & classes.

Here is my code..

```<code>func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
</code>```

How can I directly pass the different condition?
can I write like that..

```<code>hasAnyMatches(numbers, condition: { $0 < 10 })
</code>```

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times)
So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

答:
The way you wrote it was fine! You're just missing the first argument label in the call. It should be:</p>

```<code>hasAnyMatches(list: numbers, condition: { $0 < 10 })
</code>```

Body:
I wrote the following code in playground and try to learn from Apple doc function & classes.

Here is my code..

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)

How can I directly pass the different condition?
can I write like that..

hasAnyMatches(numbers, condition: { $0 < 10 })

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times)
So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

Body:
The way you wrote it was fine! You're just missing the first argument label in the call. It should be:

hasAnyMatches(list: numbers, condition: { $0 < 10 })


问:
Change Toggle Switch status dynamically
I am trying to figure out how to set toggle switch button base on a value. I am using bootstrap for the button. Anyone please tell me what is wrong? </p>

<p>*user.isActive only have two value either true or false.</p>

```<code><td><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='${user.isActive}'/></td>

<script>
 $(document).ready(function() {

                if($('#activeStatus').val() == 'true'){
                      $("#activeSwitch").attr("checked", "checked");
                }

                else if($('#activeStatus').val() == 'false'){
                     ...
                }
            });
</script>
</code>```

答:
I found the answer so wanted to share with people who need help too. For people using bootstrap use:

```<code>$(document).ready(function() {

              if ($('#activeStatus').val().trim() == 'true') {
                  $("#activeSwitch").bootstrapToggle('on');
              } else if ($('#activeStatus').val().trim() == 'false') {
                  $("#activeSwitch").bootstrapToggle('off');
              }
            });
</code>```

Use .bootstrap('on') instead of prop or attr if they are not working.

Title: Change Toggle Switch status dynamically

Body:
I am trying to figure out how to set toggle switch button base on a value. I am using bootstrap for the button. Anyone please tell me what is wrong?

*user.isActive only have two value either true or false.

<input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='${user.isActive}'/>

Body:
I found the answer so wanted to share with people who need help too. For people using bootstrap use:

$(document).ready(function() {

              if ($('#activeStatus').val().trim() == 'true') {
                  $("#activeSwitch").bootstrapToggle('on');
              } else if ($('#activeStatus').val().trim() == 'false') {
                  $("#activeSwitch").bootstrapToggle('off');
              }
            });

Use .bootstrap('on') instead of prop or attr if they are not working.


问:
can not resolve symbol 'from' Error in Android Studio
can not resolve symbol 'from' in

```<code>LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
</code>```

this is my complete class:

```<code>package ir.sangram.sangram.chat;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import ir.sangram.sangram.R;

/**
 * Created by HOW on 07/04/2017.
 */
class ChatListViewHolder extends RecyclerView.ViewHolder{
    public CircleImageView profile_picture;
    public TextView user_name, last_chat, unread_messages;
    public ChatListViewHolder(View itemView) {
        super(itemView);
        profile_picture = (CircleImageView) itemView.findViewById(R.id.profile_picture);
        user_name = (TextView) itemView.findViewById(R.id.user_name);
        last_chat = (TextView) itemView.findViewById(R.id.last_chat);
        unread_messages = (TextView) itemView.findViewById(R.id.unread_messages);
    }
}
public class ChatListAdapter extends RecyclerView.Adapter<ChatListViewHolder>{
    private List<ChatListData> chat_list = new ArrayList<ChatListData>();

    public ChatListAdapter(List<ChatListData> chat_list) {
        this.chat_list = chat_list;
    }

    @Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
        //LayoutInflater inflater;// = new LayoutInflater.from(parent.getContext());
        //inflater = ( LayoutInflater )parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);//!!!!!!!!!!
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ChatListViewHolder holder, int position) {
        holder.profile_picture.setImageResource(chat_list.get(position).getProfile_picture_id());
        holder.user_name.setText(chat_list.get(position).getUser_name());
        holder.unread_messages.setText(chat_list.get(position).getUnread_messages());
        holder.last_chat.setText(chat_list.get(position).getLast_chat());
    }

    @Override
    public int getItemCount() {
        return chat_list.size();
    }
}
</code>```

What can i do?
please help me
thnx

答:
There is no need for "new" keyword. Try the code as follows :</p>

```<code>@Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater =  LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }
</code>```

Body:
can not resolve symbol 'from' in

LayoutInflater inflater = new LayoutInflater.from(parent.getContext());

this is my complete class:

package ir.sangram.sangram.chat;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import ir.sangram.sangram.R;

/**
 * Created by HOW on 07/04/2017.
 */
class ChatListViewHolder extends RecyclerView.ViewHolder{
    public CircleImageView profile_picture;
    public TextView user_name, last_chat, unread_messages;
    public ChatListViewHolder(View itemView) {
        super(itemView);
        profile_picture = (CircleImageView) itemView.findViewById(R.id.profile_picture);
        user_name = (TextView) itemView.findViewById(R.id.user_name);
        last_chat = (TextView) itemView.findViewById(R.id.last_chat);
        unread_messages = (TextView) itemView.findViewById(R.id.unread_messages);
    }
}
public class ChatListAdapter extends RecyclerView.Adapter<ChatListViewHolder>{
    private List<ChatListData> chat_list = new ArrayList<ChatListData>();

    public ChatListAdapter(List<ChatListData> chat_list) {
        this.chat_list = chat_list;
    }

    @Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
        //LayoutInflater inflater;// = new LayoutInflater.from(parent.getContext());
        //inflater = ( LayoutInflater )parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);//!!!!!!!!!!
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ChatListViewHolder holder, int position) {
        holder.profile_picture.setImageResource(chat_list.get(position).getProfile_picture_id());
        holder.user_name.setText(chat_list.get(position).getUser_name());
        holder.unread_messages.setText(chat_list.get(position).getUnread_messages());
        holder.last_chat.setText(chat_list.get(position).getLast_chat());
    }

    @Override
    public int getItemCount() {
        return chat_list.size();
    }
}

What can i do?
please help me
thnx

Body:
There is no need for "new" keyword. Try the code as follows :

@Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater =  LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }


问:
Refreshing a parent window when both are modal
This is a tough one that's left me high and dry, because its a unique variation on a more common problem.

I have a modal parent window spawning a modal child window (with a standard window.showModal call to open it).  The user performs some actions on this new page, and then closes it.  On the close, I want to refresh the parent modal window.

What makes this tough is that both are modal.  I've seen solutions for how to refresh normally (window.opener.location.refresh(true)) and if the child is a modal window (window.dialogArguments.location.reload(true); where the parent window is passed as the 2nd argument).

Any suggestions on what to do?  I think the modal nature of the parent is breaking the refresh, and I can't figure out how to work around it.

答:
When you open a Model window with window.showModalDialog the code in the parent page is stoped, so the code after the opening of the modal window won't be executed until the child is closed.

Having said that, just try:

```<code>// Open the modal dialog
window.showModalDialog('your/child/url.com')
// after is closed, the parent will refresh it self
window.location.reload();
</code>```

Body:
When you open a Model window with window.showModalDialog the code in the parent page is stoped, so the code after the opening of the modal window won't be executed until the child is closed.

Having said that, just try:

// Open the modal dialog
window.showModalDialog('your/child/url.com')
// after is closed, the parent will refresh it self
window.location.reload();


问:
How to animate toggling of table rows?
I want to animate the appearance and disappearance of table rows.

First of all I tried using a CSS transition, but it did nothing due to the change of the display property.

So I used an animation, which works as expected.

The problem is, the full height of the row is reserved when the animation begins. See the snippet below for an illustration of the problem: Row 3 is pushed down straight away, before the animation begins.

How can I animate the height of the row progressively, so that it only takes as much space as needed?

And as a bonus:

it should not require a fixed height for rows

it should appear as a translation, rather than a scaling; it should look like it's sliding from the bottom of the row above it

it should be bidirectional (do the opposite when I hide it)

$('button').on('click', function() {
  $('tr:nth-child(2)').toggleClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@keyframes anim {
  0% {
    transform: scaleY(0);
  }
  100% {
    transform: scaleY(1);
  }
}
tr {
  background: #eee;
  border-bottom: 1px solid #ddd;
  display: none;
  transform-origin: top;
}
tr.active {
  display: table-row;
  animation: anim 0.5s ease;
}
td {
  padding: 10px;
}</code>```

<button type="button">Toggle</button>

      Row 1
      ...
      ...

      Row 2
      ...
      ...

      Row 3
      ...
      ...

```

答:
If you have the option to use CSS3 / support modern browsers you could consider using a transform:translateY transition and hide the overflow with overflow:hidden.

Do note that Edge / IE do not support the translate transforms on table elements. Chrome does support it.

Title: How to animate toggling of table rows?

Body:
I want to animate the appearance and disappearance of table rows.

First of all I tried using a CSS transition, but it did nothing due to the change of the display property.

So I used an animation, which works as expected.

The problem is, the full height of the row is reserved when the animation begins. See the snippet below for an illustration of the problem: Row 3 is pushed down straight away, before the animation begins.

How can I animate the height of the row progressively, so that it only takes as much space as needed?

And as a bonus:

it should not require a fixed height for rows

it should appear as a translation, rather than a scaling; it should look like it's sliding from the bottom of the row above it

it should be bidirectional (do the opposite when I hide it)

$('button').on('click', function() {
  $('tr:nth-child(2)').toggleClass('active');
});

@keyframes anim {
  0% {
    transform: scaleY(0);
  }
  100% {
    transform: scaleY(1);
  }
}
tr {
  background: #eee;
  border-bottom: 1px solid #ddd;
  display: none;
  transform-origin: top;
}
tr.active {
  display: table-row;
  animation: anim 0.5s ease;
}
td {
  padding: 10px;
}

<button type="button">Toggle</button>

      Row 1
      ...
      ...

      Row 2
      ...
      ...

      Row 3
      ...
      ...


问:
how to see logs like the Log.info("something") in test kitchen?
i did this but its not showing any log on the console even after running

```<code>kitchen test -l info
</code>```

答: The -l on the command line sets the log level for kitchen itself, not Chef. That is controlled via the log_level key in your provisioned config section.

Body:
i did this but its not showing any log on the console even after running

kitchen test -l info


问:
`serverless deploy` command in azure does not complete no response received in terminal
I am using serverless framework with azure functions for microservices and installed all the dependencies and there are no errors but when i run serverless deploy command it produces a code

```<code>$ serverless deploy
Serverless: Packaging service...
Serverless: Logging in to Azure
Serverless: Paste this code (copied to your clipboard) into the launched browser, and complete the authentication process: HS******
</code>```

After that this Microsoft Link opens in the browser and ask for the code then i have put the code HS****** that was received and it asks for login and after i login with my azure account it opens a new link displaying this message

You have signed in to the Microsoft Azure Cross-platform Command Line Interface application on your device. You may now close this window.

After closing the window nothing happens in the terminal the terminal does nothing and it got stuck i have tried many times but no help.

答:
Seems like your credentials are not completely set.

Setting up your Azure credentials

Once the serverless-azure-functions plugin is installed, it expects to find your Azure credentials via a set of well-known environment variables. These will be used to actually authenticate with your Azure account, so that the Serverless CLI can generate the necessary Azure resources on your behalf when you request a deployment (see below).

The following environment variables must be set, with their respective values:

azureSubId - ID of the Azure subscription you want to create your service within

azureServicePrincipalTenantId - ID of the tenant that your service principal was created within

azureServicePrincipalClientId - ID of the service principal you want to use to authenticate with Azure

azureServicePrincipalPassword - Password of the service principal you want to use to authenticate with Azure

For details on how to create a service principal and/or acquire your Azure account's subscription/tenant ID, refer to the Azure credentials documentation.

Body:
I am using serverless framework with azure functions for microservices and installed all the dependencies and there are no errors but when i run serverless deploy command it produces a code

$ serverless deploy
Serverless: Packaging service...
Serverless: Logging in to Azure
Serverless: Paste this code (copied to your clipboard) into the launched browser, and complete the authentication process: HS******

After that this Microsoft Link opens in the browser and ask for the code then i have put the code HS****** that was received and it asks for login and after i login with my azure account it opens a new link displaying this message

You have signed in to the Microsoft Azure Cross-platform Command Line Interface application on your device. You may now close this window.

After closing the window nothing happens in the terminal the terminal does nothing and it got stuck i have tried many times but no help.


问:
Move to a view controller on click of a button inside UIPopoverPresentationController
I have a table view controller with a cell that has a button.

On click of this button I am displaying a view controller as an UIPopoverPresentationController.

This pop over controller has two buttons , YES and NO.

On click of YES I want to be able to segue to another view controller and on click of NO I will dismiss the pop over controller.

On click of NO the popover gets dismissed but on click of YES I don't move to the required view controller .

Although the view did load() method of that view controller gets called. The problem is that the new view controller is not being displayed.

On click of YES,the popover gets dismissed but remains on the previous view controller

Following is my code

TableViewController class

```<code>func onTapPickButton(sender: UIButton) {

 let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let popoverViewController = storyboard.instantiateViewController(withIdentifier: "ConfirmDialogViewController") as! ConfirmDialogViewController
        popoverViewController.preferredContentSize = CGSize(width: view.frame.width/1.33, height: view.frame.height/2.34)
        popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
        let popover: UIPopoverPresentationController = popoverViewController.popoverPresentationController!
        popover.sourceView = self.view
        popover.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        popover.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        popover.delegate = self

        present(popoverViewController, animated: true, completion: nil)
}
</code>```

PopOver View controller class

```<code>@IBAction func onTapNoButton(_ sender: UIButton) {
        self.dismiss(animated: true, completion: {})
    }

    @IBAction func onTapYesButton(_ sender: UIButton) {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "View") as! ViewController
present(viewController, animated: true, completion: nil)

    }
</code>```

Any help will be appreciated. Thank you.

答:
You can create either a closure (completion handler) or delegate to catch when 'YES' button was selected. These would be useful in case you ever want to capture any data from the Popover ViewController. For example:

Completion handler:

```<code>class ConfirmDialogViewController: UIViewController {
    open var didSelectYesHandler: ((_ selectedData: String) -> ())?

    public init(for sender: UIView, didSelectYesHandler: ((_ selectedData: String) -> ())? = nil) {
        super.init(nibName: nil, bundle: nil)

        modalPresentationStyle = .popover
        self.sender = sender
        self.didSelectDataHandler = didSelectDataHandler

        guard let popoverPC = popoverPresentationController else { return }
        popoverPC.sourceView = sender
        popoverPC.sourceRect = sender.bounds
        popoverPC.delegate = self
    }

    @IBAction func onTapYesButton(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
        didSelectDataHandler?("YES")
    }

    // MARK: - PopoverPC Delegate Methods

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.none
    }
}
</code>```

Delegate:

```<code>protocol ConfirmDialogViewControllerDelegate: class {
    func didSelectYes(_ selectedDate: String)
}

class ConfirmDialogViewController: UIViewController {
    weak var delegate: ConfirmDialogViewControllerDelegate?

    @IBAction func onTapYesButton(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
        delegate?.didSelectData("YES")
    }
}

// In your current view controller set
popoverViewController.delegate = self
</code>```

Bonus:

Check out this library if you want to have a popover containing a data list for selection.

Body:
I have a table view controller with a cell that has a button.

On click of this button I am displaying a view controller as an UIPopoverPresentationController.

This pop over controller has two buttons , YES and NO.

On click of YES I want to be able to segue to another view controller and on click of NO I will dismiss the pop over controller.

On click of NO the popover gets dismissed but on click of YES I don't move to the required view controller .

Although the view did load() method of that view controller gets called. The problem is that the new view controller is not being displayed.

On click of YES,the popover gets dismissed but remains on the previous view controller

Following is my code

TableViewController class

func onTapPickButton(sender: UIButton) {

 let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let popoverViewController = storyboard.instantiateViewController(withIdentifier: "ConfirmDialogViewController") as! ConfirmDialogViewController
        popoverViewController.preferredContentSize = CGSize(width: view.frame.width/1.33, height: view.frame.height/2.34)
        popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
        let popover: UIPopoverPresentationController = popoverViewController.popoverPresentationController!
        popover.sourceView = self.view
        popover.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        popover.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        popover.delegate = self

        present(popoverViewController, animated: true, completion: nil)
}

PopOver View controller class

@IBAction func onTapNoButton(_ sender: UIButton) {
        self.dismiss(animated: true, completion: {})
    }

    @IBAction func onTapYesButton(_ sender: UIButton) {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "View") as! ViewController
present(viewController, animated: true, completion: nil)

    }

Any help will be appreciated. Thank you.

Body:
You can create either a closure (completion handler) or delegate to catch when 'YES' button was selected. These would be useful in case you ever want to capture any data from the Popover ViewController. For example:

Completion handler:

class ConfirmDialogViewController: UIViewController {
    open var didSelectYesHandler: ((_ selectedData: String) -> ())?

    public init(for sender: UIView, didSelectYesHandler: ((_ selectedData: String) -> ())? = nil) {
        super.init(nibName: nil, bundle: nil)

        modalPresentationStyle = .popover
        self.sender = sender
        self.didSelectDataHandler = didSelectDataHandler

        guard let popoverPC = popoverPresentationController else { return }
        popoverPC.sourceView = sender
        popoverPC.sourceRect = sender.bounds
        popoverPC.delegate = self
    }

    @IBAction func onTapYesButton(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
        didSelectDataHandler?("YES")
    }

    // MARK: - PopoverPC Delegate Methods

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.none
    }
}

Delegate:

protocol ConfirmDialogViewControllerDelegate: class {
    func didSelectYes(_ selectedDate: String)
}

class ConfirmDialogViewController: UIViewController {
    weak var delegate: ConfirmDialogViewControllerDelegate?

    @IBAction func onTapYesButton(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
        delegate?.didSelectData("YES")
    }
}

// In your current view controller set
popoverViewController.delegate = self

Bonus:

Check out this library if you want to have a popover containing a data list for selection.


问:
How to detect that the HTML element has text by clicking on text content area?
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

```<code><div>
some text
<span class="box"></span>
</div>

<div>
some text
</div>

<div><span class="box"></span></div>
</code>```

JS:

```<code>$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('<span>You clicked on a text</span>');
    }

});
</code>```

答:
wrap your text in separate element and fire click event on that element and also use .stopPropagation() method...</p>

```<code>  $("#demo").click(function(event){
    event.stopPropagation();
    alert("your text element was clicked");
  });
</code>```

Body:
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

some text

some text

JS:

$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('You clicked on a text');
    }

});

Body:
wrap your text in separate element and fire click event on that element and also use .stopPropagation() method...

  $("#demo").click(function(event){
    event.stopPropagation();
    alert("your text element was clicked");
  });


问:
Strange behavior when trying to append a row to each group in a group by object
This question is about a function behaving in an unexpected manner when applied on two different dataframes - more precisely, groupby objects. Either I'm missing something that is obviously wrong or there's a bug in pandas.

I wrote the below function to append a row to each group in a groupby object.This question is another question that is related to the function.

```<code>def myfunction(g, now):

    '''This function appends a row to each group and populates the DTM column value of that row with the current timestamp. Other columns of the new row will have NaN s.
       g: a groupby object
       now: current timestamp

       returns a dataframe that has the current timestamp appended in the DTM column for each group

    '''
        g.loc[g.shape[0], 'DTM'] = now # Appending the current timestamp to a DTM column in each group

        return g
</code>```

We'll run two tests to test the function.

TEST 1

It works as expected on the dataframe a in the linked question(demonstrated in the above question). Here's a slightly augmented a re-run for more clarity (mostly copy-pasted from the linked question).

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)

    a
Out[50]:
                     0
first second
bar   one     0.134379
      one     0.967928
      two     0.067502
baz   one     0.182887
      two     0.926932
foo   one     0.806225
      two     0.718322
      two     0.932114
qux   one     0.772494
      two     0.141510
</code>```

Applying the function,

```<code> a = a.reset_index().groupby(['first', 'second']).apply(lambda x: myfunction(x, now))
</code>```

It has appended a new row to each group. A new DTM column was added because it wasn't in the original a. A group is a first - second pair.

```<code>a
Out[52]:
               first second         0                     DTM
first second
bar   one    0   bar    one  0.134379                     NaT
             1   bar    one  0.967928                     NaT
             2   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    2   bar    two  0.067502                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
baz   one    3   baz    one  0.182887                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    4   baz    two  0.926932                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
foo   one    5   foo    one  0.806225                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    6   foo    two  0.718322                     NaT
             7   foo    two  0.932114                     NaT
             2   NaN    NaN       NaN 2017-07-03 18:56:33.183
qux   one    8   qux    one  0.772494                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    9   qux    two  0.141510                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
</code>```

Some refinement,

```<code>a = a.reset_index(level = 2).drop(('level_2', 'first', 'second')).loc[:,(0,'DTM')]
</code>```

this gives final a as,

```<code>a
Out[62]:
                     0                     DTM
first second
bar   one     0.371683                     NaT
      one     0.327870                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.048794                     NaT
      two          NaN 2017-07-03 18:56:33.183
baz   one     0.462747                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.758674                     NaT
      two          NaN 2017-07-03 18:56:33.183
foo   one     0.238607                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.156104                     NaT
      two     0.594270                     NaT
      two          NaN 2017-07-03 18:56:33.183
qux   one     0.091088                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.795864                     NaT
      two          NaN 2017-07-03 18:56:33.183
</code>```

So far so good. This is the expected behavior. A new row has been appended to each first-second pair and the DTM column of that row has been populated with the current timestamp.

TEST 2

Surprisingly, I couldn't reproduce that behavior in the below dataframe df. A group is an ID-SEQ combination

This df can be reproduced using:

1.Copying the below

```<code>    C1  572  5/9/2017 10:13  PE
    C1  572  5/9/2017 12:24  OK
    C1  579  5/9/2017 10:19  PE
    C1  579  5/9/2017 13:25  OK
    C1  587  5/9/2017 10:20  PE
    C1  587  5/9/2017 12:25  OK
    C1  590  5/9/2017 10:21  PE
    C1  590  5/9/2017 13:09  OK
    C1  604  5/9/2017 10:38  PE
    C1  604  5/9/2017 12:32  OK
    C1  609  5/9/2017 10:39  PE
    C1  609  5/9/2017 13:29  OK
    C1  613  5/9/2017 10:39  PE
    C1  613  5/9/2017 13:08  OK
    C1  618  5/9/2017 10:40  PE
    C1  618  5/9/2017 13:33  OK
    C1  636  5/9/2017 10:54  PE
    C1  636  5/9/2017 13:36  OK
    C1  642  5/9/2017 10:55  PE
    C1  642  5/9/2017 13:35  OK
    C1  643  5/9/2017 10:56  PE
    C1  643  5/9/2017 13:34  OK
    C1  656  5/9/2017 10:55  PE
    C1  656  5/9/2017 13:36  OK
    C2  86  9/5/2016 19:45   PE
    C2  86  9/6/2016 11:55   OK
    C3  10  4/17/2017 12:23  PE
    C3  10  4/17/2017 14:51  OK
    C4  38  3/25/2017 10:35  PE
    C4  38  3/25/2017 10:51  OK
</code>```

2.And then executing these,

```<code>  df = pd.read_clipboard(sep = '[ ]{2,}')
  df.columns = ['ID', 'SEQ', 'DTM', 'STATUS']
</code>```

Setting a multi-index

```<code>d = df.set_index(['ID', 'SEQ', 'DTM']) # I have three index levels this time in the original dataframe
</code>```

What d looks like,

```<code>d
Out[40]:
                       STATUS
ID SEQ DTM
C1 572 5/9/2017 10:13      PE
       5/9/2017 12:24      OK
   579 5/9/2017 10:19      PE
       5/9/2017 13:25      OK
   587 5/9/2017 10:20      PE
       5/9/2017 12:25      OK
   590 5/9/2017 10:21      PE
       5/9/2017 13:09      OK
   604 5/9/2017 10:38      PE
       5/9/2017 12:32      OK
   609 5/9/2017 10:39      PE
       5/9/2017 13:29      OK
   613 5/9/2017 10:39      PE
       5/9/2017 13:08      OK
   618 5/9/2017 10:40      PE
       5/9/2017 13:33      OK
   636 5/9/2017 10:54      PE
       5/9/2017 13:36      OK
   642 5/9/2017 10:55      PE
       5/9/2017 13:35      OK
   643 5/9/2017 10:56      PE
       5/9/2017 13:34      OK
   656 5/9/2017 10:55      PE
       5/9/2017 13:36      OK
C2 86  9/5/2016 19:45      PE
       9/6/2016 11:55      OK
C3 10  4/17/2017 12:23     PE
       4/17/2017 14:51     OK
C4 38  3/25/2017 10:35     PE
       3/25/2017 10:51     OK
</code>```

Applying the function,

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)

    a
Out[50]:
                     0
first second
bar   one     0.134379
      one     0.967928
      two     0.067502
baz   one     0.182887
      two     0.926932
foo   one     0.806225
      two     0.718322
      two     0.932114
qux   one     0.772494
      two     0.141510
</code>```0

This returns, (notice the fourth row)

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)

    a
Out[50]:
                     0
first second
bar   one     0.134379
      one     0.967928
      two     0.067502
baz   one     0.182887
      two     0.926932
foo   one     0.806225
      two     0.718322
      two     0.932114
qux   one     0.772494
      two     0.141510
</code>```1

some refinement,

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)

    a
Out[50]:
                     0
first second
bar   one     0.134379
      one     0.967928
      two     0.067502
baz   one     0.182887
      two     0.926932
foo   one     0.806225
      two     0.718322
      two     0.932114
qux   one     0.772494
      two     0.141510
</code>```2

Problem

A new row containing the current timestamp has been appended to each ID-SEQ group with the exception of C1-579 group! (4th row in dd and ddd)

Questions

What caused this problem?

What is the additional index level introduced in dd?

答:
After a lot debugging problem was noticed.

There is problem with same number in level 3 - in your last sample is shape of group 2, but this value exist before, so new row was no added onlu row was overwritten.

```<code>            ID    SEQ                        DTM STATUS
ID SEQ
C1 572 0    C1  572.0 2017-05-09 10:13:00.000000     PE
       1    C1  572.0 2017-05-09 12:24:00.000000     OK
       2   NaN    NaN 2017-07-06 08:46:02.341472    NaN
   579 2    C1  579.0 2017-07-06 08:46:02.341472     PE <- ovetwritten values in row
       3    C1  579.0 2017-05-09 13:25:00.000000     OK
   587 4    C1  587.0 2017-05-09 10:20:00.000000     PE
       5    C1  587.0 2017-05-09 12:25:00.000000     OK
       2   NaN    NaN 2017-07-06 08:46:02.341472    NaN
</code>```

First sample was nice because second group has only one row.

But if has 2 rows:

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'two','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
print (a)
                     0
first second
bar   one     0.366258
      two     0.583205
      two     0.159388
baz   one     0.598198
      two     0.274027
foo   one     0.086461
      two     0.353577
      two     0.823377
qux   one     0.098737
      two     0.128470
</code>```

same problem.

```<code>print (a)
               first second         0                        DTM
first second
bar   one    0   bar    one  0.366258                        NaT
             1   NaN    NaN       NaN 2017-07-06 08:47:55.610671
      two    1   bar    two  0.583205                        NaT
             2   bar    two  0.159388 2017-07-06 08:47:55.610671 <- ovetwritten
baz   one    3   baz    one  0.598198                        NaT
             1   NaN    NaN       NaN 2017-07-06 08:47:55.610671
      two    4   baz    two  0.274027                        NaT
</code>```

So if function is a bit changed all works perfectly:

```<code>now = pd.datetime.now()

def myfunction(g, now):

    g.loc[str(g.shape[0]) + 'a', 'DTM'] = now
    return g

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'two','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
print (a)

a = a.reset_index().groupby(['first', 'second']).apply(lambda x: myfunction(x, now))
print (a)
                first second         0                        DTM
first second
bar   one    0    bar    one  0.677641                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
      two    1    bar    two  0.274588                        NaT
             2    bar    two  0.524903                        NaT
             2a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
baz   one    3    baz    one  0.198272                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
      two    4    baz    two  0.787949                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
foo   one    5    foo    one  0.484197                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
</code>```

Body:
This question is about a function behaving in an unexpected manner when applied on two different dataframes - more precisely, groupby objects. Either I'm missing something that is obviously wrong or there's a bug in pandas.

I wrote the below function to append a row to each group in a groupby object.This question is another question that is related to the function.

def myfunction(g, now):

    '''This function appends a row to each group and populates the DTM column value of that row with the current timestamp. Other columns of the new row will have NaN s.
       g: a groupby object
       now: current timestamp

       returns a dataframe that has the current timestamp appended in the DTM column for each group

    '''
        g.loc[g.shape[0], 'DTM'] = now # Appending the current timestamp to a DTM column in each group

        return g

We'll run two tests to test the function.

TEST 1

It works as expected on the dataframe a in the linked question(demonstrated in the above question). Here's a slightly augmented a re-run for more clarity (mostly copy-pasted from the linked question).

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)

    a
Out[50]:
                     0
first second
bar   one     0.134379
      one     0.967928
      two     0.067502
baz   one     0.182887
      two     0.926932
foo   one     0.806225
      two     0.718322
      two     0.932114
qux   one     0.772494
      two     0.141510

Applying the function,

 a = a.reset_index().groupby(['first', 'second']).apply(lambda x: myfunction(x, now))

It has appended a new row to each group. A new DTM column was added because it wasn't in the original a. A group is a first - second pair.

a
Out[52]:
               first second         0                     DTM
first second
bar   one    0   bar    one  0.134379                     NaT
             1   bar    one  0.967928                     NaT
             2   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    2   bar    two  0.067502                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
baz   one    3   baz    one  0.182887                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    4   baz    two  0.926932                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
foo   one    5   foo    one  0.806225                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    6   foo    two  0.718322                     NaT
             7   foo    two  0.932114                     NaT
             2   NaN    NaN       NaN 2017-07-03 18:56:33.183
qux   one    8   qux    one  0.772494                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183
      two    9   qux    two  0.141510                     NaT
             1   NaN    NaN       NaN 2017-07-03 18:56:33.183

Some refinement,

a = a.reset_index(level = 2).drop(('level_2', 'first', 'second')).loc[:,(0,'DTM')]

this gives final a as,

a
Out[62]:
                     0                     DTM
first second
bar   one     0.371683                     NaT
      one     0.327870                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.048794                     NaT
      two          NaN 2017-07-03 18:56:33.183
baz   one     0.462747                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.758674                     NaT
      two          NaN 2017-07-03 18:56:33.183
foo   one     0.238607                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.156104                     NaT
      two     0.594270                     NaT
      two          NaN 2017-07-03 18:56:33.183
qux   one     0.091088                     NaT
      one          NaN 2017-07-03 18:56:33.183
      two     0.795864                     NaT
      two          NaN 2017-07-03 18:56:33.183

So far so good. This is the expected behavior. A new row has been appended to each first-second pair and the DTM column of that row has been populated with the current timestamp.

TEST 2

Surprisingly, I couldn't reproduce that behavior in the below dataframe df. A group is an ID-SEQ combination

This df can be reproduced using:

1.Copying the below

    C1  572  5/9/2017 10:13  PE
    C1  572  5/9/2017 12:24  OK
    C1  579  5/9/2017 10:19  PE
    C1  579  5/9/2017 13:25  OK
    C1  587  5/9/2017 10:20  PE
    C1  587  5/9/2017 12:25  OK
    C1  590  5/9/2017 10:21  PE
    C1  590  5/9/2017 13:09  OK
    C1  604  5/9/2017 10:38  PE
    C1  604  5/9/2017 12:32  OK
    C1  609  5/9/2017 10:39  PE
    C1  609  5/9/2017 13:29  OK
    C1  613  5/9/2017 10:39  PE
    C1  613  5/9/2017 13:08  OK
    C1  618  5/9/2017 10:40  PE
    C1  618  5/9/2017 13:33  OK
    C1  636  5/9/2017 10:54  PE
    C1  636  5/9/2017 13:36  OK
    C1  642  5/9/2017 10:55  PE
    C1  642  5/9/2017 13:35  OK
    C1  643  5/9/2017 10:56  PE
    C1  643  5/9/2017 13:34  OK
    C1  656  5/9/2017 10:55  PE
    C1  656  5/9/2017 13:36  OK
    C2  86  9/5/2016 19:45   PE
    C2  86  9/6/2016 11:55   OK
    C3  10  4/17/2017 12:23  PE
    C3  10  4/17/2017 14:51  OK
    C4  38  3/25/2017 10:35  PE
    C4  38  3/25/2017 10:51  OK

2.And then executing these,

  df = pd.read_clipboard(sep = '[ ]{2,}')
  df.columns = ['ID', 'SEQ', 'DTM', 'STATUS']

Setting a multi-index

d = df.set_index(['ID', 'SEQ', 'DTM']) # I have three index levels this time in the original dataframe

What d looks like,

d
Out[40]:
                       STATUS
ID SEQ DTM
C1 572 5/9/2017 10:13      PE
       5/9/2017 12:24      OK
   579 5/9/2017 10:19      PE
       5/9/2017 13:25      OK
   587 5/9/2017 10:20      PE
       5/9/2017 12:25      OK
   590 5/9/2017 10:21      PE
       5/9/2017 13:09      OK
   604 5/9/2017 10:38      PE
       5/9/2017 12:32      OK
   609 5/9/2017 10:39      PE
       5/9/2017 13:29      OK
   613 5/9/2017 10:39      PE
       5/9/2017 13:08      OK
   618 5/9/2017 10:40      PE
       5/9/2017 13:33      OK
   636 5/9/2017 10:54      PE
       5/9/2017 13:36      OK
   642 5/9/2017 10:55      PE
       5/9/2017 13:35      OK
   643 5/9/2017 10:56      PE
       5/9/2017 13:34      OK
   656 5/9/2017 10:55      PE
       5/9/2017 13:36      OK
C2 86  9/5/2016 19:45      PE
       9/6/2016 11:55      OK
C3 10  4/17/2017 12:23     PE
       4/17/2017 14:51     OK
C4 38  3/25/2017 10:35     PE
       3/25/2017 10:51     OK

Applying the function,

dd = d.reset_index().groupby(['ID', 'SEQ']).apply(lambda x: myfunction(x, now)) # a group is a unique combination of ID-SEQ pairs

This returns, (notice the fourth row)

dd
Out[37]:
            ID    SEQ                         DTM STATUS
ID SEQ
C1 572 0    C1  572.0              5/9/2017 10:13     PE
       1    C1  572.0              5/9/2017 12:24     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   579 2    C1  579.0  2017-07-03 18:56:33.183000     PE
       3    C1  579.0              5/9/2017 13:25     OK
   587 4    C1  587.0              5/9/2017 10:20     PE
       5    C1  587.0              5/9/2017 12:25     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   590 6    C1  590.0              5/9/2017 10:21     PE
       7    C1  590.0              5/9/2017 13:09     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   604 8    C1  604.0              5/9/2017 10:38     PE
       9    C1  604.0              5/9/2017 12:32     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   609 10   C1  609.0              5/9/2017 10:39     PE
       11   C1  609.0              5/9/2017 13:29     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   613 12   C1  613.0              5/9/2017 10:39     PE
       13   C1  613.0              5/9/2017 13:08     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   618 14   C1  618.0              5/9/2017 10:40     PE
       15   C1  618.0              5/9/2017 13:33     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   636 16   C1  636.0              5/9/2017 10:54     PE
       17   C1  636.0              5/9/2017 13:36     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   642 18   C1  642.0              5/9/2017 10:55     PE
       19   C1  642.0              5/9/2017 13:35     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   643 20   C1  643.0              5/9/2017 10:56     PE
       21   C1  643.0              5/9/2017 13:34     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
   656 22   C1  656.0              5/9/2017 10:55     PE
       23   C1  656.0              5/9/2017 13:36     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
C2 86  24   C2   86.0              9/5/2016 19:45     PE
       25   C2   86.0              9/6/2016 11:55     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
C3 10  26   C3   10.0             4/17/2017 12:23     PE
       27   C3   10.0             4/17/2017 14:51     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN
C4 38  28   C4   38.0             3/25/2017 10:35     PE
       29   C4   38.0             3/25/2017 10:51     OK
       2   NaN    NaN  2017-07-03 18:56:33.183000    NaN

some refinement,

ddd = dd.reset_index(level = 2).drop(('level_2', 'ID', 'SEQ')).loc[:,('DTM','STATUS')]

ddd
Out[39]:
                               DTM STATUS
ID SEQ
C1 572              5/9/2017 10:13     PE
   572              5/9/2017 12:24     OK
   572  2017-07-03 18:56:33.183000    NaN
   579  2017-07-03 18:56:33.183000     PE
   579              5/9/2017 13:25     OK
   587              5/9/2017 10:20     PE
   587              5/9/2017 12:25     OK
   587  2017-07-03 18:56:33.183000    NaN
   590              5/9/2017 10:21     PE
   590              5/9/2017 13:09     OK
   590  2017-07-03 18:56:33.183000    NaN
   604              5/9/2017 10:38     PE
   604              5/9/2017 12:32     OK
   604  2017-07-03 18:56:33.183000    NaN
   609              5/9/2017 10:39     PE
   609              5/9/2017 13:29     OK
   609  2017-07-03 18:56:33.183000    NaN
   613              5/9/2017 10:39     PE
   613              5/9/2017 13:08     OK
   613  2017-07-03 18:56:33.183000    NaN
   618              5/9/2017 10:40     PE
   618              5/9/2017 13:33     OK
   618  2017-07-03 18:56:33.183000    NaN
   636              5/9/2017 10:54     PE
   636              5/9/2017 13:36     OK
   636  2017-07-03 18:56:33.183000    NaN
   642              5/9/2017 10:55     PE
   642              5/9/2017 13:35     OK
   642  2017-07-03 18:56:33.183000    NaN
   643              5/9/2017 10:56     PE
   643              5/9/2017 13:34     OK
   643  2017-07-03 18:56:33.183000    NaN
   656              5/9/2017 10:55     PE
   656              5/9/2017 13:36     OK
   656  2017-07-03 18:56:33.183000    NaN
C2 86               9/5/2016 19:45     PE
   86               9/6/2016 11:55     OK
   86   2017-07-03 18:56:33.183000    NaN
C3 10              4/17/2017 12:23     PE
   10              4/17/2017 14:51     OK
   10   2017-07-03 18:56:33.183000    NaN
C4 38              3/25/2017 10:35     PE
   38              3/25/2017 10:51     OK
   38   2017-07-03 18:56:33.183000    NaN

Problem

A new row containing the current timestamp has been appended to each ID-SEQ group with the exception of C1-579 group! (4th row in dd and ddd)

Questions

What caused this problem?

What is the additional index level introduced in dd?

Body:
After a lot debugging problem was noticed.

There is problem with same number in level 3 - in your last sample is shape of group 2, but this value exist before, so new row was no added onlu row was overwritten.

            ID    SEQ                        DTM STATUS
ID SEQ
C1 572 0    C1  572.0 2017-05-09 10:13:00.000000     PE
       1    C1  572.0 2017-05-09 12:24:00.000000     OK
       2   NaN    NaN 2017-07-06 08:46:02.341472    NaN
   579 2    C1  579.0 2017-07-06 08:46:02.341472     PE <- ovetwritten values in row
       3    C1  579.0 2017-05-09 13:25:00.000000     OK
   587 4    C1  587.0 2017-05-09 10:20:00.000000     PE
       5    C1  587.0 2017-05-09 12:25:00.000000     OK
       2   NaN    NaN 2017-07-06 08:46:02.341472    NaN

First sample was nice because second group has only one row.

But if has 2 rows:

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'two','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
print (a)
                     0
first second
bar   one     0.366258
      two     0.583205
      two     0.159388
baz   one     0.598198
      two     0.274027
foo   one     0.086461
      two     0.353577
      two     0.823377
qux   one     0.098737
      two     0.128470

same problem.

print (a)
               first second         0                        DTM
first second
bar   one    0   bar    one  0.366258                        NaT
             1   NaN    NaN       NaN 2017-07-06 08:47:55.610671
      two    1   bar    two  0.583205                        NaT
             2   bar    two  0.159388 2017-07-06 08:47:55.610671 <- ovetwritten
baz   one    3   baz    one  0.598198                        NaT
             1   NaN    NaN       NaN 2017-07-06 08:47:55.610671
      two    4   baz    two  0.274027                        NaT

So if function is a bit changed all works perfectly:

now = pd.datetime.now()

def myfunction(g, now):

    g.loc[str(g.shape[0]) + 'a', 'DTM'] = now
    return g

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'two','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
print (a)

a = a.reset_index().groupby(['first', 'second']).apply(lambda x: myfunction(x, now))
print (a)
                first second         0                        DTM
first second
bar   one    0    bar    one  0.677641                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
      two    1    bar    two  0.274588                        NaT
             2    bar    two  0.524903                        NaT
             2a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
baz   one    3    baz    one  0.198272                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
      two    4    baz    two  0.787949                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671
foo   one    5    foo    one  0.484197                        NaT
             1a   NaN    NaN       NaN 2017-07-06 08:54:47.481671


问:
Getting error undefined method `[]' for nil:NilClass (NoMethodError)
Here is the code

```<code>class Tech
  attr_reader :content, :tech_hash
  @tech_hash = Hash.new(0)
  def initialize(content)
    @content = content
    showTech(content)
  end
  def showTech(content)
    content.split.each do |word|
    @tech_hash[word] += 1
    end
    @tech_hash = @tech_hash.sort_by{|k,v| -v}.to_h
    p @tech_hash
  end
end

class Digital
  def analyze()
    File.foreach('test.txt') do |content|
      ob = Tech.new(content)
    end
  end
end

digi = Digital.new()
digi.analyze()
</code>```

Here is the error

```<code>D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:10:in `block in showTech': undefined method `[]' for nil:NilClass (NoMethodError)
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `each'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `showTech'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:6:in `initialize'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `new'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `block in analyze'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `foreach'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `analyze'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:29:in `<main>'
</code>```

答:
@tech_hash is defined outside of an instance method, what makes it a class variable. Therefore within showTech there is still no @tech_hash instance variable defined and therefore it returns nil

Just move @tech_hash into the initialize method to initialize an instance variable:

```<code>def initialize(content)
  @content = content
  @tech_hash = Hash.new(0)

  showTech(content)
end
</code>```

Body:
Here is the code

class Tech
  attr_reader :content, :tech_hash
  @tech_hash = Hash.new(0)
  def initialize(content)
    @content = content
    showTech(content)
  end
  def showTech(content)
    content.split.each do |word|
    @tech_hash[word] += 1
    end
    @tech_hash = @tech_hash.sort_by{|k,v| -v}.to_h
    p @tech_hash
  end
end

class Digital
  def analyze()
    File.foreach('test.txt') do |content|
      ob = Tech.new(content)
    end
  end
end

digi = Digital.new()
digi.analyze()

Here is the error

D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:10:in `block in showTech': undefined method `[]' for nil:NilClass (NoMethodError)
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `each'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `showTech'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:6:in `initialize'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `new'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `block in analyze'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `foreach'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `analyze'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:29:in `'

Body:
@tech_hash is defined outside of an instance method, what makes it a class variable. Therefore within showTech there is still no @tech_hash instance variable defined and therefore it returns nil

Just move @tech_hash into the initialize method to initialize an instance variable:

def initialize(content)
  @content = content
  @tech_hash = Hash.new(0)

  showTech(content)
end