问:
JQuery: start slideToggle() as hidden
I created this:

    $(document).ready(function(){
        var speed = 500;

        $('.brewed').click(function(){
            $('.ifBrewed').slideToggle(speed);
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
        background-color: black;
        color: white;
    }

    input[type=checkbox] {
    display:none;
    }

    .step_1, .step_2, .step_3 {
        padding: 2%;
        margin: 0 auto;
        font-weight: 100;
    }

    input[type=checkbox]:checked + label {
        border: 3px solid white;
    }

    .ifBrewed {
        background-color: #181818;
        padding: 2%;
        display: none;
    }</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

How do you enjoy your coffee?

                <input type="checkbox" name="site" id="so" />

Espresso

add the description here about this coffee!

                 <input type="checkbox" name="site" id="sf" />

Brewed

add the description here about this coffee!

                <input type="checkbox" name="site" id="ba" />

Drip coffee

                <input type="checkbox" name="site" id="bb" />

Aeropress

                <input type="checkbox" name="site" id="bc" />

French press

                <input type="checkbox" name="site" id="bd" />

Vacuum pot

                <input type="checkbox" name="site" id="be" />

Syphon

                <input type="checkbox" name="site" id="bf" />

V60

                <input type="checkbox" name="site" id="bg" />

Chemex

                <input type="checkbox" name="site" id="bh" />

Moka pot

                <input type="checkbox" name="site" id="bi" />

Percolato

                <input type="checkbox" name="site" id="bj" />

Eva solo

```

I did like other threads said, Add the display:none feature, and I did try on both CSS and JQuery .css().
It's going well, but I need help with this little bug.

As you can see, when you click the Slide toggle input it toggles then toggles back, but I want it to stay without toggling off until I click it again.

How do I do that?

Thank you!

答:
I think this has something to do with the label. When you click on the .brewed div the labels click event is also being triggered. I think this is making jquery think that 2 click events have occurred.

I have just added e.preventDefault() which prevents any default element click behavior from occurring. I did notice that even without my added code the checkboxes are not being checked on click. This is because they have display none set. Having display none on the checkboxes will also mean they will not be posted if they are part of a form submission. I am not sure if that is in issue for you.

$(document).ready(function(){
    var speed = 500;

    $('.brewed').click(function(e){
      e.preventDefault();
      $('.ifBrewed').slideToggle(speed);
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  background-color: black;
  color: white;
}

input[type=checkbox] {
  display: none;
}

.step_1,
.step_2,
.step_3 {
  padding: 2%;
  margin: 0 auto;
  font-weight: 100;
}

input[type=checkbox]:checked+label {
  border: 3px solid white;
}

.ifBrewed {
  background-color: #181818;
  padding: 2%;
  display: none;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

How do you enjoy your coffee?

        <input type="checkbox" name="site" id="so" />

Espresso

add the description here about this coffee!

        <input type="checkbox" name="site" id="sf" />

Brewed

add the description here about this coffee!

          <input type="checkbox" name="site" id="ba" />

Drip coffee

          <input type="checkbox" name="site" id="bb" />

Aeropress

          <input type="checkbox" name="site" id="bc" />

French press

          <input type="checkbox" name="site" id="bd" />

Vacuum pot

          <input type="checkbox" name="site" id="be" />

Syphon

          <input type="checkbox" name="site" id="bf" />

V60

          <input type="checkbox" name="site" id="bg" />

Chemex

          <input type="checkbox" name="site" id="bh" />

Moka pot

          <input type="checkbox" name="site" id="bi" />

Percolato

          <input type="checkbox" name="site" id="bj" />

Eva solo

```

Title: JQuery: start slideToggle() as hidden

Body:
I created this:

    $(document).ready(function(){
        var speed = 500;

        $('.brewed').click(function(){
            $('.ifBrewed').slideToggle(speed);
        });
    });

html, body {
        background-color: black;
        color: white;
    }

    input[type=checkbox] {
    display:none;
    }

    .step_1, .step_2, .step_3 {
        padding: 2%;
        margin: 0 auto;
        font-weight: 100;
    }

    input[type=checkbox]:checked + label {
        border: 3px solid white;
    }

    .ifBrewed {
        background-color: #181818;
        padding: 2%;
        display: none;
    }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

How do you enjoy your coffee?

                <input type="checkbox" name="site" id="so" />

Espresso

add the description here about this coffee!

                 <input type="checkbox" name="site" id="sf" />

Brewed

add the description here about this coffee!

                <input type="checkbox" name="site" id="ba" />

Drip coffee

                <input type="checkbox" name="site" id="bb" />

Aeropress

                <input type="checkbox" name="site" id="bc" />

French press

                <input type="checkbox" name="site" id="bd" />

Vacuum pot

                <input type="checkbox" name="site" id="be" />

Syphon

                <input type="checkbox" name="site" id="bf" />

V60

                <input type="checkbox" name="site" id="bg" />

Chemex

                <input type="checkbox" name="site" id="bh" />

Moka pot

                <input type="checkbox" name="site" id="bi" />

Percolato

                <input type="checkbox" name="site" id="bj" />

Eva solo

I did like other threads said, Add the display:none feature, and I did try on both CSS and JQuery .css().
It's going well, but I need help with this little bug.

As you can see, when you click the Slide toggle input it toggles then toggles back, but I want it to stay without toggling off until I click it again.

How do I do that?

Thank you!

Body:
I think this has something to do with the label. When you click on the .brewed div the labels click event is also being triggered. I think this is making jquery think that 2 click events have occurred.

I have just added e.preventDefault() which prevents any default element click behavior from occurring. I did notice that even without my added code the checkboxes are not being checked on click. This is because they have display none set. Having display none on the checkboxes will also mean they will not be posted if they are part of a form submission. I am not sure if that is in issue for you.

$(document).ready(function(){
    var speed = 500;

    $('.brewed').click(function(e){
      e.preventDefault();
      $('.ifBrewed').slideToggle(speed);
    });
});

html,
body {
  background-color: black;
  color: white;
}

input[type=checkbox] {
  display: none;
}

.step_1,
.step_2,
.step_3 {
  padding: 2%;
  margin: 0 auto;
  font-weight: 100;
}

input[type=checkbox]:checked+label {
  border: 3px solid white;
}

.ifBrewed {
  background-color: #181818;
  padding: 2%;
  display: none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <!-- Step 1 -->
  <div class="row">
    <h2>How do you enjoy your coffee?</h2>
    <div class="col-lg-6 col-sm-6 col-xs-6 step_1 text-center">
      <div>
        <input type="checkbox" name="site" id="so" />
        <label for="so">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Espresso</h3>
                    <p>add the description here about this coffee!</p>
                </label>
      </div>
    </div>
    <div class="col-lg-6 col-sm-6 col-xs-6 step_1 brewed text-center">
      <div>
        <input type="checkbox" name="site" id="sf" />
        <label for="sf">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Brewed</h3>
                    <p>add the description here about this coffee!</p>
                </label>
      </div>
    </div>
  </div>

  <!-- Step 1.5 -->
  <div class="ifBrewed">
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="ba" />
          <label for="ba">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Drip coffee</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bb" />
          <label for="bb">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Aeropress</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bc" />
          <label for="bc">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>French press</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bd" />
          <label for="bd">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Vacuum pot</h3>
                </label>
        </div>
      </div>
    </div>
    <!-- Row 2 -->
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="be" />
          <label for="be">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Syphon</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bf" />
          <label for="bf">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>V60</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bg" />
          <label for="bg">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Chemex</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bh" />
          <label for="bh">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Moka pot</h3>
                </label>
        </div>
      </div>
    </div>
    <!-- Row 3 -->
    <div class="row">
      <div class="col-lg-3 col-md-3"></div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bi" />
          <label for="bi">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Percolato</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bj" />
          <label for="bj">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Eva solo</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3"></div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Why are my flex items wrapping off the screen?
I have a flex nav and it's wrapping to the left and partially off of the screen. Does anyone with more experience know what could be causing this? I can't figure out why it's doing this.

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    justify-content: flex-end;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <h1>Seraph Chronicles</h1>
  <nav>
    <ul class="main-nav">
      <li class="main-nav-item">Home</li>
      <li class="main-nav-item">About</li>
      <li class="main-nav-item characters">
        Characters
        <ul class="drop-menu">
          <li>Ethan Clarke</li>
          <li>Serena Kiriaga</li>
          <li>Marcus Flynn</li>
          <li>Emily Ashdown</li>
          <li>Director Miles West</li>
        </ul>
      </li>
      <li class="main-nav-item">Author</li>
    </ul>
  </nav>
</header></code>```

https://jsfiddle.net/ca75sqzc/17/

答:
Short Answer

Don't use percentages on flex item margins. Use another unit, such as px or em.

revised demo

Explanation

When you make the primary container (.header) a flex container, its children become flex items.

These are the two children: h1 and nav (red borders added below)

Each nav item (li) has a horizontal margin (1% on each side).

```<code>nav ul li{
   border-radius: 8px;
   padding: 5px;
   margin: 4px 1%;
   font-size: 1.5rem;
}
</code>```

This causes them to overflow the container.

Then, because the container has justify-content: flex-end, the items are aligned to the container's right edge. This means the overflow occurs on the left side (see image above).

On smaller screens, the nav element wraps to the left edge of the header, and the overflowing items go out of view:

If you switch to justify-content: flex-start, the items overflow on the right side.

But the real problem is actually this:

Why isn't the ul container expanding to accommodate the li children?

The answer appears to be the use of percentages for the horizontal margins.

```<code>nav ul {
   display: flex;
   justify-content: flex-end;
   margin: 0 8% 0 0;
}

nav ul li {
   border-radius: 8px;
   padding: 5px;
   margin: 4px 1%;
   font-size: 1.5rem;
}
</code>```

The container is not recognizing this unit on the margins and, therefore, not expanding.

Note that the flexbox spec recommends against using percentage margins and padding on flex items.

4.2. Flex Item Margins and
  Paddings

Authors should avoid using percentages in paddings or margins on flex
  items entirely, as they will get different behavior in different browsers.

Once you switch to non-percentage units on your margins, everything seems to work.

ContentLicense: CC BY-SA 3.0

Body:
I have a flex nav and it's wrapping to the left and partially off of the screen. Does anyone with more experience know what could be causing this? I can't figure out why it's doing this.

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    justify-content: flex-end;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}

Seraph Chronicles

Home

About

        Characters

Ethan Clarke

Serena Kiriaga

Marcus Flynn

Emily Ashdown

Director Miles West

Author

https://jsfiddle.net/ca75sqzc/17/

Body:
Short Answer

Don't use percentages on flex item margins. Use another unit, such as px or em.

revised demo

Explanation

When you make the primary container (.header) a flex container, its children become flex items.

These are the two children: h1 and nav (red borders added below)

Each nav item (li) has a horizontal margin (1% on each side).

nav ul li{
   border-radius: 8px;
   padding: 5px;
   margin: 4px 1%;
   font-size: 1.5rem;
}

This causes them to overflow the container.

Then, because the container has justify-content: flex-end, the items are aligned to the container's right edge. This means the overflow occurs on the left side (see image above).

On smaller screens, the nav element wraps to the left edge of the header, and the overflowing items go out of view:

If you switch to justify-content: flex-start, the items overflow on the right side.

But the real problem is actually this:

Why isn't the ul container expanding to accommodate the li children?

The answer appears to be the use of percentages for the horizontal margins.

nav ul {
   display: flex;
   justify-content: flex-end;
   margin: 0 8% 0 0;
}

nav ul li {
   border-radius: 8px;
   padding: 5px;
   margin: 4px 1%;
   font-size: 1.5rem;
}

The container is not recognizing this unit on the margins and, therefore, not expanding.

Note that the flexbox spec recommends against using percentage margins and padding on flex items.

4.2. Flex Item Margins and
  Paddings

Authors should avoid using percentages in paddings or margins on flex
  items entirely, as they will get different behavior in different browsers.

Once you switch to non-percentage units on your margins, everything seems to work.


问:
How do you set the delegate when passing data from ViewController to View?
Here's the relevant code:

in ViewController

```<code>protocol LocationDelegate {

    func setLocation(coordinate: CLLocationCoordinate2D)
}

var locationDelegate: LocationDelegate?

func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {

    locationDelegate?.setLocation(coordinate: coordinate)

    createPostView = createViewFromNib()
    createPostView.center = SCREEN_CENTER_POSITION
    self.view.addSubview(createPostView)
}
</code>```

in CreatePostView

```<code>class CreatePostView: UIView, UINavigationControllerDelegate, LocationDelegate {

 var location: CLLocation! = CLLocation()

 func setLocation(coordinate: CLLocationCoordinate2D) {

    self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
 }

}
</code>```

This doesn't work. "location" is always being saved as empty and I believe it's because I haven't set the delegate. I know this is usually done in prepareForSegue when passing data between two ViewControllers, but in this case, I'm not sure when to set it. How should I go about this?

答:
```<code>func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
    createPostView = createViewFromNib() as! CreatePostView
    createPostView.setLocation(coordinate: coordinate)
    createPostView.center = SCREEN_CENTER_POSITION
    self.view.addSubview(createPostView)
}
</code>```

Body:
Here's the relevant code:

in ViewController

protocol LocationDelegate {

    func setLocation(coordinate: CLLocationCoordinate2D)
}

var locationDelegate: LocationDelegate?

func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {

    locationDelegate?.setLocation(coordinate: coordinate)

    createPostView = createViewFromNib()
    createPostView.center = SCREEN_CENTER_POSITION
    self.view.addSubview(createPostView)
}

in CreatePostView

class CreatePostView: UIView, UINavigationControllerDelegate, LocationDelegate {

 var location: CLLocation! = CLLocation()

 func setLocation(coordinate: CLLocationCoordinate2D) {

    self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
 }

}

This doesn't work. "location" is always being saved as empty and I believe it's because I haven't set the delegate. I know this is usually done in prepareForSegue when passing data between two ViewControllers, but in this case, I'm not sure when to set it. How should I go about this?


问:
django wagtail page not found when i don't use "127.0.0.1:8000"
I have added the following to my settings.py

```<code>ALLOWED_HOSTS = ['0.0.0.0','127.0.0.1','192.168.0.05']
</code>```

My url.py

```<code>urlpatterns = [
url(r'^django-admin/', include(admin.site.urls)),

url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),

#url(r'^search/$', search_views.search, name='search'),

# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
#url(r'', include(wagtail_urls)),

# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
#    url(r'^pages/', renders(wagtail_urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),

]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += i18n_patterns(
# These URLs will have /<language_code>/ appended to the beginning
url(r'^search/$', search_views.search, name='search'),
url(r'', include(wagtail_urls)),
#url(r'^$', include(wagtail_urls)),
 )
</code>```

The dilema is when I do "http://127.0.0.1:8000/en" it works just fine however when I do "http://192.168.0.5:8000/en/" from my mobile phone on the same lan or even from the laptop its hosted on I keep getting "Page not found (404)".

What would cause such behavior did I overlook something in my url.py.

I have tried running it as follows :

```<code>python manage.py runserver 192.168.0.13:8000
python manage.py runserver 0.0.0.0:8000
</code>```

Non of which helps.

I know its not a firewall issue as the page not found is as a result of the django service responding.

答: Check the site records under Settings -> Sites in the Wagtail admin. When a request comes in, Wagtail will only serve a page if the hostname matches one named in a site record, or the 'is default site' box is checked.</p>

Body:
I have added the following to my settings.py

ALLOWED_HOSTS = ['0.0.0.0','127.0.0.1','192.168.0.05']

My url.py

urlpatterns = [
url(r'^django-admin/', include(admin.site.urls)),

url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),

#url(r'^search/$', search_views.search, name='search'),

# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
#url(r'', include(wagtail_urls)),

# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
#    url(r'^pages/', renders(wagtail_urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),

]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += i18n_patterns(
# These URLs will have /<language_code>/ appended to the beginning
url(r'^search/$', search_views.search, name='search'),
url(r'', include(wagtail_urls)),
#url(r'^$', include(wagtail_urls)),
 )

The dilema is when I do "http://127.0.0.1:8000/en" it works just fine however when I do "http://192.168.0.5:8000/en/" from my mobile phone on the same lan or even from the laptop its hosted on I keep getting "Page not found (404)".

What would cause such behavior did I overlook something in my url.py.

I have tried running it as follows :

python manage.py runserver 192.168.0.13:8000
python manage.py runserver 0.0.0.0:8000

Non of which helps.

I know its not a firewall issue as the page not found is as a result of the django service responding.


问:
Equation within JLabel doesn't work?
I am trying to display a JLabel that holds the final points, the number of aliens found in the game and the percentage out of 30 aliens. Whenever I run my program the score/30*100 part just produces 0 instead of the actual percentage. I've tried creating a separate variable called percent with the equation and subbing it into the setText but it still doesn't work. Help?</p>

```<code>    sb.scoreLabel.setText("<html> Final Score: <html>" + (score-(incorrect)) + "<html>00<p> You got "
                    + score + "/30 aliens! (<html>" + ((score/30)*100) + "<html>%) <html>" );
</code>```

答:
```<code>((score/30)*100)
</code>```

You are using integer math so (score/30) is 0 (assuming score is less than 30).

Instead use:

```<code>((score * 100) / 30)
</code>```

Title: Equation within JLabel doesn't work?

Body:
I am trying to display a JLabel that holds the final points, the number of aliens found in the game and the percentage out of 30 aliens. Whenever I run my program the score/30*100 part just produces 0 instead of the actual percentage. I've tried creating a separate variable called percent with the equation and subbing it into the setText but it still doesn't work. Help?

    sb.scoreLabel.setText(" Final Score: " + (score-(incorrect)) + "00
 You got "
                    + score + "/30 aliens! (" + ((score/30)*100) + "%) " );

Body:
((score/30)*100)

You are using integer math so (score/30) is 0 (assuming score is less than 30).

Instead use:

((score * 100) / 30)


问:
Auto height of parent div where child divs have skewed edges
I was working on a little something for myself and I walked into a problem i simply cant solve. I am trying to achieve a small effect where there are  2 divs with skewed edges. However, their parent div gets a scrollbar because the skew falls outside.

HTML

```<code><div class="c-r">
        <div class=" c-c c-r-l-1">

        </div>
        <div class="c-c c-r-r-1">

        </div>
</div>
</code>```

CSS

```<code>.c-r{
display: block;
height: auto;
overflow: auto;
}
.c-c{
    width: 50%;
    height: 300px;
    margin-top: 150px;
    position: relative;
    display: inline-block;
    float: left;
    background: #44bf86;
}

.c-r-l-1:before, .c-r-l-1:after {
    content: '';
    width: 100%;
    height: inherit;
    position: absolute;
    background: inherit;
    z-index: -1;
    transition: ease all .5s;
    -webkit-transform:skewY(5deg) ;
    -moz-transform: skewY(5deg);
    -ms-transform: skewY(5deg);
    -o-transform:skewY(5deg) ;
    transform:skewY(5deg) ;
}
.c-r-l-1:before {
    top: 0;
    z-index: 12;
    transform-origin: right top;
}
.c-r-l-1:after {
    bottom: 0;
    z-index: 12;
    transform-origin: left bottom;
}
.c-r-r-1:before, .c-r-r-1:after {
    content: '';
    width: 100%;
    height: inherit;
    position: absolute;
    background: inherit;
    z-index: -1;
    transition: ease all .5s;
}
.c-r-r-1:before {
    top: 0;
    transform-origin: left top;
    transform: skewY(-5deg);
}
.c-r-r-1:after {
    bottom: 0;
    transform-origin: right bottom;
    transform: skewY(-5deg);
}
@media screen and (max-width: 720px){

    .c-r{
        display: block;
        overflow: auto;
    }
    .c-c{
        width: 100%;
    }
}
</code>```

I am not really sure what other info I can give you than this. I hope you all can help me out and thank you for taking your time.

~Greetings

答:
I found the fix to my problem.

All i had to do was add:

```<code>padding-top: 5%;
padding-bottom: 5%;
</code>```

The reason why it has to be 5 is because my skew is going 5 degrees!

To my outer div. everything works fine now. Thanks everyone for their time!

Body:
I was working on a little something for myself and I walked into a problem i simply cant solve. I am trying to achieve a small effect where there are  2 divs with skewed edges. However, their parent div gets a scrollbar because the skew falls outside.

HTML

CSS

.c-r{
display: block;
height: auto;
overflow: auto;
}
.c-c{
    width: 50%;
    height: 300px;
    margin-top: 150px;
    position: relative;
    display: inline-block;
    float: left;
    background: #44bf86;
}

.c-r-l-1:before, .c-r-l-1:after {
    content: '';
    width: 100%;
    height: inherit;
    position: absolute;
    background: inherit;
    z-index: -1;
    transition: ease all .5s;
    -webkit-transform:skewY(5deg) ;
    -moz-transform: skewY(5deg);
    -ms-transform: skewY(5deg);
    -o-transform:skewY(5deg) ;
    transform:skewY(5deg) ;
}
.c-r-l-1:before {
    top: 0;
    z-index: 12;
    transform-origin: right top;
}
.c-r-l-1:after {
    bottom: 0;
    z-index: 12;
    transform-origin: left bottom;
}
.c-r-r-1:before, .c-r-r-1:after {
    content: '';
    width: 100%;
    height: inherit;
    position: absolute;
    background: inherit;
    z-index: -1;
    transition: ease all .5s;
}
.c-r-r-1:before {
    top: 0;
    transform-origin: left top;
    transform: skewY(-5deg);
}
.c-r-r-1:after {
    bottom: 0;
    transform-origin: right bottom;
    transform: skewY(-5deg);
}
@media screen and (max-width: 720px){

    .c-r{
        display: block;
        overflow: auto;
    }
    .c-c{
        width: 100%;
    }
}

I am not really sure what other info I can give you than this. I hope you all can help me out and thank you for taking your time.

~Greetings

Body:
I found the fix to my problem.

All i had to do was add:

padding-top: 5%;
padding-bottom: 5%;

The reason why it has to be 5 is because my skew is going 5 degrees!

To my outer div. everything works fine now. Thanks everyone for their time!


问:
Remove hover style from every button in C#
I want to add this code to every button in my C# Project:

```<code>button1.FlatAppearance.MouseDownBackColor = button1.BackColor;
button1.FlatAppearance.MouseOverBackColor = button1.BackColor;
button1.FlatStyle = FlatStyle.Flat;
</code>```

I've tried this code in the Form_Load event but the var b stays null:

```<code>foreach (Control c in Controls)
        {
            Button b = c as Button;
            if (b != null)
            {
                b.FlatAppearance.MouseOverBackColor = b.BackColor;
                b.FlatAppearance.MouseDownBackColor = b.BackColor;
                b.FlatStyle = FlatStyle.Flat;
            }
        }
</code>```

What can i do?

答:
I'll just assume this is about WinForms.

As your code seems to work when the buttons are directly on the form, they probably are on another control (a container) on the form. You could now search for container and check wether they contain a button, however this gets awkward when they have container as well. Therefore I'd suggest to use recursion:

```<code>private List<Control> GetAllControls(Control parent)
{
    List<Control> controls = new List<Control>();
    controls.AddRange(parent.Controls.Cast<Control>()); //add all controls directly being on the current control
    controls.AddRange(parent.Controls.Cast<Control>().SelectMany(GetAllControls)); //add all children from each control
    return controls;
}
</code>```

Which you can call like this:

```<code>foreach (Control c in GetAllControls(this))
{
    Button b = c as Button;
    if (b != null)
    {
        b.FlatAppearance.MouseOverBackColor = b.BackColor;
        b.FlatAppearance.MouseDownBackColor = b.BackColor;
        b.FlatStyle = FlatStyle.Flat;
    }
}
</code>```

You can read more about recursion here.

Body:
I want to add this code to every button in my C# Project:

button1.FlatAppearance.MouseDownBackColor = button1.BackColor;
button1.FlatAppearance.MouseOverBackColor = button1.BackColor;
button1.FlatStyle = FlatStyle.Flat;

I've tried this code in the Form_Load event but the var b stays null:

foreach (Control c in Controls)
        {
            Button b = c as Button;
            if (b != null)
            {
                b.FlatAppearance.MouseOverBackColor = b.BackColor;
                b.FlatAppearance.MouseDownBackColor = b.BackColor;
                b.FlatStyle = FlatStyle.Flat;
            }
        }

What can i do?

Body:
I'll just assume this is about WinForms.

As your code seems to work when the buttons are directly on the form, they probably are on another control (a container) on the form. You could now search for container and check wether they contain a button, however this gets awkward when they have container as well. Therefore I'd suggest to use recursion:

private List<Control> GetAllControls(Control parent)
{
    List<Control> controls = new List<Control>();
    controls.AddRange(parent.Controls.Cast<Control>()); //add all controls directly being on the current control
    controls.AddRange(parent.Controls.Cast<Control>().SelectMany(GetAllControls)); //add all children from each control
    return controls;
}

Which you can call like this:

foreach (Control c in GetAllControls(this))
{
    Button b = c as Button;
    if (b != null)
    {
        b.FlatAppearance.MouseOverBackColor = b.BackColor;
        b.FlatAppearance.MouseDownBackColor = b.BackColor;
        b.FlatStyle = FlatStyle.Flat;
    }
}

You can read more about recursion here.


问:
How does one continue code from the line where the function was on in Python?
I have a nameType() function in my text game, and it is used two times:

Creating a stats class (or whatever) so the program can save them, and

A function in-game for some variable changing.

Here's the current code that this post targets (may be subject to change):

```<code>def TitleScreen():
blankHuge()
anar()
print('The Game of Hierarchy and Anarchy\nBy Roach\nText Edition\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nType "new" to start a new game.\nTo load a game, type "load".\nTo exit, type "exit".')
StartGame = input()
if StartGame == 'new':
    print('► Crew Member: Hello, fine man. I can see you are on an adventure to the land of Salbury.\nBefore you disembark the boat, please enter your name.')
    for filename in file:
        os.unlink(filename)
    nameType()
    global PlayerIG
    PlayerIG = Player(CharName)
    print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
    saveGame()
    MainMenu()
# more stuff that aren't related down here...
</code>```

Here's the nameType() function:

```<code>def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes': # If this is true, then jump to next codeline from where the nameType() func was placed...
            pause() # Doesn't work

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()
</code>```

And here's the function which is supposed to continue the code from where it was, but it doesn't work:

```<code>def pause():
pause = input('► Press Enter to continue.')
if pause != '':
    pause()
</code>```

Is there any way I can continue my code?

Example (most likely not going to work):

```<code>def TitleScreen():
    ...
    nameType() # Someway, jump to next line after code in nameType() has been executed...
    global PlayerIG
    PlayerIG = Player(CharName)
    ...
    saveGame()
    MainMenu()

def management():
    ...
    opt = input()
    if opt = 'name':
        nameType() # Someway, jump to next line after code in nameType() has been executed...
        PlayerIG.nameWait = 12
        PlayerIG.heat = 0
    ...
</code>```

NOTE: I have an idea of how this will work, but I'm not sure if it will work. It is:

```<code># outside of nameType()
if confirmName == 'yes':
    ...
</code>```

答:
My idea worked, using if outside the nameType() function does work. I used global (I know it's bad coding, but whatever), and now the function works.

```<code>def nameType():
global confirmName
global CharName
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()
# Items down here for the confirmName input removed

# This is the system for the 'jump':
if confirmName == 'blah1':
    # add stuff here...
    if confirmName == 'no':
        # add stuff here...
    else:
        # add stuff here...
</code>```

Body:
I have a nameType() function in my text game, and it is used two times:

Creating a stats class (or whatever) so the program can save them, and

A function in-game for some variable changing.

Here's the current code that this post targets (may be subject to change):

def TitleScreen():
blankHuge()
anar()
print('The Game of Hierarchy and Anarchy\nBy Roach\nText Edition\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nType "new" to start a new game.\nTo load a game, type "load".\nTo exit, type "exit".')
StartGame = input()
if StartGame == 'new':
    print('► Crew Member: Hello, fine man. I can see you are on an adventure to the land of Salbury.\nBefore you disembark the boat, please enter your name.')
    for filename in file:
        os.unlink(filename)
    nameType()
    global PlayerIG
    PlayerIG = Player(CharName)
    print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
    saveGame()
    MainMenu()
# more stuff that aren't related down here...

Here's the nameType() function:

def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes': # If this is true, then jump to next codeline from where the nameType() func was placed...
            pause() # Doesn't work

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()

And here's the function which is supposed to continue the code from where it was, but it doesn't work:

def pause():
pause = input('► Press Enter to continue.')
if pause != '':
    pause()

Is there any way I can continue my code?

Example (most likely not going to work):

def TitleScreen():
    ...
    nameType() # Someway, jump to next line after code in nameType() has been executed...
    global PlayerIG
    PlayerIG = Player(CharName)
    ...
    saveGame()
    MainMenu()

def management():
    ...
    opt = input()
    if opt = 'name':
        nameType() # Someway, jump to next line after code in nameType() has been executed...
        PlayerIG.nameWait = 12
        PlayerIG.heat = 0
    ...

NOTE: I have an idea of how this will work, but I'm not sure if it will work. It is:

# outside of nameType()
if confirmName == 'yes':
    ...

Body:
My idea worked, using if outside the nameType() function does work. I used global (I know it's bad coding, but whatever), and now the function works.

def nameType():
global confirmName
global CharName
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()
# Items down here for the confirmName input removed

# This is the system for the 'jump':
if confirmName == 'blah1':
    # add stuff here...
    if confirmName == 'no':
        # add stuff here...
    else:
        # add stuff here...


问:
What is the best way to bulk copying SQL data over a dial-up connection?
I have a few remote SQL servers that I need to pull a large amount of data from regularly (say 5,000,000 rows per server). This data also needs to be formatted and FTPed to another server. The dial-up portion is fine, I can connect and communicate with the server, but sometimes the connection is slow, maybe only 19Kbps.

Once connected I tried to use System.Data.SqlClient.SqlBulkCopy, but it just throws a timeout error. I've set the timeout on the bulk copy to 7200 seconds, and the timeout on the connection strings to each database at 900 seconds, but it still times out at around 30 seconds.

I tried using a DataReader and running SqlCommand.ExecuteNonQuery() to insert each row, which works OK, but it's slow and sometimes the connection is lost.

I also tried setting up a DTS package on the remote servers, scheduling them to dump the data I need to text, and then tried downloading the files. But, they can be a few hundred MB (possibly even GB on some servers) and the dial-up connection is usually dropped at some point.

答:
What I ended up doing was creating a small app in C (a few of these are WINNT and that was the easiest way, it also allows other to retrieve the data manually if necessary without the ability to alter the source) that takes a few arguments to build the query I need. It then runs the query and dumps the results in the required CSV format. Then it calls 7zip with the highest compression level to compact the data as small as possible (this reduces a 500MB file to about 20MB).

Because I have to bring the data back to me before I can FTP it to the necessary place, and the remote servers don't have any internet access, I'm still just copying the file to a windows share, then decompressing it locally and FTP the uncompressed data (as requested) to it's destination.

This may not be the best approach, but it's working. Thanks

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: NXC


问:
Easy way to get daily pageviews (different to each url)?
I need to display daily pageviews in my wordpress site. The problem is I need it to be url aware I mean not count visits for the whole site but just count how many visits the current URL had. Is there an easy way to do so?</p>

答:
Try using the Wordpress.com stats plugin or Google Analytics.

There is also a Google Analytics Wordpress plugin


问:
How do I prefetch related objects for a list of already fetched ones?
I'm displaying 7 random objects on a home page. For that I use solution based on this answer:

```<code>class ProductManager(models.Manager):
    def random(self, n_products, filter={}, select_related=None):
        n_products_total = self.filter(**filter).count()
        if n_products_total == 0:
            return []
        r = [
            self.random_impl(n_products_total, filter, select_related)
            for i in range(n_products)
        ]
        return [p for p in r if p is not None]

    def random_impl(self, n_products, filter, select_related=None):
        random_index = randint(0, n_products - 1)
        try:
            return self.filter(**filter) \
                .select_related(select_related)[random_index]
        except IndexError:
            return None

random_products = Product.objects.random(
    7, filter={'enabled': True}, select_related='category'
)
</code>```

If I pass prefetch_related=Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk')) to random_impl method, it prefetches 1 photo at a time for each product. Which is not surprising. Can I prefetch related objects manually after products has already been fetched?

答:
To my surprise, there's a legal way. Documented, that is. You just need to add:

prefetch_related_objects(
    random_products,
    Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk')),
)
```

ContentLicense: CC BY-SA 4.0

Body:
I'm displaying 7 random objects on a home page. For that I use solution based on this answer:

class ProductManager(models.Manager):
    def random(self, n_products, filter={}, select_related=None):
        n_products_total = self.filter(**filter).count()
        if n_products_total == 0:
            return []
        r = [
            self.random_impl(n_products_total, filter, select_related)
            for i in range(n_products)
        ]
        return [p for p in r if p is not None]

    def random_impl(self, n_products, filter, select_related=None):
        random_index = randint(0, n_products - 1)
        try:
            return self.filter(**filter) \
                .select_related(select_related)[random_index]
        except IndexError:
            return None

random_products = Product.objects.random(
    7, filter={'enabled': True}, select_related='category'
)

If I pass prefetch_related=Prefetch('productphoto_set', queryset=ProductPhoto.objects.order_by('pk')) to random_impl method, it prefetches 1 photo at a time for each product. Which is not surprising. Can I prefetch related objects manually after products has already been fetched?


问:
DLL load failed error when importing cv2
I have installed opencv on my windows machine using python 3.6 without any issues, using:

```<code>pip install opencv-python
</code>```

but when I try to import cv2 I get the following error

```<code>ImportError: DLL load failed: The specified module could not be found.
</code>```

I have seen this post

It says cv2 doesn't work with python 3 I was wondering if this has been fixed or if there is a way around it

答: I had the same issue when installing opencv 2.4.13 on Anaconda3 (Python 3.6)... I managed to fix this issue by reverting to Anaconda2 (Python 2.7)</p>

Body:
I have installed opencv on my windows machine using python 3.6 without any issues, using:

pip install opencv-python

but when I try to import cv2 I get the following error

ImportError: DLL load failed: The specified module could not be found.

I have seen this post

It says cv2 doesn't work with python 3 I was wondering if this has been fixed or if there is a way around it


问:
How to insert elements into the list at arbitrary positions?
I have this

```<code>>>> a = [1, 4, 7, 11, 17]
</code>```

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

```<code>['-', 1, '-', 4, 7, '-', '-', 11, 17]
</code>```

答:
Python has insert(index, value) list method that will do the trick.
What you want is:

```<code>import random

l = [1, 2, 3, 4]
for x in range(0, 4): # this line will ensure 4 element insertion
   l.insert(random.randrange(0, len(l)-1), '-')
</code>```

randrange() will generate random integers from within index range of your list.
Thats it.

Body:
I have this

>>> a = [1, 4, 7, 11, 17]

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

['-', 1, '-', 4, 7, '-', '-', 11, 17]

Body:
Python has insert(index, value) list method that will do the trick.
What you want is:

import random

l = [1, 2, 3, 4]
for x in range(0, 4): # this line will ensure 4 element insertion
   l.insert(random.randrange(0, len(l)-1), '-')

randrange() will generate random integers from within index range of your list.
Thats it.


问:
NameError: uninitialized constant Capybara::Webkit.configure
I must not be understanding correctly where to place this method call. I have this test_helper.rb file

```<code>ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require 'rails/test_help'
require 'minitest/rails/capybara'
require 'capybara'
require 'capybara/rails'
require 'capybara/webkit'

Dir[Rails.root.join('test/support/**/*.rb')].each { |f| require f }

Capybara::Webkit.configure do |config|
  config.allow_unknown_urls
end
</code>```

And I get this error when I run rake test

NoMethodError: undefined method configure' for Capybara::Webkit:Module
/Users/sameer/code/rails/door_app/test/test_helper.rb:XX:in'

It seems like I'm doing what's described in the README at the Capybara-webkit Github page.

答:
You need to install a gem </p>

```<code>group :test do
  ...
  gem 'capybara-webkit'

end
</code>```

Body:
I must not be understanding correctly where to place this method call. I have this test_helper.rb file

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require 'rails/test_help'
require 'minitest/rails/capybara'
require 'capybara'
require 'capybara/rails'
require 'capybara/webkit'

Dir[Rails.root.join('test/support/**/*.rb')].each { |f| require f }

Capybara::Webkit.configure do |config|
  config.allow_unknown_urls
end

And I get this error when I run rake test

NoMethodError: undefined method configure' for Capybara::Webkit:Module
/Users/sameer/code/rails/door_app/test/test_helper.rb:XX:in'

It seems like I'm doing what's described in the README at the Capybara-webkit Github page.

Body:
You need to install a gem

group :test do
  ...
  gem 'capybara-webkit'

end


问:
Case-when or if-then to control table creation in Redshift
I have a handful of data sources that I'd like to apply the same analyses to and eventually load into a larger table database (uniformtable). Different sources contain different columns, and sometimes sources involve crosswalk files that I need to join. I'd like to have one query that converts all sources' data into uniformtable formatting, based on a unique key for each source. Something along the lines of this:

```<code>case when source.sourceid = 1 then
create uniformtable as
select column1a as uniforma, column1b as uniformb, sourceid from source
else
when source.sourceid = 2 then
create uniformtable as
select column2a as uniforma, column2b as uniformb, sourceid from source
end;
</code>```

I've tried using if-then and case-when to accomplish this, but I get syntax errors pointing to the very start of my query. Does Redshift allow you to use if logic for this kind of control?

答:
No, this logic is not permitted.

CASE statements are only valid within a SELECT statement.

You would need to perform this logic external to Amazon Redshift, and then just send the final SQL to create the table.

Body:
I have a handful of data sources that I'd like to apply the same analyses to and eventually load into a larger table database (uniformtable). Different sources contain different columns, and sometimes sources involve crosswalk files that I need to join. I'd like to have one query that converts all sources' data into uniformtable formatting, based on a unique key for each source. Something along the lines of this:

case when source.sourceid = 1 then
create uniformtable as
select column1a as uniforma, column1b as uniformb, sourceid from source
else
when source.sourceid = 2 then
create uniformtable as
select column2a as uniforma, column2b as uniformb, sourceid from source
end;

I've tried using if-then and case-when to accomplish this, but I get syntax errors pointing to the very start of my query. Does Redshift allow you to use if logic for this kind of control?


问:
Docker doesn't work after installed on Ubuntu 14 based on official tutorial
I am using official Ubuntu 14

I am following this official document to install docker.

After install, docker exists on the server, but it just doesn't work.

```<code>docker ps
// or
docker run hello-world
</code>```

All return the same error

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

I am really new to docker, what is going wrong? How to run docker deamon?

Result of "sudo service docker status" command:

答:
I see you using the 'sudo' command when starting/stopping/checking the Docker service, but not when issuing the 'docker' commands.  Try using: sudo docker <command>

It's likely due to the user you are issuing the docker commands with not being apart of the Docker-associated group.

Try: cat /etc/group | grep docker

This should spit back the docker group that exists...on my CentOS 7 the group is called 'dockerroot'

So, I add myself to the 'dockerroot' group: sudo usermod -aG dockerroot username

Obviously, replace username with your actual username.

Body:
I am using official Ubuntu 14

I am following this official document to install docker.

After install, docker exists on the server, but it just doesn't work.

docker ps
// or
docker run hello-world

All return the same error

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

I am really new to docker, what is going wrong? How to run docker deamon?

Result of "sudo service docker status" command:


问:
google script - require string input before submit
I use a little script based on html and javascript to enable third parties to upload files to my drive. They are supposed to name the file so that I can identify it later on. Unfortunately many forget to do so. Which changes are necessary to force input in myName before submitting?

html code

<form id="myForm">
<input type="text" name="myName" placeholder="name of the file..">
<input type="file" name="myFile">
<input type="submit" value="Abschicken"
onclick="this.value='Please wait..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>

```

<p>google script</p>

<pre class="lang-js prettyprint-override"><code>function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
    try {
      var dropbox = "Fotos";
    var folder, folders = DriveApp.getFoldersByName(dropbox);
     if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    var blob = form.myFile;
    var file = folder.createFile(blob);
    file.setDescription("Projekt: " + form.myName);
    file.setName("FOTO_" + form.myName);
    return "Upload completed.";
    } catch (error) {
    return error.toString();
  }
}
</code>```

答:
You can add te required attribute to the form.

```<code><input type="text" required name="myName" placeholder="name of the file..">
</code>```

This will cause the browser to check that a value is entered before submitting the form. If the field is empty the browser will show an error and won't submit the form.

The user could still remove the required attribute but since you don't have access to the server side this is the best you can do.

Body:
I use a little script based on html and javascript to enable third parties to upload files to my drive. They are supposed to name the file so that I can identify it later on. Unfortunately many forget to do so. Which changes are necessary to force input in myName before submitting?

html code

<form id="myForm">
<input type="text" name="myName" placeholder="name of the file..">
<input type="file" name="myFile">
<input type="submit" value="Abschicken"
onclick="this.value='Please wait..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>

google script

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
    try {
      var dropbox = "Fotos";
    var folder, folders = DriveApp.getFoldersByName(dropbox);
     if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    var blob = form.myFile;
    var file = folder.createFile(blob);
    file.setDescription("Projekt: " + form.myName);
    file.setName("FOTO_" + form.myName);
    return "Upload completed.";
    } catch (error) {
    return error.toString();
  }
}

Body:
You can add te required attribute to the form.

<input type="text" required name="myName" placeholder="name of the file..">

This will cause the browser to check that a value is entered before submitting the form. If the field is empty the browser will show an error and won't submit the form.

The user could still remove the required attribute but since you don't have access to the server side this is the best you can do.


答:
You could randomly interleave the '-'s using iterators and random.sample():

```<code>In [1]:
a = [1, 4, 7, 11, 17]
pop = [iter(a)]*len(a) + [iter('-'*4)]*4
[next(p) for p in random.sample(pop, k=len(pop))]

Out[1]:
['-', '-', 1, '-', 4, 7, 11, '-', 17]
</code>```

Title: How to insert elements into the list at arbitrary positions?

Body:
You could randomly interleave the '-'s using iterators and random.sample():

In [1]:
a = [1, 4, 7, 11, 17]
pop = [iter(a)]*len(a) + [iter('-'*4)]*4
[next(p) for p in random.sample(pop, k=len(pop))]

Out[1]:
['-', '-', 1, '-', 4, 7, 11, '-', 17]


问:
How to paint r x r field with n different colors without using same color at same column, row
Recently, I encountered this problem and I can't solve it because of time over.

'Make a program that answers how many ways to paint r by r field with n different colors, without using the same color at same row, same column.'

I coded for it, but it takes over 30 mins to answer at only 6 by 6 field with 6 colors.

So, I thought about multi-dimensional memoization, but I don't have an idea to add memoization array at my code.

Please help me make my code faster or suggest the new way.

```<code>#include<stdio.h>
#include<stdlib.h>
int check[100][100], scheck[100][100], n, r;
long long cnt;
void arr(int x, int y) {
   int i, k=0;
   for (int j = 0; j < n; j++) { //about n colors
      if (check[y][j] == 0 && scheck[x][j] == 0) { //if there is no j th color in same row and column
         check[y][j] = 1; // check 'there is j th color in y th row, x th column
         scheck[x][j] = 1; // to make same effect with inputing j at virtual field[y][x]
         if (x == r - 1) { // if x th column is the end of right
             if (y == r - 1) cnt++; // if y th column is the bottom, count this
             else arr(0, y + 1); // else fill next row, first column
         }
         else arr(x + 1, y); // else fill next right square
         check[y][j] = 0; // check 'there is no j th color in y th row, x th column
         scheck[x][j] = 0; // to make same effect with erasing j virtual field[y][x]
      }
   }
   return;
}
void main() {
    printf("Input n, r (paint r x r field with n colors, same color cannot be used in same column and row) \n: ");
    scanf("%d %d", &n, &r);
    arr(0, 0);
    printf("There are %ld ways to paint.\n", cnt);
}
</code>```

答:
This is also an example of a generalized exact cover problem, a class of problems that includes familiar examples like Sudoku puzzle (you can note the similarity) and the N queens problem. The problem is NP-complete so there isn't a super efficient algorithm, but there is a canonical solution known as Algorithm X, due to Donald Knuth.

To translate your problem into the language of an exact cover, note that there are r^2+2rn constraints that must be satisfied exactly zero or one times: for row and column 0 <= i,j < r, have only one entry, and for each 0 <= k < r and 0 <= c < n, have an entry of color c in row (or column) k. There are nr^2 possible entries in the table, i.e. placing a color c at row i and column j. Each one of these satisfied two constraints (i.e. color c and row i, color c at row j) while not satisfying any of the others. Thus, you can construct a matrix with nr^2 rows and 2rn columns. Solving the exact cover problem for this table only is a little over restrictive, as it requires each of the n colors to appear in each row and column once, rather than at most once. This difference is what makes the problem a generalized exact cover problem, and is addressed by adding 2rn book-keeping rows, each with a 1 at exactly one of the 2rn constraints corresponding to the row/column color conditions.

Body:
Recently, I encountered this problem and I can't solve it because of time over.

'Make a program that answers how many ways to paint r by r field with n different colors, without using the same color at same row, same column.'

I coded for it, but it takes over 30 mins to answer at only 6 by 6 field with 6 colors.

So, I thought about multi-dimensional memoization, but I don't have an idea to add memoization array at my code.

Please help me make my code faster or suggest the new way.

#include<stdio.h>
#include<stdlib.h>
int check[100][100], scheck[100][100], n, r;
long long cnt;
void arr(int x, int y) {
   int i, k=0;
   for (int j = 0; j < n; j++) { //about n colors
      if (check[y][j] == 0 && scheck[x][j] == 0) { //if there is no j th color in same row and column
         check[y][j] = 1; // check 'there is j th color in y th row, x th column
         scheck[x][j] = 1; // to make same effect with inputing j at virtual field[y][x]
         if (x == r - 1) { // if x th column is the end of right
             if (y == r - 1) cnt++; // if y th column is the bottom, count this
             else arr(0, y + 1); // else fill next row, first column
         }
         else arr(x + 1, y); // else fill next right square
         check[y][j] = 0; // check 'there is no j th color in y th row, x th column
         scheck[x][j] = 0; // to make same effect with erasing j virtual field[y][x]
      }
   }
   return;
}
void main() {
    printf("Input n, r (paint r x r field with n colors, same color cannot be used in same column and row) \n: ");
    scanf("%d %d", &n, &r);
    arr(0, 0);
    printf("There are %ld ways to paint.\n", cnt);
}


问:
D3.js: randomly animate donut inside another donut
I found this code:

http://digodat.com/ba_test.html

That randomly changes proportions in a donut chart.

The, I found this other code:

http://digodat.com/ba_test_4.html

That lets me create a donut inside a donut.

Now, I want a button that can randomly create the same effect I have in my first file, but applied to the two donuts of my second file, so when I click the button, every slice changes.

I've tried copying and testing specific parts of the code, but I can't get it to work

答:
There's many ways to do what you want.  Here's a quick refactor of your second example:

  <title></title>

      <svg style="height:300px;width:100%"></svg>
      <button class="random">Random Inner</button>
      <button class="random">Random Outer</button>

```

Body:
There's many ways to do what you want.  Here's a quick refactor of your second example:

<html>

<head>
  <script type="text/javascript" src="https://d3js.org/d3.v3.min.js"></script>
  <title></title>

  <body>
    <div id="duration">
      <svg style="height:300px;width:100%"></svg>
      <button class="random">Random Inner</button>
      <button class="random">Random Outer</button>
    </div>

    <script type="text/javascript">

      var dataset = {
        apples: [13245, 28479, 11111, 11000, 3876],
        oranges: [53245, 28479, 19697, 24037, 19654],
      };

      var width = d3.select('#duration').node().offsetWidth,
        height = 300,
        cwidth = 33;

      var color = [
        ['#1352A4', '#2478E5', '#5D9CEC', '#A4C7F4', '#DBE8FB'],
        ['#58A53B', '#83C969', '#A8D996', '#CDE9C3', '#E6F4E1']
      ];

      var pie = d3.layout.pie()
        .sort(null);

      var arcs = [d3.svg.arc()
        .innerRadius(95)
        .outerRadius(cwidth * 2.5),
        d3.svg.arc()
        .innerRadius(70 + cwidth)
        .outerRadius(cwidth * 3.5)
      ];

      var svg = d3.select("#duration svg")
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

      var gs = svg.selectAll("g")
        .data(d3.values(dataset))
        .enter()
        .append("g")
        .attr("class", function(d, i) {
          return i === 0 ? "inner" : "outer";
        });

      var path = gs.selectAll("path")
        .data(function(d, i) {
          return pie(d);
        })
        .enter().append("path")
        .attr("fill", function(d, i, j) {
          return color[j][i];
        })
        .attr("d", function(d, i, j) {
          return arcs[j](d);
        });

      d3.selectAll(".random").on("click", function(d, i) {

        var slices = i === 0 ? d3.selectAll(".inner>path") : d3.selectAll(".outer>path");

        var randData = pie(d3.range(5).map(function() {
          return Math.random() * 1000;
        }));

        randData.forEach(function(d, i) {
          d._current = slices.data()[i];
        })

        slices
          .data(randData)
          .transition().duration(1000)
          .attrTween("d", function(d) {
            var interpolate = d3.interpolate(d._current, d);
            return function(t) {
              return arcs[i](interpolate(t));
            };
          })

      })
    </script>
  </body>

</html>


问:
LARAVEL - Multiple databases per user, user choses database connection each time
fairly new to Laravel so accept my apologies in advance if I am lacking any essential knowledge.

So, I am building an app where each user can login to a personal dashboard. This dashboard displays data from a certain database. Each user has multiple databases but each database belongs to only one user. The user can create new databases from the dashboard (this is handled by the back-end, only mentioning it to give you a better idea of how the app works). Finally, there is a separate database, common for all users where the user-database relationships are stored.

What I need for every user is:

When they log in, their dashboard displays data of the latest created database that belongs to that user.
The user can then select what database they want to "view" from a dropdown menu and dashboard contents change accordingly.
Now, I have this working for a single database per user (hard-coded) but want to add the dynamic element described above.

I found something similar here:

https://laracasts.com/discuss/channels/general-discussion/change-database-name-of-connection-on-the-fly?page=1

but there seem to be some answers missing from the thread so could not quite follow it.

Each one of the databases has the exact same structure so there is only one controller and model needed that will dynamically get values for database name.

So the workflow what I would need looks as follows:

User logs in

View composer gets a list of all available databases for that user and generates a dropdown menu

Model connects to latest created database

Controller uses that connection to retrieve and pass data to the view

User selects a different database from the dropdown menu

Model connection updated to new selected database

Controller uses that connection to get data from that database to pass to view

My main issue is defining the procedures that will assign a the current database name to a variable and then the models use this variable to set up a dynamic connection and finally call controllers to retrieve and show data.

Is a process like that feasible and what would be the best approach towards it?

Thank you in advance for the help!!

答:
I see what you're trying to do here, and I have spent a few minutes thinking and researching.

Take a look at: https://laracasts.com/discuss/channels/tips/set-up-dynamic-database-connection-globally

This essentially says that you need to have two MySQL connection configuration details in your Laravel database.php file. main for your master database and a secondary connection (called tenant in examples below), which is blank, used for connecting to the user specific database.

Somewhere high up in the application (service provider?) you will need to set the specific database config, eg:

```<code>Config::set('database.connections.tenant.host', $tenant->host);
Config::set('database.connections.tenant.username', $tenant->username);
Config::set('database.connections.tenant.password', $tenant->password);
Config::set('database.connections.tenant.database', $tenant->database);
</code>```

You can then set the protected $connection property in the models to use this secondary database connection.

```<code>class MyModel extends Model {
    protected $connection = 'tenant';
}
</code>```

Body:
I see what you're trying to do here, and I have spent a few minutes thinking and researching.

Take a look at: https://laracasts.com/discuss/channels/tips/set-up-dynamic-database-connection-globally

This essentially says that you need to have two MySQL connection configuration details in your Laravel database.php file. main for your master database and a secondary connection (called tenant in examples below), which is blank, used for connecting to the user specific database.

Somewhere high up in the application (service provider?) you will need to set the specific database config, eg:

Config::set('database.connections.tenant.host', $tenant->host);
Config::set('database.connections.tenant.username', $tenant->username);
Config::set('database.connections.tenant.password', $tenant->password);
Config::set('database.connections.tenant.database', $tenant->database);

You can then set the protected $connection property in the models to use this secondary database connection.

class MyModel extends Model {
    protected $connection = 'tenant';
}


问:
Cannot convert string to string[]
I'm trying to read each line in the text file and create a folder for it.

```<code>{
    Console.Write("Enter Path: ");
    Linktopaths = Console.ReadLine();
    var informtations = System.IO.File.ReadAllLines(Linktopaths);
    System.IO.Directory.CreateDirectory(informtations);
}
</code>```

I have an error message,

Cannot convert string to string[]

on the last word in the code (informtations)

答:
ReadAllLines returns string[] (array of strings) while CreateDirectory expects a single string

depending on what it is you are trying to achieve you should extract a string from the array and pass that to the CreateDirectory method.

```<code>Console.Write("Enter Path: ");
Linktopaths = Console.ReadLine();
string[] informations = System.IO.File.ReadAllLines(Linktopaths);
foreach (string path in informations)
{
    System.IO.Directory.CreateDirectory(path);
}
</code>```

Title: Cannot convert string to string[]

Body:
I'm trying to read each line in the text file and create a folder for it.

{
    Console.Write("Enter Path: ");
    Linktopaths = Console.ReadLine();
    var informtations = System.IO.File.ReadAllLines(Linktopaths);
    System.IO.Directory.CreateDirectory(informtations);
}

I have an error message,

Cannot convert string to string[]

on the last word in the code (informtations)

Body:
ReadAllLines returns string[] (array of strings) while CreateDirectory expects a single string

depending on what it is you are trying to achieve you should extract a string from the array and pass that to the CreateDirectory method.

Console.Write("Enter Path: ");
Linktopaths = Console.ReadLine();
string[] informations = System.IO.File.ReadAllLines(Linktopaths);
foreach (string path in informations)
{
    System.IO.Directory.CreateDirectory(path);
}


问:
When does Django ImageKit create the thumbnail file?
I am trying to understand how Django ImageKit works with respect to creating thumbnail files (for example). I am using the example code:

from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill

class Profile(models.Model):
    avatar = models.ImageField(upload_to='avatars')
    avatar_thumbnail = ImageSpecField(source='avatar',
                                      processors=[ResizeToFill(100, 50)],
                                      format='JPEG',
                                      options={'quality': 60})```

I am uploading the avatar image from an app. This works fine with an entry made in the Profile table and the file created in AWS S3. What I am struggling to understand is when/where/how the avatar_thumbnail is created. Do I have to do something explicit to get it stored in AWS S3 along with the avatar image? Or is the avatar_thumbnail only ever created on the fly? I need it stored somewhere for later use.

答:
I don't get it 100%, but from what I understood the thumbnail is a generator that is only called when the thumbnail is first requested, and is then cached.

My personal experience with it suggests so as well. I created a dummy instance of the model (same code as above) through the admin interface. I then created an html page that displays the thumbnails with template tagging (). Checking my folders, no images generated so far. Then I launch a server, navigate to that page. It takes unusual time to load (that's an indication that the thumbnails are being created) on the first try, but then it speeds up. And the files are there.

Body:
I am trying to understand how Django ImageKit works with respect to creating thumbnail files (for example). I am using the example code:

from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill

class Profile(models.Model):
    avatar = models.ImageField(upload_to='avatars')
    avatar_thumbnail = ImageSpecField(source='avatar',
                                      processors=[ResizeToFill(100, 50)],
                                      format='JPEG',
                                      options={'quality': 60})

I am uploading the avatar image from an app. This works fine with an entry made in the Profile table and the file created in AWS S3. What I am struggling to understand is when/where/how the avatar_thumbnail is created. Do I have to do something explicit to get it stored in AWS S3 along with the avatar image? Or is the avatar_thumbnail only ever created on the fly? I need it stored somewhere for later use.

Body:
I don't get it 100%, but from what I understood the thumbnail is a generator that is only called when the thumbnail is first requested, and is then cached.

My personal experience with it suggests so as well. I created a dummy instance of the model (same code as above) through the admin interface. I then created an html page that displays the thumbnails with template tagging (<img src="instance.thumbnail.url">). Checking my folders, no images generated so far. Then I launch a server, navigate to that page. It takes unusual time to load (that's an indication that the thumbnails are being created) on the first try, but then it speeds up. And the files are there.


问:
How to retrieve products by tags (SQL question)
I have two MySQL tables:

product has id, title, price and some other product attributes

tag has *product_id* and *tag_name* fields

each product row can have one ore more rows in table tag joined by *product_id* field.
Question: how do I select products by *tag_name* and other attributes?
Example: I need to select all books cheaper than $10 and tagged 'foreign' and 'sci-fi'

I know how to select products with one tag (join product and tag by *product_id* and set where clause)
I know how to select products with more than one tag using a stored procedure, however queries take very long time to run.
Is there a way to avoid stored procedure and still get the result?

Update: StackOverflow does something like this when you click "Related Tags" on the right hand side bar. Now, I don't know what architechture their DB has, but the result is fairly quick selection of all questions tagged with multiple tags.

答:
It seems to be simple query, if I have the problem right.

What I see is:

```<code>Select Product.*
from Product, Tag
where Product.id = Tag.product_id
and Product.price<$10
and tag.tag_name in ('foreign', 'sci-fi')
</code>```

Body:
It seems to be simple query, if I have the problem right.

What I see is:

Select Product.*
from Product, Tag
where Product.id = Tag.product_id
and Product.price<$10
and tag.tag_name in ('foreign', 'sci-fi')


问:
JavaScript will not run at all
I have this template as my sinatra layout.erb

```<code><!DOCTYPE html>
<html>
<head>
    <title>Invoicer</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/static/css/font-awesome.min.css">
</head>
<body>
    <nav class="navbar navbar-default">
       ...
    </nav>
    <div class="container">
        <%= yield %>
    </div>
    <%#<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>%>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <script src="/static/js/bootstrap.min.js"/>
    <script src="/static/js/jobs/new.js" />
</body>
</html>
</code>```

and this small javascript call

```<code>console.log("running")
$('#datepicker').datepicker()
</code>```

the server gets a 200 call to the js file but nothing will print to the console or execute.

答: Always use .

Title: JavaScript will not run at all

Body:
I have this template as my sinatra layout.erb

<!DOCTYPE html>

    <title>Invoicer</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/static/css/font-awesome.min.css">

       ...

        <%= yield %>

    <%#%>

Body:
Always use <script></script>.

<script src="..." /> is not a valid tag. When the HTML is parsed, it thinks that <script src="/static/js/jobs/new.js" /> is in the body of the <script src="/static/js/bootstrap.min.js"/> tag like this:

...
<script src="/static/js/bootstrap.min.js">
  <script src="/static/js/jobs/new.js">
...

From MDN <script> documentation:

Tag omission

None, both the starting and ending tag are mandatory.


问:
Amazon's aws cli times out on macOS 10.12.5
I just installed the aws cli (via pip install awscli per Amazon's installation instructions) on macOS 10.12.5. The installation completed without issue. But when I run the app (e.g. $ aws help) it just hangs for about a minute and finally fails with:

```<code>$ aws help
ssh: connect to host xxx.xxx.xxx.xxx port 22: Operation timed out
</code>```

I've tried running it from both Python 3.6.1 and 2.7.13 environments. The macOS firewall is disabled so I'm not blocking any outbound requests.

I'm not sure what else to try at this point.

答:
That is very strange behaviour. The AWS CLI does not activate ssh.

I would suggest that you have another script called aws somewhere in your PATH that you previously used to connect to an Amazon EC2 instance, and that script is running rather than the AWS CLI.

Run this command to discover which one it is running:

```<code>$ which aws
/usr/local/bin/aws
</code>```

In this case, mine is in $ /usr/local/bin/aws help, but yours is likely to be elsewhere.

To run the correct one, use:

```<code>$ /usr/local/bin/aws help
</code>```

Body:
I just installed the aws cli (via pip install awscli per Amazon's installation instructions) on macOS 10.12.5. The installation completed without issue. But when I run the app (e.g. $ aws help) it just hangs for about a minute and finally fails with:

$ aws help
ssh: connect to host xxx.xxx.xxx.xxx port 22: Operation timed out

I've tried running it from both Python 3.6.1 and 2.7.13 environments. The macOS firewall is disabled so I'm not blocking any outbound requests.

I'm not sure what else to try at this point.

Body:
That is very strange behaviour. The AWS CLI does not activate ssh.

I would suggest that you have another script called aws somewhere in your PATH that you previously used to connect to an Amazon EC2 instance, and that script is running rather than the AWS CLI.

Run this command to discover which one it is running:

$ which aws
/usr/local/bin/aws

In this case, mine is in $ /usr/local/bin/aws help, but yours is likely to be elsewhere.

To run the correct one, use:

$ /usr/local/bin/aws help


问:
Growing Array in C
Can any one Explain me plz the concept of Growing Array Of Structs.
i mean dynamic Arrays.
thanks for your Time.</p>

答: I have a dynamically growing string buffer implementation. You can get it from here. It uses the same malloc and realloc technique.

Title: Growing Array in C


问:
CSS styling for a specific table
I have been asked to remove the grey areas from this page http://ccl.vincentandbell.com/partners/

I have tried giving the table an ID
, and have added the following in my style.css file:

```<code>#customtable {
    background-color: #fffff;
}
</code>```

However, this didn't change the color of the gray areas.

Here's the HTML of one grey area:

```<code><tr>
    <td width="105"></td>
    <td width="498"><strong> </strong><p></p>
        <h3>Cumbria Methodist District</h3>
        <p>
            <a href="http://www.cumbriamethodistdistrict.org.uk/welcome.htm">http://www.cumbriamethodistdistrict.org.uk/welcome.htm</a>
        </p>
    </td>
</tr>
</code>```

And the CSS applied to it:

```<code>table tbody tr:nth-child(even) {
    background-color: #f2f2f2;
}
</code>```

答:
1.) Note: you used #fffff as a color value, which is an invalid color value - use eiter #fff or #ffffff (6 times f)

2.) Theoretically, it should work with this CSS added, as @Daniel Fois wrote, since that corresponds to / overwrites an original CSS rule:

```<code>table tbody tr:nth-child(2n) {
    background-color: #ffffff;
}
</code>```

3.) If it should be restricted to that particular page (and not the whole website), you can use the page ID class page-id-16 (which is in the body tag) in a combined CSS selector, plus add !important, if necessary:

```<code>.page-id-16 table tr {
    background-color: #ffffff !important;
}
</code>```

Title: CSS styling for a specific table

Body:
I have been asked to remove the grey areas from this page http://ccl.vincentandbell.com/partners/

I have tried giving the table an ID
, and have added the following in my style.css file:

#customtable {
    background-color: #fffff;
}

However, this didn't change the color of the gray areas.

Here's the HTML of one grey area:

Cumbria Methodist District

            http://www.cumbriamethodistdistrict.org.uk/welcome.htm

And the CSS applied to it:

table tbody tr:nth-child(even) {
    background-color: #f2f2f2;
}

Body:
1.) Note: you used #fffff as a color value, which is an invalid color value - use eiter #fff or #ffffff (6 times f)

2.) Theoretically, it should work with this CSS added, as @Daniel Fois wrote, since that corresponds to / overwrites an original CSS rule:

table tbody tr:nth-child(2n) {
    background-color: #ffffff;
}

3.) If it should be restricted to that particular page (and not the whole website), you can use the page ID class page-id-16 (which is in the body tag) in a combined CSS selector, plus add !important, if necessary:

.page-id-16 table tr {
    background-color: #ffffff !important;
}


问:
Force autoloading of a specific class
This previous question shows how to force autoloading of all classes.

However I need to force autoloading of just one class on its own. How could I do that?

It mustn't:

Involve changing the class's source code

Rely on any part of the class's source code (methods, variables, modifiers e.g. it must be free to change from concrete to abstract without affecting this).

Also, preferably it would not involve coding the class's name as a string. (To help with IDE refactoring and so on).

The best option I have found so far would be to just use spl_autoload_call():

```<code>spl_autoload_call("Jodes\\MyClass");
</code>```

or for non-namespaced classes:

```<code>spl_autoload_call("MyClass");
</code>```

答:
I had the same need recently. Doing require_once was not an option because the class really needed to be located by the autoloader because of some more complex rules, there was no way to know exactly the path to the file with the class.

Although the function spl_autoload_call($classname) is designed to do precisely this, it suffers from a fundamental flaw: it will throw a FATAL ERROR in case you call it twice for the same classname or even if some of the child classes of that class were already loaded. This happens because it's not possible to redeclare classes in PHP:

```<code><?php

spl_autoload_call('TheClass');
// no problem

spl_autoload_call('TheClass');
// PHP Fatal error:  Cannot declare class TheClass, because the name is already in use in ... on line ...
</code>```

My solution for this problem is no rely on the side-effect of class_exists($classname) which was not designed for this purpose, but is more configurable and, therefor, offers more control about triggering the autoloader.

Even better, it has absolutely no problem on multiple calls or if something was already loaded in the inheritance chain. It simply has the side-effect (if you want) of requiring the file, if the class is not there yet!

```<code><?php

class_exists('TheClass');
// no problem

class_exists('TheClass');
// already exists. No need to autoload it and no fatal errors!
</code>```

With this you have a safe and idempotent way to load the class through the autoloader.

And, if you don't want to hard-code the string with the classname in there, from PHP version 5.5 onward, you can use the ::class pseudo constant, which is resolved at compile time to the string with the fully qualified classname (including namespaces):

```<code><?php

class_exists(TheClass::class);
</code>```

Title: Force autoloading of a specific class

Body:
This previous question shows how to force autoloading of all classes.

However I need to force autoloading of just one class on its own. How could I do that?

It mustn't:

Involve changing the class's source code

Rely on any part of the class's source code (methods, variables, modifiers e.g. it must be free to change from concrete to abstract without affecting this).

Also, preferably it would not involve coding the class's name as a string. (To help with IDE refactoring and so on).

The best option I have found so far would be to just use spl_autoload_call():

spl_autoload_call("Jodes\\MyClass");

or for non-namespaced classes:

spl_autoload_call("MyClass");

Body:
I had the same need recently. Doing require_once was not an option because the class really needed to be located by the autoloader because of some more complex rules, there was no way to know exactly the path to the file with the class.

Although the function spl_autoload_call($classname) is designed to do precisely this, it suffers from a fundamental flaw: it will throw a FATAL ERROR in case you call it twice for the same classname or even if some of the child classes of that class were already loaded. This happens because it's not possible to redeclare classes in PHP:

<?php

spl_autoload_call('TheClass');
// no problem

spl_autoload_call('TheClass');
// PHP Fatal error:  Cannot declare class TheClass, because the name is already in use in ... on line ...

My solution for this problem is no rely on the side-effect of class_exists($classname) which was not designed for this purpose, but is more configurable and, therefor, offers more control about triggering the autoloader.

Even better, it has absolutely no problem on multiple calls or if something was already loaded in the inheritance chain. It simply has the side-effect (if you want) of requiring the file, if the class is not there yet!

<?php

class_exists('TheClass');
// no problem

class_exists('TheClass');
// already exists. No need to autoload it and no fatal errors!

With this you have a safe and idempotent way to load the class through the autoloader.

And, if you don't want to hard-code the string with the classname in there, from PHP version 5.5 onward, you can use the ::class pseudo constant, which is resolved at compile time to the string with the fully qualified classname (including namespaces):

<?php

class_exists(TheClass::class);


问:
Size of ellipsis
What is the size of ellipsis in C? I mean, what is the value of sizeof(...)?

答: That's not a valid expression. ... simply means the caller can pass in more arguments than the number of parameters the function formally specifies.

Title: Size of ellipsis


问:
Tensorflow tf.constant_initializer is very slow
Trying to use pre trained word2vec embeddings of 100 dim for training a LSTM

```<code>@staticmethod
def load_embeddings(pre_trained_embeddings_path, word_embed_size):
    embd = []
    import time
    start_time = time.time()
    cnt = 4
    with codecs.open(pre_trained_embeddings_path, mode="r", encoding='utf-8') as f:
        for line in f.readlines():
            values = line.strip().split(' ')
            embd.append(values[1:])
            cnt += 1
            if cnt % 100000 == 0:
                print("word-vectors loaded: %d" % cnt)

    embedding, vocab_size, embed_dim = embd, len(embd), len(embd[0])

    load_end_time = time.time()
    print("word vectors loaded from and start initialising, cnt: %d, time taken: %d secs " % (vocab_size, load_end_time - start_time))

    embedding_init = tf.constant_initializer(embedding, dtype=tf.float16)
    src_word_embedding = tf.get_variable(shape=[vocab_size, embed_dim], initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

    print("word-vectors loaded and initialised, cnt: %d, time taken: %d secs" % (vocab_size, time.time() - load_end_time))

    return src_word_embedding
</code>```

And the output of this when running this method is like :

```<code>word vectors loaded from and start initialising, cnt: 2419080, time taken: 74 secs
word-vectors loaded and initialised, cnt: 2419080, time taken: 1647 secs
</code>```

system info: tensorflow 1.1.0, tcmalloc, python 3.6, ubuntu 14.04

HALF an hour to initialize seems to be very slow or is it a normal behavior ? Any idea what could be the issue or is there one ?

UPDATE: using @sirfz method of supplying the embeddings made it really fast to load the embeddings Initialization Done in 85 secs

答:
I do not know whether this is an intended behavior, but I can explain why is it can slow on a small example:

```<code>import tensorflow as tf

x = [[0, 1], [2, 3]]
a = tf.constant(x, name='a')
b = tf.Variable(x, name='b')
c = a + b

with tf.Session() as sess:
    writer = tf.summary.FileWriter('logs', sess.graph)
    writer.close()
</code>```

When you initialize the constant, the value of this constant is added to the graph. If you will open the graph you can see it by clicking on the a value.

In my case it was a 2x2 matrix, but it looks like in your case it is 2M x ? matrix, which is huge. So in my opinion this is the reason for such a slow execution.

Try to initialize this as a variable and feed you embedding there.

Body:
Trying to use pre trained word2vec embeddings of 100 dim for training a LSTM

@staticmethod
def load_embeddings(pre_trained_embeddings_path, word_embed_size):
    embd = []
    import time
    start_time = time.time()
    cnt = 4
    with codecs.open(pre_trained_embeddings_path, mode="r", encoding='utf-8') as f:
        for line in f.readlines():
            values = line.strip().split(' ')
            embd.append(values[1:])
            cnt += 1
            if cnt % 100000 == 0:
                print("word-vectors loaded: %d" % cnt)

    embedding, vocab_size, embed_dim = embd, len(embd), len(embd[0])

    load_end_time = time.time()
    print("word vectors loaded from and start initialising, cnt: %d, time taken: %d secs " % (vocab_size, load_end_time - start_time))

    embedding_init = tf.constant_initializer(embedding, dtype=tf.float16)
    src_word_embedding = tf.get_variable(shape=[vocab_size, embed_dim], initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

    print("word-vectors loaded and initialised, cnt: %d, time taken: %d secs" % (vocab_size, time.time() - load_end_time))

    return src_word_embedding

And the output of this when running this method is like :

word vectors loaded from and start initialising, cnt: 2419080, time taken: 74 secs
word-vectors loaded and initialised, cnt: 2419080, time taken: 1647 secs

system info: tensorflow 1.1.0, tcmalloc, python 3.6, ubuntu 14.04

HALF an hour to initialize seems to be very slow or is it a normal behavior ? Any idea what could be the issue or is there one ?

UPDATE: using @sirfz method of supplying the embeddings made it really fast to load the embeddings Initialization Done in 85 secs

Body:
I do not know whether this is an intended behavior, but I can explain why is it can slow on a small example:

import tensorflow as tf

x = [[0, 1], [2, 3]]
a = tf.constant(x, name='a')
b = tf.Variable(x, name='b')
c = a + b

with tf.Session() as sess:
    writer = tf.summary.FileWriter('logs', sess.graph)
    writer.close()

When you initialize the constant, the value of this constant is added to the graph. If you will open the graph you can see it by clicking on the a value.

In my case it was a 2x2 matrix, but it looks like in your case it is 2M x ? matrix, which is huge. So in my opinion this is the reason for such a slow execution.

Try to initialize this as a variable and feed you embedding there.


问:
error 'makeHalloRichTextEditable is not defined' with Django form in Wagtail 1.10.1
I'm running Wagtail 1.10.1 on Django 1.11.1 and Python 3.5.2.
I have a Django form for people to submit pages to the website without being users.

I added the next paragraph to add some more information.

The basic idea is that someone who isn't logged in can submit an entry via a form. This is the web page that shows the error message. The admin view of the information once it's been submitted shows no such errors. All the script files are appropriately loaded.

The error message on my dev machine (localhost) for the form (not the admin page) is

Uncaught ReferenceError: makeHalloRichTextEditable is not defined
    at localhost/:136

The relevant part of the form HTML looks like

```<code><label for="id_body">Content of the item.</label>
<textarea name="body" cols="40" id="id_body" rows="10">
</textarea><script>makeHalloRichTextEditable("id_body");</script>
</code>```

In the template that section looks like

```<code>{{ form.body.label_tag }}
{{ form.body }}
{{ form.body.errors }}
</code>```

The relevant bit of the models.py file is

```<code>class NewsPage(Page):
    body = RichTextField(blank=True)
    submitted_by = models.CharField(max_length=255)
    submitter_email = models.EmailField()
</code>```

答: The Javascript code for Wagtail's rich text field is pulled in using Django's form media mechanism. If you're re-using the rich text widget outside of the Wagtail admin, you'll need to ensure that the field's Javascript is output on your page, by adding a tag such as {{ form.media.js }} in the page header (where form is the template variable corresponding to your form object).

Body:
I'm running Wagtail 1.10.1 on Django 1.11.1 and Python 3.5.2.
I have a Django form for people to submit pages to the website without being users.

I added the next paragraph to add some more information.

The basic idea is that someone who isn't logged in can submit an entry via a form. This is the web page that shows the error message. The admin view of the information once it's been submitted shows no such errors. All the script files are appropriately loaded.

The error message on my dev machine (localhost) for the form (not the admin page) is

Uncaught ReferenceError: makeHalloRichTextEditable is not defined
    at localhost/:136

The relevant part of the form HTML looks like

Content of the item.
<textarea name="body" cols="40" id="id_body" rows="10">
</textarea>

In the template that section looks like

{{ form.body.label_tag }}
{{ form.body }}
{{ form.body.errors }}

The relevant bit of the models.py file is

class NewsPage(Page):
    body = RichTextField(blank=True)
    submitted_by = models.CharField(max_length=255)
    submitter_email = models.EmailField()


问:
There's a way to filter changes commit on Jenkins?
I'd like to know if exists some way (Jenkins plug-in) to filter commits that you doesn't want to see, for example exclude someone who belongs to other team.

Thank you very much,

Regards

答:
Assuming you are using polling to determine if Jenkins should run a build

It's possible to do this using the git-plugin.

Under Source Code Management > Additional Behaviours you will have options for:

Polling ignores commits from certain users

Polling ignores commits in certain paths

Polling ignores commits with certain messages

EDIT

For subversion, the Subversion Plugin might have what you want.

Under Source Code Management > Advanced you can find the following options:

Excluded Regions

Included Regions

Excluded Users

Excluded Commit Messages