问:
how to change several images with a single click
Im really new to javascript, and while Im learning, Im trying to change images in a gallery to others with an onclick function.
I have links to different galleries. When I click on link 1, the imgs are one1.jpg, one2.jpg and so on. When I click on link 2, imgs are two1.jpg, two2.jpg, etc.

This is the rough script I made for Link 1:

```<code><script>
  function one() {
    document.getElementById("foto1").src="one1.jpg";
    document.getElementById("foto2").src="one2.jpg";
          }
</script>

<a href="#" onclick="one()">Link 1</a>
<a href="#" onclick="two()">Link 2</a>
<img id="foto1" src="tre1.jpg"></a>
<img id="foto2" src="tre2.jpg"></a>
</code>```

etc.

I made another function called two() for the second link with same content but changing src to what I want. And for every link I add, I copy the script and change it a little.
I know there is a way to optimize to a single script with variables or something .
Any help?
Thanks

答:
In order to differentiate group of images there must be a pattern.
try to add a class on each img tag to differentiate images for changing their source, and the you can loop through images as follows:</p>

```<code>    <a href="#" onclick="one()">Link 1</a>
    <a href="#" onclick="two()">Link 2</a>
    <img class="img1" id="foto1" src="foto1.jpg">
    <img class="img1" id="foto2" src="foto1.jpg">

    <img class="img2" id="foto3" src="pic1.jpg">
    <img class="img2" id="foto4" src="pic2.jpg">
    <script>
  function one() {
      var img = document.getElementsByClassName("img1");
      for (var i in img) {
          img[i].src = "foto" + 1 + ".jpg"
      }
  }

  function two() {
      var img = document.getElementsByClassName("img2");
      for (var i in img) {
          img[i].src = "pic" + 1 + ".jpg"
      }
  }
  </script>
</code>```

Body:
Im really new to javascript, and while Im learning, Im trying to change images in a gallery to others with an onclick function.
I have links to different galleries. When I click on link 1, the imgs are one1.jpg, one2.jpg and so on. When I click on link 2, imgs are two1.jpg, two2.jpg, etc.

This is the rough script I made for Link 1:

Link 1
Link 2

etc.

I made another function called two() for the second link with same content but changing src to what I want. And for every link I add, I copy the script and change it a little.
I know there is a way to optimize to a single script with variables or something .
Any help?
Thanks

Body:
In order to differentiate group of images there must be a pattern.
try to add a class on each img tag to differentiate images for changing their source, and the you can loop through images as follows:

    <a href="#" onclick="one()">Link 1</a>
    <a href="#" onclick="two()">Link 2</a>
    <img class="img1" id="foto1" src="foto1.jpg">
    <img class="img1" id="foto2" src="foto1.jpg">

    <img class="img2" id="foto3" src="pic1.jpg">
    <img class="img2" id="foto4" src="pic2.jpg">
    <script>
  function one() {
      var img = document.getElementsByClassName("img1");
      for (var i in img) {
          img[i].src = "foto" + 1 + ".jpg"
      }
  }

  function two() {
      var img = document.getElementsByClassName("img2");
      for (var i in img) {
          img[i].src = "pic" + 1 + ".jpg"
      }
  }
  </script>


来源: stackexchange

问:
c# sql How to get row selected value?
I used datagrid to show sql table datagrid.

And I showed one column on datagrid from sql.

Now I want to determine that which rows is now open & what is that values.

Like this.

See what I want to do.

And I used this code to show datatable on my datagrid.

```<code>string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.ItemsSource = dt.DefaultView;

}
</code>```

And its show only row column. But I want to declare like my previous image.

答:
You could select all values that you are interested in up front of but only display the "roll" column in the DataGrid:

```<code>string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll, tc, tf, pc, pf FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.AutoGenerateColumns = false;
    MydataGrid_roll.Columns.Add(new DataGridTextColumn() { Header = "roll", Binding = new Binding("roll") });
    MydataGrid_roll.ItemsSource = dt.DefaultView;
}
</code>```

You can then retrive any column values of the selected row in the DataGrid like this:

```<code>DataRowView drv = MydataGrid_roll.SelectedItem as DataRowView;
if(drv != null)
{
    int selectedRoll = Convert.ToInt32(drv["roll"]);
    if(drv["tc"] != DBNull.Value)
    {
        string selectedTc = drv["tc"].ToString();
    }
    //...
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: c# sql How to get row selected value?

Body:
I used datagrid to show sql table datagrid.

And I showed one column on datagrid from sql.

Now I want to determine that which rows is now open & what is that values.

Like this.

See what I want to do.

And I used this code to show datatable on my datagrid.

string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.ItemsSource = dt.DefaultView;

}

And its show only row column. But I want to declare like my previous image.

Body:
You could select all values that you are interested in up front of but only display the "roll" column in the DataGrid:

string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll, tc, tf, pc, pf FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.AutoGenerateColumns = false;
    MydataGrid_roll.Columns.Add(new DataGridTextColumn() { Header = "roll", Binding = new Binding("roll") });
    MydataGrid_roll.ItemsSource = dt.DefaultView;
}

You can then retrive any column values of the selected row in the DataGrid like this:

DataRowView drv = MydataGrid_roll.SelectedItem as DataRowView;
if(drv != null)
{
    int selectedRoll = Convert.ToInt32(drv["roll"]);
    if(drv["tc"] != DBNull.Value)
    {
        string selectedTc = drv["tc"].ToString();
    }
    //...
}


问:
Plesk / Pin domain to the same home directory as another domain
is it possible to pin domain to another's domain home directory?

Example: I have domain1.com and domain2.com. Now I want domain2.com pin to same home directory as domain1.com to access the same files.

I don't want Alias Domain, because it's just redirecting doman2 to domain1.

Thanks

答: Your goal will result in issues/errors/problems, due to the fact, that each domain will create it's very own domain - specific system-user, who owns files/folders, when you use Plesk. The domain - specific system-user from domain2 will not be able to interact with the content of domain1.</p>


问:
Bind a button to a callback from Kivy to python
I've been banging my head on this for days now.  I made it work in Python only (not using the .kv file) but now I just can't figure this out.

Basically, I'll have a series of button to control GPIOs on a Raspberry Pi.  In the Python only version, I have one call back with a serie of IFs looking for the right button "text" to determine wich pin to activate.  Now in the kivy version, I dumbed it down to a single button, moved the callback to many places in the code, etc but nothing seems to work.

Here's the pyton code:

```<code># Set up GPIO:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
defrost = 27
GPIO.setup(defrost, GPIO.OUT)
GPIO.output(defrost, GPIO.LOW)

class ConsoleUI(BoxLayout):
    def press_callback(obj):

            if obj.state == "down":
               GPIO.output(defrost, GPIO.HIGH)
            else:
               GPIO.output(defrost, GPIO.LOW)

    pass

class ConsolesimpleApp(App):
    def build(self):
        return ConsoleUI()

if __name__ == '__main__':
    ConsolesimpleApp().run()

GPIO.cleanup()
</code>```

Here's the KV code:

```<code># Console.kv

<ConsoleUI>:

    ToggleButton:
        id: Defrost
        on_press: root.press_callback()
        Image:
            source: 'rear-window-defrost.png'
</code>```

And the current error message:

```<code> AttributeError: 'ConsoleUI' object has no attribute 'state'
</code>```

Thank you for any pointers you can give me!

Bonus question: is it better form to have a distinct callback for each button or is the "if obj.text ==" standard?  Since I won't have text on my buttons...

答:
The problem is, what you really are doing in press_callback(obj) is checking for state of the BoxLayout (ConsoleUI), since obj in this case is the same as saying self. And as you see, boxlayout does not have any state attribute.

So what you really want to do, is check for the state of the togglebutton. Luckily you allready gave it an id, so try change your method like this:

def press_callback(self):

        if self.ids.Defrost.state == "down":
           GPIO.output(defrost, GPIO.HIGH)
        else:
           GPIO.output(defrost, GPIO.LOW)
```

<p>And to answer your bonus question.<br>
You can pass stuff to the callback. So I would pass the button itself, and the pin number. Now you can actually forget what I said above.<br>
Try run this little example, to see what I mean:</p>

```from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''

<ConsoleUI>:

    ToggleButton:
        on_press: root.press_callback(self,1)

    ToggleButton:
        on_press: root.press_callback(self,2)

    ToggleButton:
        on_press: root.press_callback(self,3)

''')

class ConsoleUI(BoxLayout):

    def press_callback(self,button,pin):
            if button.state == "down":
               print("pin {} goes high".format(pin))
            else:
               print("pin {} goes low".format(pin))

class ConsolesimpleApp(App):
    def build(self):
        return ConsoleUI()

if __name__ == '__main__':
    ConsolesimpleApp().run()
```

Body:
I've been banging my head on this for days now.  I made it work in Python only (not using the .kv file) but now I just can't figure this out.

Basically, I'll have a series of button to control GPIOs on a Raspberry Pi.  In the Python only version, I have one call back with a serie of IFs looking for the right button "text" to determine wich pin to activate.  Now in the kivy version, I dumbed it down to a single button, moved the callback to many places in the code, etc but nothing seems to work.

Here's the pyton code:

# Set up GPIO:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
defrost = 27
GPIO.setup(defrost, GPIO.OUT)
GPIO.output(defrost, GPIO.LOW)

class ConsoleUI(BoxLayout):
    def press_callback(obj):

            if obj.state == "down":
               GPIO.output(defrost, GPIO.HIGH)
            else:
               GPIO.output(defrost, GPIO.LOW)

    pass

class ConsolesimpleApp(App):
    def build(self):
        return ConsoleUI()

if __name__ == '__main__':
    ConsolesimpleApp().run()

GPIO.cleanup()

Here's the KV code:

# Console.kv

<ConsoleUI>:

    ToggleButton:
        id: Defrost
        on_press: root.press_callback()
        Image:
            source: 'rear-window-defrost.png'

And the current error message:

 AttributeError: 'ConsoleUI' object has no attribute 'state'

Thank you for any pointers you can give me!

Bonus question: is it better form to have a distinct callback for each button or is the "if obj.text ==" standard?  Since I won't have text on my buttons...

Body:
The problem is, what you really are doing in press_callback(obj) is checking for state of the BoxLayout (ConsoleUI), since obj in this case is the same as saying self. And as you see, boxlayout does not have any state attribute.

So what you really want to do, is check for the state of the togglebutton. Luckily you allready gave it an id, so try change your method like this:

def press_callback(self):

        if self.ids.Defrost.state == "down":
           GPIO.output(defrost, GPIO.HIGH)
        else:
           GPIO.output(defrost, GPIO.LOW)

And to answer your bonus question.

You can pass stuff to the callback. So I would pass the button itself, and the pin number. Now you can actually forget what I said above.

Try run this little example, to see what I mean:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''

<ConsoleUI>:

    ToggleButton:
        on_press: root.press_callback(self,1)

    ToggleButton:
        on_press: root.press_callback(self,2)

    ToggleButton:
        on_press: root.press_callback(self,3)

''')

class ConsoleUI(BoxLayout):

    def press_callback(self,button,pin):
            if button.state == "down":
               print("pin {} goes high".format(pin))
            else:
               print("pin {} goes low".format(pin))

class ConsolesimpleApp(App):
    def build(self):
        return ConsoleUI()

if __name__ == '__main__':
    ConsolesimpleApp().run()


问:
How do I create a field or parameter that can help me toggle between two measures?
I have 1 excel file with 2 sheets (Imports and Exports) and each sheet has a table.

Each table looks like this:

```<code>Country Name    Year    Thousand of units
Belgium         2005    1,044,074
Belgium         2006    1,092,214
Belgium         2007    1,079,477
Bulgaria        2005    25,660
Bulgaria        2006    34,310
Bulgaria        2007    60,228
Czech Republic  2005    261,999
Czech Republic  2006    262,207
Czech Republic  2007    254,053
</code>```

As a visualization option, I'm using the world map view and can use AVG([Thousand of units]) for each Import and Export option (drag and drop in Marks card), but I would like to use a toggle between AVG([Thousand of units (Imports)]) and AVG([Thousand of units (Exports)]) - like a parameter option.

Please note that I'm currently using Tableau 10.2

答:
When you edit the data source in Tableau, drag one sheet on top of the other in the central pane of the data source editor (where is says Drag Sheets Here) to make a Union of both sheets.

Then rename either the Sheet or Table Name fields to be Type or such to distinguish imports from exports.

Body:
I have 1 excel file with 2 sheets (Imports and Exports) and each sheet has a table.

Each table looks like this:

Country Name    Year    Thousand of units
Belgium         2005    1,044,074
Belgium         2006    1,092,214
Belgium         2007    1,079,477
Bulgaria        2005    25,660
Bulgaria        2006    34,310
Bulgaria        2007    60,228
Czech Republic  2005    261,999
Czech Republic  2006    262,207
Czech Republic  2007    254,053

As a visualization option, I'm using the world map view and can use AVG([Thousand of units]) for each Import and Export option (drag and drop in Marks card), but I would like to use a toggle between AVG([Thousand of units (Imports)]) and AVG([Thousand of units (Exports)]) - like a parameter option.

Please note that I'm currently using Tableau 10.2


问:
javascript - How to get values from a dynamic table
I have a table that is dynamically created on the webpage. The table has 3 columns.'filename', 'fileurl', and a column with a textnode that says'download'.
Some thing like this

```<code>filename     fileurl        download
file1     www.pathtofile1   download
file2     www.pathtofile2   download
file3     www.pathtofile3   download
</code>```

The requirement here is, if the user clicks the 'download' in a particular row, i should get the corresponding values of 'filename' and 'fileurl' in that row.
How do i do that?

答:
This should be enough

$("table tr .download").click(function(){
  var row = $(this).closest("tr");
  var name = row.find(".name").html(),
      url = row.find(".url").html();
  console.log(name,url)
});```
<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>
<table>
<tbody>
<tr>
  <td class="name">file1</td>
  <td class="url">www.pathtofile1</td>
  <td class="download">Download</td>
</tr>
<tr>
  <td class="name">file2</td>
  <td class="url">www.pathtofile2</td>
  <td class="download">Download</td>
</tr>
<tr>
  <td class="name">file3</td>
  <td class="url">www.pathtofile3</td>
  <td class="download">Download</td>
</tr></code>```

Body:
I have a table that is dynamically created on the webpage. The table has 3 columns.'filename', 'fileurl', and a column with a textnode that says'download'.
Some thing like this

filename     fileurl        download
file1     www.pathtofile1   download
file2     www.pathtofile2   download
file3     www.pathtofile3   download

The requirement here is, if the user clicks the 'download' in a particular row, i should get the corresponding values of 'filename' and 'fileurl' in that row.
How do i do that?

Body:
This should be enough

$("table tr .download").click(function(){
  var row = $(this).closest("tr");
  var name = row.find(".name").html(),
      url = row.find(".url").html();
  console.log(name,url)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
  <td class="name">file1</td>
  <td class="url">www.pathtofile1</td>
  <td class="download">Download</td>
</tr>
<tr>
  <td class="name">file2</td>
  <td class="url">www.pathtofile2</td>
  <td class="download">Download</td>
</tr>
<tr>
  <td class="name">file3</td>
  <td class="url">www.pathtofile3</td>
  <td class="download">Download</td>
</tr>


问:
Function should return object, but it's returned as undefined
i try to get image width and height returned from a function, but every time it get's returned as undefined, if i console.log values in the function it shows up, but it returns undefined every time.

The main problem i suspect is with scope, because it is a nested function, but i am not really sure, if thats the case.

JS code

```<code>  //get image width and height
    $(document).ready(function(){
      //object method
      function dimensions($width, $height){
        this.getWidth = $width;
        this.getHeight = $height;
      }
      //gets image data
      function readURL(input) {
          var reader = new FileReader();
          var image  = new Image();
          reader.onload = function (e) {
            image.src = e.target.result;
          }
          reader.readAsDataURL(input.files[0]);
          return image;
      }
      //gets image dimensions (width height)
      function getImageDimensions($img){
        var $dimensions;
          $img.onload = function(){
          $dimensions = new dimensions($img.width, $img.height);
        }
          return $dimensions;
      }

  $("#imgInp").change(function(){
    alert(getImageDimensions(readURL(this)));
  });
  });
</code>```

Html code

```<code>  <form id="form1" runat="server">
    <input type='file' id="imgInp"  accept="image/*"/>
  </form>
</code>```

Can anyone explain to me why it doesn't return a object, but returns undefined?

答:
that's because your image doesn't have width or height until it is rendered in the DOM.
So you are right to put the instanciation in a onload handler.
The thing is that handler is triggered only when your images load, but your execute the return line before.
In other words you execute this line

```<code>return $dimensions;
</code>```

before this function

```<code> $img.onload = function(){
      $dimensions = new dimensions($img.width, $img.height);
    }
</code>```

put the return in $img.onload like this:

```<code> $img.onload = function(){
         return new dimensions($img.width, $img.height);
        }
</code>```

Body:
i try to get image width and height returned from a function, but every time it get's returned as undefined, if i console.log values in the function it shows up, but it returns undefined every time.

The main problem i suspect is with scope, because it is a nested function, but i am not really sure, if thats the case.

JS code

  //get image width and height
    $(document).ready(function(){
      //object method
      function dimensions($width, $height){
        this.getWidth = $width;
        this.getHeight = $height;
      }
      //gets image data
      function readURL(input) {
          var reader = new FileReader();
          var image  = new Image();
          reader.onload = function (e) {
            image.src = e.target.result;
          }
          reader.readAsDataURL(input.files[0]);
          return image;
      }
      //gets image dimensions (width height)
      function getImageDimensions($img){
        var $dimensions;
          $img.onload = function(){
          $dimensions = new dimensions($img.width, $img.height);
        }
          return $dimensions;
      }

  $("#imgInp").change(function(){
    alert(getImageDimensions(readURL(this)));
  });
  });

Html code

  <form id="form1" runat="server">
    <input type='file' id="imgInp"  accept="image/*"/>
  </form>

Can anyone explain to me why it doesn't return a object, but returns undefined?

Body:
that's because your image doesn't have width or height until it is rendered in the DOM.
So you are right to put the instanciation in a onload handler.
The thing is that handler is triggered only when your images load, but your execute the return line before.
In other words you execute this line

return $dimensions;

before this function

 $img.onload = function(){
      $dimensions = new dimensions($img.width, $img.height);
    }

put the return in $img.onload like this:

 $img.onload = function(){
         return new dimensions($img.width, $img.height);
        }


问:
BingMap - getting prototype of null error
I have searched google and stackoverflow, but could not find a solution for this issue. I am loading the map like this, in my view.

```<code><img
      ng-src='https://dev.virtualearth.net/REST/v1/Imagery/Map/Road/
              {{Latitude.__text}},{{Longitude.__text}}/12?mapSize=77,120&
                           key={{Key}}'></img>
</code>```

Below is how its loaded in index.html

```<code><script type='text/javascript' src='https://www.bing.com/mapspreview/sdkrelease/mapcontrol?callback=loadMapScenario' async defer></script>
<script type='text/javascript' src='app/services/bing.js?' async defer></script>
</code>```

Below is my controller code, where i am trying to call the maps.

```<code>function GetMap() {
    if (typeof Microsoft !== undefined && typeof Microsoft.Maps !== undefined &&
        Microsoft.Maps.Map !== null) {
        //Map API available add your map load code.
        angular.element(document).ready(function() {
            map = new Microsoft.Maps.Map(document.getElementById('myMapL'), {
                credentials: Key,
                mapTypeId: "r",
                zoom: 4
            });
        });
    } else {
        setTimeout(GetMap(), 100);
    }
}
</code>```

I am getting the below error:

```<code>TypeError: Cannot read property 'prototype' of null
    at k (bing.js:11)
    at h (bing.js:11)
    at e (bing.js:11)
    at t.l [as instance] (bing.js:11)
    at h (bing.js:11)
    at e (bing.js:11)
    at t.l [as instance] (bing.js:11)
    at new Microsoft.Maps.Map (bing.js:13)
    at HTMLDocument.<anonymous> (file-location.js:121)
    at j (jquery-1.11.0.min.js:2)
</code>```

答:
In the map script URL you are using a different callback function that you o function to load the map. (loadScenario vs GetMap). Also, it looks like you are using the redirect URL rather than the documented map script URL (this will likely break in the future). Try changing the map script URL to this:

```<code><script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=GetMap' async defer></script>
</code>```

Not sure what bing.js is in your app. Assuming this is where you have you map load code. You will want to load this before the map script otherwise the map script may load before your code does and thus try to load the map before your GetMap function is loaded into the page.

Alternatively, you may find this code sample useful: https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/Experimental/Map_WithAngular1.html

Body:
I have searched google and stackoverflow, but could not find a solution for this issue. I am loading the map like this, in my view.

Below is how its loaded in index.html

Below is my controller code, where i am trying to call the maps.

function GetMap() {
    if (typeof Microsoft !== undefined && typeof Microsoft.Maps !== undefined &&
        Microsoft.Maps.Map !== null) {
        //Map API available add your map load code.
        angular.element(document).ready(function() {
            map = new Microsoft.Maps.Map(document.getElementById('myMapL'), {
                credentials: Key,
                mapTypeId: "r",
                zoom: 4
            });
        });
    } else {
        setTimeout(GetMap(), 100);
    }
}

I am getting the below error:

TypeError: Cannot read property 'prototype' of null
    at k (bing.js:11)
    at h (bing.js:11)
    at e (bing.js:11)
    at t.l [as instance] (bing.js:11)
    at h (bing.js:11)
    at e (bing.js:11)
    at t.l [as instance] (bing.js:11)
    at new Microsoft.Maps.Map (bing.js:13)
    at HTMLDocument.<anonymous> (file-location.js:121)
    at j (jquery-1.11.0.min.js:2)

Body:
In the map script URL you are using a different callback function that you o function to load the map. (loadScenario vs GetMap). Also, it looks like you are using the redirect URL rather than the documented map script URL (this will likely break in the future). Try changing the map script URL to this:

<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=GetMap' async defer></script>

Not sure what bing.js is in your app. Assuming this is where you have you map load code. You will want to load this before the map script otherwise the map script may load before your code does and thus try to load the map before your GetMap function is loaded into the page.

Alternatively, you may find this code sample useful: https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/Experimental/Map_WithAngular1.html


问:
What is the best comment in source code you have ever encountered?
What is the best comment in source code you have ever encountered?</p>

答:
```<code>// If you're reading this, that means you have been put in charge of my previous project.
// I am so, so sorry for you. God speed.
</code>```

OwnerDisplayName: endpoint

LastEditorDisplayName: Brian

OwnerDisplayName: Evan Fosmark

ContentLicense: CC BY-SA 2.5


问:
getopt not quite working, what am I doing wrong?
I am not sure why the code below does not work - I get the error

```<code>NameError: name 'group1' is not defined.
</code>```

The code worked fine before I tried to use getopt..  I am trying to parse the command line input so that eg if I put

```<code>python -q file1 file2 -r file3 file4
</code>```

the file1 and file2 become the input into my first loop as 'group1'.

```<code>import sys
import csv
import vcf
import getopt
#set up the args
try:
    opts, args = getopt.getopt(sys.argv[1:], 'q:r:h', ['query', 'reference', 'help'])
except getopt.GetoptError as err:
    print str(err)
    sys.exit(2)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        print "Usage python -q [query files] -r [reference files]"
        print "-h this help message"
    elif opt in ('-q', '--query'):
        group1 = arg
    elif opt in ('-r', '--reference'):
        group2 = arg
    else:
        print"check your args"

#extract core snps from query file, saving these to the set universal_snps
snps = []
outfile = sys.argv[1]
for variants in group1:

    vcf_reader = vcf.Reader(open(variants))
</code>```

答:
The problem is that group1 = arg is never running, so when it later gets to for variants in group1:, the variable is not defined.

This is because you are calling the function incorrectly for how you defined your options. When you have the line:

```<code> opts, args = getopt.getopt(sys.argv[1:], 'q:r:h', ['query', 'reference', 'help'])
</code>```

There is a requirement that the arguments with flags (i.e. -q file1 and -r file3 be specified before any other arguments. Therefore, if you were to call the function as:

```<code>python <scriptName> -q file1 -r file3 file2 file4
</code>```

You would have the intended behaviour. This is because all the parameters without an associated flag appear at the end of the call (and would be retrievable through the args parameter

Body:
I am not sure why the code below does not work - I get the error

NameError: name 'group1' is not defined.

The code worked fine before I tried to use getopt..  I am trying to parse the command line input so that eg if I put

python -q file1 file2 -r file3 file4

the file1 and file2 become the input into my first loop as 'group1'.

import sys
import csv
import vcf
import getopt
#set up the args
try:
    opts, args = getopt.getopt(sys.argv[1:], 'q:r:h', ['query', 'reference', 'help'])
except getopt.GetoptError as err:
    print str(err)
    sys.exit(2)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        print "Usage python -q [query files] -r [reference files]"
        print "-h this help message"
    elif opt in ('-q', '--query'):
        group1 = arg
    elif opt in ('-r', '--reference'):
        group2 = arg
    else:
        print"check your args"

#extract core snps from query file, saving these to the set universal_snps
snps = []
outfile = sys.argv[1]
for variants in group1:

    vcf_reader = vcf.Reader(open(variants))

Body:
The problem is that group1 = arg is never running, so when it later gets to for variants in group1:, the variable is not defined.

This is because you are calling the function incorrectly for how you defined your options. When you have the line:

 opts, args = getopt.getopt(sys.argv[1:], 'q:r:h', ['query', 'reference', 'help'])

There is a requirement that the arguments with flags (i.e. -q file1 and -r file3 be specified before any other arguments. Therefore, if you were to call the function as:

python <scriptName> -q file1 -r file3 file2 file4

You would have the intended behaviour. This is because all the parameters without an associated flag appear at the end of the call (and would be retrievable through the args parameter


问:
Is there a way to allow browserify modules access to the global scope (window object)?
The Scenario

I'm using Browserify (or NodeJS/CommonJS like imports) to require some JavaScript libraries. However, I'm having trouble getting them to play nice since apparently Browserify by default denies global scope access to all modules. For example, doing this doesn't work;

file1.js

```<code>require('moment');
</code>```

file2.js

```<code>moment(new Date()); // throws moment is undefined
</code>```

But this works by changing the contents of file1.js to the following;

```<code>window.moment = require('moment');
</code>```

The Problem

This has worked well enough so far, however now I'm having trouble loading the moment timezone library (an extension of MomentJS). Moment Timezone's docs imply both scripts should run on the window global scope by adding them as script tags like so;

```<code><script src="moment.js"></script>
<script src="moment-timezone-with-data.js"></script>
</code>```

So they can be used like this;

```<code>moment().tz("America/Los_Angeles").format();
</code>```

This however, seems very hard to achieve, since if I try the following;

```<code>window.moment = require('moment');
require('./../../node_modules/moment-timezone/builds/moment-timezone-with-data-2010-2020'); // the location of my moment-timezone library
</code>```

I get a runtime error saying that moment.tz is undefined (meaning that the second library wasn't run with the global scope). And if I try to add the window.moment to the second line of code, I'll be rewriting the first instance of the full library.

So, in short;

Is there a way to allow certain Browserify imports to have global scope access, or to run with the window object as their scope?

I'm aware of the security implications this has, but selectively used, this would be immensely useful while requiring things like JavaScript libraries that need global access to set up themselves correctly. Any help would be greatly appreciated.

答:
Install the moment-timezone package as instructed on the website.

```<code>npm install moment-timezone --save
</code>```

In file1.js, define window.moment as so:

```<code>window.moment = require('moment-timezone/builds/moment-timezone-with-data-2010-2020');
</code>```

This should allow you to use moment().tz() in file2.js

Body:
The Scenario

I'm using Browserify (or NodeJS/CommonJS like imports) to require some JavaScript libraries. However, I'm having trouble getting them to play nice since apparently Browserify by default denies global scope access to all modules. For example, doing this doesn't work;

file1.js

require('moment');

file2.js

moment(new Date()); // throws moment is undefined

But this works by changing the contents of file1.js to the following;

window.moment = require('moment');

The Problem

This has worked well enough so far, however now I'm having trouble loading the moment timezone library (an extension of MomentJS). Moment Timezone's docs imply both scripts should run on the window global scope by adding them as script tags like so;

So they can be used like this;

moment().tz("America/Los_Angeles").format();

This however, seems very hard to achieve, since if I try the following;

window.moment = require('moment');
require('./../../node_modules/moment-timezone/builds/moment-timezone-with-data-2010-2020'); // the location of my moment-timezone library

I get a runtime error saying that moment.tz is undefined (meaning that the second library wasn't run with the global scope). And if I try to add the window.moment to the second line of code, I'll be rewriting the first instance of the full library.

So, in short;

Is there a way to allow certain Browserify imports to have global scope access, or to run with the window object as their scope?

I'm aware of the security implications this has, but selectively used, this would be immensely useful while requiring things like JavaScript libraries that need global access to set up themselves correctly. Any help would be greatly appreciated.

Body:
Install the moment-timezone package as instructed on the website.

npm install moment-timezone --save

In file1.js, define window.moment as so:

window.moment = require('moment-timezone/builds/moment-timezone-with-data-2010-2020');

This should allow you to use moment().tz() in file2.js


问:
Mongoose: Push data to array in for loop
i have small problem i have this code:

```<code>Messages.findOne({id_user: to}, function (err, toUser) {

                    //dopisujemy wiadomość w tablicy użytkownika
                    var messArray = toUser.messagesArray;
                    //przeszukujemy tablice z wiadomościami aby znaleźć odpowiedniego użytkownika
                    for(var i=0;i<messArray.length; ++i) {
                        if(messArray[i].id_converser = who) {
                            // console.log(messArray[i]);
                            toUser.messagesArray[i].messages.push({id_converser: who,message: message,date: Date()});

                            toUser.save(function (err) {
                                if(err) console.log(err);
                                console.log('Wiadomość dodana');
                            })
                            return;

                        }
                    }

            }) //end zapisujemy wiadomość w miejscu przeznaczenia
</code>```

and everything seems fine, in console i have message "wiadomosc dodana", but when i check it in database i not see this added data, why.
Thanks for reply.

答: In order to push to the array in the actual database you need to use $push or something like $addToSet operator </p>

Body:
i have small problem i have this code:

Messages.findOne({id_user: to}, function (err, toUser) {

                    //dopisujemy wiadomość w tablicy użytkownika
                    var messArray = toUser.messagesArray;
                    //przeszukujemy tablice z wiadomościami aby znaleźć odpowiedniego użytkownika
                    for(var i=0;i<messArray.length; ++i) {
                        if(messArray[i].id_converser = who) {
                            // console.log(messArray[i]);
                            toUser.messagesArray[i].messages.push({id_converser: who,message: message,date: Date()});

                            toUser.save(function (err) {
                                if(err) console.log(err);
                                console.log('Wiadomość dodana');
                            })
                            return;

                        }
                    }

            }) //end zapisujemy wiadomość w miejscu przeznaczenia

and everything seems fine, in console i have message "wiadomosc dodana", but when i check it in database i not see this added data, why.
Thanks for reply.


问:
django.db.utils.OperationalError: unable to open database file
When I run

```<code>python manage.py runserver
</code>```

I get this error

File "/usr/local/lib/python2.7/dist-packages/Django-1.10.1-py2.7.egg/django/db/backends/sqlite3/base.py", line 209, in get_new_connection
    conn = Database.connect(**conn_params)
django.db.utils.OperationalError: unable to open database file

my settings.py:

```<code>DATABASES = {
    'default': dj_database_url.config(
        default="sqlite:///{}".format(
            os.path.join(BASE_DIR, 'db/db.sqlite3')
        )
    )
}
</code>```

答:
I had the same problem, just solved it. Make sure www-data (or whatever daemon running your web server) has access to both the db.sqlite3 file, and also the path to it. So:</p>

```<code>sudo chown :www-data <project_folder>/
sudo chown :www-data <project_folder>/db.sqlite3
sudo chmod 664 <project_folder>/db.sqlite3
</code>```

Body:
When I run

python manage.py runserver

I get this error

File "/usr/local/lib/python2.7/dist-packages/Django-1.10.1-py2.7.egg/django/db/backends/sqlite3/base.py", line 209, in get_new_connection
    conn = Database.connect(**conn_params)
django.db.utils.OperationalError: unable to open database file

my settings.py:

DATABASES = {
    'default': dj_database_url.config(
        default="sqlite:///{}".format(
            os.path.join(BASE_DIR, 'db/db.sqlite3')
        )
    )
}

Body:
I had the same problem, just solved it. Make sure www-data (or whatever daemon running your web server) has access to both the db.sqlite3 file, and also the path to it. So:

sudo chown :www-data <project_folder>/
sudo chown :www-data <project_folder>/db.sqlite3
sudo chmod 664 <project_folder>/db.sqlite3


问:
How to use variables in for loop statements in javascript?
So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?</p>

```<code><!DOCTYPE html>
<html>
<body>

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

<p id="display"></p>

<script>
var random = [];
document.getElementById("display").innerHTML = random;
a = document.getElementById("diceamount").innerHTML;

function FirstFunction() {
for (i=0; i<"a"; i++) {
    x = Math.floor(Math.random() * 4) + 1;
    random.push(x);
    document.getElementById("display").innerHTML = random;
    }
}
</script>

</body>
</html>
</code>```

答:
Here is how you could do it. There are several issues highlighted in comments:

function FirstFunction() {
    // Reset array within this function
    var random = [];
    // Get value property, and convert to number (with +)
    // And use var!
    var a = +document.getElementById("diceamount").value;
    // No quotes around a, and use var!
    for (var i=0; i<a; i++) {
        // Use var!
        var x = Math.floor(Math.random() * 4) + 1;
        random.push(x);
    }
    // Only show after the loop, and use textContent
    document.getElementById("display").textContent = random;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

<p id="display"></p></code>```

Note that the array gets implicitly formatted as a comma separated value string when you display it.

Body:
So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?

<!DOCTYPE html>

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

Body:
Here is how you could do it. There are several issues highlighted in comments:

function FirstFunction() {
    // Reset array within this function
    var random = [];
    // Get value property, and convert to number (with +)
    // And use var!
    var a = +document.getElementById("diceamount").value;
    // No quotes around a, and use var!
    for (var i=0; i<a; i++) {
        // Use var!
        var x = Math.floor(Math.random() * 4) + 1;
        random.push(x);
    }
    // Only show after the loop, and use textContent
    document.getElementById("display").textContent = random;
}

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

<p id="display"></p>

Note that the array gets implicitly formatted as a comma separated value string when you display it.


问:
Do all modern Kernels use 3 kinds of scheduler?
I'm referring to the Long-term, Mid-term, and Short-term scheduler.

Do these three always work in conjunction during scheduling or can they be implemented separately?  One without the other two or two without the other one?

This really confuses me.

答:
Do remember that the number and type of scheduler a system has, completely depends upon the configurational requirements and what it takes to create a stable system.

A long term scheduler manages the degree of multi-programming of a system. Its primary responsibility is to make sure that programs are loaded into main memory from the storage location i.e it changes the state of a process from New to Ready.

A short term scheduler allocates processor to the programs lying in the main memory. It also controls the degree of context-switching. Thus it changes the status of the process from Ready to Running and vice versa or from Running to Waiting.

A medium term scheduler controls swapping i.e. moves programs in-and-out of the main memory.

In modern time-sharing Operating Systems like Windows, long term
  scheduler is absent and the programs are directly sent to main
  memory in the Ready state.

Therefore, the answer to your question is, No, all modern Kernels do not use all the 3 kinds of scheduler.


答:
It seems you are doing it wrong ,...

Suppose you want to take the value of input which has id = "diceamount"
so for that you have to store the value of the input in variable.

```<code>var a = document.getElementById('diceamount').value;
for(i = ; i<= a; i++){
 your code

}
</code>```

make this question down ; and look for some tutorials for javascript

Title: How to use variables in for loop statements in javascript?

Body:
It seems you are doing it wrong ,...

Suppose you want to take the value of input which has id = "diceamount"
so for that you have to store the value of the input in variable.

var a = document.getElementById('diceamount').value;
for(i = ; i<= a; i++){
 your code

}

make this question down ; and look for some tutorials for javascript


问:
Mozilla firefox columns fix
I have problem with fixing columns in firefox. i'm trying to make 3 columns with 10px gap. it's working on google chrome and opera perfectly, but in firefox not.

There is an image:
http://i.stack.imgur.com/GM0L9.png

And the css code:

```<code>div#columns {
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
-ms-column-count: 3;
-ms-column-gap: 10px;
-ms-column-fill: auto;
column-count: 3;
column-gap: 10px;
column-fill: auto;}

div.pin_shop {
display: inline-block;
background: #ffffff;
border: 1px solid rgba(0,0,0,.11);
margin: 0 25px 25px 0;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
padding: 8px;}
</code>```

答:
column-fill is not necessary and now it's working.

```<code>column-count: 3;
column-gap: 10px;
-moz-column-count: 3;
-moz-column-gap: 10px;
-webkit-column-count: 3;
-webkit-column-gap: 10px;
</code>```

Title: Mozilla firefox columns fix

Body:
I have problem with fixing columns in firefox. i'm trying to make 3 columns with 10px gap. it's working on google chrome and opera perfectly, but in firefox not.

There is an image:
http://i.stack.imgur.com/GM0L9.png

And the css code:

div#columns {
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
-ms-column-count: 3;
-ms-column-gap: 10px;
-ms-column-fill: auto;
column-count: 3;
column-gap: 10px;
column-fill: auto;}

div.pin_shop {
display: inline-block;
background: #ffffff;
border: 1px solid rgba(0,0,0,.11);
margin: 0 25px 25px 0;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
padding: 8px;}

Body:
column-fill is not necessary and now it's working.

column-count: 3;
column-gap: 10px;
-moz-column-count: 3;
-moz-column-gap: 10px;
-webkit-column-count: 3;
-webkit-column-gap: 10px;

ContentLicense: CC BY-SA 4.0


问:
Deploye UWP app on WS2K12R2
I have a question about UWP application. It's possible deploye this type of application for a Windows server 2012 R2 ?

Or it's only reserved for Windows 10 ?

答: UWP runs on Windows 10 and Server 2016. Not 2012</p>

Title: Deploye UWP app on WS2K12R2


问:
Not able to read Configuration file Using scala typesafe API
I have a spark/scala project named as Omega

I have a conf file inside Omega/conf/omega.config

I use API's from typesafe to load the config file from  conf/omega.config.
It was working fine and I was able to read the respective value for each key

Now today, For the first time I added some more key-value pairs in my omega.config file and tried to retrieve them from my scala code. It throws

```<code> Exception in thread "main" com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'job_name'
</code>```

This issue started happening after adding new value for the key job_name in my omega.config file.
Also I am not able to read the newly added -key-values, I am still able to read all old values using config. getString method

I am building my spark/scala application using maven.

Omega.config

```<code>input_path="/user/cloudera/data
user_name="surender"
job_name="SAMPLE"
</code>```

I am Not able to access the recently added key "job_name" alone
   package com.pack1

```<code>import com.pack2.ApplicationUtil
object OmegaMain {

  val config_loc = "conf/omega.config"

  def main(args: Array[String]): Unit = {

   val config               = ApplicationUtil.loadConfig(config_loc)
   val jobName              = ApplicationUtil.getFromConfig(config,"job_name")
}
}

package com.pack2
import com.typesafe.config.{Config, ConfigFactory}

object ApplicationUtil {

 def loadConfig(filePath:String):Config={
  val config = ConfigFactory.parseFile(new File(filePath))

  config
 }

  def getFromConfig(config:Config,jobName:String):String={
    config.getString(jobName)
  }

}
</code>```

Could some one help me what went wrong?

答:
I am guessing the file isn't on the classpath after you build with Maven.

Since you are using Maven to build a jar, you need your omega.config to be in the classpath. This means that you either have to put it into src/main/resources by default or explicitly tell Maven to add conf to the default resources classpath.

Body:
I have a spark/scala project named as Omega

I have a conf file inside Omega/conf/omega.config

I use API's from typesafe to load the config file from  conf/omega.config.
It was working fine and I was able to read the respective value for each key

Now today, For the first time I added some more key-value pairs in my omega.config file and tried to retrieve them from my scala code. It throws

 Exception in thread "main" com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'job_name'

This issue started happening after adding new value for the key job_name in my omega.config file.
Also I am not able to read the newly added -key-values, I am still able to read all old values using config. getString method

I am building my spark/scala application using maven.

Omega.config

input_path="/user/cloudera/data
user_name="surender"
job_name="SAMPLE"

I am Not able to access the recently added key "job_name" alone
   package com.pack1

import com.pack2.ApplicationUtil
object OmegaMain {

  val config_loc = "conf/omega.config"

  def main(args: Array[String]): Unit = {

   val config               = ApplicationUtil.loadConfig(config_loc)
   val jobName              = ApplicationUtil.getFromConfig(config,"job_name")
}
}

package com.pack2
import com.typesafe.config.{Config, ConfigFactory}

object ApplicationUtil {

 def loadConfig(filePath:String):Config={
  val config = ConfigFactory.parseFile(new File(filePath))

  config
 }

  def getFromConfig(config:Config,jobName:String):String={
    config.getString(jobName)
  }

}

Could some one help me what went wrong?


问:
Popover not showing in button inside table row
I have a table being built via the map function of JavaScript (ReactJS).

On the last column, I should be having buttons that are meant to open a popover that will (eventually) hold some information. This cell is being done like this:

```<code><td>
    <div>
        <button className="btn btn-primary"
                tabIndex="0"
                role="button"
                data-toggle="popover"
                data-trigger="focus"
                title="Details"
                data-content="Testing, Testing">
               <b>IN PIT</b>
         </button>
    </div>
</td>
</code>```

So far, the said button appears, but no popover whatsoever. I'm not using npm or anything of the sorts since I'm not a front-end-designer myself, and that doesn't seem trivial to setup. I just want something "good enough" for testing purposes.

What am I missing?

答:
Looking at your https://pastebin.com/KuRHjWxr. Popovers won't work, you have to implement them other way.
You initiate
$('[data-toggle="popover"]').popover();
$('[data-toggle="tooltip"]').tooltip(); when there are no buttons in DOM.

Call .popover() and .tooltip() after your buttons are successfully rendered to the DOM.

Body:
I have a table being built via the map function of JavaScript (ReactJS).

On the last column, I should be having buttons that are meant to open a popover that will (eventually) hold some information. This cell is being done like this:

        <button className="btn btn-primary"
                tabIndex="0"
                role="button"
                data-toggle="popover"
                data-trigger="focus"
                title="Details"
                data-content="Testing, Testing">
               IN PIT
         </button>

So far, the said button appears, but no popover whatsoever. I'm not using npm or anything of the sorts since I'm not a front-end-designer myself, and that doesn't seem trivial to setup. I just want something "good enough" for testing purposes.

What am I missing?


问:
How to group comma seperated columns into one single string in a unix for loop
I am working with a pipe separated list(text file), which looks like

```<code>recipename|category|list_items
-------------------------------------------
veg_quesadilla|groupA|lettuce, spinach, beans
burrito_bowl|groupA|brown_rice, black_beans, lettuce, pepper
french_fries|groupB
beverage|groupC|pepsi
</code>```

I have below statement

```<code>for recipename in `head -4 list_catalog.txt | awk -F "|" '{print $1}'`
do
if [ `cat list_catalog.txt | grep $recipename |  awk -F "|" '{print $3}'` != NULL ]
then
    for list_items in `cat list_catalog.txt | grep $recipename | awk -F "|" '{print $3}'`
do
echo -e ${list_items}
done
fi
done
</code>```

In the first loop, i am iterating over each recipe name, and i am checking if the list_items exists for each recipe. If yes, then i want to print all the column seperated items as one string, instead of seperated items. I mean all the comma separated items (which starts after second pipe symbol) as one string

Like this:

```<code>lettuce, spinach, beans
</code>```

Instead of:

```<code>lettuce,
spinach,
beans
</code>```

And when i run the code i am getting error,

```<code>line 3: [: too many arguments
</code>```

Not sure, if i am doing right with AWK or not. Please correct me.

答:
@try:

```<code>cat script.ksh
recipe_name="etc"
awk -vrec_name="$recipe_name" -F"|" '($0 ~ rec_name) && $3{print $3}'  Input_file
</code>```

Simply making field separator as | and checking $3 is present or not if yes then print $3 which means 3rd field.

Body:
I am working with a pipe separated list(text file), which looks like

recipename|category|list_items
-------------------------------------------
veg_quesadilla|groupA|lettuce, spinach, beans
burrito_bowl|groupA|brown_rice, black_beans, lettuce, pepper
french_fries|groupB
beverage|groupC|pepsi

I have below statement

for recipename in `head -4 list_catalog.txt | awk -F "|" '{print $1}'`
do
if [ `cat list_catalog.txt | grep $recipename |  awk -F "|" '{print $3}'` != NULL ]
then
    for list_items in `cat list_catalog.txt | grep $recipename | awk -F "|" '{print $3}'`
do
echo -e ${list_items}
done
fi
done

In the first loop, i am iterating over each recipe name, and i am checking if the list_items exists for each recipe. If yes, then i want to print all the column seperated items as one string, instead of seperated items. I mean all the comma separated items (which starts after second pipe symbol) as one string

Like this:

lettuce, spinach, beans

Instead of:

lettuce,
spinach,
beans

And when i run the code i am getting error,

line 3: [: too many arguments

Not sure, if i am doing right with AWK or not. Please correct me.

Body:
@try:

cat script.ksh
recipe_name="etc"
awk -vrec_name="$recipe_name" -F"|" '($0 ~ rec_name) && $3{print $3}'  Input_file

Simply making field separator as | and checking $3 is present or not if yes then print $3 which means 3rd field.


问:
What is window.Window?
I'm having trouble tracking this down for somewhat obvious reasons. What is the Window object in javascript? Not the window object..

Using console.dir(Window) in Chrome shows it has the properties PERSISTANT, TEMPORARY and a length.

答:
Window is the constructor function that is used to create window.

Try alert(window.constructor);

Title: What is window.Window?


问:
req.user is undefined Express.js Passport.js
The middleware function below can't access req.user or check is the user is logged in after the user logs in.

I know that passport.serializeUser is succeeding after the log in and that  req is defined at the time it is accessed from the middleware function.

I am new to node and its packages, so I might be missing something basic. Any help is greatly appreciated.

Middleware function:

```<code>app.use('/private/*', function(req, res, next) {
    console.log(req.user); // returns undefined
    console.log(req.isAuthenticated()) // returns false
    res.redirect('/')
});
</code>```

Full Code:

```<code>var express = require('express'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    bodyParser = require('body-parser'),
    flash = require('express-flash'),
    http = require('http');

var app = express()

app.use(flash());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(session({
secret: 'akdsgklasdglkadsgladsglk',
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize())
app.use(passport.session())
app.use(cookieParser('sdagahafdhfdshdfshfsd'))

// Store users
var users = {}

// Configure passport validation
function get_pass(username, password, callback) {
var params = {
          "username": username,
          "password": password,
          "app_token": 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
          "app_version": '1.0'
        }

var options = {
    hostname: 'sub_domain.domain.com',
    path: '/path/path/path/authenticate',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    }
};

var plasma_req = http.request(options, function(plasma_res) {
    if (plasma_res.statusCode === 201) {
        // Login passed
        plasma_res.setEncoding('utf8');
        let rawData = '';
        plasma_res.on('data', (chunk) => rawData += chunk);
        plasma_res.on('end', () => {
            try {
                let parsedData = JSON.parse(rawData);
                var user = {'username': parsedData['user']['username'],
                    'fname': parsedData['user']['first_name'],
                    'lname': parsedData['user']['last_name'],
                    'user_id': parsedData['user']['user_id'],
                    'email': parsedData['user']['email']
                };
                // add user to local database
                users["id" + user['user_id']] = user
                callback([true, user])
            } catch (e) {
                console.log(e.message);
            }
        });
    } else {
        // Login failed
        console.log('Failed Status: ' + plasma_res.statusCode);
        callback([false, {}])
    }
});
plasma_req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});
plasma_req.write(JSON.stringify(params));
plasma_req.end();
}

// Define passport strategy
passport.use(new LocalStrategy(
function (username, password, done) {
    status = get_pass(username, password, function(status) {
        if (status[0]) {
            console.log("Success")
            // return true
            return done(null, status[1])
        } else {
            console.log("Failure", status)
            // return false
            return done(null, false, { message: "Incorrect credentials"})
        }
    });
}
));

// Serialise user
passport.serializeUser(function (user, done) {
if (users['id' + user.user_id]) {
    done(null, 'id' + user.user_id);
} else {
    done(new Error("CANT_SERIALIZE_THIS_USER"));
}
});

// Deserialise user
passport.deserializeUser(function (userid, done) {
if (users[userid]) {
    done(null, users[userid]);
} else {
    done(new Error("THAT_USER_DOESNT_EXIST"));
}
});

// Login
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: 'login',
successFlash: {message : 'Welcome!'},
failureFalse: true
}));

app.use('/private/*', function(req, res, next) {
    console.log(req.user); // returns undefined
    console.log(req.isAuthenticated()) // returns false
    res.redirect('/')
});
app.use(express.static(__dirname + '/public'))

// Serve it up
var PORT = process.env.PORT || 3000;
app.listen(PORT, function () {
console.log('Server running @ port ' + PORT )
})
</code>```

答:
Fixed the problem</p>

```<code>var express = require('express'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bodyParser = require('body-parser'),
flash = require('express-flash');

var app = express()

app.use(flash());
app.use(session({
    secret: 'cat_on_keyboard',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

app.use(cookieParser('cat_on_keyboard'))
app.use(passport.initialize())
app.use(passport.session())

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Store users
var users = {
    "id1" : { user_id: 1, username: "admin", password: "admin"}
};

// Config passport local
passport.use(new LocalStrategy(
    function (username, password, done) {
        for (userid in users) {
            var user = users[userid];
            if (user.username.toLowerCase() == username.toLowerCase()) {
                if (user.password == password) {
                    return done(null, user)
                }
            }
        }
        return done(null, false, { message: "Incorect credentials" });
    }
));

// Serialise user
passport.serializeUser(function (user, done) {
    if (users['id' + user.user_id]) {
        done(null, 'id' + user.user_id);
    } else {
        done(new Error("CANT_SERIALIZE_THIS_USER"));
    }
});

// Deserialise user
passport.deserializeUser(function (userid, done) {
    if (users[userid]) {
        done(null, users[userid]);
    } else {
        done(new Error("THAT_USER_DOESNT_EXIST"));
    }
});

app.get('/', function (req, res) {
    console.log(req.flash());

    h_page = '<h1>Title of landing page</h1>' +
    '<a href="/login"><div style="display: inline-block; padding: 5px; margin: 10px; border-radius: 3px; border: 1px solid grey; cursor: pointer; background-color: #F8F8F8;"><span>Log In</span></div></a>' +
    '<a href="/private"><div style="display: inline-block; padding: 5px; margin: 10px; border-radius: 3px; border: 1px solid grey; cursor: pointer; background-color: #F8F8F8;"><span>Private</span></div></a>';

    res.send(h_page)
});

app.get("/login", function (req, res) {
    var error = req.flash("error");
    var form = '<!DOCTYPE html>' +
    '<html>' +
    '    <body>HTML Login form</body>' +
    '</html>';

    res.send(form);
});

// Login
app.post('/login', passport.authenticate('local', {
    successRedirect: '/private',
    failureRedirect: '/login',
    successFlash: {message : 'Welcome!'},
    failureFlash: true
}));

app.get('/private', authenticateOrNot, function(req, res) {
    console.log(req.flash('success'));
    res.end('Secrets');
});

function authenticateOrNot (req, res, next) {
    if (req.isAuthenticated()) {
        next()
    } else {
        console.log("Unathenticated user, redirecting to login");
        res.redirect('/login')
    }
}

// Serve it up
var PORT = process.env.PORT || 8080;
app.listen(PORT, function () {
    console.log('Server running @ port ' + PORT )
})
</code>```

Body:
The middleware function below can't access req.user or check is the user is logged in after the user logs in.

I know that passport.serializeUser is succeeding after the log in and that  req is defined at the time it is accessed from the middleware function.

I am new to node and its packages, so I might be missing something basic. Any help is greatly appreciated.

Middleware function:

app.use('/private/*', function(req, res, next) {
    console.log(req.user); // returns undefined
    console.log(req.isAuthenticated()) // returns false
    res.redirect('/')
});

Full Code:

var express = require('express'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    bodyParser = require('body-parser'),
    flash = require('express-flash'),
    http = require('http');

var app = express()

app.use(flash());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(session({
secret: 'akdsgklasdglkadsgladsglk',
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize())
app.use(passport.session())
app.use(cookieParser('sdagahafdhfdshdfshfsd'))

// Store users
var users = {}

// Configure passport validation
function get_pass(username, password, callback) {
var params = {
          "username": username,
          "password": password,
          "app_token": 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
          "app_version": '1.0'
        }

var options = {
    hostname: 'sub_domain.domain.com',
    path: '/path/path/path/authenticate',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    }
};

var plasma_req = http.request(options, function(plasma_res) {
    if (plasma_res.statusCode === 201) {
        // Login passed
        plasma_res.setEncoding('utf8');
        let rawData = '';
        plasma_res.on('data', (chunk) => rawData += chunk);
        plasma_res.on('end', () => {
            try {
                let parsedData = JSON.parse(rawData);
                var user = {'username': parsedData['user']['username'],
                    'fname': parsedData['user']['first_name'],
                    'lname': parsedData['user']['last_name'],
                    'user_id': parsedData['user']['user_id'],
                    'email': parsedData['user']['email']
                };
                // add user to local database
                users["id" + user['user_id']] = user
                callback([true, user])
            } catch (e) {
                console.log(e.message);
            }
        });
    } else {
        // Login failed
        console.log('Failed Status: ' + plasma_res.statusCode);
        callback([false, {}])
    }
});
plasma_req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});
plasma_req.write(JSON.stringify(params));
plasma_req.end();
}

// Define passport strategy
passport.use(new LocalStrategy(
function (username, password, done) {
    status = get_pass(username, password, function(status) {
        if (status[0]) {
            console.log("Success")
            // return true
            return done(null, status[1])
        } else {
            console.log("Failure", status)
            // return false
            return done(null, false, { message: "Incorrect credentials"})
        }
    });
}
));

// Serialise user
passport.serializeUser(function (user, done) {
if (users['id' + user.user_id]) {
    done(null, 'id' + user.user_id);
} else {
    done(new Error("CANT_SERIALIZE_THIS_USER"));
}
});

// Deserialise user
passport.deserializeUser(function (userid, done) {
if (users[userid]) {
    done(null, users[userid]);
} else {
    done(new Error("THAT_USER_DOESNT_EXIST"));
}
});

// Login
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: 'login',
successFlash: {message : 'Welcome!'},
failureFalse: true
}));

app.use('/private/*', function(req, res, next) {
    console.log(req.user); // returns undefined
    console.log(req.isAuthenticated()) // returns false
    res.redirect('/')
});
app.use(express.static(__dirname + '/public'))

// Serve it up
var PORT = process.env.PORT || 3000;
app.listen(PORT, function () {
console.log('Server running @ port ' + PORT )
})

Body:
Fixed the problem

var express = require('express'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bodyParser = require('body-parser'),
flash = require('express-flash');

var app = express()

app.use(flash());
app.use(session({
    secret: 'cat_on_keyboard',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

app.use(cookieParser('cat_on_keyboard'))
app.use(passport.initialize())
app.use(passport.session())

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Store users
var users = {
    "id1" : { user_id: 1, username: "admin", password: "admin"}
};

// Config passport local
passport.use(new LocalStrategy(
    function (username, password, done) {
        for (userid in users) {
            var user = users[userid];
            if (user.username.toLowerCase() == username.toLowerCase()) {
                if (user.password == password) {
                    return done(null, user)
                }
            }
        }
        return done(null, false, { message: "Incorect credentials" });
    }
));

// Serialise user
passport.serializeUser(function (user, done) {
    if (users['id' + user.user_id]) {
        done(null, 'id' + user.user_id);
    } else {
        done(new Error("CANT_SERIALIZE_THIS_USER"));
    }
});

// Deserialise user
passport.deserializeUser(function (userid, done) {
    if (users[userid]) {
        done(null, users[userid]);
    } else {
        done(new Error("THAT_USER_DOESNT_EXIST"));
    }
});

app.get('/', function (req, res) {
    console.log(req.flash());

    h_page = '<h1>Title of landing page</h1>' +
    '<a href="/login"><div style="display: inline-block; padding: 5px; margin: 10px; border-radius: 3px; border: 1px solid grey; cursor: pointer; background-color: #F8F8F8;"><span>Log In</span></div></a>' +
    '<a href="/private"><div style="display: inline-block; padding: 5px; margin: 10px; border-radius: 3px; border: 1px solid grey; cursor: pointer; background-color: #F8F8F8;"><span>Private</span></div></a>';

    res.send(h_page)
});

app.get("/login", function (req, res) {
    var error = req.flash("error");
    var form = '<!DOCTYPE html>' +
    '<html>' +
    '    <body>HTML Login form</body>' +
    '</html>';

    res.send(form);
});

// Login
app.post('/login', passport.authenticate('local', {
    successRedirect: '/private',
    failureRedirect: '/login',
    successFlash: {message : 'Welcome!'},
    failureFlash: true
}));

app.get('/private', authenticateOrNot, function(req, res) {
    console.log(req.flash('success'));
    res.end('Secrets');
});

function authenticateOrNot (req, res, next) {
    if (req.isAuthenticated()) {
        next()
    } else {
        console.log("Unathenticated user, redirecting to login");
        res.redirect('/login')
    }
}

// Serve it up
var PORT = process.env.PORT || 8080;
app.listen(PORT, function () {
    console.log('Server running @ port ' + PORT )
})


问:
How do I figure out what user & group Apache is running as?
On DreamHost shared hosting, I'm setting up htpasswd, but Apache does not have permission to read the file. How do I give it permission? I want to either change the owner or group of the .htpasswd file instead of giving it insecure permissions. I don't think I have access to the httpd.conf file, so I can't use this method to find what user Apache runs as. Also, running top or ps aux only shows the processes I'm running but doesn't show the apache process.

Based on the output from cat /etc/passwd and cat /etc/group, I'm guessing it's www-data.

Well, I followed the instructions for Password-protecting directories on Dreamhost. It generated a directory with a .htpasswd file with the group dhapache and permissions 440. It also put a .htaccess file in there with under my group. For some reason, when I try chgrp dhapache test_file.txt I get chgrp: changing group of 'test_file.txt': Operation not permitted. So, I just moved the .htpasswd file that DreamHost generated to where I wanted it and edited the .htaccess file it generated, despite its warnings.

答:
Actually, you don't need access to httpd.conf:

```<code>ps aux | grep apache2
groups apache_user
</code>```

should yield what You want

Body:
Actually, you don't need access to httpd.conf:

ps aux | grep apache2
groups apache_user

should yield what You want


问:
Python multiprocessing exception handling
Given the following program structure I am looking for a way to:

Detect child failures in the parent process

Terminate all processes (parent and children) and exit with status code 1

Achieve the above without relaxing the max queue size

Here's the code:

```<code>import multiprocessing

def worker1(queue1, queue2):
    while True:
        item = queue1.get()
        if item == 10:
            raise
        if item == 'stop':
            return
        # do something with item that generates multiple queue entries
        for x in xrange(1000):
            queue2.put(x)

def worker2(queue2, queue3):
    while True:
        item = queue2.get()
        if item == 'stop':
            return
        # do something with item, only one result to pass to the next queue
        queue3.put(1)

def worker3(queue3):
    while True:
        item = queue3.get()
        if item == 'stop':
            return
        # do something with item

def main():
    queue1 = multiprocessing.Queue()
    queue2 = multiprocessing.Queue(100)
    queue3 = multiprocessing.Queue(100)

    pool1 = multiprocessing.Pool(2, worker1, (queue1,queue2,))
    pool2 = multiprocessing.Pool(8, worker2, (queue2,queue3,))
    pool3 = multiprocessing.Pool(4, worker3, (queue3,))

    for i in xrange(100):
        queue1.put(i)
    for _ in range(pool1.__dict__['_processes']):
        queue1.put('stop')
    pool1.close()
    pool1.join()

    for _ in range(pool2.__dict__['_processes']):
        queue2.put('stop')
    pool2.close()
    pool2.join()

    for _ in range(pool3.__dict__['_processes']):
        queue3.put('stop')
    pool3.close()
    pool3.join()

    print 'finished'

if __name__ == '__main__':
    main()
</code>```

Thanks!

答:
You are kind of misusing the Pool objects here.

Instead of Pool objects, use Process objects directly.

Program the worker functions to exit with an error code when an exception is raised.

Then you can use the is_alive() method to check if the process is still running, and check the exitcode property of dead processes.

Body:
Given the following program structure I am looking for a way to:

Detect child failures in the parent process

Terminate all processes (parent and children) and exit with status code 1

Achieve the above without relaxing the max queue size

Here's the code:

import multiprocessing

def worker1(queue1, queue2):
    while True:
        item = queue1.get()
        if item == 10:
            raise
        if item == 'stop':
            return
        # do something with item that generates multiple queue entries
        for x in xrange(1000):
            queue2.put(x)

def worker2(queue2, queue3):
    while True:
        item = queue2.get()
        if item == 'stop':
            return
        # do something with item, only one result to pass to the next queue
        queue3.put(1)

def worker3(queue3):
    while True:
        item = queue3.get()
        if item == 'stop':
            return
        # do something with item

def main():
    queue1 = multiprocessing.Queue()
    queue2 = multiprocessing.Queue(100)
    queue3 = multiprocessing.Queue(100)

    pool1 = multiprocessing.Pool(2, worker1, (queue1,queue2,))
    pool2 = multiprocessing.Pool(8, worker2, (queue2,queue3,))
    pool3 = multiprocessing.Pool(4, worker3, (queue3,))

    for i in xrange(100):
        queue1.put(i)
    for _ in range(pool1.__dict__['_processes']):
        queue1.put('stop')
    pool1.close()
    pool1.join()

    for _ in range(pool2.__dict__['_processes']):
        queue2.put('stop')
    pool2.close()
    pool2.join()

    for _ in range(pool3.__dict__['_processes']):
        queue3.put('stop')
    pool3.close()
    pool3.join()

    print 'finished'

if __name__ == '__main__':
    main()

Thanks!


问:
Closing of a messagebox with space
Simple question but can't figure out how to do this.

I have a messagebox with just one single "OK" Button, which appears by catching invalid datatypes/formats on inputs.

I want that the "OK" Button will be pushed after pressing Space (and only Space)

I guess I need some sort of event, which checks if the space button is pressed (but only) on this messagebox. But somehow it sounds a bit to inconvinient for such a simple task.

答:
Well, guessing from your tags. I think you are talking about Window Forms in C#.
Yes, there is a way to do that. But not as simple as a message box. All you have to do is:

Create a Form and Design it like a MessageBox

Override the PreviewKeydown event handler ( or overriding KeyPress event handler will also work)

And then match the case when Space key is pressed.

A Sample code is below to give you an idea:

```<code>switch (e.KeyCode)
{
    case Keys.Space:
       //Call The Event handler for Ok Button
        e.Handled = true;
        e.Suppressed = true;
        break;
}
</code>```

(Note: You can also create new event handler for PreviewKeyDown Event instead of overriding. )

As you want to show it as a messagebox use ShowDialog() when showing the form instead of Show() method.

Title: Closing of a messagebox with space

Body:
Well, guessing from your tags. I think you are talking about Window Forms in C#.
Yes, there is a way to do that. But not as simple as a message box. All you have to do is:

Create a Form and Design it like a MessageBox

Override the PreviewKeydown event handler ( or overriding KeyPress event handler will also work)

And then match the case when Space key is pressed.

A Sample code is below to give you an idea:

switch (e.KeyCode)
{
    case Keys.Space:
       //Call The Event handler for Ok Button
        e.Handled = true;
        e.Suppressed = true;
        break;
}

(Note: You can also create new event handler for PreviewKeyDown Event instead of overriding. )

As you want to show it as a messagebox use ShowDialog() when showing the form instead of Show() method.


答:
When you modify any deep property or array property of an object in JavaScript you need to use isModified method in order to tell Mongoose that a property of the object is modified and update it in the database.

http://mongoosejs.com/docs/api.html#document_Document-isModified

So you need to execute it after the push function like that:

toUser.isModified('messagesArray')

Title: Mongoose: Push data to array in for loop

Body:
i have small problem i have this code:

Messages.findOne({id_user: to}, function (err, toUser) {

                    //dopisujemy wiadomość w tablicy użytkownika
                    var messArray = toUser.messagesArray;
                    //przeszukujemy tablice z wiadomościami aby znaleźć odpowiedniego użytkownika
                    for(var i=0;i<messArray.length; ++i) {
                        if(messArray[i].id_converser = who) {
                            // console.log(messArray[i]);
                            toUser.messagesArray[i].messages.push({id_converser: who,message: message,date: Date()});

                            toUser.save(function (err) {
                                if(err) console.log(err);
                                console.log('Wiadomość dodana');
                            })
                            return;

                        }
                    }

            }) //end zapisujemy wiadomość w miejscu przeznaczenia

and everything seems fine, in console i have message "wiadomosc dodana", but when i check it in database i not see this added data, why.
Thanks for reply.


问:
webclient and expect100continue
What is the best way to set expect100continue when using WebClient(C#.NET). I have this code below, I still see 100 continue in the header. Stupid apache still complains with 505 error.

```<code>        string url = "http://aaaa.com";
        ServicePointManager.Expect100Continue = false;

        WebClient service = new WebClient();
        service.Credentials = new NetworkCredential("username", "password");
        service.Headers.Add("Content-Type","text/xml");

        service.UploadStringCompleted += (sender, e) => CompleteCallback(BuildResponse(e));
        service.UploadStringAsync(new Uri(url), "POST", query);
</code>```

Note: If I put the above in a console app and let it run - then I do not see the headers in fiddler. But, my code is embedded in a user library which is loaded by a WPF app. So, Is there more to Expect100Continue in terms of thread, initialization, etc. Now, I think it is more of my code issue.

答:
The only way to do this is to create an override.

```<code>   public class ExpectContinueAware : System.Net.WebClient
    {
        protected override System.Net.WebRequest GetWebRequest(Uri address)
        {
            System.Net.WebRequest request = base.GetWebRequest(address);
            if (request is System.Net.HttpWebRequest)
            {
                var hwr = request as System.Net.HttpWebRequest;
                hwr.ServicePoint.Expect100Continue = false;
            }
            return request;
        }
    }
</code>```

This works perfect.

Title: webclient and expect100continue

Body:
What is the best way to set expect100continue when using WebClient(C#.NET). I have this code below, I still see 100 continue in the header. Stupid apache still complains with 505 error.

        string url = "http://aaaa.com";
        ServicePointManager.Expect100Continue = false;

        WebClient service = new WebClient();
        service.Credentials = new NetworkCredential("username", "password");
        service.Headers.Add("Content-Type","text/xml");

        service.UploadStringCompleted += (sender, e) => CompleteCallback(BuildResponse(e));
        service.UploadStringAsync(new Uri(url), "POST", query);

Note: If I put the above in a console app and let it run - then I do not see the headers in fiddler. But, my code is embedded in a user library which is loaded by a WPF app. So, Is there more to Expect100Continue in terms of thread, initialization, etc. Now, I think it is more of my code issue.

Body:
The only way to do this is to create an override.

   public class ExpectContinueAware : System.Net.WebClient
    {
        protected override System.Net.WebRequest GetWebRequest(Uri address)
        {
            System.Net.WebRequest request = base.GetWebRequest(address);
            if (request is System.Net.HttpWebRequest)
            {
                var hwr = request as System.Net.HttpWebRequest;
                hwr.ServicePoint.Expect100Continue = false;
            }
            return request;
        }
    }

This works perfect.


问:
Firebase Update is Making New one With the same id except last character
I am using this code to update data on Firebase but it makes new one. I tried a lot of code and it dose the same making new one with same key except last character.

I used this as the Firebase site recommended, but it doesn't work. I created a new one and the next time its update:

```<code>    Map<String, Object> childUpdate = new HashMap<>();
childUpdate.put("/masjeds/" + masjed.getId(), masjed.toMap());
reference.updateChildren(childUpdate);
</code>```

and this code done the same

```<code>     final FirebaseDatabase database = FirebaseDatabase.getInstance();
    masjeds = database.getReference("masjeds");

        reference.child(masjed.getId()).setValue(masjed, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
         //   Toast.makeText(MyMasjedsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
</code>```

Masjed Class is plain java object

```<code>public class Masjed {
private String userID;
private String id;
private String name;
private String address;
private String phone;
private boolean matloopEmam;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserID() {
    return userID;
}

public void setUserID(String userID) {
    this.userID = userID;
}

public boolean isMatloopEmam() {
    return matloopEmam;
}

public void setMatloopEmam(boolean matloopEmam) {
    this.matloopEmam = matloopEmam;
}

public Masjed(String name, String address, String phone) {
    this.name = name;
    this.address = address;
    this.phone = phone;
}

public Masjed() {

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public Map<String, Object> toMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("name", name);
    map.put("address", address);
    map.put("phone", phone);
    map.put("id", id);
    map.put("userID", userID);
    return map;
}

}
</code>```

the id is the problem I was assuming that push.getkey and put it as ID
then use push.setValue(masjed) will use the same key
it turn out that it is not always the Case the Key changes when I am use it dosnt exist and so it create new one the answer that helped me is Chester Answer

答:
```<code>   final FirebaseDatabase database = FirebaseDatabase.getInstance();
   masjeds = database.getReference("masjeds");

    // ** what is reference here? This must be masjeds **
    reference.child(masjed.getId()).setValue(masjed, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
     //   Toast.makeText(MyMasjedsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});
</code>```

I have added my findings as a comment above which I found as a suspect, you might be pointing to wrong reference. You are targeting to reference node while masjeds node is unused. Please verify it and for better understanding put Database of firebase.

Body:
I am using this code to update data on Firebase but it makes new one. I tried a lot of code and it dose the same making new one with same key except last character.

I used this as the Firebase site recommended, but it doesn't work. I created a new one and the next time its update:

    Map<String, Object> childUpdate = new HashMap<>();
childUpdate.put("/masjeds/" + masjed.getId(), masjed.toMap());
reference.updateChildren(childUpdate);

and this code done the same

     final FirebaseDatabase database = FirebaseDatabase.getInstance();
    masjeds = database.getReference("masjeds");

        reference.child(masjed.getId()).setValue(masjed, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
         //   Toast.makeText(MyMasjedsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

Masjed Class is plain java object

public class Masjed {
private String userID;
private String id;
private String name;
private String address;
private String phone;
private boolean matloopEmam;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getUserID() {
    return userID;
}

public void setUserID(String userID) {
    this.userID = userID;
}

public boolean isMatloopEmam() {
    return matloopEmam;
}

public void setMatloopEmam(boolean matloopEmam) {
    this.matloopEmam = matloopEmam;
}

public Masjed(String name, String address, String phone) {
    this.name = name;
    this.address = address;
    this.phone = phone;
}

public Masjed() {

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public Map<String, Object> toMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("name", name);
    map.put("address", address);
    map.put("phone", phone);
    map.put("id", id);
    map.put("userID", userID);
    return map;
}

}

the id is the problem I was assuming that push.getkey and put it as ID
then use push.setValue(masjed) will use the same key
it turn out that it is not always the Case the Key changes when I am use it dosnt exist and so it create new one the answer that helped me is Chester Answer

Body:
   final FirebaseDatabase database = FirebaseDatabase.getInstance();
   masjeds = database.getReference("masjeds");

    // ** what is reference here? This must be masjeds **
    reference.child(masjed.getId()).setValue(masjed, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
     //   Toast.makeText(MyMasjedsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

I have added my findings as a comment above which I found as a suspect, you might be pointing to wrong reference. You are targeting to reference node while masjeds node is unused. Please verify it and for better understanding put Database of firebase.


问:
Extract xml data from gzip file using apache tika?
I am working a project in which i need to extract xml(sitemap)data from gz file using apache tika[AM NEW TO TIKA].
the fie name is something like sitemap01.xml.gz
I could extract data from normal text file or html,but i don't know how to extract xml from gz and extract the meta and data from xml...
I searched Google for past two days.

Do i need to use delegateParser in tika to extract data from xml?
Please guide me to some sample or articles....

Here is my try

```<code>public void parseXml() throws IOException{
    Metadata metadata = new Metadata();
    ContentHandler handler = new BodyContentHandler();
    Parser parser = new AutoDetectParser();
    ParseContext context = new ParseContext();
     InputStream stream =this.getClass().getResourceAsStream("sitemap.xml.gz");
    try {
        parser.parse(stream,handler,metadata,context);
        for(int i = 0; i <metadata.names().length; i++) {
            String name = metadata.names()[i];
            System.out.println(name + " : " + metadata.get(name));
          }
        System.out.println(handler.toString());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TikaException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
         if(stream!=null) {
                stream.close();
            }
    }

}
</code>```

答:
Here is how you can use XML parser from Apache Tika for your case:</p>

```<code> //detecting the file type
  BodyContentHandler handler = new BodyContentHandler(-1);
  Metadata metadata = new Metadata();
  File inFile = new File("sitemap.xml.gz");
  System.out.println(inFile.isFile());
  FileInputStream inputstream = new FileInputStream(inFile);
  ParseContext pcontext = new ParseContext();

  //Xml parser
  XMLParser xmlparser = new XMLParser();
  xmlparser.parse(inputstream, handler, metadata, pcontext);
  System.out.println(pcontext.toString());

  System.out.println("Contents of the document:" + handler.toString());//this one contains all contents from xml files and tags are also removed
  System.out.println("Metadata of the document:");
  String[] metadataNames = metadata.names();

  for(String name : metadataNames) {
    System.out.println(name + ": " + metadata.get(name));
</code>```

Body:
I am working a project in which i need to extract xml(sitemap)data from gz file using apache tika[AM NEW TO TIKA].
the fie name is something like sitemap01.xml.gz
I could extract data from normal text file or html,but i don't know how to extract xml from gz and extract the meta and data from xml...
I searched Google for past two days.

Do i need to use delegateParser in tika to extract data from xml?
Please guide me to some sample or articles....

Here is my try

public void parseXml() throws IOException{
    Metadata metadata = new Metadata();
    ContentHandler handler = new BodyContentHandler();
    Parser parser = new AutoDetectParser();
    ParseContext context = new ParseContext();
     InputStream stream =this.getClass().getResourceAsStream("sitemap.xml.gz");
    try {
        parser.parse(stream,handler,metadata,context);
        for(int i = 0; i <metadata.names().length; i++) {
            String name = metadata.names()[i];
            System.out.println(name + " : " + metadata.get(name));
          }
        System.out.println(handler.toString());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TikaException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
         if(stream!=null) {
                stream.close();
            }
    }

}

Body:
Here is how you can use XML parser from Apache Tika for your case:

 //detecting the file type
  BodyContentHandler handler = new BodyContentHandler(-1);
  Metadata metadata = new Metadata();
  File inFile = new File("sitemap.xml.gz");
  System.out.println(inFile.isFile());
  FileInputStream inputstream = new FileInputStream(inFile);
  ParseContext pcontext = new ParseContext();

  //Xml parser
  XMLParser xmlparser = new XMLParser();
  xmlparser.parse(inputstream, handler, metadata, pcontext);
  System.out.println(pcontext.toString());

  System.out.println("Contents of the document:" + handler.toString());//this one contains all contents from xml files and tags are also removed
  System.out.println("Metadata of the document:");
  String[] metadataNames = metadata.names();

  for(String name : metadataNames) {
    System.out.println(name + ": " + metadata.get(name));


问:
Get input value on Change
I am pretty new to reactjs. I am trying to print the value 0f input. I tried doing this.

```<code> var ProductListing = React.createClass({
        onIdChange : function (a){
            //var test=0;
            console.log(a)

        },
        render : function(){
            return (

                    <div>
                        <div className="field">
                            <label htmlFor="">Id :</label>
                            <input type="number" id="txtId"  onChange={this.onIdChange.bind(this)}/>
                        </div>
</code>```

This doesn't work. How can I do it?

答:
Your code seems correct. As your method is already getting called, just try  this code.

```<code>onIdChange : function (e){
          this.setState({inputValue:e.target.value})
            console.log(e.target.value)
    },
</code>```

And add value attribute like this,

```<code><input type="number" id="txtId" value={this.state.inputValue} onChange={this.onIdChange.bind(this)}/>
</code>```

Title: Get input value on Change

Body:
I am pretty new to reactjs. I am trying to print the value 0f input. I tried doing this.

 var ProductListing = React.createClass({
        onIdChange : function (a){
            //var test=0;
            console.log(a)

        },
        render : function(){
            return (

                            Id :
                            <input type="number" id="txtId"  onChange={this.onIdChange.bind(this)}/>

This doesn't work. How can I do it?

Body:
Your code seems correct. As your method is already getting called, just try  this code.

onIdChange : function (e){
          this.setState({inputValue:e.target.value})
            console.log(e.target.value)
    },

And add value attribute like this,

<input type="number" id="txtId" value={this.state.inputValue} onChange={this.onIdChange.bind(this)}/>


答:
It's the interface that the global window object is an instance of. MDN says:

The window object implements the Window interface, which in turn inherits from the AbstractView interface.

A W3C spec defines the interface here: https://www.w3.org/TR/html5/browsers.html#window

Title: What is window.Window?

Body:
I'm having trouble tracking this down for somewhat obvious reasons. What is the Window object in javascript? Not the window object..

Using console.dir(Window) in Chrome shows it has the properties PERSISTANT, TEMPORARY and a length.