问:
What's the benefit of Scala (singleton) object vs. typical class level artifacts
I understand one of the main benefits from using object is, they are real objects instead of system wide functionality.  But finally those objects are also system wide accessible.

Beside of being more "pure"  what additional benefit does scala "objects" offer.

I bet there are a number but I can't really figure out which.

答: The use of singleton objects as a replacement for static containers have as much advantage as OO has over purely imperative programming. After all, static stuff is essentially imperative, and singleton objects are object oriented.


来源: stackexchange

问:
Navigating to Child Components with Vue.js
I have an app built with Vue.js. In this app, I'm using the Vue Router. I successfully have top-level routes working. However, I'm unable to get child routes to work. My code seems to ignore any routes defined within the children property of a route. I've setup the problem in this fiddle. The relevant code looks like this:

```<code>const CustomerMenu = { template: '<div><br />please choose: <router-link to="/customers/list">list</router-link>  <router-link to="/customers/stats">stats</router-link></div>' }
const CustomerList = { template: '<div>A list of customers here</div>' };
const CustomerStats = { template: '<div>Customer statistics</div>' };
const Suppliers = { template: '<div>Suppliers</div>' }

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/customers', component: CustomerMenu, children: [
      { path: 'list', component: CustomerList },
      { path: 'stats', component: CustomerStats }
    ]},
    { path: '/suppliers', component: Suppliers }
  ]
})

new Vue({
    router,
  el: '#app',
  data: {}
});
</code>```

How do I show the content associated with a route defined in the children property of a route. In other words, how do I get the "list" or "stats" components to appear when a user selects there respective links?

Thank you!

答:
You were missing <router-view/> inside your CustomerMenu component.
http://jsfiddle.net/sn5vu6ek/

Remember - every component which has children routes has to have  to be able to display children components.

If you just want to have some part of path common between components, you can either create parent with just <router-view/> inside, or specify full path for multiple components.

ContentLicense: CC BY-SA 3.0

Body:
I have an app built with Vue.js. In this app, I'm using the Vue Router. I successfully have top-level routes working. However, I'm unable to get child routes to work. My code seems to ignore any routes defined within the children property of a route. I've setup the problem in this fiddle. The relevant code looks like this:

const CustomerMenu = { template: '

please choose: <router-link to="/customers/list">list</router-link>  <router-link to="/customers/stats">stats</router-link>
' }
const CustomerList = { template: '
A list of customers here
' };
const CustomerStats = { template: '
Customer statistics
' };
const Suppliers = { template: '
Suppliers
' }

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/customers', component: CustomerMenu, children: [
      { path: 'list', component: CustomerList },
      { path: 'stats', component: CustomerStats }
    ]},
    { path: '/suppliers', component: Suppliers }
  ]
})

new Vue({
    router,
  el: '#app',
  data: {}
});

How do I show the content associated with a route defined in the children property of a route. In other words, how do I get the "list" or "stats" components to appear when a user selects there respective links?

Thank you!


问:
How do I add a new value to a dictionary's key on top of the old one, to create a sum?
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

```<code>seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass
</code>```

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

```<code>my_dict[then_string] = my_dict.get(then_string) + seconds
</code>```

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

答:
Dictionary Approach

Going down the dictionary method as per the original post, this would be how I would tackle it. Note the try/except - in place addition will throw a KeyError if the key doesn't yet exist.

```<code>seconds = 0
my_dict = {}
stop = 0

while stop != 1:
    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        try:
            # let's assume the key exists
            my_dict[then_string] += seconds
        except KeyError:
            # oh no! it doens't exist, let's set it at seconds
            my_dict[then_string] = seconds
        seconds = 0 #Resets the seconds.
    else:
        pass
</code>```

Collections Approach

However, python has a special container type for just this task called collections.Counter(), which is an extended dictionary.

```<code>from collections import Counter
seconds = 0
my_counter = Counter()
stop = 0

while stop != 1:
    sv = getStringValue()
    c.update(sv = 1)
    sleep(1)
    # do something here to ascertain when to set stop = 1
else:
    del sv
# output a nice count of all sv's and the second count
print(c)
</code>```

Body:
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

my_dict[then_string] = my_dict.get(then_string) + seconds

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

Body:
Dictionary Approach

Going down the dictionary method as per the original post, this would be how I would tackle it. Note the try/except - in place addition will throw a KeyError if the key doesn't yet exist.

seconds = 0
my_dict = {}
stop = 0

while stop != 1:
    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        try:
            # let's assume the key exists
            my_dict[then_string] += seconds
        except KeyError:
            # oh no! it doens't exist, let's set it at seconds
            my_dict[then_string] = seconds
        seconds = 0 #Resets the seconds.
    else:
        pass

Collections Approach

However, python has a special container type for just this task called collections.Counter(), which is an extended dictionary.

from collections import Counter
seconds = 0
my_counter = Counter()
stop = 0

while stop != 1:
    sv = getStringValue()
    c.update(sv = 1)
    sleep(1)
    # do something here to ascertain when to set stop = 1
else:
    del sv
# output a nice count of all sv's and the second count
print(c)


问:
Regex string between underscore
I need to get the markings between the underscores, for example:
Com_x0020_este_x002C__x0020_texto

Com_x0020_este_x002C_ _x0020_texto

Thank you!

答:
You can try this, if I understand the question correctly: /_(.*?)_/g

See https://regex101.com/r/H3exx4/1/ for an example.

Title: Regex string between underscore


问:
batch doen't read text file till save it first
My code stops at line 3 in the .dat file ,but when i save the .dat file it reads all the lines and work properly why this happening and what to do??

this is code my data contain Latina characters and symbols.

```<code>@ECHO Off
SET "sourcedir=D:\yyyyy\Orgin_file_Ma\MA_SMS"
SET "destdir=D:\llllll\STG_file_Ma"
FOR %%f IN ("%sourcedir%\*.dat") DO > "%destdir%\%%~nf.txt" (
FOR /f "usebackqdelims=" %%a IN ("%%f") DO (
set Typ=SMS
  ECHO %%a^|!Typ!
 )
   )
</code>```

答:
This is effectively the same question you asked yesterday.

An answer cannot be provided unless you change your code to something that works; try this:

@ECHO OFF
SET "SOURCEDIR=D:\yyyyy\Orgin_file_Ma\MA_SMS"
SET "DESTDIR=D:\llllll\STG_file_Ma"
SET "TYP=SMS"
FOR %%F IN ("%SOURCEDIR%\*.dat") DO FOR /F "USEBACKQ DELIMS=" %%A IN ("%%F"
) DO >"%DESTDIR%\%%~nF.txt" ECHO %%A^|%TYP%
```

After confirming the structure of the above script is correct, add it to your question above by way of the edit facility and provide much more information on those dat files.

Depending upon those dat files it is likely that ECHO may not be the correct command to use.

Body:
My code stops at line 3 in the .dat file ,but when i save the .dat file it reads all the lines and work properly why this happening and what to do??

this is code my data contain Latina characters and symbols.

@ECHO Off
SET "sourcedir=D:\yyyyy\Orgin_file_Ma\MA_SMS"
SET "destdir=D:\llllll\STG_file_Ma"
FOR %%f IN ("%sourcedir%\*.dat") DO > "%destdir%\%%~nf.txt" (
FOR /f "usebackqdelims=" %%a IN ("%%f") DO (
set Typ=SMS
  ECHO %%a^|!Typ!
 )
   )

Body:
This is effectively the same question you asked yesterday.

An answer cannot be provided unless you change your code to something that works; try this:

@ECHO OFF
SET "SOURCEDIR=D:\yyyyy\Orgin_file_Ma\MA_SMS"
SET "DESTDIR=D:\llllll\STG_file_Ma"
SET "TYP=SMS"
FOR %%F IN ("%SOURCEDIR%\*.dat") DO FOR /F "USEBACKQ DELIMS=" %%A IN ("%%F"
) DO >"%DESTDIR%\%%~nF.txt" ECHO %%A^|%TYP%

After confirming the structure of the above script is correct, add it to your question above by way of the edit facility and provide much more information on those dat files.

Depending upon those dat files it is likely that ECHO may not be the correct command to use.


问:
How to check element level difference of 2 dataframes in r?
> all.equal(df,df2)
[1] "Component “q09”: Mean relative difference: 1.82404"

There is only one column q09 differ in df,df2.Next setp, I need to find which row of q09 is different and what's the difference.

I read similar question, anti_join can only find row difference.

As to find each element difference, how to do it?

答:
@lmo is right. To give a reproducible example for the OP

```<code>df <- data.frame (
  q09 = c(0,1,2,3,4,5,7)
)

df2 <- data.frame (
  q09 = c(0,1,2.5,3,4,5,6)
)
</code>```

you get the indexes with

```<code>which(df != df2)
</code>```

that gives you

```<code>[1] 3 7
</code>```

Body:
@lmo is right. To give a reproducible example for the OP

df <- data.frame (
  q09 = c(0,1,2,3,4,5,7)
)

df2 <- data.frame (
  q09 = c(0,1,2.5,3,4,5,6)
)

you get the indexes with

which(df != df2)

that gives you

[1] 3 7


问:
How can i hold a first letter of `h1` content after pressing backspace
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}</code>```

    Click here to edit content

```

答:
Check this. I have checked content length based on that h1 values will be replaced

https://jsfiddle.net/5brr7sj1/10/

```<code> $('.editor').keyup(function(){
  if($('.editor').html().length == 2){
  $(this).text(splitTxt[1]);
 }
 });
</code>```

Body:
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});

.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}

    Click here to edit content

Body:
Check this. I have checked content length based on that h1 values will be replaced

https://jsfiddle.net/5brr7sj1/10/

 $('.editor').keyup(function(){
  if($('.editor').html().length == 2){
  $(this).text(splitTxt[1]);
 }
 });


问:
(PHP) Web form inserting blank values into the database! Error - array(1) { [“g-recaptcha-response”]=> string(484)-
When sending information from my web form, it inserts blank values into the database. The auto increments on the ID work fine. When performing an Var Dump $_POST, I get this response:

```<code>array(1) { ["g-recaptcha-response"]=> string(484) + random letters and numbers
</code>```

I am trying to pass three values into my database from the user. First Name. Last Name and Email. It checks the values on my web site and looks like the Google Recaptcha V2 is working the way it was intended. I think it has something to do with the Recaptcha PHP script is not passing it to my insert PHP script.

Any Ideas? Thanks for taking the time to help me out.

PHP:

```<code><?php
function post_captcha($user_response) {
    $fields_string = '';
    $fields = array(
        'secret' => '',
        'response' => $user_response
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}

// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);

if (!$res['success']) {
    // What happens when the CAPTCHA wasn't checked
    echo '<p>Please Check the Security CAPTCHA Box.</p><br>';
} else {
    // If CAPTCHA is successfully completed...
    // Paste mail function or whatever else you want to happen here!

$dbhost = "localhost";
$dbname = "";
$dbusername = "";
$dbpassword = "";

try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$statement = $link->prepare("INSERT INTO MailV2(Fname, Lname, Email) VALUES(:Fname, :Lname, :Email)");

$FirstName = $_POST['Fname'];
$LastName = $_POST['Lname'];
$Email = $_POST['Email'];

$statement->execute(array(
":Fname" => "$FirstName",
":Lname" => "$LastName",
":Email" => "$Email"));
 // Echo Successful attempt
        echo "<p Data added to database.</p></br></br>";

    }
    catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
      }
?>
</code>```

HTML:

```<code><article class="contact-form">
    <form action="" method="POST">
        <div class="col-md-5 col-md-offset-1 contact-form-left">
            <input class="Fname" type="text" placeholder="FIRST NAME*">
            <input class="Lname" type="text" placeholder="LAST NAME*">
            <input class="Email" type="email" placeholder="EMAIL*">
        </div>
        <div class="col-md-5 contact-form-right text-right">
            <div class="g-recaptcha" data-sitekey=""></div>
            <br>
            <input type="submit" class="submit-btn" value="Subscribe">
        </div>
    </form>
</article>
</code>```

答:
Thanks KAF, I just realize that and fix it.  I was so fixed on my php, I didn't notice it until I posted it here.  It always the simple things.

Fixed HTML:

```<code><article class="contact-form">
    <form action="" method="POST">
        <div class="col-md-5 col-md-offset-1 contact-form-left">
            <input name="Fname" type="text" placeholder="FIRST NAME*">
            <input name="Lname" type="text" placeholder="LAST NAME*">
            <input name="Email" type="email" placeholder="EMAIL*">
        </div>
        <div class="col-md-5 contact-form-right text-right">
            <div class="g-recaptcha" data-sitekey=""></div>
            <br>
            <input type="submit" class="submit-btn" value="Subscribe">
        </div>
    </form>
</article>
</code>```

Body:
When sending information from my web form, it inserts blank values into the database. The auto increments on the ID work fine. When performing an Var Dump $_POST, I get this response:

array(1) { ["g-recaptcha-response"]=> string(484) + random letters and numbers

I am trying to pass three values into my database from the user. First Name. Last Name and Email. It checks the values on my web site and looks like the Google Recaptcha V2 is working the way it was intended. I think it has something to do with the Recaptcha PHP script is not passing it to my insert PHP script.

Any Ideas? Thanks for taking the time to help me out.

PHP:

<?php
function post_captcha($user_response) {
    $fields_string = '';
    $fields = array(
        'secret' => '',
        'response' => $user_response
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}

// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);

if (!$res['success']) {
    // What happens when the CAPTCHA wasn't checked
    echo '
Please Check the Security CAPTCHA Box.

';
} else {
    // If CAPTCHA is successfully completed...
    // Paste mail function or whatever else you want to happen here!

$dbhost = "localhost";
$dbname = "";
$dbusername = "";
$dbpassword = "";

try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$statement = $link->prepare("INSERT INTO MailV2(Fname, Lname, Email) VALUES(:Fname, :Lname, :Email)");

$FirstName = $_POST['Fname'];
$LastName = $_POST['Lname'];
$Email = $_POST['Email'];

$statement->execute(array(
":Fname" => "$FirstName",
":Lname" => "$LastName",
":Email" => "$Email"));
 // Echo Successful attempt
        echo "getMessage();
    }
      }
?>

HTML:

    <form action="" method="POST">

            <input class="Fname" type="text" placeholder="FIRST NAME*">
            <input class="Lname" type="text" placeholder="LAST NAME*">
            <input class="Email" type="email" placeholder="EMAIL*">

            <input type="submit" class="submit-btn" value="Subscribe">

    </form>

Body:
Thanks KAF, I just realize that and fix it.  I was so fixed on my php, I didn't notice it until I posted it here.  It always the simple things.

Fixed HTML:

<article class="contact-form">
    <form action="" method="POST">
        <div class="col-md-5 col-md-offset-1 contact-form-left">
            <input name="Fname" type="text" placeholder="FIRST NAME*">
            <input name="Lname" type="text" placeholder="LAST NAME*">
            <input name="Email" type="email" placeholder="EMAIL*">
        </div>
        <div class="col-md-5 contact-form-right text-right">
            <div class="g-recaptcha" data-sitekey=""></div>
            <br>
            <input type="submit" class="submit-btn" value="Subscribe">
        </div>
    </form>
</article>


问:
How to remove provisioning profiles from Xcode
Does anyone know how to remove previously installed provisioning profiles from Xcode?

I have seen this link, but I am not able to find that location in my system.

So I think there must be some other way to remove provisioning profiles.

答: I found out how to find provisioning profiles in Xcode 8. Archive your project (Product -> Archive) and then hit the validate button. Xcode will prepare the binary and the entitlements. When the summary windows comes up just hit the little arrow at the right of the window. A finder window will open with all your downloaded profiles.enter image description here</p>


问:
The Role Manager feature has not been enabled
Got the following ProviderException :

The Role Manager feature has not been enabled.

So far so good.

Is there somewhere a method that can be called to check if the Role Manager has been enabled or not?

答:
If you are using ASP.NET Identity UserManager you can get it like this as well:

```<code>var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

var roles = userManager.GetRoles(User.Identity.GetUserId());
</code>```

If you have changed key for user from Guid to Int for example use this code:

```<code>var roles = userManager.GetRoles(User.Identity.GetUserId<int>());
</code>```

Body:
If you are using ASP.NET Identity UserManager you can get it like this as well:

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

var roles = userManager.GetRoles(User.Identity.GetUserId());

If you have changed key for user from Guid to Int for example use this code:

var roles = userManager.GetRoles(User.Identity.GetUserId<int>());


问:
Debug Qt app in Visual Studio and inspect opaque objects (e.g. QDir or QFileInfo)
I am debugging a Qt application in Visual Studio 2013. I have the official Visual Studio plugin from Qt installed. I can see the contents of QString, but for any other QObject such as a QDir or a QFileInfo object I am not able to see its contents.

Am I doing something wrong or is this simply not possible?

When I unfold a QDir instance I can only see a member named d_ptr which references a QDirPrivate object that I cannot inspect. I can also not call other functions of QDir or QFileInfo such as path(), or filePath() at runtime from the debugger. When I try that Visual Studio claims that the address of the function has been optimized away.

Is there anyway to debug this without adding dozens of log statements to the program?

答:
UPDATE

After detailing in last answer that it was not possible, today I've found a way to make the debugger show the private (hiding) information.

Note: I'm keeping the old post below because it exposes the whole path I've followed to reach this solution and I think it worth keeping track of mistakes made and wrong conclusions, so nobody else made them again ;).

Suppose you have a QDir d; variable. You can inspect its inner data by making a manual cast in the Watch window:

```<code>(Qt5Cored.dll!QDirPrivate*)d.d_ptr.d
</code>```

Unfortunately it doesn't show any useful information since you'll face the same problem for inner members (private data not being printed).

However, from this point you can now modify your .natvis file to show the wanted data on hover:

```<code><?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="QDir">
    <DisplayString>path={((Qt5Cored.dll!QDirPrivate*)d_ptr.d)->dirEntry.m_filePath}</DisplayString>
  </Type>
</AutoVisualizer>
</code>```

I haven't been able to print this information on the Watch window (if I add a Expand section to the .natvis file it seems to be omitted), but at least you have this information on debug time.

I suggest you to take a look at the private header files or the Watch window (as described at the beginning of the answer) for the types you want to inspect so you can add the correct data to the .natvis file.

What was wrong about previous analysis?

I think the key point is the manual casting. I mentioned that

dirEntry is part of QDirPrivate, so it is clear that the debugger is not able to inspect it.

It was partially correct. The problem was that the debugger didn't know where to locate QDirPrivate since it is not an exported symbol of Qt; once we've indicated it explicitly (through the (Qt5Cored.dll!QDirPrivate*) cast) it was able to inspect it.

ORIGINAL ANSWER

AFAIK this is not possible for those classes. Unfortunately there are some private structures that are not exported and that seem the debugger cannot view.

Note: I'm working with Qt 5.6.1 so I'm going to use its source code from qt.io repository to match my examples.

Let's take QDir for example: it is defined in qdir.h, which is part of the public API of Qt. In the same file it declares QDirPrivate but its full definition is in qtdir_p.h which is not part of the public API.

Even if symbols are loaded, somehow the definition of this class remains obscure to the debugger. See example below of the .natvis file I've used:

```<code><?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="QDir">
    <DisplayString>Path: {d_func()->dirEntry.m_filePath}</DisplayString>
  </Type>
</AutoVisualizer>
</code>```

But the debugger shows the following when trying to watch QDir d(qApp->applicationDirPath());:

Error: class "QDirPrivate" has no member "dirEntry"

Error while evaluating 'd_func()->dirEntry.m_filePath'

but dirEntry is part of QDirPrivate, so it is clear that the debugger is not able to inspect it. dirEntry is of type QFileSystemEntry, defined in qfilesystementry_p.h (another private class).

Finally, if you take a look at the qt5.natvis file from Qt VS Tools and find corresponding classes in the source code you'll see that all the included classes exposes the definition of the structures used by the .natvis file.

UPDATE

The only public API of such classes are methods, unfortunately, calling functions from debugger is not supported. Citing the response in a MSDN forum from a Microsoft Staff:

Calling a function from the debugger is playing with fire. You are likely to deadlock on cross thread dependencies (even if you don't have any explicit cross thread dependencies, there are shared locks for things like memory allocation). This is why the C++ debugger has no support for implicit funceval.

Actually, if you try to invoke any method like QDir::absolutePath() in the watch window or in the .natvis file you'll see the following error message:

Error: Function QDir::absolutePath has no address, possibly due to compiler optimizations.

NOT SO ELEGANT WORKAROUND

A possible solution would be to use wrapper classes that store those private values. You'd need to replace each object with the wrapper but may help.

Below you'll find a very simple example for QDir (you'd need to complete with required constructors and to save the information you want). Keep in mind that this type of classes in Qt has been designed to be not extensible, so there are no virtual methods (so be aware of reimplementing some of them and to use the object casted to the base class).

```<code>class MyQDir : public QDir {
public:
  MyQDir(const QString& path) : QDir(path) {
    m_absolutePath = absolutePath();
  }

private:
  QString m_absolutePath;
};
</code>```

and following .natvis file to display MyQDir's path on hover:

```<code><?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="MyQDir">
    <DisplayString>Path: {m_absolutePath}</DisplayString>
  </Type>
</AutoVisualizer>
</code>```

Finally, I think the only solution left would be to print the information to console (qDebug()).

As a side note, this tutorial explains how to write a custom .natvis file. It is for 2015 but I've used it for 2017 flawlessly. I hope it is valid for 2013 too.

Body:
UPDATE

After detailing in last answer that it was not possible, today I've found a way to make the debugger show the private (hiding) information.

Note: I'm keeping the old post below because it exposes the whole path I've followed to reach this solution and I think it worth keeping track of mistakes made and wrong conclusions, so nobody else made them again ;).

Suppose you have a QDir d; variable. You can inspect its inner data by making a manual cast in the Watch window:

(Qt5Cored.dll!QDirPrivate*)d.d_ptr.d

Unfortunately it doesn't show any useful information since you'll face the same problem for inner members (private data not being printed).

However, from this point you can now modify your .natvis file to show the wanted data on hover:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="QDir">
    <DisplayString>path={((Qt5Cored.dll!QDirPrivate*)d_ptr.d)-&gt;dirEntry.m_filePath}</DisplayString>
  </Type>
</AutoVisualizer>

I haven't been able to print this information on the Watch window (if I add a Expand section to the .natvis file it seems to be omitted), but at least you have this information on debug time.

I suggest you to take a look at the private header files or the Watch window (as described at the beginning of the answer) for the types you want to inspect so you can add the correct data to the .natvis file.

What was wrong about previous analysis?

I think the key point is the manual casting. I mentioned that

dirEntry is part of QDirPrivate, so it is clear that the debugger is not able to inspect it.

It was partially correct. The problem was that the debugger didn't know where to locate QDirPrivate since it is not an exported symbol of Qt; once we've indicated it explicitly (through the (Qt5Cored.dll!QDirPrivate*) cast) it was able to inspect it.

ORIGINAL ANSWER

AFAIK this is not possible for those classes. Unfortunately there are some private structures that are not exported and that seem the debugger cannot view.

Note: I'm working with Qt 5.6.1 so I'm going to use its source code from qt.io repository to match my examples.

Let's take QDir for example: it is defined in qdir.h, which is part of the public API of Qt. In the same file it declares QDirPrivate but its full definition is in qtdir_p.h which is not part of the public API.

Even if symbols are loaded, somehow the definition of this class remains obscure to the debugger. See example below of the .natvis file I've used:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="QDir">
    <DisplayString>Path: {d_func()-&gt;dirEntry.m_filePath}</DisplayString>
  </Type>
</AutoVisualizer>

But the debugger shows the following when trying to watch QDir d(qApp->applicationDirPath());:

Error: class "QDirPrivate" has no member "dirEntry"

Error while evaluating 'd_func()->dirEntry.m_filePath'

but dirEntry is part of QDirPrivate, so it is clear that the debugger is not able to inspect it. dirEntry is of type QFileSystemEntry, defined in qfilesystementry_p.h (another private class).

Finally, if you take a look at the qt5.natvis file from Qt VS Tools and find corresponding classes in the source code you'll see that all the included classes exposes the definition of the structures used by the .natvis file.

UPDATE

The only public API of such classes are methods, unfortunately, calling functions from debugger is not supported. Citing the response in a MSDN forum from a Microsoft Staff:

Calling a function from the debugger is playing with fire. You are likely to deadlock on cross thread dependencies (even if you don't have any explicit cross thread dependencies, there are shared locks for things like memory allocation). This is why the C++ debugger has no support for implicit funceval.

Actually, if you try to invoke any method like QDir::absolutePath() in the watch window or in the .natvis file you'll see the following error message:

Error: Function QDir::absolutePath has no address, possibly due to compiler optimizations.

NOT SO ELEGANT WORKAROUND

A possible solution would be to use wrapper classes that store those private values. You'd need to replace each object with the wrapper but may help.

Below you'll find a very simple example for QDir (you'd need to complete with required constructors and to save the information you want). Keep in mind that this type of classes in Qt has been designed to be not extensible, so there are no virtual methods (so be aware of reimplementing some of them and to use the object casted to the base class).

class MyQDir : public QDir {
public:
  MyQDir(const QString& path) : QDir(path) {
    m_absolutePath = absolutePath();
  }

private:
  QString m_absolutePath;
};

and following .natvis file to display MyQDir's path on hover:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="MyQDir">
    <DisplayString>Path: {m_absolutePath}</DisplayString>
  </Type>
</AutoVisualizer>

Finally, I think the only solution left would be to print the information to console (qDebug()).

As a side note, this tutorial explains how to write a custom .natvis file. It is for 2015 but I've used it for 2017 flawlessly. I hope it is valid for 2013 too.


问:
WebException Could not establish trust relationship for the SSL/TLS secure channel
My company has developed a .NET web service and a client dll that uses that web service. The webservice is hosted on our server over ssl and the cert is provided and signed by GoDaddy.  We have some clients in a hosted environment that are getting the following error message from the client dll when it tries to access our web service.

System.Net.WebException The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Our fix has been to have them open IE on the server, which is a challenge in and of itself for a lot of the hosted services, and go to the WSDL url. IE then prompts them with a security alert dialog. It says the cert date is valid and a valid name matching the name of the page, but was issued by a company you have not chosen to trust. When they click Yes to proceed, the client dll can then succesfully connect to the web service and operate as normal.

Does anyone have any idea why GoDaddy would not have been in there valid publishers list? All of the servers we have running has GoDaddy as a valid authority. I'm guessing, for security reasons, they've uninstalled the authority for GoDaddy, but not totally convinced that there's not some other underlying issue.

Unfortunately, I haven't had much luck trying to recreate this locally. If I go into Internet Options and remove the GoDaddy authorities and hit our service, ssl works just fine. I go back into the list of publishers and GoDaddy gets put right back in. So my second question is, How the heck do you get rid of GoDaddy so I can get an invalid cert warning?

Okay, last question. Is there a way in code I can tell the web service to ignore invalid certs. I've seen some posts on doing this programatically with WCF but not old web services.

答:
This is really more of a serverfault question, but I'll add what I can here.

The root cert authority list that windows machines normally trust is updated fairly regularly.  This comes down as a windows update to IE.  You can see MSDN for more information.

If your clients do not have windows update turned on or are actively ignoring windows updates, which is unfortunately very common for a lot of IT departments, then there's not much you can do other than switch SSL providers.

Basically, they need to get the certificate updates or you need to switch to a cert provider that has a high probability of already being trusted by the machines in question.  Typically this means Verisign or Thawte.  The third alternative is the route you've been going down: have them manually trust the root CA.

At the end of the day I hate the idea of changing an app in this way simply because the IT departments in question are morons but the real question boils down to how your company wants to handle this.

ContentLicense: CC BY-SA 2.5


问:
zfcuser - whitelist routes and all childroutes
I'am using ZfcUser module in my application to protect access to /admin route. As I want to block all childroutes of /admin, except for /login, /register etc.

In order to do so, I've added a code from accepted answer here - Zend Framework 2 - Global check for authentication with ZFCUser

```<code>protected $whitelist = array('zfcuser/login', 'default');

  public function onBootstrap($e)
  {
      $app = $e->getApplication();
      $em  = $app->getEventManager();
      $sm  = $app->getServiceManager();

      $list = $this->whitelist;
      $auth = $sm->get('zfcuser_auth_service');

      $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
          $match = $e->getRouteMatch();

          // No route match, this is a 404
          if (!$match instanceof RouteMatch) {
              return;
          }

          // Route is whitelisted
          $name = $match->getMatchedRouteName();
          if (in_array($name, $list)) {
              return;
          }

          // User is authenticated
          if ($auth->hasIdentity()) {
              return;
          }

          // Redirect to the user login page, as an example
          $router   = $e->getRouter();
          $url      = $router->assemble(array(), array(
              'name' => 'zfcuser/login'
          ));

          $response = $e->getResponse();
          $response->getHeaders()->addHeaderLine('Location', $url);
          $response->setStatusCode(302);

          return $response;
      }, -100);
  }
</code>```

It works, however it also block access to root routes - and as there is plenty of them, I do not really want to add every single route to whitelist. Is there any way to restrict access only to /admin routes?

答:
You may protect access to admin area by checking each controller name instead of checking route names. Thus you may control user's accessibility with less effort and it is more portable than checking route names.

List your controllers where you want to limit accesses. So everything related to a controller should be restricted. Wherever you need to restrict access just list them here. You do not need to make your hands dirty with onBootstrap() method anymore.

```<code>protected $whitelist = array(
    'ZfcUser\Controller\User', // or use 'zfcuser'
);
</code>```

Put right controller name in the $whitelist. You can get that by echoing $controller in the onBootstrap() method. Please check out the commented area below.

Next catch up the controller name and then check whether that is listed in your list or not.

```<code>public function onBootstrap(MvcEvent $e)
{
    $app = $e->getApplication();
    $em  = $app->getEventManager();
    $sm  = $app->getServiceManager();

    $list = $this->whitelist;
    $auth = $sm->get('zfcuser_auth_service');

    $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {

        // get the current route
        $route = $e->getRouteMatch()->getMatchedRouteName();

        // check for 'zfcuser/login' and 'zfcuser/register' routes
        if (in_array($route, array('zfcuser/login', 'zfcuser/register'))) {
            return;
        }

        // get the current controller name
        $controller = $e->getRouteMatch()->getParam('controller');

        // Check the right controller name by echoing
        // echo $controller;

        // check if a user has access on the current controller
        if (in_array($controller, $list)) {

            if(! $auth->hasIdentity()) {

                $router = $e->getRouter();
                $url = $router->assemble(array(), array(
                    'name' => 'zfcuser/login'
                ));

                $response = $e->getResponse();
                $response->getHeaders()->addHeaderLine('Location', $url);
                $response->setStatusCode(302);

                return $response;
            }
        }

    }, -100);
}
</code>```

Let us know if it helps you!

Body:
I'am using ZfcUser module in my application to protect access to /admin route. As I want to block all childroutes of /admin, except for /login, /register etc.

In order to do so, I've added a code from accepted answer here - Zend Framework 2 - Global check for authentication with ZFCUser

protected $whitelist = array('zfcuser/login', 'default');

  public function onBootstrap($e)
  {
      $app = $e->getApplication();
      $em  = $app->getEventManager();
      $sm  = $app->getServiceManager();

      $list = $this->whitelist;
      $auth = $sm->get('zfcuser_auth_service');

      $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
          $match = $e->getRouteMatch();

          // No route match, this is a 404
          if (!$match instanceof RouteMatch) {
              return;
          }

          // Route is whitelisted
          $name = $match->getMatchedRouteName();
          if (in_array($name, $list)) {
              return;
          }

          // User is authenticated
          if ($auth->hasIdentity()) {
              return;
          }

          // Redirect to the user login page, as an example
          $router   = $e->getRouter();
          $url      = $router->assemble(array(), array(
              'name' => 'zfcuser/login'
          ));

          $response = $e->getResponse();
          $response->getHeaders()->addHeaderLine('Location', $url);
          $response->setStatusCode(302);

          return $response;
      }, -100);
  }

It works, however it also block access to root routes - and as there is plenty of them, I do not really want to add every single route to whitelist. Is there any way to restrict access only to /admin routes?

Body:
You may protect access to admin area by checking each controller name instead of checking route names. Thus you may control user's accessibility with less effort and it is more portable than checking route names.

List your controllers where you want to limit accesses. So everything related to a controller should be restricted. Wherever you need to restrict access just list them here. You do not need to make your hands dirty with onBootstrap() method anymore.

protected $whitelist = array(
    'ZfcUser\Controller\User', // or use 'zfcuser'
);

Put right controller name in the $whitelist. You can get that by echoing $controller in the onBootstrap() method. Please check out the commented area below.

Next catch up the controller name and then check whether that is listed in your list or not.

public function onBootstrap(MvcEvent $e)
{
    $app = $e->getApplication();
    $em  = $app->getEventManager();
    $sm  = $app->getServiceManager();

    $list = $this->whitelist;
    $auth = $sm->get('zfcuser_auth_service');

    $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {

        // get the current route
        $route = $e->getRouteMatch()->getMatchedRouteName();

        // check for 'zfcuser/login' and 'zfcuser/register' routes
        if (in_array($route, array('zfcuser/login', 'zfcuser/register'))) {
            return;
        }

        // get the current controller name
        $controller = $e->getRouteMatch()->getParam('controller');

        // Check the right controller name by echoing
        // echo $controller;

        // check if a user has access on the current controller
        if (in_array($controller, $list)) {

            if(! $auth->hasIdentity()) {

                $router = $e->getRouter();
                $url = $router->assemble(array(), array(
                    'name' => 'zfcuser/login'
                ));

                $response = $e->getResponse();
                $response->getHeaders()->addHeaderLine('Location', $url);
                $response->setStatusCode(302);

                return $response;
            }
        }

    }, -100);
}

Let us know if it helps you!


问:
Cookie management using the Java Apache HttpClient Fluent API
I am having trouble figuring out how to use the Apache HttpComponents/HttpClient Fluent API and get it to properly send back cookies to a web server that requires a login and then sending back the cookies to access other parts of the site. I am using version 4.5.3.

According to the Fluent API tutorial, you can use an (HttpComponents) Executor "in order to execute requests in a specific security context whereby authentication details are cached and re-used for subsequent requests." https://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fluent.html

So I tried that but I get a 403 Access Denied on any attempt to access another page after logging in.
Here's the code I've tried:

```<code>CookieStore httpCookieStore = new BasicCookieStore();
List<Cookie> cookies = httpCookieStore.getCookies();

String username = "admin";
String password = "admin";
Executor httpExecutor = Executor.newInstance().auth(username, password);
httpExecutor.use(httpCookieStore);
Response response = httpExecutor.execute(Request.Get("http://myserver.example.com/login").useExpectContinue());
String loginOutput = response.returnContent().asString();
System.out.println(loginOutput);  // works - gets the expected page

String swaggerUrl = "http://myserver.example.com/swagger/index.html";
response = httpExecutor.execute(Request.Get(swaggerUrl));
HttpResponse httpResponse = response.returnResponse();
System.out.println(httpResponse);  // Response is 403 Access Denied
// prints: HttpResponseProxy{HTTP/1.1 403 Access Denied [X-Content-Type-Options: nosniff, X-XSS-Protection: 1; mode=block, Pragma: no-cache, X-Frame-Options: DENY, Content-Type: text/html;charset=ISO-8859-1, Cache-Control: must-revalidate,no-cache,no-store, Content-Length: 1391, Server: Jetty(8.1.16.v20140903)] [Content-Type: text/html; charset=ISO-8859-1,Content-Length: 1391,Chunked: false]}
</code>```

I checked the contents of the CookieStore after the login and it has the correct cookie:

```<code>System.out.println(httpCookieStore.getCookies().size()); // prints 1
System.out.println(httpCookieStore.getCookies().get(0));
// prints: [version: 0][name: JSESSIONID][value: 14b1yp7hf85es1vc6zpe2y376n][domain: myserver.example.com][path: /][expiry: null]
</code>```

So I also tried explicitly adding the cookie to the Header of the GET Request, but that still fails with same 403 Access Denied error:

```<code>CookieStore httpCookieStore = new BasicCookieStore();
List<Cookie> cookies = httpCookieStore.getCookies();

String username = "admin";
String password = "admin";
Executor httpExecutor = Executor.newInstance().auth(username, password);
httpExecutor.use(httpCookieStore);
Response response = httpExecutor.execute(Request.Get("http://myserver.example.com/login").useExpectContinue());
String loginOutput = response.returnContent().asString();
System.out.println(loginOutput);  // works - gets the expected page

String swaggerUrl = "http://myserver.example.com/swagger/index.html";
response = httpExecutor.execute(Request.Get(swaggerUrl).addHeader(authCookieName, authCookieValue));
HttpResponse httpResponse = response.returnResponse();
System.out.println(httpResponse);  // Response is 403 Access Denied
</code>```

Any ideas how to make this work with the fluent API?

答:
When looking at the HttpClient documentation, you linked, they started with this warning (emphasis mine) :

As of version of 4.2 HttpClient comes with an easy to use facade API based on the concept of a fluent interface. Fluent facade API exposes only the most fundamental functions of HttpClient and is intended for simple use cases that do not require the full flexibility of HttpClient. For instance, fluent facade API relieves the users from having to deal with connection management and resource deallocation.

You might well be in the case of unsupported configuration through the fluent api (and to answer your quote from their doc, authentication, and session management are linked, but not mandatory with each other : you might have some stateless service that ask for auth info with every request without ever starting a session, and you can obviously create session (backed by a cookie) without ever asking auth info)

You might have to resort to the other, more verbose, API :

```<code>BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCookieStore(cookieStore)
    .build();
try {
    HttpGet httpget = new HttpGet("https://someportal/");
    CloseableHttpResponse response1 = httpclient.execute(httpget);
    try {
       ...
</code>```

Body:
I am having trouble figuring out how to use the Apache HttpComponents/HttpClient Fluent API and get it to properly send back cookies to a web server that requires a login and then sending back the cookies to access other parts of the site. I am using version 4.5.3.

According to the Fluent API tutorial, you can use an (HttpComponents) Executor "in order to execute requests in a specific security context whereby authentication details are cached and re-used for subsequent requests." https://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fluent.html

So I tried that but I get a 403 Access Denied on any attempt to access another page after logging in.
Here's the code I've tried:

CookieStore httpCookieStore = new BasicCookieStore();
List<Cookie> cookies = httpCookieStore.getCookies();

String username = "admin";
String password = "admin";
Executor httpExecutor = Executor.newInstance().auth(username, password);
httpExecutor.use(httpCookieStore);
Response response = httpExecutor.execute(Request.Get("http://myserver.example.com/login").useExpectContinue());
String loginOutput = response.returnContent().asString();
System.out.println(loginOutput);  // works - gets the expected page

String swaggerUrl = "http://myserver.example.com/swagger/index.html";
response = httpExecutor.execute(Request.Get(swaggerUrl));
HttpResponse httpResponse = response.returnResponse();
System.out.println(httpResponse);  // Response is 403 Access Denied
// prints: HttpResponseProxy{HTTP/1.1 403 Access Denied [X-Content-Type-Options: nosniff, X-XSS-Protection: 1; mode=block, Pragma: no-cache, X-Frame-Options: DENY, Content-Type: text/html;charset=ISO-8859-1, Cache-Control: must-revalidate,no-cache,no-store, Content-Length: 1391, Server: Jetty(8.1.16.v20140903)] [Content-Type: text/html; charset=ISO-8859-1,Content-Length: 1391,Chunked: false]}

I checked the contents of the CookieStore after the login and it has the correct cookie:

System.out.println(httpCookieStore.getCookies().size()); // prints 1
System.out.println(httpCookieStore.getCookies().get(0));
// prints: [version: 0][name: JSESSIONID][value: 14b1yp7hf85es1vc6zpe2y376n][domain: myserver.example.com][path: /][expiry: null]

So I also tried explicitly adding the cookie to the Header of the GET Request, but that still fails with same 403 Access Denied error:

CookieStore httpCookieStore = new BasicCookieStore();
List<Cookie> cookies = httpCookieStore.getCookies();

String username = "admin";
String password = "admin";
Executor httpExecutor = Executor.newInstance().auth(username, password);
httpExecutor.use(httpCookieStore);
Response response = httpExecutor.execute(Request.Get("http://myserver.example.com/login").useExpectContinue());
String loginOutput = response.returnContent().asString();
System.out.println(loginOutput);  // works - gets the expected page

String swaggerUrl = "http://myserver.example.com/swagger/index.html";
response = httpExecutor.execute(Request.Get(swaggerUrl).addHeader(authCookieName, authCookieValue));
HttpResponse httpResponse = response.returnResponse();
System.out.println(httpResponse);  // Response is 403 Access Denied

Any ideas how to make this work with the fluent API?

Body:
When looking at the HttpClient documentation, you linked, they started with this warning (emphasis mine) :

As of version of 4.2 HttpClient comes with an easy to use facade API based on the concept of a fluent interface. Fluent facade API exposes only the most fundamental functions of HttpClient and is intended for simple use cases that do not require the full flexibility of HttpClient. For instance, fluent facade API relieves the users from having to deal with connection management and resource deallocation.

You might well be in the case of unsupported configuration through the fluent api (and to answer your quote from their doc, authentication, and session management are linked, but not mandatory with each other : you might have some stateless service that ask for auth info with every request without ever starting a session, and you can obviously create session (backed by a cookie) without ever asking auth info)

You might have to resort to the other, more verbose, API :

BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCookieStore(cookieStore)
    .build();
try {
    HttpGet httpget = new HttpGet("https://someportal/");
    CloseableHttpResponse response1 = httpclient.execute(httpget);
    try {
       ...


问:
Best way to open browser popup window containing ExtJS grid
In our ExtJS application, we have some menus and a tab panel. Clicking on a menuItem opens a grid.

we have a requirement where user can open a display containing a grid in any of the two modes:

Inline - Grid will open as a tab item in the tabpanel.

Popup - A new browser window is opened using window.open and whole
ExtJS library is loaded first and then the grid is loaded. Popup as browser window is to facilitate multiple monitors.

So the problem here is whenever we open a popup window ExtJS library is needed and it is taking up a lot of memory in IE.

Is there any other way we can load a browser window popup with ExtJS grid without loading the whole ExtJS framework?

Or any other idea are most welcome, as we are really facing a lot of memory issues in IE and users are not willing to use chrome.

Thanks in advance.

答:
It is not possible to load a grid into a new window without loading the Ext framework (or at least the parts required for a grid) in the new window first. You cannot access the copy of the ExtJS framework of the parent window and use that because ExtJS requires components to be in the same window to work correctly. This is partly caused by browser security which forbids to copy or share certain structures between windows, and partly by ExtJS architecture.

Regarding browser security, that may even cause problems when you just copy the grid contents. Make sure that you test all different browsers. Copying data between the windows may require you to serialize and deserialize to work in all browsers. For instance, I was unable to copy simple javascript dates between a browser window and an iframe in Chrome, they came up null. I had to serialize the records, transmit them, and deserialize them again:

```<code>var serializedRecords = dataStore.getRange().map(function(record) {
    return record.getData({serialize:true, persist:true}); // <- serialization required
});
iframe.contentWindow.Ext.getStore("DataStore").
    loadRawData(serializedRecords); // <- loadRawData deserializes records
},
</code>```

Body:
It is not possible to load a grid into a new window without loading the Ext framework (or at least the parts required for a grid) in the new window first. You cannot access the copy of the ExtJS framework of the parent window and use that because ExtJS requires components to be in the same window to work correctly. This is partly caused by browser security which forbids to copy or share certain structures between windows, and partly by ExtJS architecture.

Regarding browser security, that may even cause problems when you just copy the grid contents. Make sure that you test all different browsers. Copying data between the windows may require you to serialize and deserialize to work in all browsers. For instance, I was unable to copy simple javascript dates between a browser window and an iframe in Chrome, they came up null. I had to serialize the records, transmit them, and deserialize them again:

var serializedRecords = dataStore.getRange().map(function(record) {
    return record.getData({serialize:true, persist:true}); // <- serialization required
});
iframe.contentWindow.Ext.getStore("DataStore").
    loadRawData(serializedRecords); // <- loadRawData deserializes records
},


问:
Invoke javascript function (which is in parameter) from native ios code
I have javascript function like this.

```<code>function getState(){
   return "Hello";
}

var cryptico = (function() {

var my = {};

    my.generateRSAKey = function(passphrase, bitlength)
    {
        Math.seedrandom(sha256.hex(passphrase));
        var rsa = new RSAKey();
        rsa.generate(bitlength, "03");
        return rsa;
    }

}());
</code>```

If function is outside, I can easily invoke like this.

```<code>NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"cryptico" ofType:@"js"];

NSString *scriptString = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];

JSContext *context = [[JSContext alloc] init];
context = [[JSContext alloc] init];
[context evaluateScript:scriptString];

JSValue *test10 = context[@"getState"];
JSValue *test11 = [test10 callWithArguments:@[]]; //will be Hello
</code>```

But how can I call something inside variable? I have tried many different ways but it is not okay.

答:
According to the JSValue Apple Documentation:

An Objective-C block (Swift clousre) and a javascript function should be converted to each other using

```<code>valueWithObject:inContext:
</code>```

to convert to a JSValue, as you have done in your code, and

```<code>toObject
</code>```

to convert to its actual type, which is in this case a block. So first try

```<code>[test10 toObject];
</code>```

and store to a block, then call the block as normal

Body:
I have javascript function like this.

function getState(){
   return "Hello";
}

var cryptico = (function() {

var my = {};

    my.generateRSAKey = function(passphrase, bitlength)
    {
        Math.seedrandom(sha256.hex(passphrase));
        var rsa = new RSAKey();
        rsa.generate(bitlength, "03");
        return rsa;
    }

}());

If function is outside, I can easily invoke like this.

NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"cryptico" ofType:@"js"];

NSString *scriptString = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];

JSContext *context = [[JSContext alloc] init];
context = [[JSContext alloc] init];
[context evaluateScript:scriptString];

JSValue *test10 = context[@"getState"];
JSValue *test11 = [test10 callWithArguments:@[]]; //will be Hello

But how can I call something inside variable? I have tried many different ways but it is not okay.

Body:
According to the JSValue Apple Documentation:

An Objective-C block (Swift clousre) and a javascript function should be converted to each other using

valueWithObject:inContext:

to convert to a JSValue, as you have done in your code, and

toObject

to convert to its actual type, which is in this case a block. So first try

[test10 toObject];

and store to a block, then call the block as normal


问:
Taxonomy of a website and considerations
Please let me know is why taxonomy is important for website development?  What are the important considerations for taxonomy development?  Many thanks,  </p>

答:
A site taxonomy is also very important for Search Engine Optimization (SEO).  It allows spiders to understand the semantics of your site and provide the most relevant results to users in the search engine results page SERP).

With proper implementation, your taxonomy can drive your breadcrumnb navigation which also is important for SEO.

Understanding taxonomy is also about content governance and placing keywords on pages for a reason.


问:
struct.unpack(...) works different on x64 machine
I am trying to do
key = struct.unpack('L', bytes_key)[0] where bytes_key is b'\xa6\x0b\xddE' and it works fine on my x32 machine, but whenever I am trying to execute it on x64 machine it getting me error.

Traceback (most recent call last):

  File "unpacker.py", line 42, in <module>
      decompile(obj[1])   File "unpacker.py", line 13, in decompile
      f.write(decrypt_record(arg).content)   File "crypt.py", line 61, in crypt.decrypt_record (crypt.c:2447)
      record.checksum = decrypt(record.checksum, checksum_key)

  File "crypt.py", line 36, in crypt.decrypt (crypt.c:1821)
      key = struct.unpack('L', bytes_key)[0]
  struct.error: unpack requires a bytes object of length 8

答:
You could try using "=" before the "L":

```<code>...
struct.unpack("=L", bytes_key)[0]
...
</code>```

As per the documentation, it says:

Standard size depends only on the format character; see the table in the Format Characters section.
  Note the difference between '@' and '=': both use native byte order, but the size and alignment of the latter is standardized.

Body:
You could try using "=" before the "L":

...
struct.unpack("=L", bytes_key)[0]
...

As per the documentation, it says:

Standard size depends only on the format character; see the table in the Format Characters section.
  Note the difference between '@' and '=': both use native byte order, but the size and alignment of the latter is standardized.


问:
How to select only Sprints 1-3 for a combobox?
I am working on a Rally app and one of the requirements of the app is to display features committed to in the first 3 sprints of a PSI, but not display features committed to in the 4th sprint. I have tried looking at examples of code involving filters and queries but none of them worked for me. I was thinking of making a combobox where you could select like "PSI 40, Sprint 1-3", that kind of thing but I don't know how to go about doing that. Maybe make a combobox for start date and one for end date but the user can only select sprints ending in "-1" for the start date and "-3" for the end date? The problem is I don't know how to set up that time frame. Also, I was able to access all the iterations that ended in "-1" (for example, Sprint 43-1") but there were multiple because there was a new one for each team.

If someone knows how to do this in a fairly simple way (I am very new to Rally app development and don't understand the more complex code just yet) that would be great. Thanks so much in advance!

答:
Features have no built in way of knowing they are related to sprints. You would have to have a custom field to indicate that. Features go into "Releases" and those are generally used to define the complete PSI.

The major problem you are going to hit is the one you hinted at towards the end of the first paragraph. The Agile Central way of dealing with timeboxes is to create an individual "Iteration" (or "Release") artefact for each project hierarchy node. If each team connects workitem artefacts to a timebox, the UI normally shows them the timeboxes in their own team node.

This means that you need to have some funky (JavaScript?) code to look at dates of timeboxes and then collect them together and use the list as a filter for the fetch of the workitems.

You cannot really rely on the name being consistent unless you enforce it, most strictly, manually. What would happen if one of the teams decided that their naming convention for the timeboxes should be different?

If you enforce naming conventions and also enforce that the timeboxes are only ever manipulated (created, updated, etc.) at the 'root' node, you could get away with selecting workitem artefacts that have been attached to timeboxes by fetching workitems into a store and defining filters along the lines of:  Release._refObjectName = timeBoxName

Another upshot of having to enforce these rules is that you can then do a fetch for timeboxes in the 'root' node only by setting the context: { projectScopeUp: false, projectScopeDown: false }, order them by start date and choose the first three names.


问:
Delphi dynamic array efficiency
I am not a Delphi expert and I was reading online about dynamic arrays and static arrays. In this article I have found a chapter called "Dynamic v. Static Arrays" with a code snippet and below the author says:

[...] access to a dynamic array can be faster than a static array!

I have understood that dynamic arrays are located on the heap (they are implemented with references/pointers).

So far I know that the access time is better on dynamic arrays. But is that the same thing with the allocation? Like if I called SetLength(MyDynArray, 5) is that slower than creating a MyArray = array[0..4] of XXX?

答:
So far I know that the access time is better on dynamic arrays.

That is not correct. The statement in that article is simply false.

But is that the same thing with the allocation? Like if I called SetLength(MyDynArray, 5) is that slower than creating a MyArray = array[0..4] of XXX?

A common fallacy is that static arrays are allocated on the heap. They could be global variables, and so allocated automatically when the module is loaded. They could be local variables and allocated on the stack. They could be dynamically allocated with calls to New or GetMem. Or they could be contained in a compound type (e.g. a record or a class) and so allocated in whatever way the owning object is allocated.

Having got that clear, let's consider a couple of common cases.

Local variable, static array type

As mentioned, static arrays declared as local variables are allocated on the stack. Allocation is automatic and essentially free. Think of the allocation as being performed by the compiler (when it generates code to reserve a stack frame). As such there is no runtime cost to the allocation. There may be a runtime cost to access because this might generate a page fault. That's all perfectly normal though, and if you want to use a small fixed size array as a local variable then there is no faster way to do it.

Member variable of a class, static array type

Again, as described above, the allocation is performed by the containing object. The static array is part of the space reserved for the object and when the object is instantiated sufficient memory is allocated on the heap. The cost for heap allocation does not typically depend significantly on the size of the block to be allocated. An exception to that statement might be really huge blocks but I'm assuming your array is relatively small in size, tens or hundreds of bytes. Armed with that knowledge we can see again that the cost for allocation is essentially zero, given that we are already allocating the memory for the containing object.

Local variable, dynamic array type

A dynamic array is represented by a pointer. So your local variable is a pointer allocated on the stack. The same argument applies as for any other local variable, for instance the local variable of static array type discussed above. The allocation is essentially free. Before you can do anything with this variable though, you need to allocate it with a call to SetLength. That incurs a heap allocation which is expensive. Likewise when you are done you have to deallocate.

Member variable of a class, dynamic array type

Again, allocation of the dynamic array pointer is free, but you must call SetLength to allocate. That's a heap allocation. There needs to be a deallocation too when the object is destroyed.

Conclusion

For small arrays, whose lengths are known at compile time, use of static arrays results in more efficient allocation and deallocation.

Note that I am only considering allocation here. If allocation is a relatively insignificant portion of the time spent working with the object then this performance characteristic may not matter. For instance, suppose the array is allocated at program startup, and then used repeatedly for the duration of the program. In such a scenario the access times dominate the allocation times and the difference between allocation times becomes insignificant.

On the flip side, imagine a short function called repeatedly during the programs lifetime, let's suppose this function is the performance bottleneck. If it operates on a small array, then it is possible that the allocation cost of using a dynamic array could be significant.

Very seldom can you draw hard and fast rules with performance. You need to understand how the tools work, and understand how your program uses these tools. You can then form opinions on which coding strategies might perform best, opinions that you should then test by profiling. You will be surprised more often than you might expect that your intuition is not a good predictor of performance.

Title: Delphi dynamic array efficiency


问:
How to divide two rows making a third row of the result?
So what I currently have is a dataframe that looks like the following...

```<code>rowId   x1    x2    x3    x4
  1     50    40    30    20
  2      5     5     5     5
</code>```

and what I want is to divide row 1 by row 2 creating a third row with the result, like this...

```<code>rowId   x1    x2    x3    x4
  1     50    40    30    20
  2      5     5     5     5
  3     10     8     6     4
</code>```

what's a simple way of going about doing this?

答:
You could do like this:</p>

```<code>df <- read.table(header = TRUE, text = "
x1    x2    x3    x4
50    40    30    20
 5     5     5     5")

df <- rbind ( df, df[1, ] / df[2, ] )
</code>```

Body:
So what I currently have is a dataframe that looks like the following...

rowId   x1    x2    x3    x4
  1     50    40    30    20
  2      5     5     5     5

and what I want is to divide row 1 by row 2 creating a third row with the result, like this...

rowId   x1    x2    x3    x4
  1     50    40    30    20
  2      5     5     5     5
  3     10     8     6     4

what's a simple way of going about doing this?

Body:
You could do like this:

df <- read.table(header = TRUE, text = "
x1    x2    x3    x4
50    40    30    20
 5     5     5     5")

df <- rbind ( df, df[1, ] / df[2, ] )


问:
In RAML, what response type (mediaType) can RAML NOT accommodate?
In the mulesoft training quiz, I came across the question
**

In RAML, what response type (mediaType) can RAML NOT accommodate?

**
The correct answer is application/text.

To verify, I edited the RAML 0.8 spec, change the response MediaType to application/text, added few Inline text lines as the output, and simulated it.
I can simulate and see the output in application/text. No errors. Why is that RAML cannot accomodate MediaType application/text ?.

答: The intent of the question is probably that application/text is not a valid MIME type.  The question is reinforcing the fact that web services described by RAML should indicate responses (along with requests) that use standard media types. One of the attributes of a RESTful architecture is "Uniform Interface", and using standard types makes your service conform to the uniform interface of the web.


问:
How do I add a new value to a dictionary's key on top of the old one, to create a sum?
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

```<code>seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass
</code>```

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

```<code>my_dict[then_string] = my_dict.get(then_string) + seconds
</code>```

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

答:
Check if key then_string exists in my_dict:

Method 1

Use in to check existence.

```<code>if then_string in my_dict:
    my_dict[then_string] += second
else:
    my_dict[then_string] = second
</code>```

Method 2

Use dict.get(key, default_value) to get value or default value if key doesn't exist.

```<code>my_dict[then_string] = my_dict.get(then_string, 0) + second
</code>```

Method 3

Use defaultdict from collection. Reference

```<code>from collections import defaultdict
my_dict = defaultdict(int)  # Set default to an int, or 0

my_dict[then_string] += second
</code>```

Example

The entire code will become

```<code>seconds = 0
my_dict = {}
stop = 0
while stop != 1:
    then_string = getStringValue()
    sleep(1)
    now_string = getStringValue()
    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        # Modify here.
        if then_string in my_dict:
            my_dict[then_string] += second
        else:
            my_dict[then_string] = second
        seconds = 0
    else:
        pass
</code>```

Body:
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

my_dict[then_string] = my_dict.get(then_string) + seconds

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

Body:
Check if key then_string exists in my_dict:

Method 1

Use in to check existence.

if then_string in my_dict:
    my_dict[then_string] += second
else:
    my_dict[then_string] = second

Method 2

Use dict.get(key, default_value) to get value or default value if key doesn't exist.

my_dict[then_string] = my_dict.get(then_string, 0) + second

Method 3

Use defaultdict from collection. Reference

from collections import defaultdict
my_dict = defaultdict(int)  # Set default to an int, or 0

my_dict[then_string] += second

Example

The entire code will become

seconds = 0
my_dict = {}
stop = 0
while stop != 1:
    then_string = getStringValue()
    sleep(1)
    now_string = getStringValue()
    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        # Modify here.
        if then_string in my_dict:
            my_dict[then_string] += second
        else:
            my_dict[then_string] = second
        seconds = 0
    else:
        pass


问:
Regex string between underscore
I need to get the markings between the underscores, for example:
Com_x0020_este_x002C__x0020_texto

Com_x0020_este_x002C_ _x0020_texto

Thank you!

答:
What you are looking for it preg_replace documentation can be found here: http://php.net/manual/en/function.preg-replace.php and the logic you are looking for it as follows:

PHP Version:

```<code> $string = "Com_x0020_este_x002C__x0020_texto";
 print preg_replace('/_(.*?)_/', " _$1_ ", $string);
</code>```

Javascript Version:

```<code>var $string = "Com_x0020_este_x002C__x0020_texto";
alert($string.replace(/_(.*?)_/g," _$1_ "));
</code>```

Result: Com _x0020_ este _x002C_ _x0020_ texto

Title: Regex string between underscore

Body:
What you are looking for it preg_replace documentation can be found here: http://php.net/manual/en/function.preg-replace.php and the logic you are looking for it as follows:

PHP Version:

 $string = "Com_x0020_este_x002C__x0020_texto";
 print preg_replace('/_(.*?)_/', " _$1_ ", $string);

Javascript Version:

var $string = "Com_x0020_este_x002C__x0020_texto";
alert($string.replace(/_(.*?)_/g," _$1_ "));

Result: Com _x0020_ este _x002C_ _x0020_ texto


问:
Compose a method name with a variable
I have this code in a Mojolicious template:

```<code>my $lang = 'de'; # de, en, ...
% $col = 'internet' . '_' . $lang;
%== markdown($rs->$col); # outputs correctly the content of the column internet_de
</code>```

Is there a way to combine the lines 2 and 3 into something like:

```<code>%== markdown($rs->'internet' . '_' . $lang); # syntax error at template ..., near "->'internet'"
</code>```

答:
I don't understand why you are striving to make your code even more concise. It is already hard to read, and golfing it further can only make it worse. In particular, you have a prime example of how comments can be used to make code less readable. And what are those % and %== doing there? Your code won't compile with those in place

You can use a scalar variable to provide the method name, but not a general expression

One improvement I would make is to use interpolation instead of string concatenation

```<code>my $lang   = 'de';
my $method = "internet_$lang";
markdown($rs->$method);
</code>```

Title: Compose a method name with a variable

Body:
I have this code in a Mojolicious template:

my $lang = 'de'; # de, en, ...
% $col = 'internet' . '_' . $lang;
%== markdown($rs->$col); # outputs correctly the content of the column internet_de

Is there a way to combine the lines 2 and 3 into something like:

%== markdown($rs->'internet' . '_' . $lang); # syntax error at template ..., near "->'internet'"

Body:
I don't understand why you are striving to make your code even more concise. It is already hard to read, and golfing it further can only make it worse. In particular, you have a prime example of how comments can be used to make code less readable. And what are those % and %== doing there? Your code won't compile with those in place

You can use a scalar variable to provide the method name, but not a general expression

One improvement I would make is to use interpolation instead of string concatenation

my $lang   = 'de';
my $method = "internet_$lang";
markdown($rs->$method);


问:
Pointer overwritten after end of the function
I have this function:

```<code>QLinkedList<hTag>::iterator *lookForLastHTag(hTags tag, QLinkedList<hTag> openedTags){
    QLinkedList<hTag>::iterator *i = new QLinkedList<hTag>::iterator();
    *i = openedTags.end();
    while(*i != openedTags.begin()){
        *i-=1;
        if ((*(*i)).tag == tag)
            return i;

    }
    return nullptr;
}
</code>```

written with the QT framework. It searches backwards through a singly linked list of hTag, a specific tag in an enumeration called hTags (please note that the former one is a struct and the second one is an enum class).

The hTag struct is defined this way:

```<code>struct hTag{
    hTags tag;
    int hierarchy;
};
</code>```

whereas the hTags enum class just defines some tags.

The problem is that, after the function returns the i pointer, it gets weirdly overwritten by other data. I don't understand that since I've allocated space dynamically in the heap for that iterator just to avoid this problem. I don't understand why the content of the pointer i (not the thing it points to, the 32-bit number inside i) is returned correctly (in the sense that the 32-bit number inside the pointer is correctly copied outside the function). However, the content of i (the pointee) isn't. Just after the end of the function, it gets overwritten with junk even if it's declared on the heap and shouldn't be influenced by the end of the function.

Could you please help me sorting that problem out?

Thanks in advance.

答:
The problem is passing the list by value:

```<code>QLinkedList<hTag>::iterator *lookForLastHTag(hTags tag, QLinkedList<hTag> openedTags)
//                                                                      ^^
</code>```

This results in a copy of the list being created, which is destroyed again as soon as control flow returns from the function.

The iterator instance you return then refers a list that does not exist any more, if you use it, you end in undefined behaviour.

To avoid this, you need to pass your list as either reference or pointer, preferrably a const one (as you do not modify it; however, you need to return a const_iterator then, too):

```<code>QLinkedList<hTag>::const_iterator* lookForLastHTag(hTags tag, QLinkedList<hTag> const& openedTags)
//                 ^                                                            ^    ^(!!!)
</code>```

Then your iterator object will point to the original list as being passed to the function and you are fine with this first point.

Additionally, you implemented a memory leak: If no element is found, the iterator remains unused, so you must delete it again before returning:

```<code>delete i;
return nullptr;
</code>```

Still, there is some non-negligible risk a user creating further memory leaks by forgetting to delete the returned pointer when not needed any more, especially, as this is a very unusual way to use iterators (sure, not your responsibility any more, but you can avoid this right from the start by better design):

```<code>QLinkedList<hTag>::const_iterator lookForLastHTag(hTags tag, QLinkedList<hTag> const& openedTags)
//                               ^ (no pointer!)
{
    QLinkedList<hTag>::const_iterator i = openTags.end();
    while(i != openTags.begin())
    {
         --i;
         if(i->tag == tag)
             return i;
    }
    return openTags.end();
}
</code>```

As side effect, the code got less complicated, won't you agree?

Side note: you might want to have a look at std::find instead; no need for re-inventing the wheel...

Body:
I have this function:

QLinkedList<hTag>::iterator *lookForLastHTag(hTags tag, QLinkedList<hTag> openedTags){
    QLinkedList<hTag>::iterator *i = new QLinkedList<hTag>::iterator();
    *i = openedTags.end();
    while(*i != openedTags.begin()){
        *i-=1;
        if ((*(*i)).tag == tag)
            return i;

    }
    return nullptr;
}

written with the QT framework. It searches backwards through a singly linked list of hTag, a specific tag in an enumeration called hTags (please note that the former one is a struct and the second one is an enum class).

The hTag struct is defined this way:

struct hTag{
    hTags tag;
    int hierarchy;
};

whereas the hTags enum class just defines some tags.

The problem is that, after the function returns the i pointer, it gets weirdly overwritten by other data. I don't understand that since I've allocated space dynamically in the heap for that iterator just to avoid this problem. I don't understand why the content of the pointer i (not the thing it points to, the 32-bit number inside i) is returned correctly (in the sense that the 32-bit number inside the pointer is correctly copied outside the function). However, the content of i (the pointee) isn't. Just after the end of the function, it gets overwritten with junk even if it's declared on the heap and shouldn't be influenced by the end of the function.

Could you please help me sorting that problem out?

Thanks in advance.

Body:
The problem is passing the list by value:

QLinkedList<hTag>::iterator *lookForLastHTag(hTags tag, QLinkedList<hTag> openedTags)
//                                                                      ^^

This results in a copy of the list being created, which is destroyed again as soon as control flow returns from the function.

The iterator instance you return then refers a list that does not exist any more, if you use it, you end in undefined behaviour.

To avoid this, you need to pass your list as either reference or pointer, preferrably a const one (as you do not modify it; however, you need to return a const_iterator then, too):

QLinkedList<hTag>::const_iterator* lookForLastHTag(hTags tag, QLinkedList<hTag> const& openedTags)
//                 ^                                                            ^    ^(!!!)

Then your iterator object will point to the original list as being passed to the function and you are fine with this first point.

Additionally, you implemented a memory leak: If no element is found, the iterator remains unused, so you must delete it again before returning:

delete i;
return nullptr;

Still, there is some non-negligible risk a user creating further memory leaks by forgetting to delete the returned pointer when not needed any more, especially, as this is a very unusual way to use iterators (sure, not your responsibility any more, but you can avoid this right from the start by better design):

QLinkedList<hTag>::const_iterator lookForLastHTag(hTags tag, QLinkedList<hTag> const& openedTags)
//                               ^ (no pointer!)
{
    QLinkedList<hTag>::const_iterator i = openTags.end();
    while(i != openTags.begin())
    {
         --i;
         if(i->tag == tag)
             return i;
    }
    return openTags.end();
}

As side effect, the code got less complicated, won't you agree?

Side note: you might want to have a look at std::find instead; no need for re-inventing the wheel...


问:
Powershell Regex vs. "other" Regex, what's different?
I've got a powershell script to match the following regex:

```<code>---\n(0[1-9]|1[0-2][\/](0[1-9]|[12]\d|3[01])[\/]\d{2}[\s\S]+?)-----
</code>```

The string to match from is the following logfile snippet:

```
-------------------------------------------------------------------------------
10/26/16 11:41:26 - Process(15925376.4) User(mqm) Program(amqzmuc0)
                    Host(aixmq1) Installation(Installation1)
                    VRMF(8.0.0.4) QMgr(ecs.queue.manager)
                    AMQ6287: WebSphere MQ V8.0.0.4 (p800-004-151017).

EXPLANATION: WebSphere MQ system information:  Host Info         :-
AIX 7.1 (MQ AIX 64-bit)  Installation      :- /usr/mqm (Installation1)
Version           :- 8.0.0.4 (p800-004-151017) ACTION: None.
-------------------------------------------------------------------------------
10/26/16 11:41:26 - Process(15925376.4) User(mqm) Program(amqzmuc0)
                    Host(aixmq1) Installation(Installation1)
                    VRMF(8.0.0.4) QMgr(ecs.queue.manager)
                    AMQ6287: WebSphere MQ V8.0.0.4 (p800-004-151017).

EXPLANATION:FFF WebSphere MQ system information:  Host Info         :-
AIX 7.1 (MQ AIX 64-bit)  Installation      :- /usr/mqm (Installation1)
Version           :- 8.0.0.4 (p800-004-151017) ACTION: None.
-------------------------------------------------------------------------------
```

Using this regex in perl and on regexr.com, it perfectly matches two sections from that logfile snippet.

Now i've implemented that same regex in powershell and it won't return any matches unless i remove the minuses preceding the \n. If i replace those minuses by a matching group that only contains minus, it will work aswell.

For the sake of consistency and understanding what is going on , i need to understand why the matching behavior is so different in powershell. Why won't it match as soon as there are minuses at the beginning?

The following .NET regex tester shows the same behavior as in powershell:

http://regexstorm.net/tester

Could someone please explain to me why the matching behavior is that different in powershell compared to perl/regexr.com?

This is the snippet of powershell code i'm currently using to match that regex:

```<code>$matches = ([regex]::matches($sInput, "---\n(0[1-9]|1[0-2][\/](0[1-9]|[12]\d|3[01])[\/]\d{2}[\s\S]+?)\n-") | %{$_.value});
</code>```

答:
On Windows, line endings are (usually) CRLF (two characters, carriage return then linefeed), whereas on unix-based operating systems (basically anything but Windows) it's just a linefeed LF. The escape sequence \n refers to LF. To match CR use \r.

So what I think is happening is that if your input contains CRLF, then -\n will not match it. But \n would because it skips the preceding CR.

The websites you're using to test it may convert the line endings, or not properly preserve them, and therefore match, while the .Net tester may do the opposite.

For reference, whenever I need to match line endings in regex, I use \r?\n (an optional CR followed by a LF), so that I can catch both types of line endings.

So in your example, you should be able to change the beginning of your regex from ---\n to ---\r?\n and have it work, if I am correct about your specific issue.

Body:
I've got a powershell script to match the following regex:

---\n(0[1-9]|1[0-2][\/](0[1-9]|[12]\d|3[01])[\/]\d{2}[\s\S]+?)-----

The string to match from is the following logfile snippet:

-------------------------------------------------------------------------------
10/26/16 11:41:26 - Process(15925376.4) User(mqm) Program(amqzmuc0)
                    Host(aixmq1) Installation(Installation1)
                    VRMF(8.0.0.4) QMgr(ecs.queue.manager)
                    AMQ6287: WebSphere MQ V8.0.0.4 (p800-004-151017).

EXPLANATION: WebSphere MQ system information:  Host Info         :-
AIX 7.1 (MQ AIX 64-bit)  Installation      :- /usr/mqm (Installation1)
Version           :- 8.0.0.4 (p800-004-151017) ACTION: None.
-------------------------------------------------------------------------------
10/26/16 11:41:26 - Process(15925376.4) User(mqm) Program(amqzmuc0)
                    Host(aixmq1) Installation(Installation1)
                    VRMF(8.0.0.4) QMgr(ecs.queue.manager)
                    AMQ6287: WebSphere MQ V8.0.0.4 (p800-004-151017).

EXPLANATION:FFF WebSphere MQ system information:  Host Info         :-
AIX 7.1 (MQ AIX 64-bit)  Installation      :- /usr/mqm (Installation1)
Version           :- 8.0.0.4 (p800-004-151017) ACTION: None.
-------------------------------------------------------------------------------

Using this regex in perl and on regexr.com, it perfectly matches two sections from that logfile snippet.

Now i've implemented that same regex in powershell and it won't return any matches unless i remove the minuses preceding the \n. If i replace those minuses by a matching group that only contains minus, it will work aswell.

For the sake of consistency and understanding what is going on , i need to understand why the matching behavior is so different in powershell. Why won't it match as soon as there are minuses at the beginning?

The following .NET regex tester shows the same behavior as in powershell:

http://regexstorm.net/tester

Could someone please explain to me why the matching behavior is that different in powershell compared to perl/regexr.com?

This is the snippet of powershell code i'm currently using to match that regex:

$matches = ([regex]::matches($sInput, "---\n(0[1-9]|1[0-2][\/](0[1-9]|[12]\d|3[01])[\/]\d{2}[\s\S]+?)\n-") | %{$_.value});


问:
Using/not using let keyword in defining variable in Typescript class
I tired using let keyword to create a variable in the class. It doesn't work.
Why cant we use let keyword in typescript class?

What is the best way of creating variables in the class, is it with let or with just a variable name.

```<code>class Simple {

    constructor(name:string){
        console.log(name);
    }
    let name_:string = "Random Name"; // It is showing unexpected token here.
}
</code>```

答:
For the structure you are showing, name_ should be a property of Simple:

```<code>class Simple {
   private name_ :string = "Random Name";
    constructor(name: string) {
        console.log(name);
    }
}
</code>```

Based on your code, the console log will show the name that is passed into Simple though, so I'm not sure where you are going with the name_ variable.

```<code>Simple s = new Simple("test"); //Will log "test"
</code>```

I'm assuming that you are going to assign name_ the value of the name parameter that is passed in, but without more details, I can only guess.

Body:
I tired using let keyword to create a variable in the class. It doesn't work.
Why cant we use let keyword in typescript class?

What is the best way of creating variables in the class, is it with let or with just a variable name.

class Simple {

    constructor(name:string){
        console.log(name);
    }
    let name_:string = "Random Name"; // It is showing unexpected token here.
}

Body:
For the structure you are showing, name_ should be a property of Simple:

class Simple {
   private name_ :string = "Random Name";
    constructor(name: string) {
        console.log(name);
    }
}

Based on your code, the console log will show the name that is passed into Simple though, so I'm not sure where you are going with the name_ variable.

Simple s = new Simple("test"); //Will log "test"

I'm assuming that you are going to assign name_ the value of the name parameter that is passed in, but without more details, I can only guess.


问:
Is it possible to refer to postman call name within the tests body
App Details:

```<code>Postman for Chrome
Version 5.0.1
win / x86-64
Chrome 58.0.3029.110
</code>```

In my collection, I have various requests within folders.
e.g. Collection>CollectionFolder1>Request1, Request2 ...

Is it possible to get a reference of the request names within the tests so that I could write something like:

```<code>try {
   ...
} catch (e) {
    tests[Test failed with exception ${e} for call request ${SOME_VARIABLE_THAT_STORES_REQUEST_NAME}] = false
}
</code>```

This would allow me to duplicate this skeleton in all my requests without having to bother about maintaining it.

Is there any postman variable or structure that would store any such info.

答:
In https://www.getpostman.com/docs/postman/scripts/postman_sandbox - paragraph Request/response related properties you can use the 'request' object.

request.name: gives you the current test case name Obsolete use pm.info.requestName

request.method: gives you the method used (PUT, GET, etc.)

request.url: gives you the target url

In order to see all the available data you may use, I suggest you to open the console (View/Show postman console or Alt+Ctrl+C) and see the data returned by this:
console.log(request)

Body:
App Details:

Postman for Chrome
Version 5.0.1
win / x86-64
Chrome 58.0.3029.110

In my collection, I have various requests within folders.
e.g. Collection>CollectionFolder1>Request1, Request2 ...

Is it possible to get a reference of the request names within the tests so that I could write something like:

try {
   ...
} catch (e) {
    tests[Test failed with exception ${e} for call request ${SOME_VARIABLE_THAT_STORES_REQUEST_NAME}] = false
}

This would allow me to duplicate this skeleton in all my requests without having to bother about maintaining it.

Is there any postman variable or structure that would store any such info.

ContentLicense: CC BY-SA 4.0


问:
Why does printing the __repr__ of an integer require parenthesis?
For a string literal, say foo, if I'd want to get it's repr by calling __repr__ of this string, all I'd do is:

```<code>>>> 'foo'.__repr__()
"'foo'"
</code>```

This also works:

```<code>>>> ('foo').__repr__()
"'foo'"
</code>```

It's the same case for floats:

```<code>>>> 1.0.__repr__()
'1.0'
>>> (1.0).__repr__()
'1.0'
</code>```

But when it comes to integers, it isn't quite the same. Trying to call __repr__ without first applying parenthesis throws an error

```<code>>>> 1.__repr__()
  File "<stdin>", line 1
    1.__repr__()
             ^
SyntaxError: invalid syntax
</code>```

However, when I apply parenthesis, it works:

```<code>>>> (1).__repr__()
'1'
</code>```

So, why does an integer require the parenthesis?

答: 1.__repr__ conflicts with floating point parsing (ex: 1.0), so you have to insert parenthesis to make python understand that the dot applies on the 1 object.

Body:
For a string literal, say foo, if I'd want to get it's repr by calling __repr__ of this string, all I'd do is:

>>> 'foo'.__repr__()
"'foo'"

This also works:

>>> ('foo').__repr__()
"'foo'"

It's the same case for floats:

>>> 1.0.__repr__()
'1.0'
>>> (1.0).__repr__()
'1.0'

But when it comes to integers, it isn't quite the same. Trying to call __repr__ without first applying parenthesis throws an error

>>> 1.__repr__()
  File "<stdin>", line 1
    1.__repr__()
             ^
SyntaxError: invalid syntax

However, when I apply parenthesis, it works:

>>> (1).__repr__()
'1'

So, why does an integer require the parenthesis?