问:
scrolling home menu nog working on detail page
We are building a one pager website with a detail page to the protfolio items. Now we have the menu scrolling on the homepage to the content on that page.

So i'm having the menu items ike this.

```<code><ul>
<li><a href="section-1">Section 1</a></li>
<li><a href="section-2">Section 2</a></li>
<li><a href="section-3">Section 3</a></li>
<li><a href="section-4">Section 4</a></li>
</ul>
</code>```

The content divs are build up like this

```<code><div id="section-1">Content</div>
</code>```

Now here is the jquery i'm using, which is working fine on the homepage

```<code>// Function: Scroll navigation to row
$('.navbar a').on('click', function(e) {
    e.preventDefault();
    var $row = $($(this).attr('href'));
    $('html, body').animate({
        scrollTop: ($row.offset().top - menuHeight - 78)
    }, 1000);
});
</code>```

So now when i'm on the detail page i just want to click on any menu item and then go back to the homepage at the right content.

But clicking on that wont work, i'm getting this error.

```<code>Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (website.js:26)
at HTMLAnchorElement.dispatch (jquery.js:3)
at HTMLAnchorElement.v.handle (jquery.js:3)
</code>```

I tried some many things already, adding the absolute path to the url, but i would like to work around with that, because it wont scroll to the content then..

答:
While $(this).attr('href') output will be section-1 You need to use #

```<code>var $row = $('#' + $(this).attr('href'));
</code>```

OR or not and you need to add # in href for all links like

```<code><ul>
  <li><a href="#section-1">Section 1</a></li>
  <li><a href="#section-2">Section 2</a></li>
  <li><a href="#section-3">Section 3</a></li>
  <li><a href="#section-4">Section 4</a></li>
</ul>
</code>```

Note: This code will work if all the elements in the same page

And about your question about on the detail page i just want to click on any menu item and then go back to the homepage at the right content.

let's start doing that

1st: You need to check the url for detail page if its the detail page stop click event

So we will assume you detail page is detail.html

On html

```<code><ul>
  <li><a href="http://www.yourwebsite/index.html#section-1">Section 1</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-2">Section 2</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-3">Section 3</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-4">Section 4</a></li>
</ul>
</code>```

on Js

```<code>$(document).ready(function(){
   var menuHeight = $('.navbar a').outerHeight(true);
   // Function: Scroll navigation to row
   $('.navbar a').on('click', function(e) {
    if(window.location.href.indexOf("detail.html") === -1) { // if url dosen't have the detail page so active the click event
      e.preventDefault(); // prevent redirect
      var $href = $(this).attr('href'); // get href
      var section = $('#' + $href.substr($href.indexOf("#") + 1));  // get the section from href
      $('html, body').animate({
          scrollTop: (section.offset().top - menuHeight - 78)
      }, 1000);
     }
  });
  // on load
   var url = window.location.href;  // get the page url
   if(window.location.hash.substr(1) !== ''){
     var section = window.location.hash.substr(1);  // get the section after the `#` on url
     $('.navbar a[href*='+section+']').click(); // if url href with this section trigger click it
   }
});
</code>```

And here is how your code should work on index page

$(document).ready(function(){
   var menuHeight = $('.navbar a').outerHeight(true);
   // Function: Scroll navigation to row
   $('.navbar a').on('click', function(e) {
    if(window.location.href.indexOf("detail.html") === -1) { // if url dosen't have the detail page so active the click event
      e.preventDefault(); // prevent redirect
      var $href = $(this).attr('href'); // get href
      var section = $('#' + $href.substr($href.indexOf("#") + 1));  // get the section from href
      $('html, body').animate({
          scrollTop: (section.offset().top - menuHeight - 78)
      }, 1000);
     }
  });
  // on load
   var url = window.location.href;  // get the page url
   if(window.location.hash.substr(1) !== ''){
     var section = window.location.hash.substr(1);  // get the section after the `#` on url
     $('.navbar a[href*='+section+']').click(); // if url href with this section trigger click it
   }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar{
 position : fixed;
 background : yellow;
 top : 0;
 left:0;
 right: 0;
 margin: 0;
 padding: 0;
}
div[id^=section]{
 background : red;
 margin : 30px;
 min-height: 300px;
}
#section-1{
 margin-top : 100px;
}</code>```

Section 1

Section 2

Section 3

Section 4

Section 1

Section 2

Section 3

Section 4
```
</div>
</div>
</p>

<p>And this is for how your code should works if returned back from <code>detail</code> page</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
   var url = 'http://www.yourwebsite/index.html#section-2';
   var menuHeight = $('.navbar a').outerHeight(true);
   // Function: Scroll navigation to row
   $('.navbar a').on('click', function(e) {
    if(window.location.href.indexOf("detail.html") === -1) { // if url dosen't have the detail page so active the click event
      e.preventDefault(); // prevent redirect
      var $href = $(this).attr('href'); // get href
      var section = $('#' + $href.substr($href.indexOf("#") + 1));  // get the section from href
      $('html, body').animate({
          scrollTop: (section.offset().top - menuHeight - 78)
      }, 1000);
     }
  });
  // on load
   //var url = window.location.href;  // get the page url
   //if(window.location.hash.substr(1) !== ''){
     var section = url.substr(url.indexOf("#") + 1);  // get the section after the `#` on url
   //alert(section);
     $('.navbar a[href*='+section+']').click(); // if url href with this section trigger click it
   //}
});</code>```

.navbar{
 position : fixed;
 background : yellow;
 top : 0;
 left:0;
 right: 0;
 margin: 0;
 padding: 0;
}
div[id^=section]{
 background : red;
 margin : 30px;
 min-height: 300px;
}
#section-1{
 margin-top : 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navbar">
  <li>Section 1</li>
  <li>Section 2</li>
  <li>Section 3</li>
  <li>Section 4</li>
</ul>
<div id="section-1">Section 1</div>
<div id="section-2">Section 2</div>
<div id="section-3">Section 3</div>
<div id="section-4">Section 4</div></code>```

Body:
We are building a one pager website with a detail page to the protfolio items. Now we have the menu scrolling on the homepage to the content on that page.

So i'm having the menu items ike this.

Section 1

Section 2

Section 3

Section 4

The content divs are build up like this

Content

Now here is the jquery i'm using, which is working fine on the homepage

// Function: Scroll navigation to row
$('.navbar a').on('click', function(e) {
    e.preventDefault();
    var $row = $($(this).attr('href'));
    $('html, body').animate({
        scrollTop: ($row.offset().top - menuHeight - 78)
    }, 1000);
});

So now when i'm on the detail page i just want to click on any menu item and then go back to the homepage at the right content.

But clicking on that wont work, i'm getting this error.

Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLAnchorElement.<anonymous> (website.js:26)
at HTMLAnchorElement.dispatch (jquery.js:3)
at HTMLAnchorElement.v.handle (jquery.js:3)

I tried some many things already, adding the absolute path to the url, but i would like to work around with that, because it wont scroll to the content then..

Body:
While $(this).attr('href') output will be section-1 You need to use #

var $row = $('#' + $(this).attr('href'));

OR or not and you need to add # in href for all links like

<ul>
  <li><a href="#section-1">Section 1</a></li>
  <li><a href="#section-2">Section 2</a></li>
  <li><a href="#section-3">Section 3</a></li>
  <li><a href="#section-4">Section 4</a></li>
</ul>

Note: This code will work if all the elements in the same page

And about your question about on the detail page i just want to click on any menu item and then go back to the homepage at the right content.

let's start doing that

1st: You need to check the url for detail page if its the detail page stop click event

So we will assume you detail page is detail.html

On html

<ul>
  <li><a href="http://www.yourwebsite/index.html#section-1">Section 1</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-2">Section 2</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-3">Section 3</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-4">Section 4</a></li>
</ul>

on Js

$(document).ready(function(){
   var menuHeight = $('.navbar a').outerHeight(true);
   // Function: Scroll navigation to row
   $('.navbar a').on('click', function(e) {
    if(window.location.href.indexOf("detail.html") === -1) { // if url dosen't have the detail page so active the click event
      e.preventDefault(); // prevent redirect
      var $href = $(this).attr('href'); // get href
      var section = $('#' + $href.substr($href.indexOf("#") + 1));  // get the section from href
      $('html, body').animate({
          scrollTop: (section.offset().top - menuHeight - 78)
      }, 1000);
     }
  });
  // on load
   var url = window.location.href;  // get the page url
   if(window.location.hash.substr(1) !== ''){
     var section = window.location.hash.substr(1);  // get the section after the `#` on url
     $('.navbar a[href*='+section+']').click(); // if url href with this section trigger click it
   }
});

And here is how your code should work on index page

$(document).ready(function(){
   var menuHeight = $('.navbar a').outerHeight(true);
   // Function: Scroll navigation to row
   $('.navbar a').on('click', function(e) {
    if(window.location.href.indexOf("detail.html") === -1) { // if url dosen't have the detail page so active the click event
      e.preventDefault(); // prevent redirect
      var $href = $(this).attr('href'); // get href
      var section = $('#' + $href.substr($href.indexOf("#") + 1));  // get the section from href
      $('html, body').animate({
          scrollTop: (section.offset().top - menuHeight - 78)
      }, 1000);
     }
  });
  // on load
   var url = window.location.href;  // get the page url
   if(window.location.hash.substr(1) !== ''){
     var section = window.location.hash.substr(1);  // get the section after the `#` on url
     $('.navbar a[href*='+section+']').click(); // if url href with this section trigger click it
   }
});

.navbar{
 position : fixed;
 background : yellow;
 top : 0;
 left:0;
 right: 0;
 margin: 0;
 padding: 0;
}
div[id^=section]{
 background : red;
 margin : 30px;
 min-height: 300px;
}
#section-1{
 margin-top : 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navbar">
  <li><a href="http://www.yourwebsite/index.html#section-1">Section 1</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-2">Section 2</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-3">Section 3</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-4">Section 4</a></li>
</ul>
<div id="section-1">Section 1</div>
<div id="section-2">Section 2</div>
<div id="section-3">Section 3</div>
<div id="section-4">Section 4</div>

And this is for how your code should works if returned back from detail page

$(document).ready(function(){
   var url = 'http://www.yourwebsite/index.html#section-2';
   var menuHeight = $('.navbar a').outerHeight(true);
   // Function: Scroll navigation to row
   $('.navbar a').on('click', function(e) {
    if(window.location.href.indexOf("detail.html") === -1) { // if url dosen't have the detail page so active the click event
      e.preventDefault(); // prevent redirect
      var $href = $(this).attr('href'); // get href
      var section = $('#' + $href.substr($href.indexOf("#") + 1));  // get the section from href
      $('html, body').animate({
          scrollTop: (section.offset().top - menuHeight - 78)
      }, 1000);
     }
  });
  // on load
   //var url = window.location.href;  // get the page url
   //if(window.location.hash.substr(1) !== ''){
     var section = url.substr(url.indexOf("#") + 1);  // get the section after the `#` on url
   //alert(section);
     $('.navbar a[href*='+section+']').click(); // if url href with this section trigger click it
   //}
});

.navbar{
 position : fixed;
 background : yellow;
 top : 0;
 left:0;
 right: 0;
 margin: 0;
 padding: 0;
}
div[id^=section]{
 background : red;
 margin : 30px;
 min-height: 300px;
}
#section-1{
 margin-top : 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navbar">
  <li><a href="http://www.yourwebsite/index.html#section-1">Section 1</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-2">Section 2</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-3">Section 3</a></li>
  <li><a href="http://www.yourwebsite/index.html#section-4">Section 4</a></li>
</ul>
<div id="section-1">Section 1</div>
<div id="section-2">Section 2</div>
<div id="section-3">Section 3</div>
<div id="section-4">Section 4</div>


来源: stackexchange

问:
How do you set the color of a Google calendar event using the API
This question has been asked a while ago but has not been answered. I think things have moved on since.

I can create an event using the API but I am unable to set the colour to anything other than the default. This is :colorId is not working? Any ideas?

```<code>    event = Google::Apis::CalendarV3::Event.new({
                                                    :summary => @measure.value,

                                                    :description => 'created by ' + current_user.username,
                                                    :start => {
                                                        :date_time => event_starttime
                                                    },
                                                    :end => {
                                                        :date_time => event_endtime
                                                    },
                                                    :colorId => "6"
                                                })
</code>```

答:
In creating calendar events using Events.insert, there's an optional property called colorId

colorId   string  The color of the event. This is an ID referring to an
  entry in the event section of the colors definition (see the colors
  endpoint). Optional.  writable

Check the Colors property resource on format for setting background and foreground colors.

ContentLicense: CC BY-SA 3.0

Body:
This question has been asked a while ago but has not been answered. I think things have moved on since.

I can create an event using the API but I am unable to set the colour to anything other than the default. This is :colorId is not working? Any ideas?

    event = Google::Apis::CalendarV3::Event.new({
                                                    :summary => @measure.value,

                                                    :description => 'created by ' + current_user.username,
                                                    :start => {
                                                        :date_time => event_starttime
                                                    },
                                                    :end => {
                                                        :date_time => event_endtime
                                                    },
                                                    :colorId => "6"
                                                })


问:
whats wrong with this code?
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

```<code>for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}
</code>```

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

```<code>for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }
</code>```

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

```<code>for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }
</code>```

答:
I would re-write your code like this, and see what output you get:

```<code>for (filename : filenames) {
   if (filename.matches(".*ham.*")) {
      System.out.println("ham:" + filename);

      // reset these to null (where are they declared?)
      read = null;
      br = null;
      try {
         read = new FileReader("trainfiles/"+filename);
         br = new BufferedReader(read);

         while ((lines = br.readLine()) != null) {
            System.out.println(lines);
            // st = new StringTokenizer(lines);
            // while (st.hasMoreTokens()) {
            //    System.out.println(st.nextToken());
            // }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (br != null) br.close();
         if (read != null) read.close();
      }
   }
}
</code>```

Some general comments on your original code:

Only use a for loop if you actually need the array index. Prefer a for-each loop (i.e. for (filename : filenames) ...).

Declare variables in the narrowest scope possible.  In this case, you should declare your read and br variables where I initialize them to null.

Never open a file unless you're going to use it.  Here, that means opening it inside the conditional block.

Since opening a file can throw an exception, br may not get initialized, in which case you can't close it. You need to check for null first.

ContentLicense: CC BY-SA 2.5

Title: whats wrong with this code?

Body:
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }

Body:
I would re-write your code like this, and see what output you get:

for (filename : filenames) {
   if (filename.matches(".*ham.*")) {
      System.out.println("ham:" + filename);

      // reset these to null (where are they declared?)
      read = null;
      br = null;
      try {
         read = new FileReader("trainfiles/"+filename);
         br = new BufferedReader(read);

         while ((lines = br.readLine()) != null) {
            System.out.println(lines);
            // st = new StringTokenizer(lines);
            // while (st.hasMoreTokens()) {
            //    System.out.println(st.nextToken());
            // }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (br != null) br.close();
         if (read != null) read.close();
      }
   }
}

Some general comments on your original code:

Only use a for loop if you actually need the array index. Prefer a for-each loop (i.e. for (filename : filenames) ...).

Declare variables in the narrowest scope possible.  In this case, you should declare your read and br variables where I initialize them to null.

Never open a file unless you're going to use it.  Here, that means opening it inside the conditional block.

Since opening a file can throw an exception, br may not get initialized, in which case you can't close it. You need to check for null first.


问:
Click Command Line Interfaces: Make options required if other optional option is unset
When writing a command-line interface (CLI) with the Python click library, is it possible to define e.g. three options where the second and third one are only required if the first (optional) one was left unset?

My use case is a log-in system which allows me to authenticate either via an authentication token (option 1), or, alternatively, via username (option 2) and password (option 3).

If the token was given, there is no need to check for username and password being defined or prompting them. Otherwise, if the token was omitted then username and password become required and must be given.

Can this be done somehow using callbacks?

My code to get started which of course does not reflect the intended pattern:

```<code>@click.command()
@click.option('--authentication-token', prompt=True, required=True)
@click.option('--username', prompt=True, required=True)
@click.option('--password', hide_input=True, prompt=True, required=True)
def login(authentication_token, username, password):
    print(authentication_token, username, password)

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

答:
This can be done by building a custom class derived from click.Option, and in that class over riding the click.Option.handle_parse_result() method like:

Custom Class:

```<code>import click

class NotRequiredIf(click.Option):
    def __init__(self, *args, **kwargs):
        self.not_required_if = kwargs.pop('not_required_if')
        assert self.not_required_if, "'not_required_if' parameter required"
        kwargs['help'] = (kwargs.get('help', '') +
            ' NOTE: This argument is mutually exclusive with %s' %
            self.not_required_if
        ).strip()
        super(NotRequiredIf, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        we_are_present = self.name in opts
        other_present = self.not_required_if in opts

        if other_present:
            if we_are_present:
                raise click.UsageError(
                    "Illegal usage: `%s` is mutually exclusive with `%s`" % (
                        self.name, self.not_required_if))
            else:
                self.prompt = None

        return super(NotRequiredIf, self).handle_parse_result(
            ctx, opts, args)
</code>```

Using Custom Class:

To use the custom class, pass the cls parameter to click.option decorator like:

```<code>@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
</code>```

How does this work?

This works because click is a well designed OO framework. The @click.option() decorator usually instantiates a click.Option object but allows this behavior to be overridden with the cls parameter. So it is a relatively easy matter to inherit from click.Option in our own class and over ride the desired methods.

In this case we over ride click.Option.handle_parse_result() and disable the need to user/password if authentication-token token is present, and complain if both user/password are authentication-token are present.

Note: This answer was inspired by this answer

Test Code:

```<code>@click.command()
@click.option('--authentication-token')
@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
@click.option('--password', prompt=True, hide_input=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
def login(authentication_token, username, password):
    click.echo('t:%s  u:%s  p:%s' % (
        authentication_token, username, password))

if __name__ == '__main__':
    login('--username name --password pword'.split())
    login('--help'.split())
    login(''.split())
    login('--username name'.split())
    login('--authentication-token token'.split())
</code>```

Results:

from login('--username name --password pword'.split()):

```<code>t:None  u:name  p:pword
</code>```

from login('--help'.split()):

```<code>Usage: test.py [OPTIONS]

Options:
  --authentication-token TEXT
  --username TEXT              NOTE: This argument is mutually exclusive with
                               authentication_token
  --password TEXT              NOTE: This argument is mutually exclusive with
                               authentication_token
  --help                       Show this message and exit.
</code>```

Body:
When writing a command-line interface (CLI) with the Python click library, is it possible to define e.g. three options where the second and third one are only required if the first (optional) one was left unset?

My use case is a log-in system which allows me to authenticate either via an authentication token (option 1), or, alternatively, via username (option 2) and password (option 3).

If the token was given, there is no need to check for username and password being defined or prompting them. Otherwise, if the token was omitted then username and password become required and must be given.

Can this be done somehow using callbacks?

My code to get started which of course does not reflect the intended pattern:

@click.command()
@click.option('--authentication-token', prompt=True, required=True)
@click.option('--username', prompt=True, required=True)
@click.option('--password', hide_input=True, prompt=True, required=True)
def login(authentication_token, username, password):
    print(authentication_token, username, password)

if __name__ == '__main__':
    login()

Body:
This can be done by building a custom class derived from click.Option, and in that class over riding the click.Option.handle_parse_result() method like:

Custom Class:

import click

class NotRequiredIf(click.Option):
    def __init__(self, *args, **kwargs):
        self.not_required_if = kwargs.pop('not_required_if')
        assert self.not_required_if, "'not_required_if' parameter required"
        kwargs['help'] = (kwargs.get('help', '') +
            ' NOTE: This argument is mutually exclusive with %s' %
            self.not_required_if
        ).strip()
        super(NotRequiredIf, self).__init__(*args, **kwargs)

    def handle_parse_result(self, ctx, opts, args):
        we_are_present = self.name in opts
        other_present = self.not_required_if in opts

        if other_present:
            if we_are_present:
                raise click.UsageError(
                    "Illegal usage: `%s` is mutually exclusive with `%s`" % (
                        self.name, self.not_required_if))
            else:
                self.prompt = None

        return super(NotRequiredIf, self).handle_parse_result(
            ctx, opts, args)

Using Custom Class:

To use the custom class, pass the cls parameter to click.option decorator like:

@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')

How does this work?

This works because click is a well designed OO framework. The @click.option() decorator usually instantiates a click.Option object but allows this behavior to be overridden with the cls parameter. So it is a relatively easy matter to inherit from click.Option in our own class and over ride the desired methods.

In this case we over ride click.Option.handle_parse_result() and disable the need to user/password if authentication-token token is present, and complain if both user/password are authentication-token are present.

Note: This answer was inspired by this answer

Test Code:

@click.command()
@click.option('--authentication-token')
@click.option('--username', prompt=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
@click.option('--password', prompt=True, hide_input=True, cls=NotRequiredIf,
              not_required_if='authentication_token')
def login(authentication_token, username, password):
    click.echo('t:%s  u:%s  p:%s' % (
        authentication_token, username, password))

if __name__ == '__main__':
    login('--username name --password pword'.split())
    login('--help'.split())
    login(''.split())
    login('--username name'.split())
    login('--authentication-token token'.split())

Results:

from login('--username name --password pword'.split()):

t:None  u:name  p:pword

from login('--help'.split()):

Usage: test.py [OPTIONS]

Options:
  --authentication-token TEXT
  --username TEXT              NOTE: This argument is mutually exclusive with
                               authentication_token
  --password TEXT              NOTE: This argument is mutually exclusive with
                               authentication_token
  --help                       Show this message and exit.


问:
How to extract weights and biases in h2o model if export_weights_and_bias argument was set to FALSE?
I have an h2o deeplearning model, "model1", that generalizes very well. Unfortunately, I forgot to set export weights and biases = TRUE when building the model.

I've tried to retrain numerous models with all the exact parameters, seed, and dataset as in the original model1 plus added set export weights and biases to true.

Unfortunately none of these new models generalize well at all. In fact they all fail miserably to generalize - although all models train, validate, cross-validate and test very well. I've even tried checkpointing the original model1 so I can add the export weights and biases argument = TRUE. However, because I did not use Modulo CV, I'm unable to checkpoint.

Irreproducibility is giving me a huge headache. In order for me to productionalize, I need to somehow extract the weights and biases of this original, working model1 - despite export weights and biases being originally set to FALSE.

I've looked at the mean weights and biases of model1 and they simply do not match any of mean weights and biases of my retrained models with same parameters, seed, dataset, etc. I'm uncertain if mean weights and biases can be used somehow to force reproducibility.

I've read that downloading model1 to POJO may allow access to the weights and biases, but I'm uncertain about this, I don't know java and I don't see any example java code to help me along.

Any suggestions or other possible solutions/workarounds?

Thank you in advance for any help.

答:
I partially resolved this on my own: after downloading model to POJO, I opened up the file with a text editor based on Darren Cook's suggestion (thank you), and I think I can see all the weights and biases here.

I'm not certain however b/c I'm unfamiliar with the POJO format.


问:
Read a config file in BASH without using "source"
I'm attempting to read a config file that is formatted as follows:

```<code>USER = username
TARGET = arrows
</code>```

I realize that if I got rid of the spaces, I could simply source the config file, but for security reasons I'm trying to avoid that.  I know there is a way to read the config file line by line.  I think the process is something like:

Read lines into an array

Filter out all of the lines that start with #

search for the variable names in the array

After that I'm lost.  Any and all help would be greatly appreciated. I've tried something like this with no success:

```<code>backup2.config>cat ~/1

grep '^[^#].*' | while read one two;do
    echo $two
done
</code>```

I pulled that from a forum post I found, just not sure how to modify it to fit my needs since I'm so new to shell scripting.

http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/

Would it be possible to automatically assign a variable by looping through both arrays?

```<code>for (( i = 0 ; i < ${#VALUE[@]} ; i++ ))
do
    "${NAME[i]}"=VALUE[i]
done
echo $USER
</code>```

Such that calling $USER would output "username"?  The above code isn't working but I know the solution is something similar to that.

答:
First, USER is a shell environment variable, so it might be better if you used something else. Using lowercase or mixed case variable names is a way to avoid name collisions.

#!/bin/bash
configfile="/path/to/file"
shopt -s extglob
while IFS='= ' read lhs rhs
do
    if [[ $lhs != *( )#* ]]
    then
        # you can test for variables to accept or other conditions here
        declare $lhs=$rhs
    fi
done < "$configfile"
```

<p>This sets the vars in your file to the value associated with it.</p>

<pre class="lang-sh prettyprint-override"><code>echo "Username: $USER, Target: $TARGET"
</code>```

would output

Username: username, Target: arrows

Another way to do this using keys and values is with an associative array:

Add this line before the while loop:

declare -A settings
```

<p>Remove the <code>declare</code> line inside the <code>while</code> loop and replace it with:</p>

<pre class="lang-sh prettyprint-override"><code>    settings[$lhs]=$rhs
</code>```

Then:

# set keys
user=USER
target=TARGET
# access values
echo "Username: ${settings[$user]}, Target: ${settings[$target]}"
```

would output

Username: username, Target: arrows

Body:
I'm attempting to read a config file that is formatted as follows:

USER = username
TARGET = arrows

I realize that if I got rid of the spaces, I could simply source the config file, but for security reasons I'm trying to avoid that.  I know there is a way to read the config file line by line.  I think the process is something like:

Read lines into an array

Filter out all of the lines that start with #

search for the variable names in the array

After that I'm lost.  Any and all help would be greatly appreciated. I've tried something like this with no success:

backup2.config>cat ~/1

grep '^[^#].*' | while read one two;do
    echo $two
done

I pulled that from a forum post I found, just not sure how to modify it to fit my needs since I'm so new to shell scripting.

http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/

Would it be possible to automatically assign a variable by looping through both arrays?

for (( i = 0 ; i < ${#VALUE[@]} ; i++ ))
do
    "${NAME[i]}"=VALUE[i]
done
echo $USER

Such that calling $USER would output "username"?  The above code isn't working but I know the solution is something similar to that.

Body:
First, USER is a shell environment variable, so it might be better if you used something else. Using lowercase or mixed case variable names is a way to avoid name collisions.

#!/bin/bash
configfile="/path/to/file"
shopt -s extglob
while IFS='= ' read lhs rhs
do
    if [[ $lhs != *( )#* ]]
    then
        # you can test for variables to accept or other conditions here
        declare $lhs=$rhs
    fi
done < "$configfile"

This sets the vars in your file to the value associated with it.

echo "Username: $USER, Target: $TARGET"

would output

Username: username, Target: arrows

Another way to do this using keys and values is with an associative array:

Add this line before the while loop:

declare -A settings

Remove the declare line inside the while loop and replace it with:

    settings[$lhs]=$rhs

Then:

# set keys
user=USER
target=TARGET
# access values
echo "Username: ${settings[$user]}, Target: ${settings[$target]}"

would output

Username: username, Target: arrows

ContentLicense: CC BY-SA 4.0


问:
Python - youtube-dl force login everytime
I want to download multiple files using youtube-dl from a site the needs login.

The issue that I have is that youtube-dl is login for the first video with no issue, but doesn't login again for next video.

How do I force youtube-dl to login for each video, every time the function is called ? Maybe reset,stop youtube-dl every time.

```<code>def video_download(path, url):

        ydl = youtube_dl.YoutubeDL(
            {
                'outtmpl': path + '.mp4',
                'format': 'bestvideo+bestaudio/best',
                'username': email,
                'password': password,
                # 'quiet': True

            })

        with ydl:
            ydl.download([url])
        time.sleep(45)
</code>```

The function is actually  called in a loop, because I set outtmpl for each file/video.

Different instances, the first one is working, the next don't login again.
I need every time the login to repeat.

```<code><youtube_dl.YoutubeDL.YoutubeDL object at 0x0000000004E74C18>
<youtube_dl.YoutubeDL.YoutubeDL object at 0x00000000032BED68>
WARNING: Unable to download kaltura session JSON: HTTP Error 401: UNAUTHORIZED
<youtube_dl.YoutubeDL.YoutubeDL object at 0x0000000004D6D898>
WARNING: Unable to download kaltura session JSON: HTTP Error 401: UNAUTHORIZED

Terminal/Output:

<youtube_dl.YoutubeDL.YoutubeDL object at 0x00000000050E4C18>
**[safari] Downloading login form
[safari] Login successful**
[safari] 9781787283664/video1_1: Downloading webpage
.............................
<youtube_dl.YoutubeDL.YoutubeDL object at 0x000000000337DD68>
[safari] 9781787283664/video1_2: Downloading webpage
[safari] 9781787283664/video1_2: Downloading kaltura session JSON
WARNING: Unable to download kaltura session JSON: HTTP Error 401: UNAUTHORIZED
</code>```

---- Update ---

I tried to use command line but I have the following error, which is not appearing if I use the python import:

ERROR: fixed output name but more than one file to download

The cmd:

```<code>youtube-dl -u username_paceholder -p password_paceholder -o 'D:\DevProj\DownloadCourses\Safari\x_downloads\Django1 \_01_Django ABC' https://www.site_placeholder.com/library/view/django-example/9781787283664/video1_2.html
</code>```

答:
Why not use the command-line ?

You can personalize the filename and folder location - and you will be sure that authentication will be done each time you run youtube-dl command (if -u and -p arguments are given)

Try something like:

```<code>import os

def video_download(path="c:\\mydir\\myfile", url="http://myvideo./url"):

    #user information
    user="myuser"
    pwd="mypwd"

    #build cmd line
    cmd="youtube-dl -u "+user+" -p "+pwd+' -o "'+path+'" '+url

    #execute commande line
    os.system(cmd)

    [...]
</code>```

Body:
I want to download multiple files using youtube-dl from a site the needs login.

The issue that I have is that youtube-dl is login for the first video with no issue, but doesn't login again for next video.

How do I force youtube-dl to login for each video, every time the function is called ? Maybe reset,stop youtube-dl every time.

def video_download(path, url):

        ydl = youtube_dl.YoutubeDL(
            {
                'outtmpl': path + '.mp4',
                'format': 'bestvideo+bestaudio/best',
                'username': email,
                'password': password,
                # 'quiet': True

            })

        with ydl:
            ydl.download([url])
        time.sleep(45)

The function is actually  called in a loop, because I set outtmpl for each file/video.

Different instances, the first one is working, the next don't login again.
I need every time the login to repeat.

<youtube_dl.YoutubeDL.YoutubeDL object at 0x0000000004E74C18>
<youtube_dl.YoutubeDL.YoutubeDL object at 0x00000000032BED68>
WARNING: Unable to download kaltura session JSON: HTTP Error 401: UNAUTHORIZED
<youtube_dl.YoutubeDL.YoutubeDL object at 0x0000000004D6D898>
WARNING: Unable to download kaltura session JSON: HTTP Error 401: UNAUTHORIZED

Terminal/Output:

<youtube_dl.YoutubeDL.YoutubeDL object at 0x00000000050E4C18>
**[safari] Downloading login form
[safari] Login successful**
[safari] 9781787283664/video1_1: Downloading webpage
.............................
<youtube_dl.YoutubeDL.YoutubeDL object at 0x000000000337DD68>
[safari] 9781787283664/video1_2: Downloading webpage
[safari] 9781787283664/video1_2: Downloading kaltura session JSON
WARNING: Unable to download kaltura session JSON: HTTP Error 401: UNAUTHORIZED

---- Update ---

I tried to use command line but I have the following error, which is not appearing if I use the python import:

ERROR: fixed output name but more than one file to download

The cmd:

youtube-dl -u username_paceholder -p password_paceholder -o 'D:\DevProj\DownloadCourses\Safari\x_downloads\Django1 \_01_Django ABC' https://www.site_placeholder.com/library/view/django-example/9781787283664/video1_2.html

Body:
Why not use the command-line ?

You can personalize the filename and folder location - and you will be sure that authentication will be done each time you run youtube-dl command (if -u and -p arguments are given)

Try something like:

import os

def video_download(path="c:\\mydir\\myfile", url="http://myvideo./url"):

    #user information
    user="myuser"
    pwd="mypwd"

    #build cmd line
    cmd="youtube-dl -u "+user+" -p "+pwd+' -o "'+path+'" '+url

    #execute commande line
    os.system(cmd)

    [...]


问:
python oracle if else issues for rows fetch
my requirements is following. Find a count(*) for a table and if not exists, create one.following is the sample code to show the issue. in both cases the else condition is coming. not sure how I achieve this, any help is appreciated.  </p>

```<code>import cx_Oracle
import os
import datetime

ts = datetime.datetime.now()
con = cx_Oracle.connect('xxxx/xxxx@xxxxx:1521/xxxxx')
print con.version
cur = con.cursor()
cur.execute('select count(*) from AAA.AAA_TEST')
rows = cur.fetchall();
print rows
print len(rows)
if (rows ==1):
  print 'there is a row'
else:
  print 'there is no row'

#result 1 where the row exists
11.2.0.4.0
[(1,)]
1
there is no row

Process finished with exit code 0

#result 2 where the row do not exists
11.2.0.4.0
[(0,)]
1
there is no row

Process finished with exit code 0
</code>```

答:
SELECT COUNT(*) always returns a row — either with 0 if there are no object in the table or with the number of objects. So there is always 1 row and you should test the count, not the number of rows. So use if (rows[0][0] >= 1):

rows[0] returns the first row, rows[0][0] gives the first column of the first row; for your SELECT COUNT(*) the first column is the count, so you test if the count is 0 of if it's >= 1.

Body:
my requirements is following. Find a count(*) for a table and if not exists, create one.following is the sample code to show the issue. in both cases the else condition is coming. not sure how I achieve this, any help is appreciated.

import cx_Oracle
import os
import datetime

ts = datetime.datetime.now()
con = cx_Oracle.connect('xxxx/xxxx@xxxxx:1521/xxxxx')
print con.version
cur = con.cursor()
cur.execute('select count(*) from AAA.AAA_TEST')
rows = cur.fetchall();
print rows
print len(rows)
if (rows ==1):
  print 'there is a row'
else:
  print 'there is no row'

#result 1 where the row exists
11.2.0.4.0
[(1,)]
1
there is no row

Process finished with exit code 0

#result 2 where the row do not exists
11.2.0.4.0
[(0,)]
1
there is no row

Process finished with exit code 0


问:
clustering in network vanet +files mobility craeted with sumo+ns2
I want to create multiple clusters on a road with mobility files created with somo in ns2.

The file mobility.tcl is mobility in sumo.

My code is as follows:

```<code>set val(chan)           Channel/WirelessChannel    ;# channel type
set val(prop)           Propagation/TwoRayGround   ;# radio-propagation model
set val(netif1)         Phy/WirelessPhy            ;# network interface type
set val(netif2)         Phy/WirelessPhy            ;# network interface type
set val(mac)            Mac/802_11p                ;# MAC type
set val(ifq)            Queue/DropTail/PriQueue    ;# interface queue type
set val(ll)             LL                         ;# link layer type
set val(ant)            Antenna/OmniAntenna        ;# antenna model
set val(ifqlen)         400                        ;# max packet in ifq
set val(nn)             747                        ;# number of mobilenodes
set val(rp)             DSDV                       ;# routing protocol
set opt(x)              6162
set opt(y)              6029
# ======================================================================
# Main Program
# =====================================================================
#
# Initialize Global Variables
#
set ns_     [new Simulator]
# set up for hierarchical routing
$ns_ node-config -addressType hierarchical

AddrParams set domain_num_ 10
lappend cluster_num 2 6 2 3 6 1 5 5 2 6
AddrParams set cluster_num_ $cluster_num
lappend eilastlevel 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
AddrParams set nodes_num_ $eilastlevel
set tracefd     [open paris.tr w]
$ns_ trace-all $tracefd
set namf  [open paris.nam w]
$ns_ namtrace-all-wireless $namf $opt(x) $opt(y)
# set up topography object
set topo       [new Topography]
$topo load_flatgrid $opt(x) $opt(y)
#
# Create God
#
create-god $val(nn)
# configure node
    $ns_ node-config -adhocRouting $val(rp) \
         -llType $val(ll) \
         -macType $val(mac) \
         -ifqType $val(ifq) \
         -ifqLen $val(ifqlen) \
         -antType $val(ant) \
         -propType $val(prop) \
         -phyType $val(netif1) \
         -channelType $val(chan) \
         -topoInstance $topo \
         -agentTrace ON \
         -routerTrace ON \
         -macTrace OFF \
         -movementTrace ON

            for {set i 0} {$i < $val(nn) } {incr i} {
    set node_($i) [$ns_ node]
    $node_($i) random-motion 0      ;# disable random motion
            $ns_ initial_node_pos $node_($i) 30
             }
     $ns_ node-config -adhocRouting $val(rp) \
         -llType $val(ll) \
         -macType $val(mac) \
         -ifqType $val(ifq) \
         -ifqLen $val(ifqlen) \
         -antType $val(ant) \
         -propType $val(prop) \
         -phyType $val(netif2) \
         -channelType $val(chan) \
         -topoInstance $topo \
         -agentTrace ON \
         -routerTrace ON \
         -macTrace OFF \
         -movementTrace ON

        for {set i 0} {$i < $val(nn) } {incr i} {
    set node_($i) [$ns_ node]
    $node_($i) random-motion 0      ;# disable random motion
            $ns_ initial_node_pos $node_($i) 30
             }
     source mobility.tcl

    set udp0 [new Agent/UDP]
    $ns attach-agent $n(0) $udp0
    set cbr0 [new Application/Traffic/CBR]
    $cbr0 attach-agent $udp0
    set udp1 [new Agent/UDP]
    $ns attach-agent $n(1) $udp1
    $udp1 set class_ 1
    set cbr1 [new Application/Traffic/CBR]
    $cbr1 attach-agent $udp1
    set null0 [new Agent/Null]
    $ns attach-agent $n(50) $null0
    set null1 [new Agent/Null]
    $ns attach-agent $n(80) $null1
    $ns connect $udp0 $null0
    $ns connect $udp1 $null1
    $ns at 1.0 "$cbr0 start"
    $ns at 1.1 "$cbr1 start"
    set tcp [new Agent/TCP]
   $tcp set class_ 2
   set sink [new Agent/TCPSink]
    $ns_ attach-agent $node_(0) $tcp
    $ns_ attach-agent $node_(22) $sink
    $ns_ connect $tcp $sink
    set ftp [new Application/FTP]
    $ftp attach-agent $tcp
    $ns_ at 10.0 "$ftp start"
     #
     # Tell nodes when the simulation ends
     #
      for {set i 0} {$i < $val(nn) } {incr i} {
   $ns_ at 500.0 "$node_($i) reset";
     }
      $ns_ at 500.0 "stop"
    $ns_ at 1000.01 "puts \"NS EXITING...\" ; $ns_ halt"
     proc stop {} {
global ns_ tracefd
$ns_ flush-trace
close $tracefd
   }
   puts "Starting Simulation..."
   $ns_ run*
</code>```

And the error is:

```<code>madani@ubuntu:~/champ elysees$ ns paris2.tcl
  num_nodes is set 747
  Error!!
  str2addr:Address 32573 outside range of address field length 2048*
</code>```

答:
Your code is almost OK, when some typos are edited. Mac/802_11p is today Mac/802_11Ext. Unless you used an old patch for 802_11p and failed the build. But I guess it's a typo. Using hierarchical: The nodes must be created hierarchical. A simple "node creation" will cause

Address 32573 outside range of address field length 2048

Typos: ns has two definitions, ns and ns_ .

node has two definitions, n and node_ ..... Easily fixed with :

```<code>$ sed -i 's/ns/ns_/g' somiMadani.tcl && sed -i 's/ns__/ns_/g' somiMadani.tcl

$ sed -i 's/n(/node_(/g' somiMadani.tcl
</code>```

The simulation: I used a SUMO mobility file with 40 nodes: mobmod-teatinos-M40A.tcl, from  http://neo.lcc.uma.es/staff/jamal/vanet/?q=node/11 . Segmentation fault happens when the trace files are about 80MB, which is usable. Nam animation: OK. The edited file, somiMadani-vanet.tcl → → Dropbox → https://www.dropbox.com/s/sv7p4tqc6pk0oje/somiMadani-vanet.tcl?dl=0 And readable, somiMadani-vanet.tcl.txt https://www.dropbox.com/s/fy8valous07m5er/somiMadani-vanet.tcl.txt?dl=0

Edit, Jun 5. Hierarchical: Creating the required hierarchical nodes: See ns-2.3x/tcl/{ex/{hier-rtg-10.tcl, hts100-0.tcl, test/hts1000.tcl} → → hts100-0.tcl, hts1000.tcl are used by
used by hier-rtg-100.tcl, hier-test-1000.tcl.

New example, your code + the hts100-0.tcl snippet "n-hts120-0.tcl": Vanet_n-802.11p.tar.gz  https://drive.google.com/file/d/0B7S255p3kFXNcVcwSXhPWGUycDA/view?usp=sharing

Body:
I want to create multiple clusters on a road with mobility files created with somo in ns2.

The file mobility.tcl is mobility in sumo.

My code is as follows:

set val(chan)           Channel/WirelessChannel    ;# channel type
set val(prop)           Propagation/TwoRayGround   ;# radio-propagation model
set val(netif1)         Phy/WirelessPhy            ;# network interface type
set val(netif2)         Phy/WirelessPhy            ;# network interface type
set val(mac)            Mac/802_11p                ;# MAC type
set val(ifq)            Queue/DropTail/PriQueue    ;# interface queue type
set val(ll)             LL                         ;# link layer type
set val(ant)            Antenna/OmniAntenna        ;# antenna model
set val(ifqlen)         400                        ;# max packet in ifq
set val(nn)             747                        ;# number of mobilenodes
set val(rp)             DSDV                       ;# routing protocol
set opt(x)              6162
set opt(y)              6029
# ======================================================================
# Main Program
# =====================================================================
#
# Initialize Global Variables
#
set ns_     [new Simulator]
# set up for hierarchical routing
$ns_ node-config -addressType hierarchical

AddrParams set domain_num_ 10
lappend cluster_num 2 6 2 3 6 1 5 5 2 6
AddrParams set cluster_num_ $cluster_num
lappend eilastlevel 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
AddrParams set nodes_num_ $eilastlevel
set tracefd     [open paris.tr w]
$ns_ trace-all $tracefd
set namf  [open paris.nam w]
$ns_ namtrace-all-wireless $namf $opt(x) $opt(y)
# set up topography object
set topo       [new Topography]
$topo load_flatgrid $opt(x) $opt(y)
#
# Create God
#
create-god $val(nn)
# configure node
    $ns_ node-config -adhocRouting $val(rp) \
         -llType $val(ll) \
         -macType $val(mac) \
         -ifqType $val(ifq) \
         -ifqLen $val(ifqlen) \
         -antType $val(ant) \
         -propType $val(prop) \
         -phyType $val(netif1) \
         -channelType $val(chan) \
         -topoInstance $topo \
         -agentTrace ON \
         -routerTrace ON \
         -macTrace OFF \
         -movementTrace ON

            for {set i 0} {$i < $val(nn) } {incr i} {
    set node_($i) [$ns_ node]
    $node_($i) random-motion 0      ;# disable random motion
            $ns_ initial_node_pos $node_($i) 30
             }
     $ns_ node-config -adhocRouting $val(rp) \
         -llType $val(ll) \
         -macType $val(mac) \
         -ifqType $val(ifq) \
         -ifqLen $val(ifqlen) \
         -antType $val(ant) \
         -propType $val(prop) \
         -phyType $val(netif2) \
         -channelType $val(chan) \
         -topoInstance $topo \
         -agentTrace ON \
         -routerTrace ON \
         -macTrace OFF \
         -movementTrace ON

        for {set i 0} {$i < $val(nn) } {incr i} {
    set node_($i) [$ns_ node]
    $node_($i) random-motion 0      ;# disable random motion
            $ns_ initial_node_pos $node_($i) 30
             }
     source mobility.tcl

    set udp0 [new Agent/UDP]
    $ns attach-agent $n(0) $udp0
    set cbr0 [new Application/Traffic/CBR]
    $cbr0 attach-agent $udp0
    set udp1 [new Agent/UDP]
    $ns attach-agent $n(1) $udp1
    $udp1 set class_ 1
    set cbr1 [new Application/Traffic/CBR]
    $cbr1 attach-agent $udp1
    set null0 [new Agent/Null]
    $ns attach-agent $n(50) $null0
    set null1 [new Agent/Null]
    $ns attach-agent $n(80) $null1
    $ns connect $udp0 $null0
    $ns connect $udp1 $null1
    $ns at 1.0 "$cbr0 start"
    $ns at 1.1 "$cbr1 start"
    set tcp [new Agent/TCP]
   $tcp set class_ 2
   set sink [new Agent/TCPSink]
    $ns_ attach-agent $node_(0) $tcp
    $ns_ attach-agent $node_(22) $sink
    $ns_ connect $tcp $sink
    set ftp [new Application/FTP]
    $ftp attach-agent $tcp
    $ns_ at 10.0 "$ftp start"
     #
     # Tell nodes when the simulation ends
     #
      for {set i 0} {$i < $val(nn) } {incr i} {
   $ns_ at 500.0 "$node_($i) reset";
     }
      $ns_ at 500.0 "stop"
    $ns_ at 1000.01 "puts \"NS EXITING...\" ; $ns_ halt"
     proc stop {} {
global ns_ tracefd
$ns_ flush-trace
close $tracefd
   }
   puts "Starting Simulation..."
   $ns_ run*

And the error is:

madani@ubuntu:~/champ elysees$ ns paris2.tcl
  num_nodes is set 747
  Error!!
  str2addr:Address 32573 outside range of address field length 2048*

Body:
Your code is almost OK, when some typos are edited. Mac/802_11p is today Mac/802_11Ext. Unless you used an old patch for 802_11p and failed the build. But I guess it's a typo. Using hierarchical: The nodes must be created hierarchical. A simple "node creation" will cause

Address 32573 outside range of address field length 2048

Typos: ns has two definitions, ns and ns_ .

node has two definitions, n and node_ ..... Easily fixed with :

$ sed -i 's/ns/ns_/g' somiMadani.tcl && sed -i 's/ns__/ns_/g' somiMadani.tcl

$ sed -i 's/n(/node_(/g' somiMadani.tcl

The simulation: I used a SUMO mobility file with 40 nodes: mobmod-teatinos-M40A.tcl, from  http://neo.lcc.uma.es/staff/jamal/vanet/?q=node/11 . Segmentation fault happens when the trace files are about 80MB, which is usable. Nam animation: OK. The edited file, somiMadani-vanet.tcl → → Dropbox → https://www.dropbox.com/s/sv7p4tqc6pk0oje/somiMadani-vanet.tcl?dl=0 And readable, somiMadani-vanet.tcl.txt https://www.dropbox.com/s/fy8valous07m5er/somiMadani-vanet.tcl.txt?dl=0

Edit, Jun 5. Hierarchical: Creating the required hierarchical nodes: See ns-2.3x/tcl/{ex/{hier-rtg-10.tcl, hts100-0.tcl, test/hts1000.tcl} → → hts100-0.tcl, hts1000.tcl are used by
used by hier-rtg-100.tcl, hier-test-1000.tcl.

New example, your code + the hts100-0.tcl snippet "n-hts120-0.tcl": Vanet_n-802.11p.tar.gz  https://drive.google.com/file/d/0B7S255p3kFXNcVcwSXhPWGUycDA/view?usp=sharing


问:
Is it possible to retrieve a users browser history via the API?
We are moving to Chromebooks in our school and would like to know if it's possible to retrieve the users browser history.  Every month we perform a device check in where the teacher physically inspects each students device for anything "suspicious".  This generally entails looking at their browser history for things like pornographic or other unsavory URLs.

I would be very handy to build a nightly process that slurps up the student's browser history, checks it for any anomalies, and reports that to the administration.  Is this possible?  Is there another way to do this?

答:
I don't think this is fully supported yet. chrome.history from Chrome API can only
 interact with the browser's record of visited pages. You can add, remove, and query for URLs in the browser's history; that's as far as API goes.</p>


问:
How do I get text to align to around a picture on a website
I'm working on a personal website highlighting my certifications on a personal website. Part of the ToS to use the images is to place a TM in the upper right corner of each image. I'm having trouble getting the text to align where it needs to be.

This is what I have:

HTML

```<code><div id="imagesMain">
        <img src="aplus.png"> TM
        <img src="network.png"> TM
        <img src="security.png"> TM
    </div>
</code>```

CSS

```<code>#imagesMain {
 padding: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
    text-align: center;
}

#imagesMain img {
    height: 100px;
     width: auto;
    vertical-align: middle;
}
</code>```

The end result gives this...

What I'd like is all images in a tight line and a small "TM" in the proper place. Any help would be appreciated.

答:
Here is the code which will put the logo on the upper right corner for you, here I have used some dummy images you can replace them with your images.

#imagesMain div{
  display:inline-block;
  position:relative;
}
#imagesMain div > p{
  position:absolute;
  top:-15px;
  right:0;
  color:#fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

</head>
<body>
<div id="imagesMain">
  <div>        <img src="http://lorempixel.com/100/100/food/1"> <p>TM</p></div>
<div>  <img src="http://lorempixel.com/100/100/food/2"> <p>TM</p></div>
<div>  <img src="http://lorempixel.com/100/100/food/3"> <p>TM</p></div>
    </div>
</body>
</html></code>```

Body:
I'm working on a personal website highlighting my certifications on a personal website. Part of the ToS to use the images is to place a TM in the upper right corner of each image. I'm having trouble getting the text to align where it needs to be.

This is what I have:

HTML

         TM
         TM
         TM

CSS

#imagesMain {
 padding: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
    text-align: center;
}

#imagesMain img {
    height: 100px;
     width: auto;
    vertical-align: middle;
}

The end result gives this...

What I'd like is all images in a tight line and a small "TM" in the proper place. Any help would be appreciated.

Body:
Here is the code which will put the logo on the upper right corner for you, here I have used some dummy images you can replace them with your images.

#imagesMain div{
  display:inline-block;
  position:relative;
}
#imagesMain div > p{
  position:absolute;
  top:-15px;
  right:0;
  color:#fff;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

</head>
<body>
<div id="imagesMain">
  <div>        <img src="http://lorempixel.com/100/100/food/1"> <p>TM</p></div>
<div>  <img src="http://lorempixel.com/100/100/food/2"> <p>TM</p></div>
<div>  <img src="http://lorempixel.com/100/100/food/3"> <p>TM</p></div>
    </div>
</body>
</html>


问:
R - read inline base64 png image and parse text
I'm trying to parse an inlined image (png), encoded in base64. I have obtained the base64 string for the purpose of simplifying what i'm doing (input).

The issue is r can't seem to handle NUL characters, and therefore, I can't write the png out in the correct format (i.e including NUL's).

When I attempt to parse the image, it simply errors.

Is there a way to write a png out including NUL's?

I'm using windows 10, r 64bit V3.3.2.

Thanks!

```<code># install.packages('tesseract')
# install.packages('base64enc')

# Load required libraries
library(tesseract)
library(base64enc)

# Define base64 string
input <- "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"
# Decode the input
x <- base64decode(input)
# Convert to raw before writing to disc (multiple=T removes Nul's, without it, it produces an error)
x <- rawToChar(x,multiple=T)
# Collapse into a string
x <- paste0(x,collapse="")

# Write the file out
fileConn<-file("c:/temp/output.txt")
writeLines(x, fileConn)
close(fileConn)

# parse image information
ocr("c:/temp/output.txt")
# error printed to console:
> Error in FUN(X[[i]], ...) : Failed to read image
</code>```

Body:
I'm trying to parse an inlined image (png), encoded in base64. I have obtained the base64 string for the purpose of simplifying what i'm doing (input).

The issue is r can't seem to handle NUL characters, and therefore, I can't write the png out in the correct format (i.e including NUL's).

When I attempt to parse the image, it simply errors.

Is there a way to write a png out including NUL's?

I'm using windows 10, r 64bit V3.3.2.

Thanks!

# install.packages('tesseract')
# install.packages('base64enc')

# Load required libraries
library(tesseract)
library(base64enc)

# Define base64 string
input <- "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"
# Decode the input
x <- base64decode(input)
# Convert to raw before writing to disc (multiple=T removes Nul's, without it, it produces an error)
x <- rawToChar(x,multiple=T)
# Collapse into a string
x <- paste0(x,collapse="")

# Write the file out
fileConn<-file("c:/temp/output.txt")
writeLines(x, fileConn)
close(fileConn)

# parse image information
ocr("c:/temp/output.txt")
# error printed to console:
> Error in FUN(X[[i]], ...) : Failed to read image


问:
removeChild(); not removing all items from list
When I run the following code, half of the items are removed from the list.. I am trying to remove all items from the list.</p>

```<code>  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      console.log(ul.children.length);

      //Moves through the unordered list and removes each list item.
      for(let i = 0; i < ul.children.length; i++) {
        ul.removeChild(ul.children[i]);
      }
  });
</code>```

答:
You are iterating over a list and inside the iteration you are manipulating the list removing elements. This is causing the issue.

For removing all the elements inside your node you can simply do:

```<code>document.getElementById("myUL").innerHTML = '';
</code>```

Otherwise if you like loops for some reason, do that:

```<code>var el = document.getElementById("myUL");
while (el.firstChild) {
   el.removeChild(el.firstChild);
}
</code>```

Body:
When I run the following code, half of the items are removed from the list.. I am trying to remove all items from the list.

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      console.log(ul.children.length);

      //Moves through the unordered list and removes each list item.
      for(let i = 0; i < ul.children.length; i++) {
        ul.removeChild(ul.children[i]);
      }
  });

Body:
You are iterating over a list and inside the iteration you are manipulating the list removing elements. This is causing the issue.

For removing all the elements inside your node you can simply do:

document.getElementById("myUL").innerHTML = '';

Otherwise if you like loops for some reason, do that:

var el = document.getElementById("myUL");
while (el.firstChild) {
   el.removeChild(el.firstChild);
}


问:
Program jumping to a function that wasn't called
I'm working on a game. Now, in my game when i get to a specific place (a function) called "room01" though I haven't further instructed it where/how to proceed onwards, it jumps back to a place in kitchen function. Why is this happening?

I'm new and i couldn't figure out how i could demonstrate my problem otherwise. Here is my complete code:

```<code>#!/usr/bin/python2

def entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    if already_there_ent == False:
        print("---------------------------------------------------------")
        print "You are standing at the entrance hall of an apartment.The door you came through won't open.\
        \nTo your immediate right is the kitchen(0),\
        \nTo your left ahead is the main Lounge(1),\
        \nStraight ahead is Room 1's door(2).\
        \nFind you're way out!"
        choice01 = raw_input("Where do you go? > ")

        if choice01 == "right" or choice01 == "kitchen" or choice01 == "0" or choice01 == "go right" or choice01 == "go to kitchen":
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "left" or choice01 == "main lounge" or choice01 == "1" or choice01 == "go left" or choice01 == "go to main lounge":
            main_lounge(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "room" or choice01 == "straight" or choice01 == "2" or choice01 == "go straight" or choice01 == "go to room":
            room01(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid option."
            raw_input("> ")
            already_there_ent = True
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

    elif already_there_ent == True:
        choice01 = raw_input("Where do you go? > ")

        if choice01 == "right" or choice01 == "kitchen" or choice01 == "0" or choice01 == "go right" or choice01 == "go to kitchen":
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "left" or choice01 == "main lounge" or choice01 == "1" or choice01 == "go left" or choice01 == "go to main lounge":
            main_Lounge(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "room" or choice01 == "straight" or choice01 == "2" or choice01 == "go straight" or choice01 == "go to room":
            room01(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid option."
            raw_input(">")
            already_there_ent = True
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

def kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    alias = {
    '0': '0',
    'first cupboard': '0',
    'check first cupboard': '0',
    'open first cupboard': '0',
    '1': '1',
    'second cupboard': '1',
    'check second cupboard': '1',
    'open second cupboard': '1',
    '2': '2',
    'third cupboard': '2',
    'check third cupboard': '2',
    'open third cupboard': '2',
    '3': '3',
    'read letter': '3',
    'check letter': '3',
    }

    dic = {
    "0":"You see a dusty empty bottles of milks, with spiderwebs at the corners of the cupboard. Nothing of Interest here.",  \
    "1":"You see some packs of likely expired cereal and a key(0).",  \
    "2":"You see an empty or dusty cupboard. Nothing of interest here.", \
    "3":"Dear Shawn..... nothing of interest",
    }

    if already_there_kit == False:
        print("---------------------------------------------------------")
        print "There are 3 different cupboards(0, 1, 2) or a letter(3) placed on the counter."
        choice02 = raw_input("What do you do? > ")

        if choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
            already_there_ent = False
            already_there_kit = False
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice02 in alias:
            print dic[alias[choice02]]
            if choice02 == "1":
                print "..."
                choice02_key = raw_input("What do you do? >")
                if choice02_key == "pick key" or choice02_key == "0" or choice02_key == "key":
                    print("---------------------------------------------------------")
                    print "You picked the key. It probably unlocks some door."
                    key_picked = True
                    already_there_kit = True
                    kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
                elif choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
                    already_there_ent = False
                    already_there_kit = False
                    entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid Option."
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

    elif already_there_kit == True:
        print "..."
        choice02 = raw_input("What do you do? >")

        if choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
            already_there_ent = False
            already_there_kit = False
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice02 in alias:
            print dic[alias[choice02]]
            if choice02 == "1":
                print "..."
                choice02_key = raw_input("What do you do? >")
                if choice02_key == "pick key" or choice02_key == "0" or choice02_key == "key":
                    print("---------------------------------------------------------")
                    print "You picked the key. It probably unlocks some door."
                    key_picked = True
                    already_there_kit = True
                    kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
                elif choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
                    already_there_ent = False
                    already_there_kit = False
                    entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid Option."
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

def room01(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    if key_picked == True:
        print("---------------------------------------------------------")
        print "You unlocked the room using the key."
        raw_input("> ")
        print "You are now inside the room!. There is a bed, 2 drawers on its sides.\
        \n The only window the room has is barricaded with iron grills.\
        \n Apart, from that there is a fine painting of an old man on the western side wall."
        choice02 = raw_input("What do you do? ")

    elif key_picked == False:
        print "This room is locked."
        already_there_ent = True
        entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

def main_lounge(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    print "Hmm.. How do i make this game interesting?"
    entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

#-----------------------------------------------------------------------------------------------------------------------------------------------#

print "Welcome to the game"
raw_input("Press RETURN to start the hunt or CTRL + C to quit anytime.")
print "Hint: Make use the keys to easily navigate through i.e. xyz(1) or do not use CAPS in your input."
raw_input("> ")

already_there_ent = False
already_there_kit = False
already_there_room = False
already_there_lounge = False
key_picked = False
entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
</code>```

答:
When your function ends it returns back to where it was called and then the program continue to the next line after the function call.
It is just how functions work</p>

Body:
I'm working on a game. Now, in my game when i get to a specific place (a function) called "room01" though I haven't further instructed it where/how to proceed onwards, it jumps back to a place in kitchen function. Why is this happening?

I'm new and i couldn't figure out how i could demonstrate my problem otherwise. Here is my complete code:

#!/usr/bin/python2

def entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    if already_there_ent == False:
        print("---------------------------------------------------------")
        print "You are standing at the entrance hall of an apartment.The door you came through won't open.\
        \nTo your immediate right is the kitchen(0),\
        \nTo your left ahead is the main Lounge(1),\
        \nStraight ahead is Room 1's door(2).\
        \nFind you're way out!"
        choice01 = raw_input("Where do you go? > ")

        if choice01 == "right" or choice01 == "kitchen" or choice01 == "0" or choice01 == "go right" or choice01 == "go to kitchen":
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "left" or choice01 == "main lounge" or choice01 == "1" or choice01 == "go left" or choice01 == "go to main lounge":
            main_lounge(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "room" or choice01 == "straight" or choice01 == "2" or choice01 == "go straight" or choice01 == "go to room":
            room01(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid option."
            raw_input("> ")
            already_there_ent = True
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

    elif already_there_ent == True:
        choice01 = raw_input("Where do you go? > ")

        if choice01 == "right" or choice01 == "kitchen" or choice01 == "0" or choice01 == "go right" or choice01 == "go to kitchen":
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "left" or choice01 == "main lounge" or choice01 == "1" or choice01 == "go left" or choice01 == "go to main lounge":
            main_Lounge(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice01 == "room" or choice01 == "straight" or choice01 == "2" or choice01 == "go straight" or choice01 == "go to room":
            room01(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid option."
            raw_input(">")
            already_there_ent = True
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

def kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    alias = {
    '0': '0',
    'first cupboard': '0',
    'check first cupboard': '0',
    'open first cupboard': '0',
    '1': '1',
    'second cupboard': '1',
    'check second cupboard': '1',
    'open second cupboard': '1',
    '2': '2',
    'third cupboard': '2',
    'check third cupboard': '2',
    'open third cupboard': '2',
    '3': '3',
    'read letter': '3',
    'check letter': '3',
    }

    dic = {
    "0":"You see a dusty empty bottles of milks, with spiderwebs at the corners of the cupboard. Nothing of Interest here.",  \
    "1":"You see some packs of likely expired cereal and a key(0).",  \
    "2":"You see an empty or dusty cupboard. Nothing of interest here.", \
    "3":"Dear Shawn..... nothing of interest",
    }

    if already_there_kit == False:
        print("---------------------------------------------------------")
        print "There are 3 different cupboards(0, 1, 2) or a letter(3) placed on the counter."
        choice02 = raw_input("What do you do? > ")

        if choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
            already_there_ent = False
            already_there_kit = False
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice02 in alias:
            print dic[alias[choice02]]
            if choice02 == "1":
                print "..."
                choice02_key = raw_input("What do you do? >")
                if choice02_key == "pick key" or choice02_key == "0" or choice02_key == "key":
                    print("---------------------------------------------------------")
                    print "You picked the key. It probably unlocks some door."
                    key_picked = True
                    already_there_kit = True
                    kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
                elif choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
                    already_there_ent = False
                    already_there_kit = False
                    entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid Option."
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

    elif already_there_kit == True:
        print "..."
        choice02 = raw_input("What do you do? >")

        if choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
            already_there_ent = False
            already_there_kit = False
            entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        elif choice02 in alias:
            print dic[alias[choice02]]
            if choice02 == "1":
                print "..."
                choice02_key = raw_input("What do you do? >")
                if choice02_key == "pick key" or choice02_key == "0" or choice02_key == "key":
                    print("---------------------------------------------------------")
                    print "You picked the key. It probably unlocks some door."
                    key_picked = True
                    already_there_kit = True
                    kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
                elif choice02 == "leave kitchen" or choice02 == "entrance hall" or choice02 == "back" or choice02 == "go to entrance hall":
                    already_there_ent = False
                    already_there_kit = False
                    entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)
        else:
            print "Not a valid Option."
            already_there_kit = True
            kitchen(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

def room01(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    if key_picked == True:
        print("---------------------------------------------------------")
        print "You unlocked the room using the key."
        raw_input("> ")
        print "You are now inside the room!. There is a bed, 2 drawers on its sides.\
        \n The only window the room has is barricaded with iron grills.\
        \n Apart, from that there is a fine painting of an old man on the western side wall."
        choice02 = raw_input("What do you do? ")

    elif key_picked == False:
        print "This room is locked."
        already_there_ent = True
        entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

def main_lounge(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked):
    print "Hmm.. How do i make this game interesting?"
    entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)

#-----------------------------------------------------------------------------------------------------------------------------------------------#

print "Welcome to the game"
raw_input("Press RETURN to start the hunt or CTRL + C to quit anytime.")
print "Hint: Make use the keys to easily navigate through i.e. xyz(1) or do not use CAPS in your input."
raw_input("> ")

already_there_ent = False
already_there_kit = False
already_there_room = False
already_there_lounge = False
key_picked = False
entrance_hall(already_there_ent, already_there_kit, already_there_room, already_there_lounge, key_picked)


问:
Errors when attempting to add custom Schema
I am attempting to add a custom schema to users on my Google Domain however I can't get even one to work. I keep getting an error for bad request, I am following all syntax provided.</p>

```<code>function myFunction() {
 var schema = {
   "kind":"admin#directory#schema",
   "schemaId":"EmployeeInfo",
   "schemaName":"Employee Information",
   "fields":[
     {
       "kind":"admin#directory#schema@fieldspec",
       "fieldId":"EmployeeID",
       "fieldName":"Employee ID",
       "fieldType":"STRING",
       "readAccessType":"ADMINS_AND_SELF"
     }
    ]
   };
  AdminDirectory.Schemas.insert(schema, "CustomerId");
 }
</code>```

答:
Check the Create a custom user schema from Directory API:

To create a custom user schema in your domains, use the following POST request and include the authorization described in Authorize requests. For the request query string properties, see the API Reference.

```<code>POST https://www.googleapis.com/admin/directory/v1/customer/my_customer or customerId/schemas
</code>```

All create requests require you to submit the information needed to fulfill the request. If you are using client libraries, they convert the data objects from your chosen language into JSON data formatted objects.

JSON request

The following JSON shows a sample request to create a custom schema. For the full list of request and response properties, see the API Reference.

```<code>{
  "schemaName": "employmentData",
  "fields": [
    {
      "fieldName": "EmployeeNumber",
      "fieldType": "STRING",
      "multiValued": "false"
    },
    {
      "fieldName": "JobFamily",
      "fieldType": "STRING",
      "multiValued": "false"
    }
  ]
}
</code>```

Body:
I am attempting to add a custom schema to users on my Google Domain however I can't get even one to work. I keep getting an error for bad request, I am following all syntax provided.

function myFunction() {
 var schema = {
   "kind":"admin#directory#schema",
   "schemaId":"EmployeeInfo",
   "schemaName":"Employee Information",
   "fields":[
     {
       "kind":"admin#directory#schema@fieldspec",
       "fieldId":"EmployeeID",
       "fieldName":"Employee ID",
       "fieldType":"STRING",
       "readAccessType":"ADMINS_AND_SELF"
     }
    ]
   };
  AdminDirectory.Schemas.insert(schema, "CustomerId");
 }

Body:
Check the Create a custom user schema from Directory API:

To create a custom user schema in your domains, use the following POST request and include the authorization described in Authorize requests. For the request query string properties, see the API Reference.

POST https://www.googleapis.com/admin/directory/v1/customer/my_customer or customerId/schemas

All create requests require you to submit the information needed to fulfill the request. If you are using client libraries, they convert the data objects from your chosen language into JSON data formatted objects.

JSON request

The following JSON shows a sample request to create a custom schema. For the full list of request and response properties, see the API Reference.

{
  "schemaName": "employmentData",
  "fields": [
    {
      "fieldName": "EmployeeNumber",
      "fieldType": "STRING",
      "multiValued": "false"
    },
    {
      "fieldName": "JobFamily",
      "fieldType": "STRING",
      "multiValued": "false"
    }
  ]
}


问:
HTTP error fetching URL
I'm trying to parse this website with Jsoup: http://www.listofnewspapers.com/2014/04/site-map.html but I am getting this error:

For 'http://www.listofnewspapers.com/2014/04/site-map.html': HTTP error fetching URL"

I believe the error is occurring atconnect(URL).get().

I printed the status code for debugging purposes, and I got 200.

I tried with multiple other websites, and they connected fine.

答:
It seems like user agents are filtered. Try setting up one:</p>

```<code>Jsoup.connect(URL).userAgent("Mozilla").get()
</code>```

Title: HTTP error fetching URL

Body:
It seems like user agents are filtered. Try setting up one:

Jsoup.connect(URL).userAgent("Mozilla").get()


答:
Use the Firefox userAgent:

```<code>.userAgent("Mozilla")
</code>```

For example:

```<code>Jsoup.connect("https://stackoverflow.com/questions/44349297/http-error-fetching-url").userAgent("Mozilla").get();
</code>```

Source: Can Jsoup simulate a button press?

Title: HTTP error fetching URL

Body:
I'm trying to parse this website with Jsoup: http://www.listofnewspapers.com/2014/04/site-map.html but I am getting this error:

For 'http://www.listofnewspapers.com/2014/04/site-map.html': HTTP error fetching URL"

I believe the error is occurring atconnect(URL).get().

I printed the status code for debugging purposes, and I got 200.

I tried with multiple other websites, and they connected fine.

Body:
Use the Firefox userAgent:

.userAgent("Mozilla")

For example:

Jsoup.connect("https://stackoverflow.com/questions/44349297/http-error-fetching-url").userAgent("Mozilla").get();

Source: Can Jsoup simulate a button press?


问:
Measure performance of a Web Server
Which tools can be used to measure performance of a webserver?</p>

答: To test a webserver, you can use Apache Jmeter.</p>

Title: Measure performance of a Web Server


问:
How to install latest version of git on CentOS 8.x/7.x/6.x
I used the usual:

```<code>yum install git
</code>```

It did not install the latest version of git on my CentOS 6. How can I update to the latest version of git for CentOS 6? The solution can be applicable to newer versions of CentOS such as CentOS 7.

答:
This may be irrelevant. It is for people don't want build the latest git on the host meanwhile they still can get the latest git.

I think most people don't like building the latest git on CentOS because the dependencies will contaminate the host and you have to run lots of commands. Therefore, I have an idea which is building git inside the Docker container and then install the executable via the docker volume mount. After that, you can delete the image and container.

Yes, the downside is you have to install docker. But the least dependencies are introduced to the host and you don't have to install other yum repo.

Here is my repository. https://github.com/wood1986/docker-library/tree/master/git

Body:
I used the usual:

yum install git

It did not install the latest version of git on my CentOS 6. How can I update to the latest version of git for CentOS 6? The solution can be applicable to newer versions of CentOS such as CentOS 7.