问:
ASP.NET Add Dynamic HTML w/ UpdatePanel & Web Controls to aspx page. Web Control update other control OnClick
I am trying to add a series of UpdatePanels with a CheckBox and  link in each.  When I click the  link I want the cooresponding CheckBox next to it to become checked as well. I can get the HTML to show up properly but am having issues getting the UpdatePanel & controls communicating with the backend.

I have a main Master page, a 2nd Master page inside the main one, then my content page I'm working with inside the child Master page.  I have a ScriptManager on my main Master page with EnablePartialRendering="True".

I get this error: asp.net CS1061
Which basically means my Control isn't finding my function in the code behind

The amount of these sections I'm creating to include the UpdatePanel is dynamic and dependent on the number of results from the Database.  I am trying to do this utilizing ASP.NETs features without resorting to Javascript

aspx page:

```<code><asp:Content ID="aBody" ContentPlaceHolderID="aContent" runat="server">
   <div id="caJumbotron" class="jumbotron aJumbotron" runat="server" >
       <asp:Label ID="auditsTable" runat="server" Text="" />
   </div>
</asp:Content>
</code>```

aspx.cs:  HTML code inside a loop

```<code>HTML += "<div class='row caSectionRow'>" +
            "<div class='col-md-6'>" +
                "<asp:UpdatePanel runat='server'>" +
                    "<ContentTemplate>" +
                        "<input type='checkbox' class='caCheckbox' name='" + dt.Rows[i]["NAME"].ToString() + "' id='" + dt.Rows[i]["ID"].ToString() + "' value='" + dt.Rows[i]["ID"].ToString() + "' > " +
                        "<a href='' class='caLink' OnClick ='AuditLinkClick' runat='server' >" + dt.Rows[i]["NAME"].ToString() + "</a>" +
                    "</ContentTemplate>" +
                "</asp:UpdatePanel>" +
            "</div>"; //Insert column data
</code>```

Then insert the dynamic HTML inside the label:

```<code>auditsTable.Text = HTML;
</code>```

My last question would be... I'm wanting to make the link's OnClick event to AuditLinkClick in the backend update the CheckBox to checked.  But the checkbox will have a dynamic ID and the sender to the function will be the link.  How would I check the CheckBox inside the same UpdatePanel as the link clicked?

```<code>    private void AuditLinkClick(object sender, EventArgs e)
    {
        Response.Write("HERE<br/>");
        //Link is what sent us here
        CheckBox btn = (CheckBox)sender;
        string id = btn.ID;
        btn.Checked = true;
    }
</code>```

Thanks for the help!

答:
@VDWWD was correct in the comments (Thanks!).  I could not add Dynamic Controls to the page as a string.  This is what I did and how I broke it down:

Put a single UpdatePanel in the front end with a Panel to hold all of the dynamic data I am adding:

```<code><asp:UpdatePanel ID="UpdatePanelCheckBoxes" runat="server">
    <ContentTemplate>
        <asp:Panel ID="caPanel" runat="server"></asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

In the Code Behind I added each control and the framework
 s around them by:

```<code>caPanel.Controls.Add(new LiteralControl("<div class='col-md-6'>"));

CheckBox aCheckBox = new CheckBox();
aCheckBox.ID = dt.Rows[i]["ID"].ToString();
caPanel.Controls.Add(aCheckBox);

Button checkboxButton = new Button();
checkboxButton.ID = "Button"+dt.Rows[i]["ID"].ToString();
checkboxButton.Text = dt.Rows[i]["NAME"].ToString();
checkboxButton.CssClass = "caButton";
checkboxButton.Click += new EventHandler(ALinkClick);
caPanel.Controls.Add(checkboxButton);

caPanel.Controls.Add(new LiteralControl("</div>"));
</code>```

One thing that held me back from discovering this sooner was the fact that I'm using Master Pages and needed to use a Panel to add the Controls to.  I was getting the error [HttpException (0x80004005): Control 'ctl00_TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server.] until I used the Panel.

This answer helped: Control 'ctl00_TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server

Body:
I am trying to add a series of UpdatePanels with a CheckBox and  link in each.  When I click the  link I want the cooresponding CheckBox next to it to become checked as well. I can get the HTML to show up properly but am having issues getting the UpdatePanel & controls communicating with the backend.

I have a main Master page, a 2nd Master page inside the main one, then my content page I'm working with inside the child Master page.  I have a ScriptManager on my main Master page with EnablePartialRendering="True".

I get this error: asp.net CS1061
Which basically means my Control isn't finding my function in the code behind

The amount of these sections I'm creating to include the UpdatePanel is dynamic and dependent on the number of results from the Database.  I am trying to do this utilizing ASP.NETs features without resorting to Javascript

aspx page:

<asp:Content ID="aBody" ContentPlaceHolderID="aContent" runat="server">

       <asp:Label ID="auditsTable" runat="server" Text="" />

</asp:Content>

aspx.cs:  HTML code inside a loop

HTML += "
" +
            "
" +
                "<asp:UpdatePanel runat='server'>" +
                    "<ContentTemplate>" +
                        "<input type='checkbox' class='caCheckbox' name='" + dt.Rows[i]["NAME"].ToString() + "' id='" + dt.Rows[i]["ID"].ToString() + "' value='" + dt.Rows[i]["ID"].ToString() + "' > " +
                        "" + dt.Rows[i]["NAME"].ToString() + "" +
                    "</ContentTemplate>" +
                "</asp:UpdatePanel>" +
            "
"; //Insert column data

Then insert the dynamic HTML inside the label:

auditsTable.Text = HTML;

My last question would be... I'm wanting to make the link's OnClick event to AuditLinkClick in the backend update the CheckBox to checked.  But the checkbox will have a dynamic ID and the sender to the function will be the link.  How would I check the CheckBox inside the same UpdatePanel as the link clicked?

    private void AuditLinkClick(object sender, EventArgs e)
    {
        Response.Write("HERE
");
        //Link is what sent us here
        CheckBox btn = (CheckBox)sender;
        string id = btn.ID;
        btn.Checked = true;
    }

Thanks for the help!

Body:
@VDWWD was correct in the comments (Thanks!).  I could not add Dynamic Controls to the page as a string.  This is what I did and how I broke it down:

Put a single UpdatePanel in the front end with a Panel to hold all of the dynamic data I am adding:

<asp:UpdatePanel ID="UpdatePanelCheckBoxes" runat="server">
    <ContentTemplate>
        <asp:Panel ID="caPanel" runat="server"></asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

In the Code Behind I added each control and the framework <div> s around them by:

caPanel.Controls.Add(new LiteralControl("<div class='col-md-6'>"));

CheckBox aCheckBox = new CheckBox();
aCheckBox.ID = dt.Rows[i]["ID"].ToString();
caPanel.Controls.Add(aCheckBox);

Button checkboxButton = new Button();
checkboxButton.ID = "Button"+dt.Rows[i]["ID"].ToString();
checkboxButton.Text = dt.Rows[i]["NAME"].ToString();
checkboxButton.CssClass = "caButton";
checkboxButton.Click += new EventHandler(ALinkClick);
caPanel.Controls.Add(checkboxButton);

caPanel.Controls.Add(new LiteralControl("</div>"));

One thing that held me back from discovering this sooner was the fact that I'm using Master Pages and needed to use a Panel to add the Controls to.  I was getting the error [HttpException (0x80004005): Control 'ctl00_TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server.] until I used the Panel.

This answer helped: Control 'ctl00_TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server


来源: stackexchange

问:
split byte array into even and odd byte array and store in file
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

```<code>        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }
</code>```

In FOR loop i have tried array.length, even.length nothing is working.

答:
The array is two times longer than even and odd arrays.

Try the following code instead:

```<code>for (int index = 0; index < even.Length; index++)
{
    even[index] = array[index * 2];
    odd[index] = array[index * 2 + 1];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }

In FOR loop i have tried array.length, even.length nothing is working.

Body:
The array is two times longer than even and odd arrays.

Try the following code instead:

for (int index = 0; index < even.Length; index++)
{
    even[index] = array[index * 2];
    odd[index] = array[index * 2 + 1];
}


问:
Send auth_token for authentication to ActionCable
```<code>module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      #puts params[:auth_token]
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
   end

  end
end
</code>```

I don't use web as end point for action cable, so I want to use auth_token for authentication. By default action cable use session user id for authentication. How to pass params to connect method?

答:
As for security of Pierre's answer: If you're using WSS protocol, which uses SSL for encryption, then the principles for sending secure data should the same as for HTTPS. When using SSL, query string parameters are encrypted as well as the body of the request. So if in HTTP APIs you're sending any kind of token through HTTPS and deem it secure, then it should be the same for WSS. Just remember that the same as for HTTPS, don't send credentials like password through query parameters, as the URL of the request could be logged on a server and thus stored with your password. Instead use things like tokens that are issued by the server.

Also you can check this out (this basically describes something like JWT authentication + IP address verification): https://devcenter.heroku.com/articles/websocket-security#authentication-authorization.

Body:
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      #puts params[:auth_token]
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
   end

  end
end

I don't use web as end point for action cable, so I want to use auth_token for authentication. By default action cable use session user id for authentication. How to pass params to connect method?


问:
Print JavaScript condition used in Shiny conditionalPanel
I'm creating a conditionalPanel in a Shiny app. I'm attempting to debug the JavaScript condition, but without inspecting it, I'm just guessing random JavaScript bits. Is there a way to inspect the condition directly?

```<code>selectizeInput('groups','Groups:',
                   choices = list('Choice1' = 'choice1','Choice2' = 'choice2'),
                   multiple = TRUE,selected = NULL
)

conditionalPanel(
          print("input.groups.indexOf('choice2') >= 0"), # desired output
          condition = "input.groups.indexOf('choice2') >= 0",
          selectInput("statusfilter", "StatusFilter",
                      list("NewChoice1" = "nc1","NewChoice2" = "nc2"))
)
</code>```

The above code (generalized from my production code) is showing the conditionalPanel at start up before I even click a choice. Once I do, it will disappear until I choose 'choice2'. If I could inspect the condition, I could fix this quickly.

答:
After commenting our the print statement so that the code runs, if you open your javascript console, you'll see an error:

Error parsing expression: input.groups.indexOf('choice2') >= 0

This suggests your JS code breaks. This is because input.groups is null , and doing .indexOf on a null value causes an error.

So what you want in the condition is:

condition = "input.groups !== null && input.groups.indexOf('choice2') >= 0"

Body:
I'm creating a conditionalPanel in a Shiny app. I'm attempting to debug the JavaScript condition, but without inspecting it, I'm just guessing random JavaScript bits. Is there a way to inspect the condition directly?

selectizeInput('groups','Groups:',
                   choices = list('Choice1' = 'choice1','Choice2' = 'choice2'),
                   multiple = TRUE,selected = NULL
)

conditionalPanel(
          print("input.groups.indexOf('choice2') >= 0"), # desired output
          condition = "input.groups.indexOf('choice2') >= 0",
          selectInput("statusfilter", "StatusFilter",
                      list("NewChoice1" = "nc1","NewChoice2" = "nc2"))
)

The above code (generalized from my production code) is showing the conditionalPanel at start up before I even click a choice. Once I do, it will disappear until I choose 'choice2'. If I could inspect the condition, I could fix this quickly.


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答:
I second MediaWiki.  It's not C#, but it can be a nice excuse to sneak some free software in through the backdoor.

If you guys are a Microsoft shop, though, and are using Sharepoint, it has some built-in wiki-esque functionality.

ContentLicense: CC BY-SA 2.5

Title: Coding Standard Wiki

OwnerDisplayName: Dana


问:
Next Composition of n into k parts - does anyone have a working algorithm?
Composition of n into k parts - I want to list all the possible compositions of n into k parts - does anyone have an algorithm (preferably in R)?  Or know if it's in library anywhere?

For example, if I have n cubes, and k bags, and want to list all the possible arrangements of the cubes in the bags.  e.g. there are 3 ways you can arrange 2 cubes into 2 bags:

```<code>(2, 0) (1, 1) (0, 2)
</code>```

I've found the NEXCOM alogarithm.  I've found a version of it here (page 46) in Fortran, but don't code in Fortran so really understand what's going on - any help?

答:
Computing compositions (I ignore how standard the term is) and combinations is equivalent in a sense. There's a bijective function between combinations of k + 1 in n + k and compositions of n into k parts. All one has to do is assign a number from 1 to n to each letter of the combinations, order the letters according to their number, then:

make a tuple composed of the differences between numbers of consecutive letters

subtract 1 to each entry of the tuple, and there you have it.

Assuming your algorithm for computing combinations yields combinations with 'ordered letters', then the rest is a trivial computation.

In Python:

```<code>from itertools import combinations, tee
  #see:
  #http://docs.python.org/library/itertools.html#itertools.combinations
  #http://docs.python.org/library/itertools.html#itertools.tee</p>

<p>def diffed_tuple(t):
    # return a new tuple but where the entries are the differences
    # between consecutive entries of the original tuple.
    #make two iterator objects which yield entries from t in parallel
    t2, t1 = tee(t)
    # advance first iterator one step
    for x in t2:
        break
    # return a tuple made of the entries yielded by the iterators
    return tuple(e2 - e1 for e2, e1 in zip(t2, t1))</p>

<p># --The Algorithm--
def compositions(n, k):
    for t in combinations(range(n+k), k+1):
        # yield the 'diffed tuple' but subtracting 1 from each entry
        yield tuple(e-1 for e in diffed_tuple(t))
```

Body:
Composition of n into k parts - I want to list all the possible compositions of n into k parts - does anyone have an algorithm (preferably in R)?  Or know if it's in library anywhere?

For example, if I have n cubes, and k bags, and want to list all the possible arrangements of the cubes in the bags.  e.g. there are 3 ways you can arrange 2 cubes into 2 bags:

(2, 0) (1, 1) (0, 2)

I've found the NEXCOM alogarithm.  I've found a version of it here (page 46) in Fortran, but don't code in Fortran so really understand what's going on - any help?

Body:
Computing compositions (I ignore how standard the term is) and combinations is equivalent in a sense. There's a bijective function between combinations of k + 1 in n + k and compositions of n into k parts. All one has to do is assign a number from 1 to n to each letter of the combinations, order the letters according to their number, then:

make a tuple composed of the differences between numbers of consecutive letters

subtract 1 to each entry of the tuple, and there you have it.

Assuming your algorithm for computing combinations yields combinations with 'ordered letters', then the rest is a trivial computation.

In Python:

from itertools import combinations, tee
  #see:
  #http://docs.python.org/library/itertools.html#itertools.combinations
  #http://docs.python.org/library/itertools.html#itertools.tee

def diffed_tuple(t):
    # return a new tuple but where the entries are the differences
    # between consecutive entries of the original tuple.
    #make two iterator objects which yield entries from t in parallel
    t2, t1 = tee(t)
    # advance first iterator one step
    for x in t2:
        break
    # return a tuple made of the entries yielded by the iterators
    return tuple(e2 - e1 for e2, e1 in zip(t2, t1))

# --The Algorithm--
def compositions(n, k):
    for t in combinations(range(n+k), k+1):
        # yield the 'diffed tuple' but subtracting 1 from each entry
        yield tuple(e-1 for e in diffed_tuple(t))


问:
Error Click total subscriber
I m using the CMD prestashop 1.7.2.4 , when i click to  'total subscriber' , i have this error :

```<code>[PrestaShop] Fatal error in module file: /home/lecoindedg/www/app/bootstrap.php.cache:3224
Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function isUsingNewTranslationSystem() on boolean in /home/lecoindedg/www/controllers/admin/AdminModulesController.php:1403 Stack trace: #0 /home/lecoindedg/www/classes/controller/AdminController.php(2849): AdminModulesControllerCore->initModal() #1 /home/lecoindedg/www/classes/controller/Controller.php(186): AdminControllerCore->init() #2 /home/lecoindedg/www/classes/Dispatcher.php(379): ControllerCore->run() #3 /home/lecoindedg/www/admin792ivsbt0/index.php(95): DispatcherCore->dispatch() #4 {main} Next LogicException: Request stack is empty in /home/lecoindedg/www/app/bootstrap.php.cache:3224 Stack trace: #0 [internal function]: Symfony\Component\HttpKernel\HttpKernel->terminateWithException(Object(Symfony\Component\Debug\Exception\FatalThrowableError)) #1 /home/lecoindedg/www/vendor/symfony/symfony/src/Symfony/Component/Debug/ErrorHandler.php(606): call_user_func(Array, Object(Symfony\Component\Debug\Exception\FatalThrowableE
</code>```

Any clue thxs ?

答:
I found a solution :

On the file : views/templates/hook/dashboard_zone_one.tpl

Change :

```<code>-               <span class="data_label"><a href="{$link->getAdminLink('AdminModules')|escape:'html':'UTF-8'}&configure=blocknewsletter&module_name=blocknewsletter">{l s='Total Subscribers' d='Modules.Dashactivity.Admin'}</a></span>
+               <span class="data_label"><a href="{$link->getAdminLink('AdminModules')|escape:'html':'UTF-8'}&configure=ps_emailsubscription&module_name=ps_emailsubscription">{l s='Total Subscribers' d='Modules.Dashactivity.Admin'}</a></span>
</code>```

Adjusted Dashboard Total subscribers link to point to ps_emailsubscription configuration page instead of blocknewsletter that doesn't exists anymore.

Title: Error Click total subscriber

Body:
I m using the CMD prestashop 1.7.2.4 , when i click to  'total subscriber' , i have this error :

[PrestaShop] Fatal error in module file: /home/lecoindedg/www/app/bootstrap.php.cache:3224
Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function isUsingNewTranslationSystem() on boolean in /home/lecoindedg/www/controllers/admin/AdminModulesController.php:1403 Stack trace: #0 /home/lecoindedg/www/classes/controller/AdminController.php(2849): AdminModulesControllerCore->initModal() #1 /home/lecoindedg/www/classes/controller/Controller.php(186): AdminControllerCore->init() #2 /home/lecoindedg/www/classes/Dispatcher.php(379): ControllerCore->run() #3 /home/lecoindedg/www/admin792ivsbt0/index.php(95): DispatcherCore->dispatch() #4 {main} Next LogicException: Request stack is empty in /home/lecoindedg/www/app/bootstrap.php.cache:3224 Stack trace: #0 [internal function]: Symfony\Component\HttpKernel\HttpKernel->terminateWithException(Object(Symfony\Component\Debug\Exception\FatalThrowableError)) #1 /home/lecoindedg/www/vendor/symfony/symfony/src/Symfony/Component/Debug/ErrorHandler.php(606): call_user_func(Array, Object(Symfony\Component\Debug\Exception\FatalThrowableE

Any clue thxs ?

Body:
I found a solution :

On the file : views/templates/hook/dashboard_zone_one.tpl

Change :

-               <span class="data_label"><a href="{$link->getAdminLink('AdminModules')|escape:'html':'UTF-8'}&amp;configure=blocknewsletter&amp;module_name=blocknewsletter">{l s='Total Subscribers' d='Modules.Dashactivity.Admin'}</a></span>
+               <span class="data_label"><a href="{$link->getAdminLink('AdminModules')|escape:'html':'UTF-8'}&amp;configure=ps_emailsubscription&amp;module_name=ps_emailsubscription">{l s='Total Subscribers' d='Modules.Dashactivity.Admin'}</a></span>

Adjusted Dashboard Total subscribers link to point to ps_emailsubscription configuration page instead of blocknewsletter that doesn't exists anymore.


问:
when is a String not a String? when it doesn't have an includes() method?
I'm trying to write a simple javascript(well coffeescript) test and have something confusing:

```<code>dclib.appendVarToUrl = (base, k, v) ->
  check base, String
  console.log("base is a:", typeof(base))
  if base.includes("?")
     ...

// called with
dclib.appendVarToUrl("some/url", "score", 5)
</code>```

gives me:

```<code>base is a: string
TypeError: Object some/url has no method 'includes'
</code>```

so why would a String not have an .includes() method?
is this coffeescript wrapping an object in a weird way?

答:
According the the specification .includes() is part of ECMAScript 6 JavaScript Version. Therefore many platforms still do not support it.

You can replace by .indexOf()!=-1 which is equivalent and belongs to ECMAScript 1 JavaScript Version. According to the specification .indexOf() returns -1 when it doesn't find the specific string.

Therefore a) and b) are equivalent

a) ECMAScript 6

```<code>var str = "Hello world";

if (str.includes("world")){
  return true
}
</code>```

b) ECMAScript 1

```<code>var str = "Hello world";

if (str.indexOf("world")!==-1){
  return true
}
</code>```

Body:
I'm trying to write a simple javascript(well coffeescript) test and have something confusing:

dclib.appendVarToUrl = (base, k, v) ->
  check base, String
  console.log("base is a:", typeof(base))
  if base.includes("?")
     ...

// called with
dclib.appendVarToUrl("some/url", "score", 5)

gives me:

base is a: string
TypeError: Object some/url has no method 'includes'

so why would a String not have an .includes() method?
is this coffeescript wrapping an object in a weird way?

Body:
According the the specification .includes() is part of ECMAScript 6 JavaScript Version. Therefore many platforms still do not support it.

You can replace by .indexOf()!=-1 which is equivalent and belongs to ECMAScript 1 JavaScript Version. According to the specification .indexOf() returns -1 when it doesn't find the specific string.

Therefore a) and b) are equivalent

a) ECMAScript 6

var str = "Hello world";

if (str.includes("world")){
  return true
}

b) ECMAScript 1

var str = "Hello world";

if (str.indexOf("world")!==-1){
  return true
}


问:
Reading Excel Files MSOffice vs Open Office
I have an application the reads excels files and move them to my MS SQL database, via C#. This is a done on a machine that host the MSSQL Server as well as an IIS Arcgis Server. The machine is not very strong only 3gb of RAM and the prospects of them giving me a true server seem close to to nil. So I wanted to know which one option is less demanding , memory wise. OpenOffice or MS Excel.</p>

答: Neither - use the OleDb provider. It's much simpler and faster. But between the two options you proposed, MS Excel is almost certainly going to be less memory intensive.</p>


问:
Can javers completely delete an object (together with all its history)?
I am new to javers and evaluating it for our new project. We have use cases that we want to use javers to track our domain objects when they are alive, but when they are deleted for a while (configurable period), we would like to be able to cleanup the space, either by on-demand calling an API to completely wiped out the deleted object all together with its history, or configure a retention policy to cleanup terminated objects older than a certain period automatically. Is this possible? Or did I miss anything?</p>

答: There is no such feature. Complete wipe out of a given object would be useful. It's not hard to implement. If you'd contribute a PR, we will merge it.</p>


问:
AutoCompleteTextView item selection programmatically
I have an AutoCompleteTextView that is filled with cities from an sqlite database that calls an AsyncTask on item click, recently I added an option to detect my location using the gps, so the problem is I can detect the city (i.e Beirut) and set the text for the AutoCompleteTextView but the thing is that the dropdown filter opens showing Beirut (which is correct) but I still need to click on the list item to invoke the listener, how to do so programmatically

How to:

Enter the Activity (DONE)

Detect location (DONE)

set text of text view (DONE)

show textview dropdown list(DONE)

choose the item that will be returned, since it will only return one city (NOT DONE)

答: The problem is that you are setting a text and the AutoCompleteTextView is only showing words that match with that text. A non elegant way of solving this is to set an high threshold (at least the max length of the names of the cities) to force Android to show you all the values of your list (this threshold is the number of characters that the field must have to search similarities).

ContentLicense: CC BY-SA 4.0


问:
Refresh table which contain a php code
I have a PHP code, which is in a table tag.It shows a text from database. I want to refresh this table, to load updated text from database in every - let's say - 1 minute without refreshing the whole page. I've found several solutions to reload table without refreshing a page and it seems it can be done with AJAX or JS, but they only refresh it with a specific content or a specific file, however, I can't figure out how to refreshed.</p>

```<code><table class="table table-striped">
  <thead>
    <tr>
      <th>Department</th>
      <th class="col_small col_center">Employees</th>
      <th class="col_small col_center">% Percentage</th>
    </tr>
  </thead>
  <tbody>
    <?php $employeeslist=$emp_departmentObj->selectorgall();
        foreach($employeeslist as $list)
        {
          $total=$emp_regObj->selectorgall();
          $totalemp=count($total);
          $deptemp=$emp_regObj->selectemployee($list->id);
          $totaldeptemp=count($deptemp);
          $percentage=($totaldeptemp/$totalemp)*100;
    ?>
    <tr>
      <td><a href="#"><?php echo $list->department ?></a></td>
      <td class="col_center">
        <?php echo $totaldeptemp; ?>
      </td>
      <td class="col_center">
        <?php echo number_format($percentage,1).'%'; ?>
      </td>
    </tr>

    <?php } ?>

  </tbody>
</table>
</code>```

答:
You can define a function in document ready like this

```<code>$(document).ready(function() {
setInterval(function() { rebindTable() }, 3000);

function rebindTable() {
    $.ajax({
        url: "http://localhost:80/data.php",
        success: function(result) {
            var data = result;
            $('#td-1-data').html(data.param1);
            $('#td-2-data').html(data.param2);
        }
    });

}
})
</code>```

this way you can use an setInterval method and re-bind the data in the table using ajax , in this i assume your http://localhost:80/data.php is returning some data which your are binding to the td of the table you have defined

Title: Refresh table which contain a php code

Body:
I have a PHP code, which is in a table tag.It shows a text from database. I want to refresh this table, to load updated text from database in every - let's say - 1 minute without refreshing the whole page. I've found several solutions to reload table without refreshing a page and it seems it can be done with AJAX or JS, but they only refresh it with a specific content or a specific file, however, I can't figure out how to refreshed.

      Department
      Employees
      % Percentage

    <?php $employeeslist=$emp_departmentObj->selectorgall();
        foreach($employeeslist as $list)
        {
          $total=$emp_regObj->selectorgall();
          $totalemp=count($total);
          $deptemp=$emp_regObj->selectemployee($list->id);
          $totaldeptemp=count($deptemp);
          $percentage=($totaldeptemp/$totalemp)*100;
    ?>

      <?php echo $list->department ?>

        <?php echo $totaldeptemp; ?>

        <?php echo number_format($percentage,1).'%'; ?>

    <?php } ?>

Body:
You can define a function in document ready like this

$(document).ready(function() {
setInterval(function() { rebindTable() }, 3000);

function rebindTable() {
    $.ajax({
        url: "http://localhost:80/data.php",
        success: function(result) {
            var data = result;
            $('#td-1-data').html(data.param1);
            $('#td-2-data').html(data.param2);
        }
    });

}
})

this way you can use an setInterval method and re-bind the data in the table using ajax , in this i assume your http://localhost:80/data.php is returning some data which your are binding to the td of the table you have defined


问:
Need to close below dropdown when click on other popover button

I need to close the dropdown when I click on another popover button

答:
you can try this in many ways:

simplest one in angularJs itself by adding a ng-click in your button which will change the value of show :

```<code> <button class="btn btn-primary dropdown-toggle" type="button" ng-click="show=0">
</code>```

otherwise:

you can add some id to your button so it will be captured easily,
e.g.

```<code><button class="btn btn-primary dropdown-toggle" type="button" id="hideDropdown">
</code>```

and can try with given solutions:

jQuery

```<code>$(document).on('click', function(evt) {
    if($(evt.target).is('#hideDropdown')) {
        // Hide code
        // e.g. show=0;
    } });
</code>```

you can try with
Javascript

```<code>document.getElementById('hideDropdown').onclick = function(e){
        // Hide code
        // e.g. show=0;
}
</code>```

or AngularJs itself by using a directive

```<code>YourApp.directive('testClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element) {
            element.onclick = function() {
                //do some thing.
            }
        }
    }
})

*html code*

<button test-click>Test Click</button>
</code>```

you may need to change the conditions as per your requirements as it is a rough code.

Body:
you can try this in many ways:

simplest one in angularJs itself by adding a ng-click in your button which will change the value of show :

 <button class="btn btn-primary dropdown-toggle" type="button" ng-click="show=0">

otherwise:

you can add some id to your button so it will be captured easily,
e.g.

<button class="btn btn-primary dropdown-toggle" type="button" id="hideDropdown">

and can try with given solutions:

jQuery

$(document).on('click', function(evt) {
    if($(evt.target).is('#hideDropdown')) {
        // Hide code
        // e.g. show=0;
    } });

you can try with
Javascript

document.getElementById('hideDropdown').onclick = function(e){
        // Hide code
        // e.g. show=0;
}

or AngularJs itself by using a directive

YourApp.directive('testClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element) {
            element.onclick = function() {
                //do some thing.
            }
        }
    }
})

*html code*

<button test-click>Test Click</button>

you may need to change the conditions as per your requirements as it is a rough code.


问:
UITextView selectionRange strange behavior with plus sign "+"
If I have a plus sign in my UITextView, and I try to set the selectionRange to immediately precede it (i.e, put the cursor before the plus sign), it automatically moves to the next space.  As far as I can tell, this is specifically for plus signs; for example, equals signs and minus signs do not exhibit this behavior.

Can anyone explain what is going on?

答: I reported this to Apple as a bug in iOS 4.2.  They asked me to try it in the iOS4.3 beta.  It appears to be fixed.</p>


问:
Caching Google API calls for unit tests
I've got a Google App Engine project that uses the Google Cloud Language API, and I'm using the Google API Client Library (Python) to make the API calls.

When running my unit tests, I make quite a few calls to the API.  This slows down my testing and also incurs costs.

I'd like to cache the calls to the Google API to speed up my tests and avoid the API charges, and I'd rather not roll my own if another solution is available.

I found this Google API page, which suggests doing this:

```<code>import httplib2
http = httplib2.Http(cache=".cache")
</code>```

And I've added these lines to my code (there is another option to use GAE memcache but won't be persisted between test code invocations) and right after these lines, I create my API call connection:

```<code>NLP = discovery.build("language", "v1", API_KEY)
</code>```

The caching isn't working and the above solution seems too simple so I suspect I am missing something.

UPDATE:

I updated my tests so that App Engine is not used (just a regular unit test) and I also figured out that I can pass the http I created to the Google API client like this:

```<code>NLP = discovery.build("language", "v1", http, API_KEY)
</code>```

Now, the initial discovery call is cached but the actual API calls are not cached,e.g., this call is not cached:

```<code>result = NLP.documents().annotateText(body=data).execute()
</code>```

答:
The suggested code:

http = httplib2.Http(cache=".cache") is trying to cache to the local filesystem in a directory called ".cache". On App Engine, you cannot write to the local filesystem, so this does nothing.

Instead, you could try caching to Memcache. The other suggestion on the Python Client docs referenced is to do exactly this:

```
  from google.appengine.api import memcache

  http = httplib2.Http(cache=memcache)
```

Since all App Engine apps get free access to shared memcache this should be better than nothing.

If this fails, you could also try memoization. I've had success memoizing calls to slow or flaky APIs, but it comes at the cost of increased memory usage (so I need bigger instances).

EDIT: I see from your comment you're having this problem locally. I was originally thinking that memoization would be an alternative, but the need to hack on httplib2 makes that overly complicated. I'm back to thinking about how to convince httplib2 to do the right thing.

Title: Caching Google API calls for unit tests

Body:
I've got a Google App Engine project that uses the Google Cloud Language API, and I'm using the Google API Client Library (Python) to make the API calls.

When running my unit tests, I make quite a few calls to the API.  This slows down my testing and also incurs costs.

I'd like to cache the calls to the Google API to speed up my tests and avoid the API charges, and I'd rather not roll my own if another solution is available.

I found this Google API page, which suggests doing this:

import httplib2
http = httplib2.Http(cache=".cache")

And I've added these lines to my code (there is another option to use GAE memcache but won't be persisted between test code invocations) and right after these lines, I create my API call connection:

NLP = discovery.build("language", "v1", API_KEY)

The caching isn't working and the above solution seems too simple so I suspect I am missing something.

UPDATE:

I updated my tests so that App Engine is not used (just a regular unit test) and I also figured out that I can pass the http I created to the Google API client like this:

NLP = discovery.build("language", "v1", http, API_KEY)

Now, the initial discovery call is cached but the actual API calls are not cached,e.g., this call is not cached:

result = NLP.documents().annotateText(body=data).execute()

Body:
The suggested code:

http = httplib2.Http(cache=".cache") is trying to cache to the local filesystem in a directory called ".cache". On App Engine, you cannot write to the local filesystem, so this does nothing.

Instead, you could try caching to Memcache. The other suggestion on the Python Client docs referenced is to do exactly this:

  from google.appengine.api import memcache

  http = httplib2.Http(cache=memcache)

Since all App Engine apps get free access to shared memcache this should be better than nothing.

If this fails, you could also try memoization. I've had success memoizing calls to slow or flaky APIs, but it comes at the cost of increased memory usage (so I need bigger instances).

EDIT: I see from your comment you're having this problem locally. I was originally thinking that memoization would be an alternative, but the need to hack on httplib2 makes that overly complicated. I'm back to thinking about how to convince httplib2 to do the right thing.


问:
Swift 3 own font for UITableViewCellActionButton
this is my first question here, so feel free to point out anything I might be doing wrong ;)

I'm currently trying to give the UITableViewRowAction-Buttons in my Application a custom font. For that I used David Seeks Answer here and put in in an extension like this:

```<code>extension UITableViewCell{

override open func layoutSubviews() {

    super.layoutSubviews()

    for subview in self.subviews {

        for sub in subview.subviews {

            if String(describing: sub).range(of: "UITableViewCellActionButton") != nil {

                for view in sub.subviews {

                    if String(describing: view).range(of: "UIButtonLabel") != nil {

                        if let label = view as? UILabel {

                            label.font = UIFont(name: "CaptureSmallz", size: label.font.pointSize)

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

It works, but it seems to cut the space of the overlying cell elements:
see screenshot
Any ideas what I'm doing wrong here?

答:
Try calling label.sizeToFit(), that should resize things after you've changed the label's font size.

This seems like a good place for a subclass of the UITableViewCell though, to achieve all the customization that you're looking for.

Body:
this is my first question here, so feel free to point out anything I might be doing wrong ;)

I'm currently trying to give the UITableViewRowAction-Buttons in my Application a custom font. For that I used David Seeks Answer here and put in in an extension like this:

extension UITableViewCell{

override open func layoutSubviews() {

    super.layoutSubviews()

    for subview in self.subviews {

        for sub in subview.subviews {

            if String(describing: sub).range(of: "UITableViewCellActionButton") != nil {

                for view in sub.subviews {

                    if String(describing: view).range(of: "UIButtonLabel") != nil {

                        if let label = view as? UILabel {

                            label.font = UIFont(name: "CaptureSmallz", size: label.font.pointSize)

}}}}}}}}

It works, but it seems to cut the space of the overlying cell elements:
see screenshot
Any ideas what I'm doing wrong here?


问:
Java ADFS SSO migration
I to migrate my application to ADFS SSO.The flow is simple. Our application needs to get information from ADFS and send it to my server. I have no access to the ADFS. I have written a little application to test communication with ADFS, it uses OneLogin and it is deployed on Azure Ubuntu VM machine. But when I try to redirect to the ADFS server it says : "An error occurred. Contact your administrator for more information.". I guess it is because ADFS needs to know about my application. What information do I need to give to ADFS administration so that we can communicate? My app has no spring.</p>

答:
What client side protocol stack are you using?

SAML, WS-Fed, ... ?

Do you have protocol metadata you can give the admin.?

What error is showing in the ADFS event log?

Update

You need a client side stack - SAML : SAML connectivity / toolkit .

From the ADFS metadata, you need the signing certificate, the entityID and the SSO and SLO endpoints.

You add these to the config. options of whatever stack you choose.

Title: Java ADFS SSO migration


问:
SQL Server: CASE WHEN with temp tables syntax errroring out
The logic I'm trying to implement is as follows: Replace certain strings with other strings for a specific column.

Leave string values that do not need to be replaced as their original values.

```<code>   SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'A-9' THEN 'A9'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
                 WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a
</code>```

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

答:
```<code>SELECT * INTO #df_ERA4_a_temp
FROM
(SELECT CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
             WHEN [REQMNT] = 'A-12' THEN 'A12'
             WHEN [REQMNT] = 'A-9' THEN 'A9'
             WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
             WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
             WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
             ELSE [REQMNT]
        END
FROM #df_ERA4_a) a
</code>```

Body:
The logic I'm trying to implement is as follows: Replace certain strings with other strings for a specific column.

Leave string values that do not need to be replaced as their original values.

   SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'A-9' THEN 'A9'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
                 WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.


问:
Php inside a javascript function?
I have a feature on my users inbox that allows users to check/uncheck messages in their inbox that they want to make favourite.

I'm currently testing what happens when a user checks the box (clicks on the image and causes it to go from greyed out to colour meaning the box is checked).

Anyway as you can see from the code below when the box ischecked this url is suppose to be loaded: http://mysite.com/messages/favourite_checked

The message_id of the row the user has checked the box on is suppose to be added onto the end of the url this then loads my controller "messages" and method "favourite_checked" which then passes a variable that grabs the message_id from the url, stores it in a variable then sends it the my model and it is used in a mysql query.

Basically I update the favourites column of my messages table and set it to = 1 where the message_id from url matches the one in the messages table in my database. So yea, where the match is found the "favourite" column in that row is updated to 1. 1 = favourite 0 = not favourite.

Any I just thought I would make it clear what was happening..

My problem is nothing happens when I check the box, nothing is updated so I feel I must be doing something wrong where I try to add the id to the url in the javascript function.

I've tried $(post) also.. nothing happens then also.

Maybe someone can spot it because I really don't know what the problem is.

```<code><script type="text/javascript">

// favourite check box
    $('input.favourite:checkbox').simpleImageCheck({
  image: '<?php echo base_url()?>images/messages/check.png',
  imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
  afterCheck: function(isChecked) {
    if (isChecked) {

  //query to db from php to update favourite number to 1
  $.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row):  ?><?php $row['id']; ?><?php endforeach; ?>');

    }
//    else (!isChecked)
//        {
//            //query to db from php to update favourite number to 0
//              $.get('http://mysite.com/messages/favourite_unchecked');
//        }
  }
});
</script>
</code>```

答:
I think your basic problem is some confusion about when the PHP is running vs the javascript.

The PHP you put on the page is server side, it will load first, then the javascript will run client-side.

This part here:

```<code>$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row):  ?><?php $row['id']; ?><?php endforeach; ?>');
</code>```

Seems like you are wanting this to be dynamic based on what you checked, but I don't see how that url is going to show specifically what you are looking for.

Title: Php inside a javascript function?

Body:
I think your basic problem is some confusion about when the PHP is running vs the javascript.

The PHP you put on the page is server side, it will load first, then the javascript will run client-side.

This part here:

$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row):  ?><?php $row['id']; ?><?php endforeach; ?>');

Seems like you are wanting this to be dynamic based on what you checked, but I don't see how that url is going to show specifically what you are looking for.


问:
Extracting all string values matching a pattern for CAS Numbers in PHP
Ok, so I working on extracting CAS Numbers from uploaded SDS files (working on docx before I move to pdf). I have successfully converted the docx to a string in the page, but I need to extract several strings if they exist.  Here is the code I'm using, and I don't think I'm using preg_match_all correctly at all.

```<code>$docObj = new DocxConversion($_FILES["sdsFile"]["tmp_name"]);
$docText = $docObj->convertToText();
preg_match_all("/[0-9]{2,7}-[0-9]{2}-[0-9]{1}/", $docText, $matches);
print_r($matches);
</code>```

This give me Array ( [0] => Array ( ) ).  Not very helpful when I'm looking for:

64742‐47‐8

64742‐65‐0

9003‐29‐6

The output of $docText is:

IDENTIFICATION PRODUCT IDENTIFIER USED ON LABEL: Finished Product Item Number Customer Item Number LABEL DESCRIPTION ACTUAL BRAND SM5802EE ECHO POWERBLEND X EXTENDED LIFE OIL ECHO SMGR33EC 6450005 ECHO POWER BLEND X ECHO SMGR01EC 6450025 ECHO POWER BLEND X ECHO SMGR07EC 6450002 ECHO POWER BLEND X ECHO SM5101EC X6972270101/99988800086 ECHO POWER BLEND X ECHO SM5905EC 6450250 ECHO BAR & CHAIN OIL ECHO SM5818ER 6450114 ECHO POWER BLEND X HIGH PERFORMANCE 2 STROKE ENGINE ECHO SM5818EG 6450103 ECHO POWER BLEND X ECHO SM5238EC 99988800088 ECHO POWER BLEND X ECHO SM5218EC X6972270201/99988800085 ECHO POWER BLEND X ECHO SMGR25EC X6974100202 ECHO POWER BLEND X ECHO SMGR02EC 6450001 ECHO POWER BLEND X ECHO SMGR29EC 6450000 ECHO POWERBLEND X ECHO SM5818EE 6450102 ECHO POWER BLEND X LOW SMOKE ECHO SM5818EC 6450100/6450099 ECHO POWER BLEND X ECHO SM5818EM 6450060 ECHO POWER BLEND X ECHO SMGR34EE ECHO POWERBLEND X ECHO SM5906EC 6450050 ECHO POWER BLEND X ECHO SM5906EM 6450062 ECHO POWER BLEND X ECHO SM5943EE 6450116 ECHO POWER BLEND X ECHO SMGR33EK 6450118 ECHO POWERBLEND X ECHO SMGR34ER 6450109 ECHO POWER BLEND X ECHO SM5926EC 6450006 ECHO POWERBLEND X XTENDED LIFE OIL ECHO SMGR34EE ECHO POWER BLEND X ECHO SMGR34EC 6450108 ECHO POWER BLEND X ECHO SMGR12EC 99988800089 ECHO POWER BLEND X ECHO SMGR34EK 6450119 ECHO POWERBLEND X ECHO SM5834EM 6450061 ECHO POWER BLEND X ECHO Finished Product Item Number Customer Item Number LABEL DESCRIPTION ACTUAL BRAND SMGR34EG 6450115 ECHO POWER BLEND X ECHO SM5955EC 6452750 ECHO POWER BLEND X ECHO RECOMMENDED USE OF THE CHEMICAL AND RESTRICTIONS ON USE; PETROLEUM LUBRICATING OIL NO OTHER USES RECOMMENDED NAME, ADDRESS, AND TELEPHONE NUMBER OF THE CHEMICAL MANUFACTURER, IMPORTER, OR OTHER RESPONSIBLE PARTY: 1.3.1. Spectrum Lubricants Corporation 500 Industrial Park Drive Selmer, TN 38375‐3276 United States of America Product Information MSDS Requests: (800) 264‐6457 or +17316454972 Technical Information: (800) 264‐6457 or +17316454972 General Information: vswedley@spectrumcorporation.comEMERGENCY PHONE NUMBER: 1.4.1. Emergency Response North America: CHEMTREC (800) 424‐9300 after 5:00pm CST Or +17035273887 Health Emergency USA: (800) 264‐6457 or +17316454972 HAZARD(S) IDENTIFICATION CLASSIFICATION OF THE CHEMICAL IN ACCORDANCE WITH PARAGRAPH (d) of §1910.1200: Acute Inhalation Category 4 Eye Irritant Category 2 Skin Corrosion/Irritation Category 2 Flammable Liquid Category 4 Signal Word: Warning Symbol: Hazard Statements: Harmful if Inhaled Causes serious eye irritation Causes skin irritation Combustible Liquid Precautionary Statements: Prevention: Avoid breathing mist or spray. Use only outdoors or in a well‐ventilated area. Wear eye/face protection Wear protective gloves Keep away from heat, hot surfaces, sparks, open flames and other ignition sources. No smoking. Response: If inhaled: Remove person to fresh air and keep comfortable for breathing. If in eyes: Rinse cautiously with water for several minutes. Remove contact lenses, if present and easy to do. Continue rinsing. If eye irritation persists get medical advice/attention. If on skin: wash with plenty of water, if irritation or rash occurs get medical advice/attention. Take off contaminated clothing and wash it before reuse. Call a poison center/doctor if you feel unwell. In case of fire: Use water fog, foam, dry chemical or carbon dioxide (CO2) to extinguish flames. Storage: Store in well‐ventilated place. Disposal: Dispose of contents/container in accordance with local/regional/national/international regulations. Composition/ information on ingredients The chemical name and concentration (exact percentage) or concentration ranges of all ingredients which are classified as health hazards in accordance with paragraph (d) of §1910.1200 3.1.1. COMPONENTS CAS Number EU Number Concentration (%) Hazard Statements (see Section 16) Distillates (petroleum), hydrotreated light 64742‐47‐8 265‐149‐8 10‐30 H226, H304, H315, Solvent‐dewaxed heavy paraffinic distillates 64742‐65‐0 265‐169‐7 40‐50 H315, H332 Polyiosbutylene 9003‐29‐6 Not available 40‐70 H315, H319, H332 FIRST AID MEASURES

There's more, but I'll spare you...

答:
You need to add other hyphens:

```<code>~\d{2,7}\p{Pd}\d{2}\p{Pd}\d~u
</code>```

See a demo on regex101.com.

Broken down:

```<code>~        # pattern delimiter
\d{2,7}  # digits, 2-7 times
\p{Pd}   # matches any kind of hyphen or dash (including unicode characters)
\d{2}    # 2 digits
\p{Pd}   # same as above
\d       # one digit
~        # pattern delimiter
u        # unicode flag (pattern modifier)
</code>```

In PHP:

```<code>preg_match_all('~\d{2,7}\p{Pd}\d{2}\p{Pd}\d~u', $docText, $matches);
</code>```

Body:
Ok, so I working on extracting CAS Numbers from uploaded SDS files (working on docx before I move to pdf). I have successfully converted the docx to a string in the page, but I need to extract several strings if they exist.  Here is the code I'm using, and I don't think I'm using preg_match_all correctly at all.

$docObj = new DocxConversion($_FILES["sdsFile"]["tmp_name"]);
$docText = $docObj->convertToText();
preg_match_all("/[0-9]{2,7}-[0-9]{2}-[0-9]{1}/", $docText, $matches);
print_r($matches);

This give me Array ( [0] => Array ( ) ).  Not very helpful when I'm looking for:

64742‐47‐8

64742‐65‐0

9003‐29‐6

The output of $docText is:

IDENTIFICATION PRODUCT IDENTIFIER USED ON LABEL: Finished Product Item Number Customer Item Number LABEL DESCRIPTION ACTUAL BRAND SM5802EE ECHO POWERBLEND X EXTENDED LIFE OIL ECHO SMGR33EC 6450005 ECHO POWER BLEND X ECHO SMGR01EC 6450025 ECHO POWER BLEND X ECHO SMGR07EC 6450002 ECHO POWER BLEND X ECHO SM5101EC X6972270101/99988800086 ECHO POWER BLEND X ECHO SM5905EC 6450250 ECHO BAR & CHAIN OIL ECHO SM5818ER 6450114 ECHO POWER BLEND X HIGH PERFORMANCE 2 STROKE ENGINE ECHO SM5818EG 6450103 ECHO POWER BLEND X ECHO SM5238EC 99988800088 ECHO POWER BLEND X ECHO SM5218EC X6972270201/99988800085 ECHO POWER BLEND X ECHO SMGR25EC X6974100202 ECHO POWER BLEND X ECHO SMGR02EC 6450001 ECHO POWER BLEND X ECHO SMGR29EC 6450000 ECHO POWERBLEND X ECHO SM5818EE 6450102 ECHO POWER BLEND X LOW SMOKE ECHO SM5818EC 6450100/6450099 ECHO POWER BLEND X ECHO SM5818EM 6450060 ECHO POWER BLEND X ECHO SMGR34EE ECHO POWERBLEND X ECHO SM5906EC 6450050 ECHO POWER BLEND X ECHO SM5906EM 6450062 ECHO POWER BLEND X ECHO SM5943EE 6450116 ECHO POWER BLEND X ECHO SMGR33EK 6450118 ECHO POWERBLEND X ECHO SMGR34ER 6450109 ECHO POWER BLEND X ECHO SM5926EC 6450006 ECHO POWERBLEND X XTENDED LIFE OIL ECHO SMGR34EE ECHO POWER BLEND X ECHO SMGR34EC 6450108 ECHO POWER BLEND X ECHO SMGR12EC 99988800089 ECHO POWER BLEND X ECHO SMGR34EK 6450119 ECHO POWERBLEND X ECHO SM5834EM 6450061 ECHO POWER BLEND X ECHO Finished Product Item Number Customer Item Number LABEL DESCRIPTION ACTUAL BRAND SMGR34EG 6450115 ECHO POWER BLEND X ECHO SM5955EC 6452750 ECHO POWER BLEND X ECHO RECOMMENDED USE OF THE CHEMICAL AND RESTRICTIONS ON USE; PETROLEUM LUBRICATING OIL NO OTHER USES RECOMMENDED NAME, ADDRESS, AND TELEPHONE NUMBER OF THE CHEMICAL MANUFACTURER, IMPORTER, OR OTHER RESPONSIBLE PARTY: 1.3.1. Spectrum Lubricants Corporation 500 Industrial Park Drive Selmer, TN 38375‐3276 United States of America Product Information MSDS Requests: (800) 264‐6457 or +17316454972 Technical Information: (800) 264‐6457 or +17316454972 General Information: vswedley@spectrumcorporation.comEMERGENCY PHONE NUMBER: 1.4.1. Emergency Response North America: CHEMTREC (800) 424‐9300 after 5:00pm CST Or +17035273887 Health Emergency USA: (800) 264‐6457 or +17316454972 HAZARD(S) IDENTIFICATION CLASSIFICATION OF THE CHEMICAL IN ACCORDANCE WITH PARAGRAPH (d) of §1910.1200: Acute Inhalation Category 4 Eye Irritant Category 2 Skin Corrosion/Irritation Category 2 Flammable Liquid Category 4 Signal Word: Warning Symbol: Hazard Statements: Harmful if Inhaled Causes serious eye irritation Causes skin irritation Combustible Liquid Precautionary Statements: Prevention: Avoid breathing mist or spray. Use only outdoors or in a well‐ventilated area. Wear eye/face protection Wear protective gloves Keep away from heat, hot surfaces, sparks, open flames and other ignition sources. No smoking. Response: If inhaled: Remove person to fresh air and keep comfortable for breathing. If in eyes: Rinse cautiously with water for several minutes. Remove contact lenses, if present and easy to do. Continue rinsing. If eye irritation persists get medical advice/attention. If on skin: wash with plenty of water, if irritation or rash occurs get medical advice/attention. Take off contaminated clothing and wash it before reuse. Call a poison center/doctor if you feel unwell. In case of fire: Use water fog, foam, dry chemical or carbon dioxide (CO2) to extinguish flames. Storage: Store in well‐ventilated place. Disposal: Dispose of contents/container in accordance with local/regional/national/international regulations. Composition/ information on ingredients The chemical name and concentration (exact percentage) or concentration ranges of all ingredients which are classified as health hazards in accordance with paragraph (d) of §1910.1200 3.1.1. COMPONENTS CAS Number EU Number Concentration (%) Hazard Statements (see Section 16) Distillates (petroleum), hydrotreated light 64742‐47‐8 265‐149‐8 10‐30 H226, H304, H315, Solvent‐dewaxed heavy paraffinic distillates 64742‐65‐0 265‐169‐7 40‐50 H315, H332 Polyiosbutylene 9003‐29‐6 Not available 40‐70 H315, H319, H332 FIRST AID MEASURES

There's more, but I'll spare you...

Body:
You need to add other hyphens:

~\d{2,7}\p{Pd}\d{2}\p{Pd}\d~u

See a demo on regex101.com.

Broken down:

~        # pattern delimiter
\d{2,7}  # digits, 2-7 times
\p{Pd}   # matches any kind of hyphen or dash (including unicode characters)
\d{2}    # 2 digits
\p{Pd}   # same as above
\d       # one digit
~        # pattern delimiter
u        # unicode flag (pattern modifier)

In PHP:

preg_match_all('~\d{2,7}\p{Pd}\d{2}\p{Pd}\d~u', $docText, $matches);


问:
VueJS and Drop down values
Am I grabbing the value of the selection incorrectly in this Vue template form? </p>

```<code><select class="form-control" v-model="object.property">
        <option selected="selected" value="Option 1">Option 1</option>
        <option value="Option 2">Option 2</option>
      </select>
</code>```

答:
You are binding the value of object.property to the select element correctly.

But, Vue is going to ignore the selected attribute on the first option element.

Here's the warning you will get if you try to use this template:

inline selected attributes on <option> will be ignored when using v-model. Declare initial values in the component's data option instead.

So, if you want the initial value of the select to be the first option, set object.property to that value when you define it in the data method.

Here's an example:

new Vue({
  el: '#app',
  data() {
    return { object: { property: "Option 1" } }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <select class="form-control" v-model="object.property">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
  </select>

  {{ object.property }}
</div></code>```

Title: VueJS and Drop down values

Body:
Am I grabbing the value of the selection incorrectly in this Vue template form?

<select class="form-control" v-model="object.property">
        <option selected="selected" value="Option 1">Option 1</option>
        <option value="Option 2">Option 2</option>
      </select>

Body:
You are binding the value of object.property to the select element correctly.

But, Vue is going to ignore the selected attribute on the first option element.

Here's the warning you will get if you try to use this template:

inline selected attributes on <option> will be ignored when using v-model. Declare initial values in the component's data option instead.

So, if you want the initial value of the select to be the first option, set object.property to that value when you define it in the data method.

Here's an example:

new Vue({
  el: '#app',
  data() {
    return { object: { property: "Option 1" } }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <select class="form-control" v-model="object.property">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
  </select>

  {{ object.property }}
</div>


问:
Object extending using javascript
I have a source object and I want to update its property value with a new target object and return the source object with modified property. Is there any predefined way in java script I have do this.

var sourceObj = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {},
        weight: 0
    }
}

var targetObj = {
    name: "3",
    street: "4"
}

var result = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {
            name: "3",
            street: "4"
        },
        weight: 0
    }
}```

答:
If you want to reuse the objects, it's literally:

```<code>sourceObj.context.to = targetObj;
// (Then don't use `result`)
</code>```

If you want to make shallow copies:

```<code>result = Object.assign({}, sourceObj);
result.context.to = Object.assign({}, targetObj);
</code>```

Live Example:

var sourceObj = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {},
        weight: 0
    }
}

var targetObj = {
    name: "3",
    street: "4"
}

var result = Object.assign({}, sourceObj);
result.context.to = Object.assign({}, targetObj);
console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

If you want to make deep copies, I leave it as an exercise to the reader based on the above. :-)

E.g., Object.assign makes shallow copies of objects.

There's also a Stage 3 proposal for rest/spread properties which we could use for this (it's likely to make the ES2018 spec, it's already implemented in at least two JavaScript engines):

```<code>result = {...sourceObj};
result.context.to = {...targetObj};
</code>```

Live Example (requires a cutting-edge browser):

var sourceObj = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {},
        weight: 0
    }
}

var targetObj = {
    name: "3",
    street: "4"
}

var result = {...sourceObj};
result.context.to = {...targetObj};
console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

Title: Object extending using javascript

Body:
If you want to reuse the objects, it's literally:

sourceObj.context.to = targetObj;
// (Then don't use `result`)

If you want to make shallow copies:

result = Object.assign({}, sourceObj);
result.context.to = Object.assign({}, targetObj);

Live Example:

var sourceObj = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {},
        weight: 0
    }
}

var targetObj = {
    name: "3",
    street: "4"
}

var result = Object.assign({}, sourceObj);
result.context.to = Object.assign({}, targetObj);
console.log(result);

.as-console-wrapper {
  max-height: 100% !important;
}

If you want to make deep copies, I leave it as an exercise to the reader based on the above. :-)

E.g., Object.assign makes shallow copies of objects.

There's also a Stage 3 proposal for rest/spread properties which we could use for this (it's likely to make the ES2018 spec, it's already implemented in at least two JavaScript engines):

result = {...sourceObj};
result.context.to = {...targetObj};

Live Example (requires a cutting-edge browser):

var sourceObj = {
    context: {
        from: {
            name: "1",
            street: "2"
        },
        to: {},
        weight: 0
    }
}

var targetObj = {
    name: "3",
    street: "4"
}

var result = {...sourceObj};
result.context.to = {...targetObj};
console.log(result);

.as-console-wrapper {
  max-height: 100% !important;
}


问:
Why a figure's Axes is not created?
I'm trying not to use pyplot, but with the code below I only print a completely white figure.

I found with 'fig.axes' that no axes at all is created for 'fig', although 'ax' is a 'matplotlib.axes._axes.Axes' instance. I'm wondering why...

(I know that there are other ways to do obtain the plot, but my question is "what is wrong/missing here?").

```<code>from matplotlib.figure import Figure
from matplotlib.axes import Axes

from matplotlib.backends.backend_agg import FigureCanvasAgg
from numpy import random

data = [random.randn(5) for i in range(5)]

fig = Figure(figsize = (20,10))
canvas = FigureCanvasAgg(fig)

ax = Axes(fig, [0.1,0.1,0.5,0.7])

ax.pcolormesh(data)

canvas.print_figure('test')
</code>```

答:
The problem is that the axes is not added to the figure. Usually you would add an axes via any of the figure's methods, like fig.add_axes() or fig.add_subplot()

Doing that here, e.g.

```<code>ax = fig.add_subplot(111)  # instead of ax = Axes(fig, [0.1,0.1,0.5,0.7])
</code>```

gives you the desired output.

There is really no reason not to use those methods. If you instantiate the Axes yourself, you need to call it

```<code>ax = Axes(fig, [0.1,0.1,0.5,0.7])
fig.add_axes(ax)
</code>```

but this is really just one extra line and no benefit compared to

```<code>ax = fig.add_axes([0.1,0.1,0.5,0.7])
</code>```

Title: Why a figure's Axes is not created?

Body:
I'm trying not to use pyplot, but with the code below I only print a completely white figure.

I found with 'fig.axes' that no axes at all is created for 'fig', although 'ax' is a 'matplotlib.axes._axes.Axes' instance. I'm wondering why...

(I know that there are other ways to do obtain the plot, but my question is "what is wrong/missing here?").

from matplotlib.figure import Figure
from matplotlib.axes import Axes

from matplotlib.backends.backend_agg import FigureCanvasAgg
from numpy import random

data = [random.randn(5) for i in range(5)]

fig = Figure(figsize = (20,10))
canvas = FigureCanvasAgg(fig)

ax = Axes(fig, [0.1,0.1,0.5,0.7])

ax.pcolormesh(data)

canvas.print_figure('test')

Body:
The problem is that the axes is not added to the figure. Usually you would add an axes via any of the figure's methods, like fig.add_axes() or fig.add_subplot()

Doing that here, e.g.

ax = fig.add_subplot(111)  # instead of ax = Axes(fig, [0.1,0.1,0.5,0.7])

gives you the desired output.

There is really no reason not to use those methods. If you instantiate the Axes yourself, you need to call it

ax = Axes(fig, [0.1,0.1,0.5,0.7])
fig.add_axes(ax)

but this is really just one extra line and no benefit compared to

ax = fig.add_axes([0.1,0.1,0.5,0.7])


问:
How do Tasks in the Task Parallel Library affect ActivityID?
Before using the Task Parallel Library, I have often used CorrelationManager.ActivityId to keep track of tracing/error reporting with multiple threads.

ActivityId is stored in Thread Local Storage, so each thread get's its own copy.  The idea is that when you fire up a thread (activity), you assign a new ActivityId.  The ActivityId will be written to the logs with any other trace information, making it possible to single out the trace information for a single 'Activity'.  This is really useful with WCF as the ActivityId can be carried over to the service component.

Here is an example of what I'm talking about:

```<code>static void Main(string[] args)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
    {
        DoWork();
    }));
}

static void DoWork()
{
    try
    {
        Trace.CorrelationManager.ActivityId = Guid.NewGuid();
        //The functions below contain tracing which logs the ActivityID.
        CallFunction1();
        CallFunction2();
        CallFunction3();
    }
    catch (Exception ex)
    {
        Trace.Write(Trace.CorrelationManager.ActivityId + " " + ex.ToString());
    }
}
</code>```

Now, with the TPL, my understanding is that multiple Tasks share Threads.  Does this mean that ActivityId is prone to being reinitialized mid-task (by another task)?  Is there a new mechanism to deal with activity tracing?

答:
Please forgive my posting this as an answer as it is not really answer to your question, however, it is related to your question since it deals with CorrelationManager behavior and threads/tasks/etc.  I have been looking at using the CorrelationManager's LogicalOperationStack (and StartLogicalOperation/StopLogicalOperation methods) to provide additional context in multithreading scenarios.

I took your example and modified it slightly to add the ability to perform work in parallel using Parallel.For.  Also, I use StartLogicalOperation/StopLogicalOperation to bracket (internally) DoLongRunningWork.  Conceptually, DoLongRunningWork does something like this each time it is executed:

```<code>DoLongRunningWork
  StartLogicalOperation
  Thread.Sleep(3000)
  StopLogicalOperation
</code>```

I have found that if I add these logical operations to your code (more or less as is), all of the logical operatins remain in sync (always the expected number of operations on stack and the values of the operations on the stack are always as expected).

In some of my own testing I found that this was not always the case.  The logical operation stack was getting "corrupted".  The best explanation I could come up with is that the "merging" back of the CallContext information into the "parent" thread context when the "child" thread exits was causing the "old" child thread context information (logical operation) to be "inherited" by another sibling child thread.

The problem might also be related to the fact that Parallel.For apparently uses the main thread (at least in the example code, as written) as one of the "worker threads" (or whatever they should be called in the parallel domain).  Whenever DoLongRunningWork is executed, a new logical operation is started (at the beginning) and stopped (at the end) (that is, pushed onto the LogicalOperationStack and popped back off of it).  If the main thread already has a logical operation in effect and if DoLongRunningWork executes ON THE MAIN THREAD, then a new logical operation is started so the main thread's LogicalOperationStack now has TWO operations.  Any subsequent executions of DoLongRunningWork (as long as this "iteration" of DoLongRunningWork is executing on the main thread) will (apparently) inherit the main thread's LogicalOperationStack (which now has two operations on it, rather than just the one expected operation).

It took me a long time to figure out why the behavior of the LogicalOperationStack was different in my example than in my modified version of your example.  Finally I saw that in my code I had bracketed the entire program in a logical operation, whereas in my modified version of your test program I did not.  The implication is that in my test program, each time my "work" was performed (analogous to DoLongRunningWork), there was already a logical operation in effect.  In my modified version of your test program, I had not bracketed the entire program in a logical operation.

So, when I modified your test program to bracket the entire program in a logical operation AND if I am using Parallel.For, I ran into exactly the same problem.

Using the conceptual model above, this will run successfully:

```<code>Parallel.For
  DoLongRunningWork
    StartLogicalOperation
    Sleep(3000)
    StopLogicalOperation
</code>```

While this will eventually assert due to an apparently out of sync LogicalOperationStack:

```<code>StartLogicalOperation
Parallel.For
  DoLongRunningWork
    StartLogicalOperation
    Sleep(3000)
    StopLogicalOperation
StopLogicalOperation
</code>```

Here is my sample program.  It is similar to yours in that it has a DoLongRunningWork method that manipulates the ActivityId as well as the LogicalOperationStack.  I also have two flavors of kicking of DoLongRunningWork.  One flavor uses Tasks one uses Parallel.For.  Each flavor can also be executed such that the whole parallelized operation is enclosed in a logical operation or not.  So, there are a total of 4 ways to execute the parallel operation.  To try each one, simply uncomment the desired "Use..." method, recompile, and run.  UseTasks, UseTasks(true), and UseParallelFor should all run to completion.  UseParallelFor(true) will assert at some point because the LogicalOperationStack does not have the expected number of entries.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace CorrelationManagerParallelTest
{
  class Program
  {
    static void Main(string[] args)
    {
      //UseParallelFor(true) will assert because LogicalOperationStack will not have expected
      //number of entries, all others will run to completion.

      UseTasks(); //Equivalent to original test program with only the parallelized
                      //operation bracketed in logical operation.
      ////UseTasks(true); //Bracket entire UseTasks method in logical operation
      ////UseParallelFor();  //Equivalent to original test program, but use Parallel.For
                             //rather than Tasks.  Bracket only the parallelized
                             //operation in logical operation.
      ////UseParallelFor(true); //Bracket entire UseParallelFor method in logical operation
    }

    private static List<int> threadIds = new List<int>();
    private static object locker = new object();

    private static int mainThreadId = Thread.CurrentThread.ManagedThreadId;

    private static int mainThreadUsedInDelegate = 0;

    // baseCount is the expected number of entries in the LogicalOperationStack
    // at the time that DoLongRunningWork starts.  If the entire operation is bracketed
    // externally by Start/StopLogicalOperation, then baseCount will be 1.  Otherwise,
    // it will be 0.
    private static void DoLongRunningWork(int baseCount)
    {
      lock (locker)
      {
        //Keep a record of the managed thread used.
        if (!threadIds.Contains(Thread.CurrentThread.ManagedThreadId))
          threadIds.Add(Thread.CurrentThread.ManagedThreadId);

        if (Thread.CurrentThread.ManagedThreadId == mainThreadId)
        {
          mainThreadUsedInDelegate++;
        }
      }

      Guid lo1 = Guid.NewGuid();
      Trace.CorrelationManager.StartLogicalOperation(lo1);

      Guid g1 = Guid.NewGuid();
      Trace.CorrelationManager.ActivityId = g1;

      Thread.Sleep(3000);

      Guid g2 = Trace.CorrelationManager.ActivityId;
      Debug.Assert(g1.Equals(g2));

      //This assert, LogicalOperation.Count, will eventually fail if there is a logical operation
      //in effect when the Parallel.For operation was started.
      Debug.Assert(Trace.CorrelationManager.LogicalOperationStack.Count == baseCount + 1, string.Format("MainThread = {0}, Thread = {1}, Count = {2}, ExpectedCount = {3}", mainThreadId, Thread.CurrentThread.ManagedThreadId, Trace.CorrelationManager.LogicalOperationStack.Count, baseCount + 1));
      Debug.Assert(Trace.CorrelationManager.LogicalOperationStack.Peek().Equals(lo1), string.Format("MainThread = {0}, Thread = {1}, Count = {2}, ExpectedCount = {3}", mainThreadId, Thread.CurrentThread.ManagedThreadId, Trace.CorrelationManager.LogicalOperationStack.Peek(), lo1));

      Trace.CorrelationManager.StopLogicalOperation();
    }

    private static void UseTasks(bool encloseInLogicalOperation = false)
    {
      int totalThreads = 100;
      TaskCreationOptions taskCreationOpt = TaskCreationOptions.None;
      Task task = null;
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StartLogicalOperation();
      }

      Task[] allTasks = new Task[totalThreads];
      for (int i = 0; i < totalThreads; i++)
      {
        task = Task.Factory.StartNew(() =>
        {
          DoLongRunningWork(encloseInLogicalOperation ? 1 : 0);
        }, taskCreationOpt);
        allTasks[i] = task;
      }
      Task.WaitAll(allTasks);

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StopLogicalOperation();
      }

      stopwatch.Stop();
      Console.WriteLine(String.Format("Completed {0} tasks in {1} milliseconds", totalThreads, stopwatch.ElapsedMilliseconds));
      Console.WriteLine(String.Format("Used {0} threads", threadIds.Count));
      Console.WriteLine(String.Format("Main thread used in delegate {0} times", mainThreadUsedInDelegate));

      Console.ReadKey();
    }

    private static void UseParallelFor(bool encloseInLogicalOperation = false)
    {
      int totalThreads = 100;
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StartLogicalOperation();
      }

      Parallel.For(0, totalThreads, i =>
      {
        DoLongRunningWork(encloseInLogicalOperation ? 1 : 0);
      });

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StopLogicalOperation();
      }

      stopwatch.Stop();
      Console.WriteLine(String.Format("Completed {0} tasks in {1} milliseconds", totalThreads, stopwatch.ElapsedMilliseconds));
      Console.WriteLine(String.Format("Used {0} threads", threadIds.Count));
      Console.WriteLine(String.Format("Main thread used in delegate {0} times", mainThreadUsedInDelegate));

      Console.ReadKey();
    }

  }
}
</code>```

This whole issue of if LogicalOperationStack can be used with Parallel.For (and/or other threading/Task constructs) or how it can be used probably merits its own question.  Maybe I will post a question.  In the meantime, I wonder if you have any thoughts on this (or, I wonder if you had considered using LogicalOperationStack since ActivityId appears to be safe).

[EDIT]

See my answer to this question for more information about using LogicalOperationStack and/or CallContext.LogicalSetData with some of the various Thread/ThreadPool/Task/Parallel contstructs.

See also my question here on SO about LogicalOperationStack and Parallel extensions:
Is CorrelationManager.LogicalOperationStack compatible with Parallel.For, Tasks, Threads, etc

Finally, see also my question here on Microsoft's Parallel Extensions forum:
http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7c5c3051-133b-4814-9db0-fc0039b4f9d9

In my testing it looks like Trace.CorrelationManager.LogicalOperationStack can become corrupted when using Parallel.For or Parallel.Invoke IF you start a logical operation in the main thread and then start/stop logical operations in the delegate.  In my tests (see either of the two links above) the LogicalOperationStack should always have exactly 2 entries when DoLongRunningWork is executing (if I start a logical operation in the main thread before kicking of DoLongRunningWork using various techniques).  So, by "corrupted" I mean that the LogicalOperationStack will eventually have many more than 2 entries.

From what I can tell, this is probably because Parallel.For and Parallel.Invoke use the main thread as one of the "worker" threads to perform the DoLongRunningWork action.

Using a stack stored in CallContext.LogicalSetData to mimic the behavior of the LogicalOperationStack (similar to log4net's LogicalThreadContext.Stacks which is stored via CallContext.SetData) yields even worse results.  If I am using such a stack to maintain context, it becomes corrupted (i.e. does not have the expected number of entries) in almost all of the scenarios where I have a "logical operation" in the main thread and a logical operation in each iteration/execution of the DoLongRunningWork delegate.

Body:
Before using the Task Parallel Library, I have often used CorrelationManager.ActivityId to keep track of tracing/error reporting with multiple threads.

ActivityId is stored in Thread Local Storage, so each thread get's its own copy.  The idea is that when you fire up a thread (activity), you assign a new ActivityId.  The ActivityId will be written to the logs with any other trace information, making it possible to single out the trace information for a single 'Activity'.  This is really useful with WCF as the ActivityId can be carried over to the service component.

Here is an example of what I'm talking about:

static void Main(string[] args)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
    {
        DoWork();
    }));
}

static void DoWork()
{
    try
    {
        Trace.CorrelationManager.ActivityId = Guid.NewGuid();
        //The functions below contain tracing which logs the ActivityID.
        CallFunction1();
        CallFunction2();
        CallFunction3();
    }
    catch (Exception ex)
    {
        Trace.Write(Trace.CorrelationManager.ActivityId + " " + ex.ToString());
    }
}

Now, with the TPL, my understanding is that multiple Tasks share Threads.  Does this mean that ActivityId is prone to being reinitialized mid-task (by another task)?  Is there a new mechanism to deal with activity tracing?

Body:
Please forgive my posting this as an answer as it is not really answer to your question, however, it is related to your question since it deals with CorrelationManager behavior and threads/tasks/etc.  I have been looking at using the CorrelationManager's LogicalOperationStack (and StartLogicalOperation/StopLogicalOperation methods) to provide additional context in multithreading scenarios.

I took your example and modified it slightly to add the ability to perform work in parallel using Parallel.For.  Also, I use StartLogicalOperation/StopLogicalOperation to bracket (internally) DoLongRunningWork.  Conceptually, DoLongRunningWork does something like this each time it is executed:

DoLongRunningWork
  StartLogicalOperation
  Thread.Sleep(3000)
  StopLogicalOperation

I have found that if I add these logical operations to your code (more or less as is), all of the logical operatins remain in sync (always the expected number of operations on stack and the values of the operations on the stack are always as expected).

In some of my own testing I found that this was not always the case.  The logical operation stack was getting "corrupted".  The best explanation I could come up with is that the "merging" back of the CallContext information into the "parent" thread context when the "child" thread exits was causing the "old" child thread context information (logical operation) to be "inherited" by another sibling child thread.

The problem might also be related to the fact that Parallel.For apparently uses the main thread (at least in the example code, as written) as one of the "worker threads" (or whatever they should be called in the parallel domain).  Whenever DoLongRunningWork is executed, a new logical operation is started (at the beginning) and stopped (at the end) (that is, pushed onto the LogicalOperationStack and popped back off of it).  If the main thread already has a logical operation in effect and if DoLongRunningWork executes ON THE MAIN THREAD, then a new logical operation is started so the main thread's LogicalOperationStack now has TWO operations.  Any subsequent executions of DoLongRunningWork (as long as this "iteration" of DoLongRunningWork is executing on the main thread) will (apparently) inherit the main thread's LogicalOperationStack (which now has two operations on it, rather than just the one expected operation).

It took me a long time to figure out why the behavior of the LogicalOperationStack was different in my example than in my modified version of your example.  Finally I saw that in my code I had bracketed the entire program in a logical operation, whereas in my modified version of your test program I did not.  The implication is that in my test program, each time my "work" was performed (analogous to DoLongRunningWork), there was already a logical operation in effect.  In my modified version of your test program, I had not bracketed the entire program in a logical operation.

So, when I modified your test program to bracket the entire program in a logical operation AND if I am using Parallel.For, I ran into exactly the same problem.

Using the conceptual model above, this will run successfully:

Parallel.For
  DoLongRunningWork
    StartLogicalOperation
    Sleep(3000)
    StopLogicalOperation

While this will eventually assert due to an apparently out of sync LogicalOperationStack:

StartLogicalOperation
Parallel.For
  DoLongRunningWork
    StartLogicalOperation
    Sleep(3000)
    StopLogicalOperation
StopLogicalOperation

Here is my sample program.  It is similar to yours in that it has a DoLongRunningWork method that manipulates the ActivityId as well as the LogicalOperationStack.  I also have two flavors of kicking of DoLongRunningWork.  One flavor uses Tasks one uses Parallel.For.  Each flavor can also be executed such that the whole parallelized operation is enclosed in a logical operation or not.  So, there are a total of 4 ways to execute the parallel operation.  To try each one, simply uncomment the desired "Use..." method, recompile, and run.  UseTasks, UseTasks(true), and UseParallelFor should all run to completion.  UseParallelFor(true) will assert at some point because the LogicalOperationStack does not have the expected number of entries.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace CorrelationManagerParallelTest
{
  class Program
  {
    static void Main(string[] args)
    {
      //UseParallelFor(true) will assert because LogicalOperationStack will not have expected
      //number of entries, all others will run to completion.

      UseTasks(); //Equivalent to original test program with only the parallelized
                      //operation bracketed in logical operation.
      ////UseTasks(true); //Bracket entire UseTasks method in logical operation
      ////UseParallelFor();  //Equivalent to original test program, but use Parallel.For
                             //rather than Tasks.  Bracket only the parallelized
                             //operation in logical operation.
      ////UseParallelFor(true); //Bracket entire UseParallelFor method in logical operation
    }

    private static List<int> threadIds = new List<int>();
    private static object locker = new object();

    private static int mainThreadId = Thread.CurrentThread.ManagedThreadId;

    private static int mainThreadUsedInDelegate = 0;

    // baseCount is the expected number of entries in the LogicalOperationStack
    // at the time that DoLongRunningWork starts.  If the entire operation is bracketed
    // externally by Start/StopLogicalOperation, then baseCount will be 1.  Otherwise,
    // it will be 0.
    private static void DoLongRunningWork(int baseCount)
    {
      lock (locker)
      {
        //Keep a record of the managed thread used.
        if (!threadIds.Contains(Thread.CurrentThread.ManagedThreadId))
          threadIds.Add(Thread.CurrentThread.ManagedThreadId);

        if (Thread.CurrentThread.ManagedThreadId == mainThreadId)
        {
          mainThreadUsedInDelegate++;
        }
      }

      Guid lo1 = Guid.NewGuid();
      Trace.CorrelationManager.StartLogicalOperation(lo1);

      Guid g1 = Guid.NewGuid();
      Trace.CorrelationManager.ActivityId = g1;

      Thread.Sleep(3000);

      Guid g2 = Trace.CorrelationManager.ActivityId;
      Debug.Assert(g1.Equals(g2));

      //This assert, LogicalOperation.Count, will eventually fail if there is a logical operation
      //in effect when the Parallel.For operation was started.
      Debug.Assert(Trace.CorrelationManager.LogicalOperationStack.Count == baseCount + 1, string.Format("MainThread = {0}, Thread = {1}, Count = {2}, ExpectedCount = {3}", mainThreadId, Thread.CurrentThread.ManagedThreadId, Trace.CorrelationManager.LogicalOperationStack.Count, baseCount + 1));
      Debug.Assert(Trace.CorrelationManager.LogicalOperationStack.Peek().Equals(lo1), string.Format("MainThread = {0}, Thread = {1}, Count = {2}, ExpectedCount = {3}", mainThreadId, Thread.CurrentThread.ManagedThreadId, Trace.CorrelationManager.LogicalOperationStack.Peek(), lo1));

      Trace.CorrelationManager.StopLogicalOperation();
    }

    private static void UseTasks(bool encloseInLogicalOperation = false)
    {
      int totalThreads = 100;
      TaskCreationOptions taskCreationOpt = TaskCreationOptions.None;
      Task task = null;
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StartLogicalOperation();
      }

      Task[] allTasks = new Task[totalThreads];
      for (int i = 0; i < totalThreads; i++)
      {
        task = Task.Factory.StartNew(() =>
        {
          DoLongRunningWork(encloseInLogicalOperation ? 1 : 0);
        }, taskCreationOpt);
        allTasks[i] = task;
      }
      Task.WaitAll(allTasks);

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StopLogicalOperation();
      }

      stopwatch.Stop();
      Console.WriteLine(String.Format("Completed {0} tasks in {1} milliseconds", totalThreads, stopwatch.ElapsedMilliseconds));
      Console.WriteLine(String.Format("Used {0} threads", threadIds.Count));
      Console.WriteLine(String.Format("Main thread used in delegate {0} times", mainThreadUsedInDelegate));

      Console.ReadKey();
    }

    private static void UseParallelFor(bool encloseInLogicalOperation = false)
    {
      int totalThreads = 100;
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StartLogicalOperation();
      }

      Parallel.For(0, totalThreads, i =>
      {
        DoLongRunningWork(encloseInLogicalOperation ? 1 : 0);
      });

      if (encloseInLogicalOperation)
      {
        Trace.CorrelationManager.StopLogicalOperation();
      }

      stopwatch.Stop();
      Console.WriteLine(String.Format("Completed {0} tasks in {1} milliseconds", totalThreads, stopwatch.ElapsedMilliseconds));
      Console.WriteLine(String.Format("Used {0} threads", threadIds.Count));
      Console.WriteLine(String.Format("Main thread used in delegate {0} times", mainThreadUsedInDelegate));

      Console.ReadKey();
    }

  }
}

This whole issue of if LogicalOperationStack can be used with Parallel.For (and/or other threading/Task constructs) or how it can be used probably merits its own question.  Maybe I will post a question.  In the meantime, I wonder if you have any thoughts on this (or, I wonder if you had considered using LogicalOperationStack since ActivityId appears to be safe).

[EDIT]

See my answer to this question for more information about using LogicalOperationStack and/or CallContext.LogicalSetData with some of the various Thread/ThreadPool/Task/Parallel contstructs.

See also my question here on SO about LogicalOperationStack and Parallel extensions:
Is CorrelationManager.LogicalOperationStack compatible with Parallel.For, Tasks, Threads, etc

Finally, see also my question here on Microsoft's Parallel Extensions forum:
http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/7c5c3051-133b-4814-9db0-fc0039b4f9d9

In my testing it looks like Trace.CorrelationManager.LogicalOperationStack can become corrupted when using Parallel.For or Parallel.Invoke IF you start a logical operation in the main thread and then start/stop logical operations in the delegate.  In my tests (see either of the two links above) the LogicalOperationStack should always have exactly 2 entries when DoLongRunningWork is executing (if I start a logical operation in the main thread before kicking of DoLongRunningWork using various techniques).  So, by "corrupted" I mean that the LogicalOperationStack will eventually have many more than 2 entries.

From what I can tell, this is probably because Parallel.For and Parallel.Invoke use the main thread as one of the "worker" threads to perform the DoLongRunningWork action.

Using a stack stored in CallContext.LogicalSetData to mimic the behavior of the LogicalOperationStack (similar to log4net's LogicalThreadContext.Stacks which is stored via CallContext.SetData) yields even worse results.  If I am using such a stack to maintain context, it becomes corrupted (i.e. does not have the expected number of entries) in almost all of the scenarios where I have a "logical operation" in the main thread and a logical operation in each iteration/execution of the DoLongRunningWork delegate.


问:
The Parent doensn't retrieve the childs hibertnate JPA
I have a Controller from rest service that I call a Hibernate method to get the result, but I really don't know why the children components didn't come. When I call this method using Junit, It works.
This is the Code:  </p>

```<code>{

@Entity
public class Product implements Serializable {
    private static final long serialVersionUID = -6131311050358241535L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false)
    private String name;

    private String description;

    @OneToMany(mappedBy = "product")
    private List<Image> images = new ArrayList<Image>();
}

{

@Entity
public class Image implements Serializable {

    private static final long serialVersionUID = 2128787860415180858L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @JoinColumn(name = "product_id")
    @ManyToOne
    private Product product;

    private ImageType type;
}
{

@PersistenceContext
private EntityManager entityManager;

public List<Product> findAllWithParentProductsAndImage() {
String hpql = "select distinct p from Product p left join fetch p.images";
List<Product> resultList = entityManager.createQuery(hpql,
        Product.class).getResultList();
return resultList;
}
}
</code>```

答:
By default @OneToMany will load lazily.
You should use @OneToMany(  mappedBy = "product", fetch=FetchType.Eager ) to do Eager fetch

Body:
I have a Controller from rest service that I call a Hibernate method to get the result, but I really don't know why the children components didn't come. When I call this method using Junit, It works.
This is the Code:

{

@Entity
public class Product implements Serializable {
    private static final long serialVersionUID = -6131311050358241535L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false)
    private String name;

    private String description;

    @OneToMany(mappedBy = "product")
    private List<Image> images = new ArrayList<Image>();
}

{

@Entity
public class Image implements Serializable {

    private static final long serialVersionUID = 2128787860415180858L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @JoinColumn(name = "product_id")
    @ManyToOne
    private Product product;

    private ImageType type;
}
{

@PersistenceContext
private EntityManager entityManager;

public List<Product> findAllWithParentProductsAndImage() {
String hpql = "select distinct p from Product p left join fetch p.images";
List<Product> resultList = entityManager.createQuery(hpql,
        Product.class).getResultList();
return resultList;
}
}


问:
filter objects with two nested levels in a query with Realm
I have a model like this:

```<code>class CalendarEvent: Object, Mappable {

dynamic var exId = ""
@objc dynamic var title:String = ""
@objc dynamic var desc:String = ""
dynamic var fullDate = Date()
dynamic var date = ""
dynamic var time = ""
dynamic var location = ""
dynamic var subcategory:Subcategory?
dynamic var update = false
var participants = List<Participant>()
}

class Category:Object, Mappable{
dynamic var exId = ""
@objc dynamic var name="";
var subcategories = List<Subcategory>()
}

class Subcategory:Object, Mappable{
dynamic var exId = ""
dynamic var name = ""
let category = LinkingObjects(fromType: Category.self, property: "subcategories")
dynamic var active:Bool = true
dynamic var update = false
}
</code>```

I need to know which CalendarEvents are from a category, when is from a subcategory I can do:

```<code>var results = realm.objects(CalendarEvent.self)
results = results.filter("ANY subcategory.exId == %@", subcategory!.exId)
</code>```

But when I need to obtain the CalendarEvents filtered by category I don´t know how to do it. I looked after the solution but didn´t find anywhere. Please help!

答:
For the record, I found the solution. It´s easy, you need to subdivide in queries and chain then using "IN". For example:</p>

```<code>let resultsSubcategory = realm.objects(Subcategory.self).filter("ANY category.exId == %@", category?.exId)
        results = results.filter("subcategory IN %@", resultsSubcategory)
</code>```

Body:
I have a model like this:

class CalendarEvent: Object, Mappable {

dynamic var exId = ""
@objc dynamic var title:String = ""
@objc dynamic var desc:String = ""
dynamic var fullDate = Date()
dynamic var date = ""
dynamic var time = ""
dynamic var location = ""
dynamic var subcategory:Subcategory?
dynamic var update = false
var participants = List<Participant>()
}

class Category:Object, Mappable{
dynamic var exId = ""
@objc dynamic var name="";
var subcategories = List<Subcategory>()
}

class Subcategory:Object, Mappable{
dynamic var exId = ""
dynamic var name = ""
let category = LinkingObjects(fromType: Category.self, property: "subcategories")
dynamic var active:Bool = true
dynamic var update = false
}

I need to know which CalendarEvents are from a category, when is from a subcategory I can do:

var results = realm.objects(CalendarEvent.self)
results = results.filter("ANY subcategory.exId == %@", subcategory!.exId)

But when I need to obtain the CalendarEvents filtered by category I don´t know how to do it. I looked after the solution but didn´t find anywhere. Please help!

Body:
For the record, I found the solution. It´s easy, you need to subdivide in queries and chain then using "IN". For example:

let resultsSubcategory = realm.objects(Subcategory.self).filter("ANY category.exId == %@", category?.exId)
        results = results.filter("subcategory IN %@", resultsSubcategory)