问:
How to have two password fields controlled by one checkbox?
```<code><form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
  document.write(
    '<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
    'Show the password as I type'
  );
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
  (kc >= 97 && kc <= 122 && sk) ||
  (kc >= 65 && kc <= 90 && !sk)
) {
  document.getElementById('capsalert').style.display = 'inline';
}
else {
  document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);

document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
</code>```

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

```<code><script>
function changeType()
{
    document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>

<body>
<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
</code>```

答:
I suggest changing your approach a bit.

You could modify the client with no impact to the server code. For example, I would try using 2 input boxes with the same name. If you ever have one box visible while the other one has the 'disabled' HTML attribute set, the visible box will always be the only one submitted.

This way, your server-side code would only have to look for 1 input, under a single name.

Body:
<form>
<fieldset>
Password: CAPS LOCK = on

<input type="password" id="pwd">

Password2:

<input type="password" id="pwd2">
</fieldset>
</form>

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>


来源: stackexchange

问:
How do websites keep the header on every page if the header is in html?
So, I'm trying to make a website, but the problem is I can't find the most effective way to keep the header on every single page. My header is HTML code, and it is the most important source of navigation on the website. The tabs navigate using links to other HTML files (all located locally on my computer) and so every single new page is another separate HTML file. Here are the many different methods I used that all fell short in one way or another:

The most basic way: Copying the header code to EVERY HTML page on the website.
 I am currently using this method, and it is probably the most ineffective and stupid method ever. The downside (which is pretty obvious) is that not only is it tedious but every time I make a change to the header (like maybe add different menus, add another tab, change the image, etc.) I have to copy the new header code to everything else. That is ridiculous!!

I tried using the w3schools method of implementing a separate HTML file (with only the HTML code) onto the page HTML files. So, I have this 1 HTML file for the header that every page uses so I make a change in that one file and it automatically applies to everything else. However, it didn't let me organize the numerous HTML files effectively because unlike referencing a stylesheet like some file named 'style.css', it doesn't let me put the HTML sheet in a folder that doesn't share the same parent folder as the referencing HTML page files. Hopefully that made sense, but basically, I couldn't get a folder that separated the HTML menu tab files ("pages") and the HTML content files ("posts") without the w3school code failing. Here's the link: https://www.w3schools.com/howto/howto_html_include.asp

I've seen other options on Stackoverflow, like getting around the "can't implement HTML files" by using js files with html code in a document.write(), but this to me is very hard to use because of all my progress so far. Also, I am very uncomfortable with the idea of using document.write because it is probably still very different from a true html file. Seriously, why is there no HTML implementing system that stylesheets and scripts have??? (script src="b.js" script and link rel="stylesheet" href="css/style.css" type="text/css")

Using jQuery. I understand this the least (being an amateur programmer) but I've heard it isn't consistent either. It doesn't seem to work on a local file, and that sounds like a nightmare. Though, if there are good suggestions, having a jquery file tag along seems not the best solution but still a plausible solution.

So, I'm in great trouble. How do other websites do this?  Do they use different files??? Do they use PHP files?? Am I going to have to scrap all my hard header HTML work and styling because PHP is another language??  Do I have to use Angular.js???  This is so complicated!

Hopefully, this question made some sense. Please ask if you have questions. Thanks in advance.

UPDATE
After checking numerous other posts on Stackoverflow suggesting PHP, I got my HTML files and then renamed it from "index.html" to "index.php", and holy macro it actually still behaved like an HTML file even if it wasn't!! Now I need to find a way to put:

```<code>    include("header.php");
</code>```

into my page PHP files that are actually in HTML code to reference a separate PHP file that has my header. How do I do that?  Does it belong in like script tags or something? How do I add PHP code in a PHP file written in HTML code? Thanks for the answers to my previous question, I'm so sorry I should've read the answers on Stackoverflow more thoroughly first.

答:
So I know it's been awhile since I asked the question and probably nobody cares anymore, but I just want to post an update after finding a solution to my question about using php code and how it all works.

First, I learned that in order for this to work, all my files had to be in php format. So I pulled up my folder of my local HTML files and literally just renamed it from something like "index.html" to "index.php". Then, without changing the HTML code, I opened it up in my browser and it was like nothing happened, except it was better!  Now it can not only read HTML and style and script codes, but also php codes as well!  I added:

```<code><?php
    include("header.php");
?>
</code>```

to the top of my index.php file, for example, and then converted the rest of the files into php format like I did for this. I copied over my header html and css code and saved it in a separate php file in the same folder, and - there was no header. I was confused. What?? Why is it not doing anything? The header.php itself is working, why is the include function not??

Then, I learned that this php include code can't be executed on my local drive, so it doesn't work on my local drive but works when it is public and on a real website hosting service. I then installed XAMPP, which is a commonly used PHP development environment that is an Apache distribution and is totally free. It runs a sort of local hosting service that will support this php code and cause it to execute the way I intended it to. I'm sorry I'm not good at explaining how this works, as I just find it and use it. Anyways, XAMPP did make the php code included above actually do its job and I finally got the header-system I always wanted. Happily ever after, right?

Nope. Now that fundamental stuff is gone, I have to face other problems like formatting (a real pain in the a** considering how I have to find css problems in tons and tons of overlapping code), creating an entire personal search system (having to figure out how to make a php file actually use my brand new MySQL database, which is also run by XAMPP), and lots of other things. But, that sounds like a great adventure that I am willing and definitely eager to go through. Now, finally I am done blabbing for the day...I wonder how many hours of other people's time I just wasted.

Oh yeah..I forgot to mention, happy Fourth of July! (and happy birthday to the beloved Captain America)

ContentLicense: CC BY-SA 3.0

Body:
So, I'm trying to make a website, but the problem is I can't find the most effective way to keep the header on every single page. My header is HTML code, and it is the most important source of navigation on the website. The tabs navigate using links to other HTML files (all located locally on my computer) and so every single new page is another separate HTML file. Here are the many different methods I used that all fell short in one way or another:

The most basic way: Copying the header code to EVERY HTML page on the website.
 I am currently using this method, and it is probably the most ineffective and stupid method ever. The downside (which is pretty obvious) is that not only is it tedious but every time I make a change to the header (like maybe add different menus, add another tab, change the image, etc.) I have to copy the new header code to everything else. That is ridiculous!!

I tried using the w3schools method of implementing a separate HTML file (with only the HTML code) onto the page HTML files. So, I have this 1 HTML file for the header that every page uses so I make a change in that one file and it automatically applies to everything else. However, it didn't let me organize the numerous HTML files effectively because unlike referencing a stylesheet like some file named 'style.css', it doesn't let me put the HTML sheet in a folder that doesn't share the same parent folder as the referencing HTML page files. Hopefully that made sense, but basically, I couldn't get a folder that separated the HTML menu tab files ("pages") and the HTML content files ("posts") without the w3school code failing. Here's the link: https://www.w3schools.com/howto/howto_html_include.asp

I've seen other options on Stackoverflow, like getting around the "can't implement HTML files" by using js files with html code in a document.write(), but this to me is very hard to use because of all my progress so far. Also, I am very uncomfortable with the idea of using document.write because it is probably still very different from a true html file. Seriously, why is there no HTML implementing system that stylesheets and scripts have??? (script src="b.js" script and link rel="stylesheet" href="css/style.css" type="text/css")

Using jQuery. I understand this the least (being an amateur programmer) but I've heard it isn't consistent either. It doesn't seem to work on a local file, and that sounds like a nightmare. Though, if there are good suggestions, having a jquery file tag along seems not the best solution but still a plausible solution.

So, I'm in great trouble. How do other websites do this?  Do they use different files??? Do they use PHP files?? Am I going to have to scrap all my hard header HTML work and styling because PHP is another language??  Do I have to use Angular.js???  This is so complicated!

Hopefully, this question made some sense. Please ask if you have questions. Thanks in advance.

UPDATE
After checking numerous other posts on Stackoverflow suggesting PHP, I got my HTML files and then renamed it from "index.html" to "index.php", and holy macro it actually still behaved like an HTML file even if it wasn't!! Now I need to find a way to put:

    include("header.php");

into my page PHP files that are actually in HTML code to reference a separate PHP file that has my header. How do I do that?  Does it belong in like script tags or something? How do I add PHP code in a PHP file written in HTML code? Thanks for the answers to my previous question, I'm so sorry I should've read the answers on Stackoverflow more thoroughly first.

Body:
So I know it's been awhile since I asked the question and probably nobody cares anymore, but I just want to post an update after finding a solution to my question about using php code and how it all works.

First, I learned that in order for this to work, all my files had to be in php format. So I pulled up my folder of my local HTML files and literally just renamed it from something like "index.html" to "index.php". Then, without changing the HTML code, I opened it up in my browser and it was like nothing happened, except it was better!  Now it can not only read HTML and style and script codes, but also php codes as well!  I added:

<?php
    include("header.php");
?>

to the top of my index.php file, for example, and then converted the rest of the files into php format like I did for this. I copied over my header html and css code and saved it in a separate php file in the same folder, and - there was no header. I was confused. What?? Why is it not doing anything? The header.php itself is working, why is the include function not??

Then, I learned that this php include code can't be executed on my local drive, so it doesn't work on my local drive but works when it is public and on a real website hosting service. I then installed XAMPP, which is a commonly used PHP development environment that is an Apache distribution and is totally free. It runs a sort of local hosting service that will support this php code and cause it to execute the way I intended it to. I'm sorry I'm not good at explaining how this works, as I just find it and use it. Anyways, XAMPP did make the php code included above actually do its job and I finally got the header-system I always wanted. Happily ever after, right?

Nope. Now that fundamental stuff is gone, I have to face other problems like formatting (a real pain in the a** considering how I have to find css problems in tons and tons of overlapping code), creating an entire personal search system (having to figure out how to make a php file actually use my brand new MySQL database, which is also run by XAMPP), and lots of other things. But, that sounds like a great adventure that I am willing and definitely eager to go through. Now, finally I am done blabbing for the day...I wonder how many hours of other people's time I just wasted.

Oh yeah..I forgot to mention, happy Fourth of July! (and happy birthday to the beloved Captain America)


问:
Chef Read File Pattern Matching
I have a text/xml file that contains the following data

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GovernmentPolicy>
    <name>Sample Policy</name>
    <description>Policy set during enrollment</description>
    <Resources>
        <ResourceID>7619f915-420d-4220-993e-1d3f1bee0ba4</ResourceID>
    </Resources>
<GovernmentPolicy>
</code>```

I wanted to read the following in my chef recipe so I have this. I wanted to get the value "7619f915-420d-4220-993e-1d3f1bee0ba4"
so I ran it thru my regexp. I am just not sure why I cannot match this.

```<code>ruby_block "Read GovernmentPolicy" do
  block do
    resourceID = ""
    governmentpolicies = "/temp/governmentpolicies.xml"
    if File.exists?("#{governmentpolicies}")
      f = File.open("#{governmentpolicies}", 'r')
      pattern = /^\<ResourceID\>/
      f.each {|line|
        if pattern.match(line)
            puts("***************MATCH FOUND*******************")
            puts line

        end
      }
      f.close
      end
  end
end
</code>```

Any hints?

答: Parsing XML using Regex is usually a bad idea. You might want to use a Ruby XML parser, like Nokogiri. </p>

Title: Chef Read File Pattern Matching

Body:
I have a text/xml file that contains the following data

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GovernmentPolicy>
    <name>Sample Policy</name>
    <description>Policy set during enrollment</description>
    <Resources>
        <ResourceID>7619f915-420d-4220-993e-1d3f1bee0ba4</ResourceID>
    </Resources>
<GovernmentPolicy>

I wanted to read the following in my chef recipe so I have this. I wanted to get the value "7619f915-420d-4220-993e-1d3f1bee0ba4"
so I ran it thru my regexp. I am just not sure why I cannot match this.

ruby_block "Read GovernmentPolicy" do
  block do
    resourceID = ""
    governmentpolicies = "/temp/governmentpolicies.xml"
    if File.exists?("#{governmentpolicies}")
      f = File.open("#{governmentpolicies}", 'r')
      pattern = /^\<ResourceID\>/
      f.each {|line|
        if pattern.match(line)
            puts("***************MATCH FOUND*******************")
            puts line

        end
      }
      f.close
      end
  end
end

Any hints?


问:
What's the STL way to fill a 2-dimensional std::array without iteration?
I have a 2-dimensional std::array of std::arrays and I want to fill it with 0s. The only solution to this that I found is to use a pointer to the first element and sizeof, like so:

```<code>std::fill(&arr2d[0][0], &arr2d[0][0] + sizeof(arr2d), 0);
</code>```

Although it works, it doesn't line up with other methods I've found for filling 1D std::arrays without pointer logic, like the following two:

```<code>std::fill(arr1d.begin(), arr1d.end(), 0);
arr1d.fill(0);
</code>```

I could iterate over each array, like so:

```<code>for (auto& it : arr2d) {
    it.fill(0);
}
</code>```

but it seems it would be much more efficient to fill the array in one pass. Is there a cleaner method for 2D arrays, or am I stuck with C-style pointer logic?

答:
In your case, simply assign (or initialize) with {}:

```<code>using arr2d_t = std::array<std::array<unsigned char, 32>, 64>;
arr2d_t arr2d = {}; // all zeroes

arr2d = {}; //ditto
</code>```

Body:
I have a 2-dimensional std::array of std::arrays and I want to fill it with 0s. The only solution to this that I found is to use a pointer to the first element and sizeof, like so:

std::fill(&arr2d[0][0], &arr2d[0][0] + sizeof(arr2d), 0);

Although it works, it doesn't line up with other methods I've found for filling 1D std::arrays without pointer logic, like the following two:

std::fill(arr1d.begin(), arr1d.end(), 0);
arr1d.fill(0);

I could iterate over each array, like so:

for (auto& it : arr2d) {
    it.fill(0);
}

but it seems it would be much more efficient to fill the array in one pass. Is there a cleaner method for 2D arrays, or am I stuck with C-style pointer logic?

Body:
In your case, simply assign (or initialize) with {}:

using arr2d_t = std::array<std::array<unsigned char, 32>, 64>;
arr2d_t arr2d = {}; // all zeroes

arr2d = {}; //ditto


问:
Chrome how to open popup in new window instead of new tab (20170629_chrome 59.0.3071.115)
Editted: For my probelm, not sure but I think hat this update of Google Chrome do not support many options for some specific browsers. So when we has them in specs param of window.open(), it omits all the height=h,width=w,left=x,top=y which make chrome open link in new window instead of new tab

For my program, now I only keep this and this solve the problem:

```<code>window.open(form_url, form_name, "width=w,height=h,left=x,top=y");
//our problem code below
//window.open(form_url, form_name, "width=w,height=h,left=x,top=y,resizable=yes,location=yes,scrollbars=yes");
</code>```

//End editted =================

Could someone help me in configuring Chrome so that popup will open in new window, instead of new tab? (Or any programmatically method for asp.net, c#)

It begin from today 2017/06/29, maybe newest update from chrome version 59.0.3071.115, and all popup in chrome would be opened in new tab instead of new window. This change our website behavior (our website use a main menu and others popup forms), and is very unexpected.

(Tested in some others site with ads popup, same behavior).

(Tested in Firefox: open popup in new window ok for all those sites, not new tab).

I have read changelog here but no mention about this change: chrome 59.0.3071.115

I have searched google, too, but got no luck, maybe because of my google skill, maybe because this is new change from Chrome so google can't find question about it?

Thank you for any help.

答:
I have the problem too. I fixed by change toolbar=no or remove toolbar feature.

```<code> window.open('http://google.com','x', 'height=600,width=600,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no')
</code>```

Body:
Editted: For my probelm, not sure but I think hat this update of Google Chrome do not support many options for some specific browsers. So when we has them in specs param of window.open(), it omits all the height=h,width=w,left=x,top=y which make chrome open link in new window instead of new tab

For my program, now I only keep this and this solve the problem:

window.open(form_url, form_name, "width=w,height=h,left=x,top=y");
//our problem code below
//window.open(form_url, form_name, "width=w,height=h,left=x,top=y,resizable=yes,location=yes,scrollbars=yes");

//End editted =================

Could someone help me in configuring Chrome so that popup will open in new window, instead of new tab? (Or any programmatically method for asp.net, c#)

It begin from today 2017/06/29, maybe newest update from chrome version 59.0.3071.115, and all popup in chrome would be opened in new tab instead of new window. This change our website behavior (our website use a main menu and others popup forms), and is very unexpected.

(Tested in some others site with ads popup, same behavior).

(Tested in Firefox: open popup in new window ok for all those sites, not new tab).

I have read changelog here but no mention about this change: chrome 59.0.3071.115

I have searched google, too, but got no luck, maybe because of my google skill, maybe because this is new change from Chrome so google can't find question about it?

Thank you for any help.

Body:
I have the problem too. I fixed by change toolbar=no or remove toolbar feature.

 window.open('http://google.com','x', 'height=600,width=600,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no')


问:
Visual studio 2015 tfs add files to source control
I have the following issue-

On Team Explorer - Pending Changes there is an option that automatically detects added files to folders that are under source control. The problem is that more than 50,000 files are detected.

Is there any way to edit this list? to remove items I don't care about so it will be relevant when I do have files I want to add?

(I know I can add items in the Source Control but I want to make this option usable)

答:
You can click the 'Detected' link to pop up the "Promote Candidate Changes" dialog, then select the files you want to check in to promote.

If you're using local workspaces, you can add a .tfignore file to ignore the files which you don't want to be detected in source control. eg: ignore by file extension .txt, then all the .txt files will be ignored in source control. They will not be detected.

Please see Customize which files are ignored by version control for details.

Please note that with TFVC you need to put .tfignore in every solution root.

.tfignore file rules The following rules apply to a .tfignore file:

# begins a comment line

The * and ? wildcards are supported.

A filespec is recursive unless prefixed by the \ character.

! negates a filespec (files that match the pattern are not ignored)

```<code>.tfignore file example

######################################
# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
#
# Ignore .txt files in this folder
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll
</code>```

Body:
You can click the 'Detected' link to pop up the "Promote Candidate Changes" dialog, then select the files you want to check in to promote.

If you're using local workspaces, you can add a .tfignore file to ignore the files which you don't want to be detected in source control. eg: ignore by file extension .txt, then all the .txt files will be ignored in source control. They will not be detected.

Please see Customize which files are ignored by version control for details.

Please note that with TFVC you need to put .tfignore in every solution root.

.tfignore file rules The following rules apply to a .tfignore file:

# begins a comment line

The * and ? wildcards are supported.

A filespec is recursive unless prefixed by the \ character.

! negates a filespec (files that match the pattern are not ignored)

.tfignore file example

######################################
# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
#
# Ignore .txt files in this folder
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll


问:
How to setup Akka Cluster in multiple machine?
I have looked into offical Akka documentation and I confuse. I follow this link and I used the same application.conf as like that and change the seed-node into my another machine ip.

```<code>akka {

actor.provider = "akka.cluster.ClusterActorRefProvider"

remote.netty.tcp.port=0
remote.netty.tcp.hostname=127.0.0.1

cluster {
seed-nodes = [
  "akka.tcp://ClusterSystem@slave01:2551",
  "akka.tcp://ClusterSystem@slave02:2552"]

auto-down-unreachable-after = 10s
}

extensions = ["akka.cluster.client.ClusterClientReceptionist"]

persistence {
journal.plugin = "akka.persistence.journal.leveldb-shared"
journal.leveldb-shared.store {
  # DO NOT USE 'native = off' IN PRODUCTION !!!
  native = off
  dir = "target/shared-journal"
}
snapshot-store.plugin = "akka.persistence.snapshot-store.local"
snapshot-store.local.dir = "target/snapshots"
}

}
</code>```

The problem is that it's said it's unreachable and connection refused. Any suggestion?

答: Have you made sure connection isn't blocked by firewall on the two hosts?  I would first check whether both slave01 and slave02 are remotely reachable using telnet at their corresponding port (e.g. telnet slave02 2552).  And in case slave01 and slave02 are hostnames or FQDN, they would need to be mapped to corresponding IP addresses in /etc/hosts or DNS, accordingly.

Body:
I have looked into offical Akka documentation and I confuse. I follow this link and I used the same application.conf as like that and change the seed-node into my another machine ip.

akka {

actor.provider = "akka.cluster.ClusterActorRefProvider"

remote.netty.tcp.port=0
remote.netty.tcp.hostname=127.0.0.1

cluster {
seed-nodes = [
  "akka.tcp://ClusterSystem@slave01:2551",
  "akka.tcp://ClusterSystem@slave02:2552"]

auto-down-unreachable-after = 10s
}

extensions = ["akka.cluster.client.ClusterClientReceptionist"]

persistence {
journal.plugin = "akka.persistence.journal.leveldb-shared"
journal.leveldb-shared.store {
  # DO NOT USE 'native = off' IN PRODUCTION !!!
  native = off
  dir = "target/shared-journal"
}
snapshot-store.plugin = "akka.persistence.snapshot-store.local"
snapshot-store.local.dir = "target/snapshots"
}

}

The problem is that it's said it's unreachable and connection refused. Any suggestion?


问:
updating a fragment from activity during runtime, view variable not global
I have a tab page with 3 fragments. I have a spinner on the page. When a user selects a value from the spinner, the 3 fragments are updated with mysql data. I am having a problem with the OnCreateView, I am inflating the layout, and returning the view, but after returned to the mainactivity, the "global" view variable is cleared and when I try to update the textboxes, I get a NPE due to the view variable being null.

```<code>public class TabFragment1 extends Fragment {

public TabFragment1() {

    // Required empty public constructor
}

View loadInflatedView;
TextView txtLoadNumber,txtAddlStops;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    loadInflatedView = inflater.inflate(R.layout.tab_fragment_1, container, false);
    return loadInflatedView;
}

public void updateFragment1(Integer LoadNumber, Integer AddlStops){

    txtLoadNumber = (TextView) loadInflatedView.findViewById(R.id.textViewLoadNumber);
    txtAddlStops = (TextView) loadInflatedView.findViewById(R.id.textViewAddlStops);

    //Log.d(TAG, "Update Dashboard Location");
    txtLoadNumber.setText(LoadNumber);
    txtAddlStops.setText(AddlStops);
}
</code>```

and my activity

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loads_tabbed);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Load"));
    tabLayout.addTab(tabLayout.newTab().setText("Shipper"));
    tabLayout.addTab(tabLayout.newTab().setText("Consignee"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setOffscreenPageLimit(4);
    final PagerAdapter adapter = new com.jrs.loadmanager.PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
</code>```

...

//this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {

```<code>    final Integer LoadNumber = parseInt( parent.getItemAtPosition(position).toString());

    Cursor res = myDb.getLoadData(LoadNumber);
    ShortcutBadger.removeCount(getApplicationContext());
    session = new SessionManager(getApplicationContext());

    if (res.moveToFirst()) {

        Integer txtLoad = parseInt(res.getString(res.getColumnIndex(Config.TAG_LOADNUMBER)));
        Integer txtStop = parseInt(res.getString(res.getColumnIndex(Config.TAG_ADDSTOPS)));
        TabFragment1 FragVar = new TabFragment1();
        FragVar.updateFragment1(txtLoad,txtStop);
</code>```

loadInflatedView is set when the OnCreateView is executed, but is null when I try to call loadInflatedView.findViewById(R.id.textViewLoadNumber);

I have searched and searched and cannot find a solution as to why this variable is clearing.

here is fatal error message:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jrs.loadmanager, PID: 11045
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.jrs.loadmanager.TabFragment1.updateFragment1(TabFragment1.java:54)
at com.jrs.loadmanager.LoadsActivity.onItemSelected(LoadsActivity.java:426)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
I think the problem is your fragment has been destroyed. As the memory manager already had destroyed your fragment. So the solution could be

1.) You can add a fragment instead of replacing it.
Like -

```<code>fragmentTransaction.add(R.id.Main, homeFragment, "Home");
</code>```

2.) You can save fragment instance in

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("tag", TAG);
}
</code>```

and restore it from

```<code>@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState)
    someVarB = savedInstanceState.getString("tag");
}
</code>```

Just make sure you've provided a tag to your view in the xml layout.

3.) If you are using a View Pager along with tab layout the you could try this.

```<code>mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(4);
</code>```

4.) If you are using ViewPager then try this one

```<code>ViewPager pager = /* get my ViewPager */;
</code>```

assume this actually has stuff in it

```<code>FragmentManager fm = getSupportFragmentManager();

pager.setAdapter(new FragmentStatePagerAdapter(fm) {
public int getCount() {
    return titles.size();
}

public Fragment getItem(int position) {
    MyFragment fragment = new MyFragment();
    fragment.setTitle(titles.get(position));
    return fragment;
}

public int getItemPosition(Object item) {
    MyFragment fragment = (MyFragment)item;
    String title = fragment.getTitle();
    int position = titles.indexOf(title);

    if (position >= 0) {
        return position;
    } else {
        return POSITION_NONE;
    }
}
</code>```

});

and you have to put this in the main activity or where your tab layout and view pager is.

Body:
I have a tab page with 3 fragments. I have a spinner on the page. When a user selects a value from the spinner, the 3 fragments are updated with mysql data. I am having a problem with the OnCreateView, I am inflating the layout, and returning the view, but after returned to the mainactivity, the "global" view variable is cleared and when I try to update the textboxes, I get a NPE due to the view variable being null.

public class TabFragment1 extends Fragment {

public TabFragment1() {

    // Required empty public constructor
}

View loadInflatedView;
TextView txtLoadNumber,txtAddlStops;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    loadInflatedView = inflater.inflate(R.layout.tab_fragment_1, container, false);
    return loadInflatedView;
}

public void updateFragment1(Integer LoadNumber, Integer AddlStops){

    txtLoadNumber = (TextView) loadInflatedView.findViewById(R.id.textViewLoadNumber);
    txtAddlStops = (TextView) loadInflatedView.findViewById(R.id.textViewAddlStops);

    //Log.d(TAG, "Update Dashboard Location");
    txtLoadNumber.setText(LoadNumber);
    txtAddlStops.setText(AddlStops);
}

and my activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loads_tabbed);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Load"));
    tabLayout.addTab(tabLayout.newTab().setText("Shipper"));
    tabLayout.addTab(tabLayout.newTab().setText("Consignee"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setOffscreenPageLimit(4);
    final PagerAdapter adapter = new com.jrs.loadmanager.PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

...

//this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {

    final Integer LoadNumber = parseInt( parent.getItemAtPosition(position).toString());

    Cursor res = myDb.getLoadData(LoadNumber);
    ShortcutBadger.removeCount(getApplicationContext());
    session = new SessionManager(getApplicationContext());

    if (res.moveToFirst()) {

        Integer txtLoad = parseInt(res.getString(res.getColumnIndex(Config.TAG_LOADNUMBER)));
        Integer txtStop = parseInt(res.getString(res.getColumnIndex(Config.TAG_ADDSTOPS)));
        TabFragment1 FragVar = new TabFragment1();
        FragVar.updateFragment1(txtLoad,txtStop);

loadInflatedView is set when the OnCreateView is executed, but is null when I try to call loadInflatedView.findViewById(R.id.textViewLoadNumber);

I have searched and searched and cannot find a solution as to why this variable is clearing.

here is fatal error message:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jrs.loadmanager, PID: 11045
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.jrs.loadmanager.TabFragment1.updateFragment1(TabFragment1.java:54)
at com.jrs.loadmanager.LoadsActivity.onItemSelected(LoadsActivity.java:426)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
I think the problem is your fragment has been destroyed. As the memory manager already had destroyed your fragment. So the solution could be

1.) You can add a fragment instead of replacing it.
Like -

fragmentTransaction.add(R.id.Main, homeFragment, "Home");

2.) You can save fragment instance in

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("tag", TAG);
}

and restore it from

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState)
    someVarB = savedInstanceState.getString("tag");
}

Just make sure you've provided a tag to your view in the xml layout.

3.) If you are using a View Pager along with tab layout the you could try this.

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(4);

4.) If you are using ViewPager then try this one

ViewPager pager = /* get my ViewPager */;

assume this actually has stuff in it

FragmentManager fm = getSupportFragmentManager();

pager.setAdapter(new FragmentStatePagerAdapter(fm) {
public int getCount() {
    return titles.size();
}

public Fragment getItem(int position) {
    MyFragment fragment = new MyFragment();
    fragment.setTitle(titles.get(position));
    return fragment;
}

public int getItemPosition(Object item) {
    MyFragment fragment = (MyFragment)item;
    String title = fragment.getTitle();
    int position = titles.indexOf(title);

    if (position >= 0) {
        return position;
    } else {
        return POSITION_NONE;
    }
}

});

and you have to put this in the main activity or where your tab layout and view pager is.


问:
PowerShell - using an objects variable for -Filter
I'm at a loss as to why this isn't working, and what to even search for.

I have a simple function Get-FileInput. It simply calls Import-CSV and checks for a specific column before passing on the data.

I have $filterType = "Name"

My test TSV is in the format

db stuff   Name
1   2   spare40

Then I have this

```<code>$data = Get-FileInput
foreach ($computer in $data)
{
    Get-ADComputer -Filter {$filterType -eq "comp1"} | Format-Table
    Write-Host "$($computer.$filterType)"
    Get-ADComputer -Filter {$filterType -eq "$($computer.$filterType)"} | Format-Table
}
</code>```

The first Get-ADComputer works fine and outputs a table.

The Write-Host produces the output comp1 in the terminal.

The second Get-ADComputer runs, but does not output anything.

答:
Do not use a script block ({...}) as the -Filter argument - it works in simple cases (e.g., {$filterType -eq "comp1"}) but falls apart in more complex ones ({$filterType -eq "$($computer.$filterType)"}).

The -Filter argument is of type [string], and you should construct it as such:

```<code>Get-ADComputer -Filter "$filterType -eq '$($computer.$filterType)'" | Format-Table
</code>```

For background information, see this answer of mine.

Body:
I'm at a loss as to why this isn't working, and what to even search for.

I have a simple function Get-FileInput. It simply calls Import-CSV and checks for a specific column before passing on the data.

I have $filterType = "Name"

My test TSV is in the format

db stuff   Name
1   2   spare40

Then I have this

$data = Get-FileInput
foreach ($computer in $data)
{
    Get-ADComputer -Filter {$filterType -eq "comp1"} | Format-Table
    Write-Host "$($computer.$filterType)"
    Get-ADComputer -Filter {$filterType -eq "$($computer.$filterType)"} | Format-Table
}

The first Get-ADComputer works fine and outputs a table.

The Write-Host produces the output comp1 in the terminal.

The second Get-ADComputer runs, but does not output anything.

Body:
Do not use a script block ({...}) as the -Filter argument - it works in simple cases (e.g., {$filterType -eq "comp1"}) but falls apart in more complex ones ({$filterType -eq "$($computer.$filterType)"}).

The -Filter argument is of type [string], and you should construct it as such:

Get-ADComputer -Filter "$filterType -eq '$($computer.$filterType)'" | Format-Table

For background information, see this answer of mine.


问:
POST arrays not showing unchecked Checkboxes
Having trouble getting my POST arrays to show all checkbox values from my form.

I have a form set up as follows:

```<code><form name='foo' method='post' action=''>
    <table>
       <tr>
          <td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
      </tr>
       <tr>
          <td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
      </tr>
       <tr>
          <td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
      </tr>
   </table>
</form>
</code>```

I have a button at the bottom bound to a jquery function that adds 5 more empty rows to the form (hence the arrays for the input name cBox[]).

Now, the problem. Lets say the first checkbox is unchecked, and the last 2 are checked. When I output the values (using PHP print_r for debugging), I will get:

```<code>Array ( [0] => on [1] => on)
</code>```

For some reason, the array does not contain any value for unchecked checkboxes.

I have seen some solutions where a hidden variable is passed with each checkbox, but can this solution be implemented in my situation (using arrays)?

答:
If you are handling dynamic checkbox array, you can try this:

HTML:

```<code><label>
  <input type="hidden" name="cBox[]" value="" />
  <input type="checkbox" class="checkbox" value="on" />
</label>
<label>
  <input type="hidden" name="cBox[]" value="" />
  <input type="checkbox" class="checkbox" value="on" />
</label>
<!-- extend -->
</code>```

Javascript (jQuery):

```<code>$(document).on("change", "input.checkbox", function() {

    var value = $(this).is(":checked") ? $(this).val() : null;

    $(this).siblings("input[name='cBox[]']").val(value);
});
</code>```

Backend result (If only checked the second one):

```<code>// PHP $_POST['cBox']
Array
(
    [0] =>
    [1] => on
)
</code>```

In this implement, the checkboxes are used to controller each hidden input in a group.

For displaying page, You can render each inputs pair back by assigning the value into hidden inputs and marking checkboxes as checked.

Body:
Having trouble getting my POST arrays to show all checkbox values from my form.

I have a form set up as follows:

<form name='foo' method='post' action=''>

          Checkbox: <input type='checkbox' name='cBox[]'/>

          Checkbox: <input type='checkbox' name='cBox[]'/>

          Checkbox: <input type='checkbox' name='cBox[]'/>

</form>

I have a button at the bottom bound to a jquery function that adds 5 more empty rows to the form (hence the arrays for the input name cBox[]).

Now, the problem. Lets say the first checkbox is unchecked, and the last 2 are checked. When I output the values (using PHP print_r for debugging), I will get:

Array ( [0] => on [1] => on)

For some reason, the array does not contain any value for unchecked checkboxes.

I have seen some solutions where a hidden variable is passed with each checkbox, but can this solution be implemented in my situation (using arrays)?

Body:
If you are handling dynamic checkbox array, you can try this:

HTML:

<label>
  <input type="hidden" name="cBox[]" value="" />
  <input type="checkbox" class="checkbox" value="on" />
</label>
<label>
  <input type="hidden" name="cBox[]" value="" />
  <input type="checkbox" class="checkbox" value="on" />
</label>
<!-- extend -->

Javascript (jQuery):

$(document).on("change", "input.checkbox", function() {

    var value = $(this).is(":checked") ? $(this).val() : null;

    $(this).siblings("input[name='cBox[]']").val(value);
});

Backend result (If only checked the second one):

// PHP $_POST['cBox']
Array
(
    [0] =>
    [1] => on
)

In this implement, the checkboxes are used to controller each hidden input in a group.

For displaying page, You can render each inputs pair back by assigning the value into hidden inputs and marking checkboxes as checked.


问:
ng-click not firing even I registered the function in controller
Hi I am working on an app and get the problem. I checked console but no error messages.

I created a component and I insert it into other template. Template itself is working(button is rendered and I inspected the element ng-click attribute is there) but when I click on the button. the function is not fired.

The project is availiable here: https://github.com/Aozaki-Touko/webApplication-dota2hero/tree/master/app

navbar.component.js:

```<code>"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self=this;
      self.changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});
</code>```

navbar.template.html:

```<code><button type="button" ng-click="$ctrl.changePathToHeroes()">Heroes</button>
</code>```

navbar.module.js:

```<code>"use strict";

angular.module("navbar",[]);
</code>```

答:
This is working for me.
It seems to me that was a problem with the function name.

"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self = this;
      function changePathToHeroes(){
        alert("Button Pressedddddd!");
        $location.path("/heroes");
      }
      self.changePathToHeroes = changePathToHeroes;
    }
  ]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" ng-click="$ctrl.changePathToHeroes();">Heroes</button></code>```

Body:
Hi I am working on an app and get the problem. I checked console but no error messages.

I created a component and I insert it into other template. Template itself is working(button is rendered and I inspected the element ng-click attribute is there) but when I click on the button. the function is not fired.

The project is availiable here: https://github.com/Aozaki-Touko/webApplication-dota2hero/tree/master/app

navbar.component.js:

"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self=this;
      self.changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});

navbar.template.html:

<button type="button" ng-click="$ctrl.changePathToHeroes()">Heroes</button>

navbar.module.js:

"use strict";

angular.module("navbar",[]);

Body:
This is working for me.
It seems to me that was a problem with the function name.

"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self = this;
      function changePathToHeroes(){
        alert("Button Pressedddddd!");
        $location.path("/heroes");
      }
      self.changePathToHeroes = changePathToHeroes;
    }
  ]
});

<button type="button" ng-click="$ctrl.changePathToHeroes();">Heroes</button>


问:
PHP files and folder structure showing, need to hide it
I have the following folder structure:

```<code>+users
   -adduser.php
   -viewuser.php
</code>```

When a visitor navigates to example.com/users it's showing the folder structure. I need to restrict visitors ability to see the file listing, either by hiding it or removing it. How can I do that in php?

答: If you don't want to (or can't) deal with Apache configuration, create an empty file named index.html (or index.php if you prefer) in your users folder.</p>

Body:
I have the following folder structure:

+users
   -adduser.php
   -viewuser.php

When a visitor navigates to example.com/users it's showing the folder structure. I need to restrict visitors ability to see the file listing, either by hiding it or removing it. How can I do that in php?


问:
how can access the age field of parent's parent in class C?
I teach some students.

How I can access A class's attribute age?

```<code>class A {
    protected int age;
    public A(int age){
        this.age = age+2;
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }
}
class C extends B{
    protected int age;
    public C(int age){
        super(age);
        this.age = age;
    }
    public void showInfo(){
//      System.out.println(A.this.age);
        System.out.println(super.age);
        System.out.println(this.age);
    }
}
</code>```

答:
With Following code , you can achieve.</p>

```<code>class A{
    protected int age;
    public A(int age){
        this.age = age+2;
    }

    public void showInfo()
    {
        System.out.println("A : " +  this.age);
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }

    public void showInfo()
    {
        super.showInfo();
        System.out.println("B : " +  this.age);
    }
}
class C extends B{
    protected int age;
    public C(int age)
    {
        super(age);
        this.age = age;
    }
    public void showInfo()
    {
        super.showInfo();
        System.out.println("C : " +  this.age);
    }
}
</code>```

Body:
I teach some students.

How I can access A class's attribute age?

class A {
    protected int age;
    public A(int age){
        this.age = age+2;
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }
}
class C extends B{
    protected int age;
    public C(int age){
        super(age);
        this.age = age;
    }
    public void showInfo(){
//      System.out.println(A.this.age);
        System.out.println(super.age);
        System.out.println(this.age);
    }
}

Body:
With Following code , you can achieve.

class A{
    protected int age;
    public A(int age){
        this.age = age+2;
    }

    public void showInfo()
    {
        System.out.println("A : " +  this.age);
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }

    public void showInfo()
    {
        super.showInfo();
        System.out.println("B : " +  this.age);
    }
}
class C extends B{
    protected int age;
    public C(int age)
    {
        super(age);
        this.age = age;
    }
    public void showInfo()
    {
        super.showInfo();
        System.out.println("C : " +  this.age);
    }
}


问:
How to extract all text under the same tag using XPath?
```<code><span rel="v:addr">
<span property="v:region">
  <a href="https://tabelog.com/en/tokyo/">
    123
  </a>
</span>
<span property="v:locality">
  <a href="https://tabelog.com/en/tokyo/A1317/A131710/rstLst/">
    456
  </a>
    <a href="https://tabelog.com/en/rstLst/">
      789
    </a>
  10
</span>
<span property="v:street-address">

</span>
</span>
</code>```

I want to extract the text inside the span tag without any space and make it as a one single string at the end.

I want this result:

```<code>12345678910
</code>```

This is my code below:

```<code>'AddressLocalityJap':"".join(response.xpath('normalize-space(//*[@id="anchor-rd-detail"]/section[1]/table/tbody/tr[4]/td/p[2]/span/span[2]//text()').extract())
</code>```

答:
Pure XPath 1.0 solution

This XPath,

```<code>translate(string(normalize-space()), ' ', '')
</code>```

will return

```<code>12345678910
</code>```

for your HTML, as requested.

Body:
    123

    456

      789

  10

I want to extract the text inside the span tag without any space and make it as a one single string at the end.

I want this result:

12345678910

This is my code below:

'AddressLocalityJap':"".join(response.xpath('normalize-space(//*[@id="anchor-rd-detail"]/section[1]/table/tbody/tr[4]/td/p[2]/span/span[2]//text()').extract())

Body:
Pure XPath 1.0 solution

This XPath,

translate(string(normalize-space()), ' ', '')

will return

12345678910

for your HTML, as requested.


问:
Extract one or more qualifying substrings from each string in an array
I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more.  I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

```<code>public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '<br>';
    }
}
</code>```

Assume that my $map array contains this:

```<code>$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];
</code>```

Desired result:

```<code>[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]
</code>```

答:
Try this:

```<code>echo $array[0][3]; //BBP160800103
echo $array[2][1]; //BBP160500010
</code>```

Etc. Refer to the indexing by number. You'd be better off creating your array with named indexes. Like this:

```<code>$array = array("Array1"=>array("key1"=>"val1","key2"=>"val2"),"Array2"=>(array("2ndKey1"=>"val1", "2ndKey2"=>"val2));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more.  I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '
';
    }
}

Assume that my $map array contains this:

$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];

Desired result:

[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]

Body:
Try this:

echo $array[0][3]; //BBP160800103
echo $array[2][1]; //BBP160500010

Etc. Refer to the indexing by number. You'd be better off creating your array with named indexes. Like this:

$array = array("Array1"=>array("key1"=>"val1","key2"=>"val2"),"Array2"=>(array("2ndKey1"=>"val1", "2ndKey2"=>"val2));


问:
LocalStorage TextBox's in JSON
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

```<code>{"website": "value","behance": "value","dribbble": "value"}
</code>```

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="uk-nav uk-nav-default" data-social="links">
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: world"></span>
      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: behance"></span>
      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: dribbble"></span>
      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

  </li>
</ul></code>```

答:
When the page loads, loop through the properties in the JSON you retrieve from localStorage and set the values of the corresponding inputs:

```<code>$(document).ready(function() {
    var json = localStorage.getItem("socialValues") || "{}";
    var savedData = JSON.parse(json);
    $.each(savedData, function(key, value) {
        $("#" + key).val(value);
    });
})
</code>```

Title: LocalStorage TextBox's in JSON

Body:
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

{"website": "value","behance": "value","dribbble": "value"}

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});

      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

Body:
When the page loads, loop through the properties in the JSON you retrieve from localStorage and set the values of the corresponding inputs:

$(document).ready(function() {
    var json = localStorage.getItem("socialValues") || "{}";
    var savedData = JSON.parse(json);
    $.each(savedData, function(key, value) {
        $("#" + key).val(value);
    });
})


问:
How to properly initialize interface in Activity?
I have this interface:

```<code>public interface SomeInterface {

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

I am trying to initialize it in Main activity and I am trying to "send it" to second activity:

```<code>private SomeInterface someInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}
</code>```

I implemented interface into second activity.

```<code>public class SecondActivity extends Activity implements SomeInterface  {

    @Override
    public void doSomething() {

    }
}
</code>```

But this is not working, I am getting follwing error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name/package.name.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to package.name.AppInterface
</code>```

What I am doing wrong? Thank you in advance.

答:
I will take what you wanna do is to once doSomething in first activity changed, you second activity would recognize it.

Then you could try this

```<code>public Interface SomeInterface
{
   void doSomething(); // here you may pass in some para maybe you want to use it to communicate with other activties
}
</code>```

then in the first activity you get the instance of the interface

```<code> public class FirstActivity extends AppCompatActivity
 {
    SomeInterface someInterface;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}
}
</code>```

In the second activity implement the interface

```<code>public void SecondActivity implements SomeInterface
{
   @Override
   public void doSomething()
   {
      // here it will run once doSomething is called in first activity,and if the interface in first activity has params, it would be passed here
   }
}
</code>```

Body:
I have this interface:

public interface SomeInterface {

    void doSomething();
}

I am trying to initialize it in Main activity and I am trying to "send it" to second activity:

private SomeInterface someInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}

I implemented interface into second activity.

public class SecondActivity extends Activity implements SomeInterface  {

    @Override
    public void doSomething() {

    }
}

But this is not working, I am getting follwing error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name/package.name.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to package.name.AppInterface

What I am doing wrong? Thank you in advance.

Body:
I will take what you wanna do is to once doSomething in first activity changed, you second activity would recognize it.

Then you could try this

public Interface SomeInterface
{
   void doSomething(); // here you may pass in some para maybe you want to use it to communicate with other activties
}

then in the first activity you get the instance of the interface

 public class FirstActivity extends AppCompatActivity
 {
    SomeInterface someInterface;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}
}

In the second activity implement the interface

public void SecondActivity implements SomeInterface
{
   @Override
   public void doSomething()
   {
      // here it will run once doSomething is called in first activity,and if the interface in first activity has params, it would be passed here
   }
}


问:
Visual Studio crashes consistently on web-related projects

I have a brand new VS2010 installed on a Win2008R2 machine.

I started getting this error when debugging a WCF service project:

"Attempted to read or write protected
  memory. This is often an indication
  that other memory is corrupt."

When I started developing a web site a week later, this became consistent - I can't debug it.
The stack dump reads:

at
  Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Connection
  conn)    at
  Microsoft.VisualStudio.WebHost.Server.OnSocketAccept(Object
  acceptedSocket)    at
  System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
  state)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback
  callback, Object state, Boolean
  ignoreSyncCtx)    at
  System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
  at
  System.Threading.ThreadPoolWorkQueue.Dispatch()
  at
  System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

I tried searching online, and some recommend turning off the "Suppress JIT Optimizations" in the Debugging options - this dos not seem to make a difference.

Clearly the problem is with the built in web server. But am I doing something wrong? Is there something I can do? Or is this a known bug?

Thanks for your time,

Guy

Update 12/31: Today I tried using CassiniDev as a replacement to the original VS2010 WebServer - exact same result. My suspicion is that there's some internal conflict between VS2010, Windows Server 2008R2 and maybe the fact that it's a 64 bit OS. I switched to using IIS as my debug server - and that seems to work, with some annoying side effects.

My conclusion: do not use a 64 bit server system as your dev machine. Develop on 32bit - deploy to 64bit.

Side conclusion: there are some scenarios Microsoft's QA doesn't test.

答:
Installing .Net Framework 3.5 fixed this exact problem for me.

Hope that helps! Sorry I can't offer any additional insight as to what exactly was going wrong with cassini, but I suspect it was missing a library or two.

====

Update:
Seems to have helped (no longer crashes on the first request), but upon further use I've come across another place where the same error crops up.)

====

Update:
And now I can't recreated it anymore. Best of luck, and if you discover any more please post!

ContentLicense: CC BY-SA 2.5


问:
initialDelayString = "#{T(java.lang.Math.random()) * 300000}"
I’m changing the delay of launching the process with

```<code>@Scheduled(fixedDelay = 300000, initialDelayString = "#{T(java.lang.Math.random()) * 300000}").
</code>```

But When I run the server it generates this error "- cannot parse into integer" although I need the solution for the “initialDelayString” to do the random

答:
i change SPEL to #{new Double((T(Math).random() * 30000)).intValue()} and it works for me
note i changed the delay 300,000 to 30,000 :-D
results in my eclipse(debuuger mode to see the running conditions) are detailly below:

step into the initDelayString calculate in org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled(Scheduled scheduled, Method method, Object bean), this run get 23601 millsecs

jump the breakpoint and let the app goes, sees the console output ,the red area is the tick app started [11:49:37], and the green area is the task start after initialDelayString's value (see step 1) 23601 millsecs[11:50:00], and the yellow area is the output with fixrate by 5000 millsecs [11:50:05, 11:51:10 ...]
[]2

by the way, the code of app i ran could be find in the spring Scheduling Tasks guide, it just a simple demo, hope it will help you!

Body:
I’m changing the delay of launching the process with

@Scheduled(fixedDelay = 300000, initialDelayString = "#{T(java.lang.Math.random()) * 300000}").

But When I run the server it generates this error "- cannot parse into integer" although I need the solution for the “initialDelayString” to do the random


问:
Implementing Non blocking thread safe singleton logging class
I want to write a logger class which writes output to a log file based on user actions. I have written a logmessage class for this purpose. Following is what I have.

```<code>public class LogMessage
{
    private  static Object padlock = new Object();
    private static string serviceDirectory ="C:\\MySite\\";
    private static string filePath = "\\Logs\\Combined\\ActivityMonitorLog-" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".log";

    private static volatile LogMessage instance = new LogMessage();
    public static LogMessage Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                        instance = new LogMessage();
                }
            }

            return instance;
        }
    }

    public void SaveLogMessage(string userName, string message, string stackTrace)
    {
        lock (padlock)
        {
            using (StreamWriter logWriter =
                new StreamWriter(serviceDirectory + filePath, true))
            {
                string logMessage = "";
                if (!string.IsNullOrEmpty(stackTrace))
                    logMessage = string.Format("{0} >> user : {1} ::: {2} ::: stack trace ::: {3}", DateTime.Now.ToString(), userName, message,stackTrace);
                else
                    logMessage = string.Format("{0} >> user : {1} ::: {2}", DateTime.Now.ToString(), userName, message);

                logWriter.WriteLine(logMessage);

            }
        }
    }
}
</code>```

And when i want do a log entry I am calling the about method like below

```<code>LogMessage.Instance.SaveLogMessage("My User", "Enter Logout PageLoad : Current Method :" + "Page_Load @ Logout.aspx.cs", "");
</code>```

I believe I have got the singleton part and thread safety achieved. But I don't think this is non blocking as multiple users are logged in at the same time each one will have to wait until the file is available to be written. I am pondering about using a backgroundworker to call this SaveLogMessage() from the LogMessage singleton object. Is that the correct way of doing it?

UPDATE

I have implemented this using backgroundworker and the complete class and how to call is mentioned in the answers. Thanks for inputs @bret and @huan

答:
In the end I have managed to achieve a non-blocking, thread safe,singleton logging class with the use of a background worker. I am submitting my solution in case someone find it useful someday.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Configuration;
/// <summary>
/// Summary description for LogMessage
/// </summary>
public class LogMessage
{
    static ReaderWriterLock locker = new ReaderWriterLock();

    private static string serviceDirectory = HttpContext.Current != null ?
        AppDomain.CurrentDomain.BaseDirectory :
        Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    private static string fullpath = serviceDirectory + "\\ActivityLog.log";
    private static readonly LogMessage instance = new LogMessage();

    public static LogMessage Instance
    {
        get { return instance; }
    }

    public void SaveLogMessage(string userName, string message, string stackTrace, bool inOut)
    {
        bool EnableActivityLogging = false;

        if (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["EnableActivityLogging"]))
            return;

        EnableActivityLogging = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableActivityLogging"]);

        if (!EnableActivityLogging)
            return;

        BackgroundWorker logbw = new BackgroundWorker();
        logbw.DoWork += logbw_DoWork;
        logbw.RunWorkerCompleted += logbw_RunWorkerCompleted;

        List<string> paramList = new List<string>();
        paramList.Add(userName);
        paramList.Add(message);
        paramList.Add(stackTrace);
        paramList.Add(inOut.ToString());

        if (!logbw.IsBusy)
        {
            logbw.RunWorkerAsync(paramList);
        }
    }

    void logbw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Debug.Write("Log Message Background Worker is now free...");
    }

    void logbw_DoWork(object sender, DoWorkEventArgs e)
    {
        List<string> paramList = (List<string>)e.Argument;
        string userName = paramList[0].ToString();
        string message = paramList[1].ToString();
        string stackTrace = paramList[2].ToString();
        bool inOut = bool.Parse(paramList[3].ToString());

        try
        {
            locker.AcquireWriterLock(int.MaxValue);
            using (StreamWriter logWriter =
                new StreamWriter(fullpath, true))
            {
                string logMessage = "";
                if (!string.IsNullOrEmpty(stackTrace))
                {
                    if (inOut)//IN
                    {
                        logMessage = string.Format("{0} U:{1} IN:{2} E:{3}", DateTime.Now.ToString(), userName, message, stackTrace);
                    }
                    else//OUT
                    {
                        logMessage = string.Format("{0} U:{1} OUT:{2} E:{3}", DateTime.Now.ToString(), userName, message, stackTrace);
                    }
                }
                else
                {
                    if (inOut)//IN
                    {
                        logMessage = string.Format("{0} U:{1} IN:{2}", DateTime.Now.ToString(), userName, message);
                    }
                    else//OUT
                    {
                        logMessage = string.Format("{0} U:{1} OUT:{2}", DateTime.Now.ToString(), userName, message);
                    }
                }

                logWriter.WriteLine(logMessage);

            }
        }
        finally
        {
            locker.ReleaseWriterLock();
        }
    }

}
</code>```

Now I can use this singleton object like below to save a log entry

```<code>    LogMessage.Instance.SaveLogMessage(Context.User.Identity.Name, "Custom Message" + " M:" + MethodInfo.GetCurrentMethod().Name + "@" + Path.GetFileName(Page.AppRelativeVirtualPath), "", true);
</code>```

Body:
I want to write a logger class which writes output to a log file based on user actions. I have written a logmessage class for this purpose. Following is what I have.

public class LogMessage
{
    private  static Object padlock = new Object();
    private static string serviceDirectory ="C:\\MySite\\";
    private static string filePath = "\\Logs\\Combined\\ActivityMonitorLog-" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".log";

    private static volatile LogMessage instance = new LogMessage();
    public static LogMessage Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                        instance = new LogMessage();
                }
            }

            return instance;
        }
    }

    public void SaveLogMessage(string userName, string message, string stackTrace)
    {
        lock (padlock)
        {
            using (StreamWriter logWriter =
                new StreamWriter(serviceDirectory + filePath, true))
            {
                string logMessage = "";
                if (!string.IsNullOrEmpty(stackTrace))
                    logMessage = string.Format("{0} >> user : {1} ::: {2} ::: stack trace ::: {3}", DateTime.Now.ToString(), userName, message,stackTrace);
                else
                    logMessage = string.Format("{0} >> user : {1} ::: {2}", DateTime.Now.ToString(), userName, message);

                logWriter.WriteLine(logMessage);

            }
        }
    }
}

And when i want do a log entry I am calling the about method like below

LogMessage.Instance.SaveLogMessage("My User", "Enter Logout PageLoad : Current Method :" + "Page_Load @ Logout.aspx.cs", "");

I believe I have got the singleton part and thread safety achieved. But I don't think this is non blocking as multiple users are logged in at the same time each one will have to wait until the file is available to be written. I am pondering about using a backgroundworker to call this SaveLogMessage() from the LogMessage singleton object. Is that the correct way of doing it?

UPDATE

I have implemented this using backgroundworker and the complete class and how to call is mentioned in the answers. Thanks for inputs @bret and @huan

Body:
In the end I have managed to achieve a non-blocking, thread safe,singleton logging class with the use of a background worker. I am submitting my solution in case someone find it useful someday.

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Configuration;
/// <summary>
/// Summary description for LogMessage
/// </summary>
public class LogMessage
{
    static ReaderWriterLock locker = new ReaderWriterLock();

    private static string serviceDirectory = HttpContext.Current != null ?
        AppDomain.CurrentDomain.BaseDirectory :
        Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    private static string fullpath = serviceDirectory + "\\ActivityLog.log";
    private static readonly LogMessage instance = new LogMessage();

    public static LogMessage Instance
    {
        get { return instance; }
    }

    public void SaveLogMessage(string userName, string message, string stackTrace, bool inOut)
    {
        bool EnableActivityLogging = false;

        if (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["EnableActivityLogging"]))
            return;

        EnableActivityLogging = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableActivityLogging"]);

        if (!EnableActivityLogging)
            return;

        BackgroundWorker logbw = new BackgroundWorker();
        logbw.DoWork += logbw_DoWork;
        logbw.RunWorkerCompleted += logbw_RunWorkerCompleted;

        List<string> paramList = new List<string>();
        paramList.Add(userName);
        paramList.Add(message);
        paramList.Add(stackTrace);
        paramList.Add(inOut.ToString());

        if (!logbw.IsBusy)
        {
            logbw.RunWorkerAsync(paramList);
        }
    }

    void logbw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Debug.Write("Log Message Background Worker is now free...");
    }

    void logbw_DoWork(object sender, DoWorkEventArgs e)
    {
        List<string> paramList = (List<string>)e.Argument;
        string userName = paramList[0].ToString();
        string message = paramList[1].ToString();
        string stackTrace = paramList[2].ToString();
        bool inOut = bool.Parse(paramList[3].ToString());

        try
        {
            locker.AcquireWriterLock(int.MaxValue);
            using (StreamWriter logWriter =
                new StreamWriter(fullpath, true))
            {
                string logMessage = "";
                if (!string.IsNullOrEmpty(stackTrace))
                {
                    if (inOut)//IN
                    {
                        logMessage = string.Format("{0} U:{1} IN:{2} E:{3}", DateTime.Now.ToString(), userName, message, stackTrace);
                    }
                    else//OUT
                    {
                        logMessage = string.Format("{0} U:{1} OUT:{2} E:{3}", DateTime.Now.ToString(), userName, message, stackTrace);
                    }
                }
                else
                {
                    if (inOut)//IN
                    {
                        logMessage = string.Format("{0} U:{1} IN:{2}", DateTime.Now.ToString(), userName, message);
                    }
                    else//OUT
                    {
                        logMessage = string.Format("{0} U:{1} OUT:{2}", DateTime.Now.ToString(), userName, message);
                    }
                }

                logWriter.WriteLine(logMessage);

            }
        }
        finally
        {
            locker.ReleaseWriterLock();
        }
    }

}

Now I can use this singleton object like below to save a log entry

    LogMessage.Instance.SaveLogMessage(Context.User.Identity.Name, "Custom Message" + " M:" + MethodInfo.GetCurrentMethod().Name + "@" + Path.GetFileName(Page.AppRelativeVirtualPath), "", true);


问:
node.js share dynamic variables between modules
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

```<code>process.env.number_of_clusters = 1;
</code>```

is it a good practice?

答:
If the other modules are running as part of the same Nodejs process,
you can just export a getter to other modules which will get the fresh value of number_of_clusters for them.
Like:

```<code>function get_number_of_clusters() {
  return number_of_clusters;
}

module.exports = { get_number_of_clusters };
</code>```

Now in other modules, you need to import this module and call this method, like:

```<code>var getter = require('path/to/above/module').get_number_of_clusters;
var number_of_clusters = getter();
</code>```

Body:
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

process.env.number_of_clusters = 1;

is it a good practice?

Body:
If the other modules are running as part of the same Nodejs process,
you can just export a getter to other modules which will get the fresh value of number_of_clusters for them.
Like:

function get_number_of_clusters() {
  return number_of_clusters;
}

module.exports = { get_number_of_clusters };

Now in other modules, you need to import this module and call this method, like:

var getter = require('path/to/above/module').get_number_of_clusters;
var number_of_clusters = getter();


问:
Map values from a dataframe
I have a dataframe with the correspondence between two values:

A another list with only one of the variables:

```<code>l = ['a','b','c']
</code>```

I want to make the mapping like:

```<code>df[l[0]]
</code>```

and get 1

```<code>df[l[1]]
</code>```

and get 2

As if it was a dictionary, how can I do that?

答:
Another way is map by Series or by dict but is necessary unique value of keys, drop_duplicates helps:

```<code>df = pd.DataFrame({'key':list('aabcc'),
                   'value':[1,1,2,3,3]})

s = df.drop_duplicates('key').set_index('key')['value']
print (s)
key
a    1
b    2
c    3
Name: value, dtype: int64

d = df.drop_duplicates('key').set_index('key')['value'].to_dict()
print (d)
{'c': 3, 'b': 2, 'a': 1}

l = ['a','b','c']

print (s[l[0]])
1

print (d[l[1]])
2
</code>```

Title: Map values from a dataframe

Body:
I have a dataframe with the correspondence between two values:

A another list with only one of the variables:

l = ['a','b','c']

I want to make the mapping like:

df[l[0]]

and get 1

df[l[1]]

and get 2

As if it was a dictionary, how can I do that?

Body:
Another way is map by Series or by dict but is necessary unique value of keys, drop_duplicates helps:

df = pd.DataFrame({'key':list('aabcc'),
                   'value':[1,1,2,3,3]})

s = df.drop_duplicates('key').set_index('key')['value']
print (s)
key
a    1
b    2
c    3
Name: value, dtype: int64

d = df.drop_duplicates('key').set_index('key')['value'].to_dict()
print (d)
{'c': 3, 'b': 2, 'a': 1}

l = ['a','b','c']

print (s[l[0]])
1

print (d[l[1]])
2


问:
How to deploy keycloak to cloudfoundry
As the title, is there any guide to deploy keycloak to cloud foundry?

Seems like cloudfoundry is only friendly to spring boot applications.

答:
Keycloak Single Instance on CF

To deploy single instance try to cf push the docker image using manifest.yml like this (Postgres DB example):

```<code>---
applications:
- name: sso
  docker:
    image: jboss/keycloak
  instances: 1
  memory: 2G
  disk_quota: 2G
  env:
    PROXY_ADDRESS_FORWARDING: true
    DB_VENDOR: postgres
    DB_ADDR: 192.168.1.23
    DB_PORT: 5432
    DB_DATABASE: keycloakdb
    DB_USER: keycloak
    DB_PASSWORD: a-lot-of-asterisks
</code>```

You can do it also with the following commands without a manifest file:

```<code>$ cf push sso --docker-image jboss/keycloak -i 1 -m 2G -k 2G --no-start

$ cf set-env sso PROXY_ADDRESS_FORWARDING true
$ cf set-env sso DB_VENDOR: postgres
$ cf set-env sso DB_ADDR 192.168.1.23
$ cf set-env sso DB_PORT 5432
$ cf set-env sso DB_DATABASE keycloakdb
$ cf set-env sso DB_USER keycloak
$ cf set-env sso DB_PASSWORD a-lot-of-asterisks

$ cf env sso
$ cf start sso

$ cf logs sso --recent
</code>```

Keycloak HA Cluster ona CF

Please look at: Keycloak standalone cluster on Cloud Foundry

References

https://hub.docker.com/r/jboss/keycloak/

https://cli.cloudfoundry.org/en-US/cf/push.html

https://docs.cloudfoundry.org/adminguide/docker.html#public

Do you consider using Cloud Foundry's UAA?

CF UAA is the central identity management service for both users and applications, that supports: federated login, LDAP, SAML, SSO and multifactor authentication.

Title: How to deploy keycloak to cloudfoundry

Body:
Keycloak Single Instance on CF

To deploy single instance try to cf push the docker image using manifest.yml like this (Postgres DB example):

---
applications:
- name: sso
  docker:
    image: jboss/keycloak
  instances: 1
  memory: 2G
  disk_quota: 2G
  env:
    PROXY_ADDRESS_FORWARDING: true
    DB_VENDOR: postgres
    DB_ADDR: 192.168.1.23
    DB_PORT: 5432
    DB_DATABASE: keycloakdb
    DB_USER: keycloak
    DB_PASSWORD: a-lot-of-asterisks

You can do it also with the following commands without a manifest file:

$ cf push sso --docker-image jboss/keycloak -i 1 -m 2G -k 2G --no-start

$ cf set-env sso PROXY_ADDRESS_FORWARDING true
$ cf set-env sso DB_VENDOR: postgres
$ cf set-env sso DB_ADDR 192.168.1.23
$ cf set-env sso DB_PORT 5432
$ cf set-env sso DB_DATABASE keycloakdb
$ cf set-env sso DB_USER keycloak
$ cf set-env sso DB_PASSWORD a-lot-of-asterisks

$ cf env sso
$ cf start sso

$ cf logs sso --recent

Keycloak HA Cluster ona CF

Please look at: Keycloak standalone cluster on Cloud Foundry

References

https://hub.docker.com/r/jboss/keycloak/

https://cli.cloudfoundry.org/en-US/cf/push.html

https://docs.cloudfoundry.org/adminguide/docker.html#public

Do you consider using Cloud Foundry's UAA?

CF UAA is the central identity management service for both users and applications, that supports: federated login, LDAP, SAML, SSO and multifactor authentication.


问:
Select a property in the property grid
I am using a PropertyGrid to display the content of an object to the user.

This PropertyGrid is synchronized with an Excel sheet, assuming a cell value match a property value.

As the user selects a property in the PropertyGrid, the application highlights the corresponding cell in the Excel sheet which is opened beside. I can do this using the SelectedGridItemChanged event.

Now, I want to have a property selected in my PropertyGrid when the user selects a cell in the Excel sheet.

```<code>void myWorkbook_SheetSelectionChangeEvent(NetOffice.COMObject Sh, Excel.Range Target)
{
    if (eventMask > 0)
        return;

    try
    {
        eventMask++;

        this.Invoke(new Action(() =>
        {
            propertyGrid1.SelectedGridItem = ... // ?
        }
    }
    finally
    {
        eventMask--;
    }
}
</code>```

I noticed that the SelectedGridItem can be written to.

Unfortunately I do not find a way to access the GridItems collection of my PropertyGrid so I can look for the right GridItem and select it.

How can I do this?

答:
I came up against this quite a bit a project so I wrote an extension method for it:

```<code>if (!SetupManagerSettings.BootStrapperLocation.IsFile()) // Just another extension method to check if its a file
{
    settingsToolStripMenuItem.Checked = true;  // Event handler OnChecked ensures the settings panel is unhidden
    settingsPropertyGrid.ActivateControl();

    settingsPropertyGrid.SelectPropertyGridItemByName("BootStrapperLocation"); // Here is the extension method

    return false;
}
</code>```

Here is the extension method with a private, supporting method for traversing the hierarchy of objects (if this applies to your object model):

```<code>    public static bool SelectPropertyGridItemByName(this PropertyGrid propertyGrid, string propertyName)
    {
        MethodInfo getPropEntriesMethod = propertyGrid.GetType().GetMethod("GetPropEntries", BindingFlags.NonPublic | BindingFlags.Instance);

        Debug.Assert(getPropEntriesMethod != null, @"GetPropEntries by reflection is still valid in .NET 4.6.1 ");

        GridItemCollection gridItemCollection = (GridItemCollection)getPropEntriesMethod.Invoke(propertyGrid, null);

        GridItem gridItem = TraverseGridItems(gridItemCollection, propertyName);

        if (gridItem == null)
        {
            return false;
        }

        propertyGrid.SelectedGridItem = gridItem;

        return true;
    }

    private static GridItem TraverseGridItems(IEnumerable parentGridItemCollection, string propertyName)
    {
        foreach (GridItem gridItem in parentGridItemCollection)
        {
            if (gridItem.Label != null && gridItem.Label.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
            {
                return gridItem;
            }

            if (gridItem.GridItems == null)
            {
                continue;
            }

            GridItem childGridItem = TraverseGridItems(gridItem.GridItems, propertyName);

            if (childGridItem != null)
            {
                return childGridItem;
            }
        }

        return null;
    }
</code>```

Title: Select a property in the property grid

Body:
I am using a PropertyGrid to display the content of an object to the user.

This PropertyGrid is synchronized with an Excel sheet, assuming a cell value match a property value.

As the user selects a property in the PropertyGrid, the application highlights the corresponding cell in the Excel sheet which is opened beside. I can do this using the SelectedGridItemChanged event.

Now, I want to have a property selected in my PropertyGrid when the user selects a cell in the Excel sheet.

void myWorkbook_SheetSelectionChangeEvent(NetOffice.COMObject Sh, Excel.Range Target)
{
    if (eventMask > 0)
        return;

    try
    {
        eventMask++;

        this.Invoke(new Action(() =>
        {
            propertyGrid1.SelectedGridItem = ... // ?
        }
    }
    finally
    {
        eventMask--;
    }
}

I noticed that the SelectedGridItem can be written to.

Unfortunately I do not find a way to access the GridItems collection of my PropertyGrid so I can look for the right GridItem and select it.

How can I do this?

Body:
I came up against this quite a bit a project so I wrote an extension method for it:

if (!SetupManagerSettings.BootStrapperLocation.IsFile()) // Just another extension method to check if its a file
{
    settingsToolStripMenuItem.Checked = true;  // Event handler OnChecked ensures the settings panel is unhidden
    settingsPropertyGrid.ActivateControl();

    settingsPropertyGrid.SelectPropertyGridItemByName("BootStrapperLocation"); // Here is the extension method

    return false;
}

Here is the extension method with a private, supporting method for traversing the hierarchy of objects (if this applies to your object model):

    public static bool SelectPropertyGridItemByName(this PropertyGrid propertyGrid, string propertyName)
    {
        MethodInfo getPropEntriesMethod = propertyGrid.GetType().GetMethod("GetPropEntries", BindingFlags.NonPublic | BindingFlags.Instance);

        Debug.Assert(getPropEntriesMethod != null, @"GetPropEntries by reflection is still valid in .NET 4.6.1 ");

        GridItemCollection gridItemCollection = (GridItemCollection)getPropEntriesMethod.Invoke(propertyGrid, null);

        GridItem gridItem = TraverseGridItems(gridItemCollection, propertyName);

        if (gridItem == null)
        {
            return false;
        }

        propertyGrid.SelectedGridItem = gridItem;

        return true;
    }

    private static GridItem TraverseGridItems(IEnumerable parentGridItemCollection, string propertyName)
    {
        foreach (GridItem gridItem in parentGridItemCollection)
        {
            if (gridItem.Label != null && gridItem.Label.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
            {
                return gridItem;
            }

            if (gridItem.GridItems == null)
            {
                continue;
            }

            GridItem childGridItem = TraverseGridItems(gridItem.GridItems, propertyName);

            if (childGridItem != null)
            {
                return childGridItem;
            }
        }

        return null;
    }