问:
Regex New RegExp - Replace all text instead of [game_name]
I need some help and hope someone can help me with this issue:

```<code>hturl = "\[game_name\]"
var myregexp = new RegExp(hturl, "ig");
contentreplace = contentreplace.replace(myregexp, '\[game_namexxxx\]');
</code>```

The above regex replace all the text like this

[game_namexxxx]ll you h[game_namexxxx]v[game_namexxxx] to bri[game_namexxxx][game_namexxxx] [game_namexxxx]lo[game_namexxxx][game_namexxxx] th[game_namexxxx] [game_namexxxx]o[game_namexxxx][game_namexxxx][game_namexxxx]t you pl[game_namexxxx]y [[game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx

instead of replacing only [game_name] with [game_namexxxx]

Thanks

答:
Use \\[ instead of \[.

\[ in a string literal escapes [, so the string literal will actually yield the string [.

Body:
I need some help and hope someone can help me with this issue:

hturl = "\[game_name\]"
var myregexp = new RegExp(hturl, "ig");
contentreplace = contentreplace.replace(myregexp, '\[game_namexxxx\]');

The above regex replace all the text like this

[game_namexxxx]ll you h[game_namexxxx]v[game_namexxxx] to bri[game_namexxxx][game_namexxxx] [game_namexxxx]lo[game_namexxxx][game_namexxxx] th[game_namexxxx] [game_namexxxx]o[game_namexxxx][game_namexxxx][game_namexxxx]t you pl[game_namexxxx]y [[game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx][game_namexxxx

instead of replacing only [game_name] with [game_namexxxx]

Thanks


来源: stackexchange

问:
Does useBean id create an instance of the bean class that it is refering to?
This is a main.JSP jsp

```<code><html>
<body>``
      <center>
         *<h2>Using JavaBeans in JSP</h2>
         <jsp:useBean id = "test" class = "servletexample1.TestBean" />*
         <jsp:setProperty name = "test"  property = "message"
            value = "Hello JSP..." />

         <p>Got message....</p>
         <jsp:getProperty name = "test" property = "message" />
      </center>
   </body>
</html>
</code>```

This is a TestBean Class

```<code>package servletexample1;

/* File: TestBean.java */
   public class TestBean {
       private String message = "No message specified";

       public String getMessage() {
          return(message);
       }
       public void setMessage(String message) {
          this.message = message;
       }
      public static void main(String[] args)
      {
          TestBean test = new TestBean();
      }
    }
</code>```

what exactly is test in main.jsp? Is it the instance of the TestBean() class?what exactly does this statement <jsp:useBean id = "test" do?

答:
Yes, useBean does create an instance. Mind that jsp functions are just syntax sugar to regular java. Everything still works as it would in regular java; you just use a different syntax.

Also, id is used to identity that bean within its scope. Example:

```<code><jsp:useBean id="foo" class="fooClass" />

<%
    foo.PrintSomething()
%>
</code>```

So yes, foo is an instance of fooClass.

ContentLicense: CC BY-SA 3.0

Body:
This is a main.JSP jsp

``

         *
Using JavaBeans in JSP

         <jsp:useBean id = "test" class = "servletexample1.TestBean" />*
         <jsp:setProperty name = "test"  property = "message"
            value = "Hello JSP..." />

Got message....

         <jsp:getProperty name = "test" property = "message" />

This is a TestBean Class

package servletexample1;

/* File: TestBean.java */
   public class TestBean {
       private String message = "No message specified";

       public String getMessage() {
          return(message);
       }
       public void setMessage(String message) {
          this.message = message;
       }
      public static void main(String[] args)
      {
          TestBean test = new TestBean();
      }
    }

what exactly is test in main.jsp? Is it the instance of the TestBean() class?what exactly does this statement <jsp:useBean id = "test" do?

Body:
Yes, useBean does create an instance. Mind that jsp functions are just syntax sugar to regular java. Everything still works as it would in regular java; you just use a different syntax.

Also, id is used to identity that bean within its scope. Example:

<jsp:useBean id="foo" class="fooClass" />

<%
    foo.PrintSomething()
%>

So yes, foo is an instance of fooClass.


问:
forbidden 403 error in 'PUT' request Ajax in django rest framwork
I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

```<code>   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" /><br>
        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>
</code>```

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know  we get this error when csrftoken is missing but I have csrf_token in my form.

```<code>$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

         });
    });
</code>```

I used ModelViewset in views.py

```<code> class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})
</code>```

答:
Thank you all for helping me but I got the solution by debug the dispatch method.Here I found that form data is missing that means there is invalid formdata in request.
There is no issue of csrf_token but issue in parameters which sent to ajax request.

In ajax currently i used -

```<code>    form = $(this).closest("form")[0],
    formData = new FormData(form);
</code>```

and send this formData in request( still now  i Don't know why it is not working here while i always used this thing in django).I just replace the above code with following code.

```<code>   form = $(this).closest("form"),
   formData  = form.serialize()
</code>```

Body:
I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" />

        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know  we get this error when csrftoken is missing but I have csrf_token in my form.

$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

         });
    });

I used ModelViewset in views.py

 class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})

Body:
Thank you all for helping me but I got the solution by debug the dispatch method.Here I found that form data is missing that means there is invalid formdata in request.
There is no issue of csrf_token but issue in parameters which sent to ajax request.

In ajax currently i used -

    form = $(this).closest("form")[0],
    formData = new FormData(form);

and send this formData in request( still now  i Don't know why it is not working here while i always used this thing in django).I just replace the above code with following code.

   form = $(this).closest("form"),
   formData  = form.serialize()


问:
bootstrap nav-bar-right floating left
I tried to look out for an answer for my problem but I can't seem to find one. If by any chance there actually is a solution out there, then, I'm sorry, my bad!

I seem to be encountering a problem with Bootstrap's default nav bar: The dropdown menu: .navbar-right is floating left for some reason. You can check it out here.
I'm working on rails 5 and the code for my nav currently looks like:

```<code>    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <%= link_to "Prodemex", root_path, class: "navbar-brand", id: "logo" %>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><%= link_to "Articulos", articles_path %></li>
        <li><%= link_to "Usuarios", users_path %></li>
        <% if logged_in? %>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Actions <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><%= link_to "Nuevo articulo", new_article_path %></li>
              <li role="separator" class="divider"></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
        </ul>
      <% end %>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <% if logged_in? %>
        <ul class="nav navbar-nav navbar-right">
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Mi cuenta<%= " - Admin " if current_user.admin? %><span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><%= link_to "Modificar mis datos", edit_user_path(current_user) %></li>
                <li><%= link_to "Ver mi perfil", user_path(current_user) %></li>
                <li><a href="#">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><%= link_to 'Cerrar sesión', logout_path, method: :delete %></li>
              </ul>
            </li>
        </ul>
        <% else %>
        <ul class="navbar-right nav navbar-nav">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Mi cuenta <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><%= link_to 'Iniciar sesión', login_path %></li>
              <li><%= link_to 'Registrarse', signup_path %></li>
            </ul>
          </li>
        </ul>
        <% end %>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
</code>```

You can retrieve more of the code on github
I have a custom CSS with all that and already tried to delete all portions related with navbar but it did nothing...

```<code>$navbar-default-bg: #3498DB;

@import "bootstrap-sprockets";
@import "bootstrap";

.gen {
  padding: 0 2%;
}

.col-xs-8 {
  float: none;
}

a {
  text-decoration: none;
}

body {
  font-weight: 200;
}

#logo {
  float: left;
  font-size: 1.7em;
  color: #fff;
  text-transform: uppercase;
  font-weight: 200;
}

#logo:hover {
  text-decoration: none;
  color: #5e82a6;
}

.navbar {
  border-radius: 0;
  margin: 0;
}

.center {
  text-align: center;
}

#home {
  background: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), image-url('cover_page.jpg');
  background-size: cover;
  background-attachment: fixed;
  height: 100vh;
}

.jumbotron {
  padding: 15.5% 20%;
  background-color: transparent;

  }

.jumbotron h1,h3 {
  color: #fff;
  font-weight: 200;
  margin-bottom: 10px;
}

.btn-xlg {
  font-size: 1.2em;
  font-weight: 200;
  background-color: #3498DB;
  border: 1px solid #3498DB;
  margin: 0;
  display: inline-block;
  letter-spacing: 1px;
}

.btn-xlge {
  font-size: 1.2em;
  font-weight: 200;
  color: #000;
  background-color: none;
  border: 1px solid #000;
  margin-left: 10px;
  display: inline-block;
}

.btn-xlge:hover,
          active {
  background-color: #337ab7;
  color: #fff;
  border: 1px solid #337ab7;
}

.footer {
  background-color: #3498DB;
  color: #fff;
  letter-spacing: 1px;
  padding: 10px;
}

footer ul {
  list-style:none;
  margin-top: 10px;
}

.footer a {
  color: #fff;
}

.footer a:hover,
.footer a:active {
  color: #ccc;
  text-decoration: none;
}

.article-actions {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  margin-top: 10px;
}

.descrition {
  margin-top: 0;
}

.article-title {
  font-size: 1.5em;
}

.article-title a {
  text-decoration: none;
}

.article-body {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  padding-bottom: 15px;
}

.article-meta-details {
  margin-top: 5px;
  margin-bottom: 0;
  font-size: 1em;
}

.article-meta-details a {
  text-decoration:none;
}

.well-lg {
  padding-bottom: 10px;
}

.listing {
  list-style: none;
  padding-left: 0;
}

.insideuser {
  padding-left: 50px;
  float: left;
}

.author {
  font-weight: 400;
  color: #3498DB;
}

.authorpage {
  margin-top: 10px;
  padding: 10px 0;
}

.pop {
  margin-top: 15px;
  -webkit-box-shadow: 4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  -moz-box-shadow:    4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  box-shadow:         4px 1px 10px 0px rgba(50, 50, 50, 0.27);
}
</code>```

And the weird thing is that when I log in, the dropdown goes back to the right where it is supposed to be...
When inspecting the code, I almost found a fix, deleting the left float to this portion:

```<code>@media (min-width: 768px)
custom.self-839…ss?body=1:5864
.navbar-nav {
    float: left;
    margin: 0;
}
</code>```

But obviously when I do that it messes up with the rest of the navbar.
Any body can help me? Thanks in advance!!

答:
try to use the bootstrap grid system it will make it easy for you to position your menu items :

*Bootstrap column syntax -- > class="col-[screen size]-[number of columns]"

screen sizes ---> xs (extra small) , sm (small) , md (medium) , lg (large)

number of columns ---> goes up to 12

*Move columns to the right using class="col-md-offset-[number of columns]" .

These classes increase the left margin of a column by a set number of columns.

For example, class="col-md-offset-4" moves a column over four columns.

*Easily change the order of our built-in grid columns with :

class ="col-md-push-[number of columns]" and class ="col-md-pull-[number of columns]"

Bootstrap Grid System

This video is showing the basic concept - This guy has a whole searies of videos ...

Edited: This is how I solved the problem of a dropdown button that was joined with the rest of the buttons ...

```<code><ul class="nav nav-pills col-lg-offset-11 col-md-offset-11 col-sm-offset-11">
 <li id="btnDrpDwn" role="presentation" class="dropdown"><a data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" class="dropdown-toggle">menu<span class="caret"></span></a>
  <ul class="dropdown-menu">
    <li role="presentation"><a href="/profile">Item 1</a></li>
    <li role="presentation"><a href="#">Item 2</a></li>
    <li role="separator" class="divider"></li>
    <li role="presentation"><a href="/logout">Item 3</a></li>
  </ul>
 </li></ul>
</code>```

Title: bootstrap nav-bar-right floating left

Body:
I tried to look out for an answer for my problem but I can't seem to find one. If by any chance there actually is a solution out there, then, I'm sorry, my bad!

I seem to be encountering a problem with Bootstrap's default nav bar: The dropdown menu: .navbar-right is floating left for some reason. You can check it out here.
I'm working on rails 5 and the code for my nav currently looks like:

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      <%= link_to "Prodemex", root_path, class: "navbar-brand", id: "logo" %>

<%= link_to "Articulos", articles_path %>

<%= link_to "Usuarios", users_path %>

        <% if logged_in? %>

            Actions

<%= link_to "Nuevo articulo", new_article_path %>

One more separated link

      <% end %>
      <form class="navbar-form navbar-left">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <% if logged_in? %>

              Mi cuenta<%= " - Admin " if current_user.admin? %>

<%= link_to "Modificar mis datos", edit_user_path(current_user) %>

<%= link_to "Ver mi perfil", user_path(current_user) %>

Something else here

<%= link_to 'Cerrar sesión', logout_path, method: :delete %>

        <% else %>

            Mi cuenta

<%= link_to 'Iniciar sesión', login_path %>

<%= link_to 'Registrarse', signup_path %>

        <% end %>

You can retrieve more of the code on github
I have a custom CSS with all that and already tried to delete all portions related with navbar but it did nothing...

$navbar-default-bg: #3498DB;

@import "bootstrap-sprockets";
@import "bootstrap";

.gen {
  padding: 0 2%;
}

.col-xs-8 {
  float: none;
}

a {
  text-decoration: none;
}

body {
  font-weight: 200;
}

#logo {
  float: left;
  font-size: 1.7em;
  color: #fff;
  text-transform: uppercase;
  font-weight: 200;
}

#logo:hover {
  text-decoration: none;
  color: #5e82a6;
}

.navbar {
  border-radius: 0;
  margin: 0;
}

.center {
  text-align: center;
}

#home {
  background: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), image-url('cover_page.jpg');
  background-size: cover;
  background-attachment: fixed;
  height: 100vh;
}

.jumbotron {
  padding: 15.5% 20%;
  background-color: transparent;

  }

.jumbotron h1,h3 {
  color: #fff;
  font-weight: 200;
  margin-bottom: 10px;
}

.btn-xlg {
  font-size: 1.2em;
  font-weight: 200;
  background-color: #3498DB;
  border: 1px solid #3498DB;
  margin: 0;
  display: inline-block;
  letter-spacing: 1px;
}

.btn-xlge {
  font-size: 1.2em;
  font-weight: 200;
  color: #000;
  background-color: none;
  border: 1px solid #000;
  margin-left: 10px;
  display: inline-block;
}

.btn-xlge:hover,
          active {
  background-color: #337ab7;
  color: #fff;
  border: 1px solid #337ab7;
}

.footer {
  background-color: #3498DB;
  color: #fff;
  letter-spacing: 1px;
  padding: 10px;
}

footer ul {
  list-style:none;
  margin-top: 10px;
}

.footer a {
  color: #fff;
}

.footer a:hover,
.footer a:active {
  color: #ccc;
  text-decoration: none;
}

.article-actions {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  margin-top: 10px;
}

.descrition {
  margin-top: 0;
}

.article-title {
  font-size: 1.5em;
}

.article-title a {
  text-decoration: none;
}

.article-body {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  padding-bottom: 15px;
}

.article-meta-details {
  margin-top: 5px;
  margin-bottom: 0;
  font-size: 1em;
}

.article-meta-details a {
  text-decoration:none;
}

.well-lg {
  padding-bottom: 10px;
}

.listing {
  list-style: none;
  padding-left: 0;
}

.insideuser {
  padding-left: 50px;
  float: left;
}

.author {
  font-weight: 400;
  color: #3498DB;
}

.authorpage {
  margin-top: 10px;
  padding: 10px 0;
}

.pop {
  margin-top: 15px;
  -webkit-box-shadow: 4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  -moz-box-shadow:    4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  box-shadow:         4px 1px 10px 0px rgba(50, 50, 50, 0.27);
}

And the weird thing is that when I log in, the dropdown goes back to the right where it is supposed to be...
When inspecting the code, I almost found a fix, deleting the left float to this portion:

@media (min-width: 768px)
custom.self-839…ss?body=1:5864
.navbar-nav {
    float: left;
    margin: 0;
}

But obviously when I do that it messes up with the rest of the navbar.
Any body can help me? Thanks in advance!!

Body:
try to use the bootstrap grid system it will make it easy for you to position your menu items :

*Bootstrap column syntax -- > class="col-[screen size]-[number of columns]"

screen sizes ---> xs (extra small) , sm (small) , md (medium) , lg (large)

number of columns ---> goes up to 12

*Move columns to the right using class="col-md-offset-[number of columns]" .

These classes increase the left margin of a column by a set number of columns.

For example, class="col-md-offset-4" moves a column over four columns.

*Easily change the order of our built-in grid columns with :

class ="col-md-push-[number of columns]" and class ="col-md-pull-[number of columns]"

Bootstrap Grid System

This video is showing the basic concept - This guy has a whole searies of videos ...

Edited: This is how I solved the problem of a dropdown button that was joined with the rest of the buttons ...

<ul class="nav nav-pills col-lg-offset-11 col-md-offset-11 col-sm-offset-11">
 <li id="btnDrpDwn" role="presentation" class="dropdown"><a data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" class="dropdown-toggle">menu<span class="caret"></span></a>
  <ul class="dropdown-menu">
    <li role="presentation"><a href="/profile">Item 1</a></li>
    <li role="presentation"><a href="#">Item 2</a></li>
    <li role="separator" class="divider"></li>
    <li role="presentation"><a href="/logout">Item 3</a></li>
  </ul>
 </li></ul>


问:
How to dismiss UIAlertController when tap outside the UIAlertController?
How to dismiss UIAlertController when tap outside the UIAlertController?

I can add a UIAlertAction of style UIAlertActionStyleCancel to dismiss the UIAlertController.

But I want to add the function that when user tap outside the UIAlertController the UIAlertController will dismiss. How to do that? Thank you.

答:
The easiest way in Obj-C:

```<code>UIAlertController *alert = [UIAlertController alertControllerWithTitle: ...
[self presentViewController:alert animated:YES completion:^{
                                       [alert.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alertControllerBackgroundTapped)]];
                                   }];
</code>```

and then:

```<code>- (void)alertControllerBackgroundTapped
{
    [self dismissViewControllerAnimated: YES
                             completion: nil];
}
</code>```

Body:
The easiest way in Obj-C:

UIAlertController *alert = [UIAlertController alertControllerWithTitle: ...
[self presentViewController:alert animated:YES completion:^{
                                       [alert.view.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alertControllerBackgroundTapped)]];
                                   }];

and then:

- (void)alertControllerBackgroundTapped
{
    [self dismissViewControllerAnimated: YES
                             completion: nil];
}


问:
How do I set the data location of a bigquery table over the API?
I'm trying to create tables programmatically, but I can't figure out how I set the data location, that is, where the data is stored. In the UI I can choose between "US" and "EU", but according to the docs here: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#resource the location field is output only.

I'm using node for doing it, but that shouldn't matter. The method I'm using is here: https://googlecloudplatform.github.io/google-cloud-node/#/docs/bigquery/0.9.2/bigquery/dataset?method=createTable

答:
Location is set on Dataset Level, not table

So you should rather look into https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets#resource


问:
ng2-dnd wrong item getting dragged and dropped(multi sortable) after applying filter
I'm using angular 2 to implement multi-sortable d&d with the following package
https://www.npmjs.com/package/ng2-dnd.

I'm able to drag and drop items from one container to other and vice versa.
However, when i filter and item and then try to drag wrong item is getting dragged and dropped into the other container(the one which generally applies that index and not the one which actually is there). This could be may be because the code uses sortableIndex

Here's the code:

```<code><div>
 <h4>Groups</h4>
    <div class="row">
      <div class="col-sm-5">
        <div class="panel panel-warning">
          <div class="panel-heading">
            Available Groups
          </div>
          <div>
              <input type="text" class="form-control" name="" placeholder="search" [(ngModel)]="name"/>
          </div>
          <div class="panel-body" dnd-sortable-container [dropZones]="['boxers-zone']" [sortableData]="listBoxers">
            <ul class="list-group" >
              <li *ngFor="let item of listBoxers | DataFilterPipe: name; let i = index" class="list-group-item" dnd-sortable [sortableIndex]="i">{{item.name}}</li>
            </ul>
          </div>
        </div>
      </div>
      <div class="col-sm-5">
        <div class="panel panel-success">
          <div class="panel-heading">
            Selected Groups
          </div>
          <div class="panel-body" dnd-sortable-container [dropZones]="['boxers-zone']" [sortableData]="listTeamOne">
            <ul class="list-group" >
              <li *ngFor="let item of listTeamOne; let i = index" class="list-group-item" dnd-sortable [sortableIndex]="i">{{item.name}}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

</div>

listBoxers:Array<object> = [];
listTeamOne:Array<object> = [];

this.listBoxers= [{id:"1",name:"ABC"}, {id:"2", name:"erwxyz"},{id:"2", name:"sdaxyz"},{id:"3", name:"sdxyz"},{id:"4", name:"xyz"}]
</code>```

Here's the screenshots:

As you can see in the second screenshot, even after filtering 'xyz', I tried to grad this item. Howver, wrong item got dragged and dropped(the one present at that index)

答: I used (ngModelChange) instead of filter pipe (DataFilterPipe). Then wrote a custom fuction for (ngModelChange). That worked.

Body:
I'm using angular 2 to implement multi-sortable d&d with the following package
https://www.npmjs.com/package/ng2-dnd.

I'm able to drag and drop items from one container to other and vice versa.
However, when i filter and item and then try to drag wrong item is getting dragged and dropped into the other container(the one which generally applies that index and not the one which actually is there). This could be may be because the code uses sortableIndex

Here's the code:

Groups

            Available Groups

              <input type="text" class="form-control" name="" placeholder="search" [(ngModel)]="name"/>

{{item.name}}

            Selected Groups

{{item.name}}

listBoxers:Array<object> = [];
listTeamOne:Array<object> = [];

this.listBoxers= [{id:"1",name:"ABC"}, {id:"2", name:"erwxyz"},{id:"2", name:"sdaxyz"},{id:"3", name:"sdxyz"},{id:"4", name:"xyz"}]

Here's the screenshots:

As you can see in the second screenshot, even after filtering 'xyz', I tried to grad this item. Howver, wrong item got dragged and dropped(the one present at that index)


问:
How do you specify variables to be final in C?
I am aware that it is possible to declare constants using the #define macro. With this, it would be simple to define integer, floating point or character literals to be constants.

But, for more complicated data structures, such as an array, or a struct, say for example:

```<code>typedef struct {
    int name;
    char* phone_number;
} person;
</code>```

I want to be able to initialise this just once and then make it a non-editable struct.

In object oriented languages, there exists the final keyword to do this easily, but there is no such thing in C. One workaround I've thought of is to use setjmp and longjmp to simulate try-catch braces and do a rollback if a change is detected. You'd need to store a backup in a file/in memory object, which can get  little messy if you have many such objects you want to protect from accidental alteration.

Q: Is it possible to effectively represent such a pattern in C? If yes, how can it be done?

答:
const is the way to go. const is a keyword that might tell the compiler two things:

Enforce the constantness of an object.

```<code>const YourType t;
</code>```

Declares a non-modifiable object. The compiler will force the const-correctness. It is important to note that the const-correctness is enforced conceptually by the compiler and there are ways to elude those rules.

constantness of pointer (or to an access to an object)

```<code>const int* pointer
</code>```

Declares a const pointer to an int (which is not const). It means that if there is a non-const pointer to that int then it can be modified.

For more info see this great answer.

Body:
I am aware that it is possible to declare constants using the #define macro. With this, it would be simple to define integer, floating point or character literals to be constants.

But, for more complicated data structures, such as an array, or a struct, say for example:

typedef struct {
    int name;
    char* phone_number;
} person;

I want to be able to initialise this just once and then make it a non-editable struct.

In object oriented languages, there exists the final keyword to do this easily, but there is no such thing in C. One workaround I've thought of is to use setjmp and longjmp to simulate try-catch braces and do a rollback if a change is detected. You'd need to store a backup in a file/in memory object, which can get  little messy if you have many such objects you want to protect from accidental alteration.

Q: Is it possible to effectively represent such a pattern in C? If yes, how can it be done?

Body:
const is the way to go. const is a keyword that might tell the compiler two things:

Enforce the constantness of an object.

const YourType t;

Declares a non-modifiable object. The compiler will force the const-correctness. It is important to note that the const-correctness is enforced conceptually by the compiler and there are ways to elude those rules.

constantness of pointer (or to an access to an object)

const int* pointer

Declares a const pointer to an int (which is not const). It means that if there is a non-const pointer to that int then it can be modified.

For more info see this great answer.


问:
How to get nearest key index in associative JavaScript array if key does not exist?
So, this might be a weird thing to try to do, but I'm curious if it's possible:

Say I have an associative array like this:

```<code>myarray[50] = 'test1'
myarray[100] = 'test2'
</code>```

I can access 'test1' by it's key, of course:

```<code>myarray[50]; // returns 'test1'
</code>```

But is there a way where if I have an index key of '60', that I can look in the array and if key 60 isn't there, get the value of the next "closest" key, '50'?

The use-case for this is that I am trying to set up cue-points for a video, and if the user seeks and misses a cue point, I want to display the information from the last cue point the user seeked beyond.

I think I can check for the existence of the key with the 'in' operator. But if it's not found, how can I get the "previous" or "next smallest" array key that DOES exist?

I assume the only way to do this is to iterate through the array, saving the "last" index value until the exit condition of "index > myKey" is found. The thing is, if it's a long video with lots of queue points and the user seeks frequently, iterating through the entire array of cue points each time might be slow. Is there a better, faster way to do this?

答:
You'd have to write your own function:

```<code>function getClosestTo(val, array) {
    if (array[val] !== undefined) {
        return val;
    } else {
        var upper = val;
        var upperMatched = false;
        var lower = val;
        var lowerMatched = false;

        while(upper < this.length) {
            if (array[++upper] !== undefined) {
                upperMatched = true;
                break;
            };
        };

        while(lower > -1) {
            if (array[--lower] !== undefined) {
                lowerMatched = true;
                break;
            };
        };

        if (upperMatched && lowerMatched) {
            return upper - val < val - lower ? upper : lower;
        } else if (upperMatched) {
            return upper;
        } else if (lowerMatched) {
            return lower;
        };
    };

    return -1;
};
</code>```

You could also add this as a method of the Array prototype, to make (what I think) is more readable:

```<code>Array.prototype.getClosestTo = function (val) {
    if (this[val] !== undefined) {
        return val;
    } else {
        var upper = val;
        var upperMatched = false;
        var lower = val;
        var lowerMatched = false;

        while(upper < this.length) {
            if (this[++upper] !== undefined) {
                upperMatched = true;
                break;
            };
        };

        while(lower > -1) {
            if (this[--upper] !== undefined) {
                lowerMatched = true;
                break;
            };
        };

        if (upperMatched && lowerMatched) {
            return upper - val < val - lower ? upper : lower;
        } else if (upperMatched) {
            return upper;
        } else if (lowerMatched) {
            return lower;
        };
    };

    return -1;
};

// Usage:
// var closestKey = theArray.getClosestTo(50);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So, this might be a weird thing to try to do, but I'm curious if it's possible:

Say I have an associative array like this:

myarray[50] = 'test1'
myarray[100] = 'test2'

I can access 'test1' by it's key, of course:

myarray[50]; // returns 'test1'

But is there a way where if I have an index key of '60', that I can look in the array and if key 60 isn't there, get the value of the next "closest" key, '50'?

The use-case for this is that I am trying to set up cue-points for a video, and if the user seeks and misses a cue point, I want to display the information from the last cue point the user seeked beyond.

I think I can check for the existence of the key with the 'in' operator. But if it's not found, how can I get the "previous" or "next smallest" array key that DOES exist?

I assume the only way to do this is to iterate through the array, saving the "last" index value until the exit condition of "index > myKey" is found. The thing is, if it's a long video with lots of queue points and the user seeks frequently, iterating through the entire array of cue points each time might be slow. Is there a better, faster way to do this?

Body:
You'd have to write your own function:

function getClosestTo(val, array) {
    if (array[val] !== undefined) {
        return val;
    } else {
        var upper = val;
        var upperMatched = false;
        var lower = val;
        var lowerMatched = false;

        while(upper < this.length) {
            if (array[++upper] !== undefined) {
                upperMatched = true;
                break;
            };
        };

        while(lower > -1) {
            if (array[--lower] !== undefined) {
                lowerMatched = true;
                break;
            };
        };

        if (upperMatched && lowerMatched) {
            return upper - val < val - lower ? upper : lower;
        } else if (upperMatched) {
            return upper;
        } else if (lowerMatched) {
            return lower;
        };
    };

    return -1;
};

You could also add this as a method of the Array prototype, to make (what I think) is more readable:

Array.prototype.getClosestTo = function (val) {
    if (this[val] !== undefined) {
        return val;
    } else {
        var upper = val;
        var upperMatched = false;
        var lower = val;
        var lowerMatched = false;

        while(upper < this.length) {
            if (this[++upper] !== undefined) {
                upperMatched = true;
                break;
            };
        };

        while(lower > -1) {
            if (this[--upper] !== undefined) {
                lowerMatched = true;
                break;
            };
        };

        if (upperMatched && lowerMatched) {
            return upper - val < val - lower ? upper : lower;
        } else if (upperMatched) {
            return upper;
        } else if (lowerMatched) {
            return lower;
        };
    };

    return -1;
};

// Usage:
// var closestKey = theArray.getClosestTo(50);


问:
Java 8 pass a clickListener as parameter using lambda
i want to create a method, which create a button in vaadin with parameter.

```<code>private void addButton(Button button, String toolTip, FontAwesome fontAwesome, ... clickEvent){
        button = new Button(fontAwesome);
        button.setDescription(toolTip);
        button.setEnabled(false);
        button.addClickListener(event -> clickEvent);
    }
</code>```

by call:

```<code>addButton(newButton, "My test Button", FontAwesome.PLUS_SQUARE, someObject.do())
</code>```

how can i set the clickListener as parameter with lambda?

答:
```<code>private void addButton(Button button, String toolTip, FontAwesome fontAwesome, Button.ClickListener clickEvent){
    button = new Button(fontAwesome);
    button.setDescription(toolTip);
    button.setEnabled(false);
    button.addClickListener(clickEvent);
}
</code>```

You'll then call your method like this addButton(newButton, "Test", o, evt -> someMethod());

[EDIT] : while I think it answers your question please note that the new Button won't be accessible from the method caller which is likely a bug in your code, you should consider returning the button instead

Body:
i want to create a method, which create a button in vaadin with parameter.

private void addButton(Button button, String toolTip, FontAwesome fontAwesome, ... clickEvent){
        button = new Button(fontAwesome);
        button.setDescription(toolTip);
        button.setEnabled(false);
        button.addClickListener(event -> clickEvent);
    }

by call:

addButton(newButton, "My test Button", FontAwesome.PLUS_SQUARE, someObject.do())

how can i set the clickListener as parameter with lambda?

Body:
private void addButton(Button button, String toolTip, FontAwesome fontAwesome, Button.ClickListener clickEvent){
    button = new Button(fontAwesome);
    button.setDescription(toolTip);
    button.setEnabled(false);
    button.addClickListener(clickEvent);
}

You'll then call your method like this addButton(newButton, "Test", o, evt -> someMethod());

[EDIT] : while I think it answers your question please note that the new Button won't be accessible from the method caller which is likely a bug in your code, you should consider returning the button instead


问:
is there any way to get the sum of the product of euler's number and an integer, where the integer can range upto 10^6000?
So I tried using BigDecimal which is giving me the value of Euler's number up to 50 decimal points. But since the constraint value is this high the number can range from 1 to 10^6000, and hence I am not getting any precision(making it optimal is another issue). Here is the block of code:</p>

```<code>for(int i=1; i<n+1; i++){
 // i is the integer value and bd is the value of the euler's number, so below i am multiplying the value of i with the euler's number
 BigDecimal x = BigDecimal.valueOf(i).multiply(bd);
 //Here i am taking floor of the above calculated value
 x.setScale(0, RoundingMode.HALF_UP);
 //and here sum is floor[1*euler's no] + floor[2*euler's number] + ... + floor[n*euler's number]
 sum += x.intValue();
}
</code>```

答:
I think you are asking how to compute Euler's number (i.e. e) to greater precision.

The answer would be to implement an algorithm that converges rapidly.  With a little bit of research, I found this page on "Calculating the Value of e".  At the bottom, it describes Brothers Formula:

```<code>e = Sum(n=0, n=∞, (2n+2) / (2n+1)! )
</code>```

which converges very rapidly.  You could code that in Java using BigDecimal to calculate to any number of digits precision that you need.

See also:

Brothers, H.J. 2004. Improving the convergence of Newton's series approximation for e. College Mathematics Journal 35(January):34-39.

which (if I understood it correctly!) gives a more complicated formula that converges even more rapidly.

Body:
So I tried using BigDecimal which is giving me the value of Euler's number up to 50 decimal points. But since the constraint value is this high the number can range from 1 to 10^6000, and hence I am not getting any precision(making it optimal is another issue). Here is the block of code:

for(int i=1; i<n+1; i++){
 // i is the integer value and bd is the value of the euler's number, so below i am multiplying the value of i with the euler's number
 BigDecimal x = BigDecimal.valueOf(i).multiply(bd);
 //Here i am taking floor of the above calculated value
 x.setScale(0, RoundingMode.HALF_UP);
 //and here sum is floor[1*euler's no] + floor[2*euler's number] + ... + floor[n*euler's number]
 sum += x.intValue();
}

Body:
I think you are asking how to compute Euler's number (i.e. e) to greater precision.

The answer would be to implement an algorithm that converges rapidly.  With a little bit of research, I found this page on "Calculating the Value of e".  At the bottom, it describes Brothers Formula:

e = Sum(n=0, n=∞, (2n+2) / (2n+1)! )

which converges very rapidly.  You could code that in Java using BigDecimal to calculate to any number of digits precision that you need.

See also:

Brothers, H.J. 2004. Improving the convergence of Newton's series approximation for e. College Mathematics Journal 35(January):34-39.

which (if I understood it correctly!) gives a more complicated formula that converges even more rapidly.


问:
k means clustering on matrix
I am trying to cluster a Multidimensional Functional Object with the "kmeans" algorithms. What does it mean: So I don't have anymore a vector per each row or Individual, even more a 3x3 observation matrix per each Individual.For example: Individual = 1 has the following observations:

(x1, x2, x3),(y1,y2,y3),(z1,z2,z3).

The same structure of observations is also given for the other Individuals. So do you know how I can cluster with "kmeans" including all 3 observation vectors -and not only one observation vector how it is normal used for "kmeans" clustering?
Would you do it for each observation vector, f.e. (x1, x2, x3), separately and then combine the Information somehow together? I want to do this with the kmeans() Function in R.

Many thanks for your answers!

答:
Using k-means you interpret each observation as a point in an N-dimensional vector space. Then you minimize the distances between your observations and the cluster centers.

Since, the data is viewed as dots in an N-dim space, the actual arrangement of the values does not matter.

You can, therefore, either tell your k-means routine to use a matrix norm,   for example the Frobenius norm, to compute the distances. The other way would be to flatten your observations from 3 by 3 matrices to 1 by 9 vectors. The Frobenius norm of a NxN matrix is equivalent to the euclidean norm of a 1xN^2 vector.

Title: k means clustering on matrix


问:
SAS-use of lead function
Suppose the dataset has three columns

```<code>Date   Region   Price
01-03    A        1
01-03    A        2
01-03    B        3
01-03    B        4
01-03    A        5
01-04    B        4
01-04    B        6
01-04    B        7
</code>```

I try to get the lead price by date and region through following code.

```<code>data want;
set have;
by _ric date_l_;
do until (eof);
set have(firstobs=2 keep=price rename=(price=lagprice)) end=eof;
end;
if last.date_l_ then call missing(lagprice);
run;
</code>```

However, the WANT only have one observations. Then I create new_date=date and try another code:

```<code>data want;
set have nobs=nobs;
  do _i = _n_ to nobs until (new_date ne Date);
  if eof1=0 then
  set have (firstobs=2 keep=price rename=(price=leadprice)) end=eof1;
  else leadprice=.;
  end;
run;
</code>```

With this code, SAS is working slowly. So I think this code is also not appropriate. Could anyone give some suggestions? Thanks

答:
Try sorting by the variables you want lead price for then set together twice:</p>

```<code>data test;
length Date   Region  $12 Price 8 ;
input Date  $ Region $   Price ;
datalines;
    01-03    A        1
    01-03    A        2
    01-03    B        3
    01-03    B        4
    01-03    A        5
    01-04    B        4
    01-04    B        6
    01-04    B        7
    ;
run;

** sort by vars you want lead price for **;
proc sort data = test;
    by DATE REGION;
run;

** set together twice -- once for lead price and once for all variables **;
data lead_price;
    set test;
    by DATE REGION;
    set test (firstobs = 2 keep = PRICE rename = (PRICE = LEAD_PRICE))
        test (obs = 1 drop = _ALL_);
    if last.DATE or last.REGION then do;
        LEAD_PRICE = .;
    end;
run;
</code>```

Title: SAS-use of lead function

Body:
Suppose the dataset has three columns

Date   Region   Price
01-03    A        1
01-03    A        2
01-03    B        3
01-03    B        4
01-03    A        5
01-04    B        4
01-04    B        6
01-04    B        7

I try to get the lead price by date and region through following code.

data want;
set have;
by _ric date_l_;
do until (eof);
set have(firstobs=2 keep=price rename=(price=lagprice)) end=eof;
end;
if last.date_l_ then call missing(lagprice);
run;

However, the WANT only have one observations. Then I create new_date=date and try another code:

data want;
set have nobs=nobs;
  do _i = _n_ to nobs until (new_date ne Date);
  if eof1=0 then
  set have (firstobs=2 keep=price rename=(price=leadprice)) end=eof1;
  else leadprice=.;
  end;
run;

With this code, SAS is working slowly. So I think this code is also not appropriate. Could anyone give some suggestions? Thanks

Body:
Try sorting by the variables you want lead price for then set together twice:

data test;
length Date   Region  $12 Price 8 ;
input Date  $ Region $   Price ;
datalines;
    01-03    A        1
    01-03    A        2
    01-03    B        3
    01-03    B        4
    01-03    A        5
    01-04    B        4
    01-04    B        6
    01-04    B        7
    ;
run;

** sort by vars you want lead price for **;
proc sort data = test;
    by DATE REGION;
run;

** set together twice -- once for lead price and once for all variables **;
data lead_price;
    set test;
    by DATE REGION;
    set test (firstobs = 2 keep = PRICE rename = (PRICE = LEAD_PRICE))
        test (obs = 1 drop = _ALL_);
    if last.DATE or last.REGION then do;
        LEAD_PRICE = .;
    end;
run;


问:
Pass data between activities Android
I want to know if there is a way to pass a class object, which can't implement serializable interface between 2 android activities.
I know that to pass data using intent you have to implement serializable interface, but unfortunately I can't do this, any idea?

```<code>public class ContactMongo implements Serializable{
private DB collection;
public ContactMongo()
{ }

}
</code>```

DB doesn't implement serializable, so I can't perform intent.putExtra();

答:
You probably want to use a service, but you haven't told us anything about what you're trying to pass, so I guess you want to use ugly hacks.

There is such an ugly hack available, but it'll quickly get out of control (especially if you cannot even search on this topic by yourself) - you can extend your Application class and use its methods to pass data between activities. Generally, it should be avoided and other ways to pass data and let activities communicate should be used (like extracting the data from the object you want to pass).

Hope this helps you, comment if you have any questions (I'll update my answer with better solution if you give more information on what you're trying to do)

Title: Pass data between activities Android

Body:
I want to know if there is a way to pass a class object, which can't implement serializable interface between 2 android activities.
I know that to pass data using intent you have to implement serializable interface, but unfortunately I can't do this, any idea?

public class ContactMongo implements Serializable{
private DB collection;
public ContactMongo()
{ }

}

DB doesn't implement serializable, so I can't perform intent.putExtra();


问:
C#.NET MDI bugs when programmatically hiding and showing again a maximized child form and when maximized, child form's icon cannot be changed
Basically I am having two problems with C#.NET MDI. You can download VS2010 solution which reproduces bugs here.

1) When programmatically hiding and showing again a maximized child form, it is not maximized properly again and becomes neither maximized or in normal state.

```<code>childForm = new Form();
childForm.Text = "Child Form";
childForm.MdiParent = this;

...

private void showButton_Click(object sender, EventArgs e)
{
    childForm.Visible = true;
}

...

private void hideButton_Click(object sender, EventArgs e)
{
    childForm.Visible = false;
}
</code>```

When child form is maximized, then programicaly hidden and shown again, it becomes something like this (please notice the menu bar - child form's control box appears, but child form is not maximized):

At this stage, child form cannot be moved around. However, I found a workaround for that, simply by showing and hiding a dummy child form, which forces the actual child form to become properly maximized. But this makes MDI area to flicker. Tried Invalidate, Refresh, Update methods, but they don't help. Maybe there are other workarounds to overcome this bug and not to make MDI area flicker with dummy child form?

```<code>private void workaround1Button_Click(object sender, EventArgs e)
{
    dummyForm.Visible = true;
    dummyForm.Visible = false;
}
</code>```

2) When child form is maximized, the icon of the child form is displayed on menu bar. However, if you have to change the icon while the child form is maximized, the icon on the menu bar is not being refreshed (see the image above). I found a workaround for that too, which basically hides and shows menu bar. Icon gets refreshed, but it makes everything below menu bar to flicker. Tried Invalidate, Refresh, Update methods, but they don't help. Is there any other way to make menu bar to refresh the child form's icon?

```<code>private void workaround2Button_Click(object sender, EventArgs e)
{
    menuStrip.Visible = false;
    menuStrip.Visible = true;
}
</code>```

Also I noticed that when parent form is in normal window state mode (not maximized) and you change the width or height of the form by 1 pixel, child form becomes maximized as it should be and child form's icon on menu bar gets refreshed properly and you don't need other workaround I described above. If I change the size of the form programicaly, form flickers by 1 pixel and I cannot do that, when parent form is maximized. Is there any way how I could invoke the repaint/refresh functionality which is called when you resize a form and which makes child form become maximized properly and the icon on the menu bar refreshed?

答:
Found a way how to come around those bugs.

First of all you need to suspend painting for a form and its children. I found a very helpful thread here, which describes how to do it.

After suspending painting, you need call UpdateBounds method of the control and increase ClientRectangle Width or Height by one and then decrease it back to the same value it was before. This invokes layout functionality which makes everything to update/repaint. Last step is to enable painting. Not very nice solution I guess, but it works.

```<code>StopDrawing();
UpdateBounds(Location.X, Location.Y, Width, Height, ClientRectangle.Width, ClientRectangle.Height + 1);
UpdateBounds(Location.X, Location.Y, Width, Height, ClientRectangle.Width, ClientRectangle.Height - 1);
StartDrawing();
</code>```

I find suspending painting very helpful not only for working around those two bugs, but also in general to make GUI work more smoothly. I guess this can help to remove any kind of flickering. However, this solution requires P/Invokes, which should be avoided in general.

Body:
Basically I am having two problems with C#.NET MDI. You can download VS2010 solution which reproduces bugs here.

1) When programmatically hiding and showing again a maximized child form, it is not maximized properly again and becomes neither maximized or in normal state.

childForm = new Form();
childForm.Text = "Child Form";
childForm.MdiParent = this;

...

private void showButton_Click(object sender, EventArgs e)
{
    childForm.Visible = true;
}

...

private void hideButton_Click(object sender, EventArgs e)
{
    childForm.Visible = false;
}

When child form is maximized, then programicaly hidden and shown again, it becomes something like this (please notice the menu bar - child form's control box appears, but child form is not maximized):

At this stage, child form cannot be moved around. However, I found a workaround for that, simply by showing and hiding a dummy child form, which forces the actual child form to become properly maximized. But this makes MDI area to flicker. Tried Invalidate, Refresh, Update methods, but they don't help. Maybe there are other workarounds to overcome this bug and not to make MDI area flicker with dummy child form?

private void workaround1Button_Click(object sender, EventArgs e)
{
    dummyForm.Visible = true;
    dummyForm.Visible = false;
}

2) When child form is maximized, the icon of the child form is displayed on menu bar. However, if you have to change the icon while the child form is maximized, the icon on the menu bar is not being refreshed (see the image above). I found a workaround for that too, which basically hides and shows menu bar. Icon gets refreshed, but it makes everything below menu bar to flicker. Tried Invalidate, Refresh, Update methods, but they don't help. Is there any other way to make menu bar to refresh the child form's icon?

private void workaround2Button_Click(object sender, EventArgs e)
{
    menuStrip.Visible = false;
    menuStrip.Visible = true;
}

Also I noticed that when parent form is in normal window state mode (not maximized) and you change the width or height of the form by 1 pixel, child form becomes maximized as it should be and child form's icon on menu bar gets refreshed properly and you don't need other workaround I described above. If I change the size of the form programicaly, form flickers by 1 pixel and I cannot do that, when parent form is maximized. Is there any way how I could invoke the repaint/refresh functionality which is called when you resize a form and which makes child form become maximized properly and the icon on the menu bar refreshed?

Body:
Found a way how to come around those bugs.

First of all you need to suspend painting for a form and its children. I found a very helpful thread here, which describes how to do it.

After suspending painting, you need call UpdateBounds method of the control and increase ClientRectangle Width or Height by one and then decrease it back to the same value it was before. This invokes layout functionality which makes everything to update/repaint. Last step is to enable painting. Not very nice solution I guess, but it works.

StopDrawing();
UpdateBounds(Location.X, Location.Y, Width, Height, ClientRectangle.Width, ClientRectangle.Height + 1);
UpdateBounds(Location.X, Location.Y, Width, Height, ClientRectangle.Width, ClientRectangle.Height - 1);
StartDrawing();

I find suspending painting very helpful not only for working around those two bugs, but also in general to make GUI work more smoothly. I guess this can help to remove any kind of flickering. However, this solution requires P/Invokes, which should be avoided in general.


问:
Mapping latitude and longitude to Canvas points in JavaScript
I'm writing an AR application in which the user sees a ship from the perspective of the captain of the ship like this

I want to use coordinates of other ships (like the one on the left) to draw the ships on top of the image using Canvas. The problem I'm having is mapping the latitude, longitude to Canvas points.

I've read about the Haversine and Bearing formulas but I can't figure out how to use them to do what I want. I know the latitude and longitude of the ship the user is looking from and tried using them to calculate the Canvas points of the other ship, but I can't get it to work. Any ideas?

答:
Finding real world object in camera's view.

This is the most simplistic answer possible, as there are many unknowns that will affect the result.

The problem

The image illustrates the problem as I understand it.

We have 3 ships (the minimum required to find a solution) marked with a red A,B,C. We know the latitude and longitude of each ship. As they are close there is no need to correct for any distortion due to converging longitudes.

The green lines represent the camera's view, the image is projected via a lens onto the CCD (green line above A) The twp gray lines then are projected onto the camera's screen below the ship.

Triangulation and triangles.

From the longitudes we can find the distance from each ship to the other, giving us the lengths of the sides of a triangle.

```<code>var ships = {
    A : { lat : ?, long : ? },
    B : { lat : ?, long : ? },
    C : { lat : ?, long : ? },
}
var AB = Math.hypot(ships.A.lat - ships.B.lat, ships.A.long - ships.B.long);
var BC = Math.hypot(ships.C.lat - ships.B.lat, ships.C.long - ships.B.long);
var CA = Math.hypot(ships.A.lat - ships.C.lat, ships.A.long - ships.C.long);
</code>```

The inset triangle shows how to find the angle of a corner given the lengths of the sides.

For this we are after the angle pheta

```<code>var pheta = Math.acos(BC * BC - AB * AB + CA * CA) / (-2 * AB * CA));
</code>```

The camera's field of view.

Now we need an extra bit of information. That is the field of view of the camera (in image as the green lines and red FOV). You will have to find those details for the camera you are using.

A typical phone camera has a focal length (fl) from 24-35mm equivalent and knowing the CCD size in relative terms you can find the FOV with var FOV = 2 * Math.atan((CCD.width / 2) / fl) But this is problematic as a modern phone is under 10mm thick and the CCD is tiny, what are the actual dimensions?

There is a long and complicated process you can use to determine the  FOV without knowing the internal dimensions of the camera, but easy to look up the phone specs.

For now let's assume the camera has a FOV of 67deg (1.17radians). If the camera has a resolution of 1280 and we ignore lens distortions, and keep the camera vertical and at the same level as the targets , we can calculate the distance in pixels between the two ships via the angle between them.

```<code>var FOV = 1.17; // radians the Field of View of the camera
var pixels = (1.17 / 1280) * pheta; // 1280 is horizontal resolution of display
</code>```

So now we have the distance in pixels between the two ships on the camera. Assuming that they fit on the camera we are missing one more important bit of information.

Bearings

We need to know which way the camera is pointing as a bearing. Only when we have that can we find the ships. So lets assume the GPS on the phone gives you the live bearing. What we need is the bearing to one of the ships.

I had to dig deep into my archives to find this, It had no source or referance so  can only provide as is. All it had is Haversin so assuming that is the method used.

After some further digging I found a referance to what is likely the original source code that this was derived from Calculate distance, bearing and more between Latitude/Longitude points

```<code>function deg2rad(angle) {  return angle * 0.017453292519943295 }
function rad2deg(angle) {  return angle / 0.017453292519943295 }
//return bearing in radians.
function getBearing(lat1,lon1,lat2,lon2){
    var earth = 6371e3;
    var lat1 = lat1.toRadians();
    var lat2 = lat2.toRadians();
    var lon1 = lon1.toRadians();
    var lon2 = lon2.toRadians();
    var latD = lat2-lat1;
    var lonD = lon2-lon1;
    var a = Math.sin(latD / 2) * Math.sin(latD / 2) +  Math.cos(lat1 ) * Math.cos(lat2) *  Math.sin(lonD / 2) * Math.sin(lonD / 2);
    var c = 2 * Math.atan2( Math.sqrt(a),  Math.sqrt(1-a) );
    return earth * c;
}
</code>```

So now you can get the bearing from you to one of the ships.  Use that and your bearing to find the difference in angle between you and it.

```<code>   var yourBearing = ?; // in radians
   var shipBBearing = getBearing(ships.A.lat, ships.A.long, ships.B.lat, ships.B.long);
</code>```

Now get the differance in angle

```<code>   var shipBAt = yourBearing - shipBBearing
</code>```

Knowing the pixel FOV

```<code>   var shipBPixelsFromCenter = (FOV / 1280) * shipBAt;

   var shipBXpos = 1280 / 2 - shipBPixelsFromCenter;
   // and from above the dif in pixels between ships is
   var shipCXpos = shipBXpos + pixels.
</code>```

And done.

Body:
Finding real world object in camera's view.

This is the most simplistic answer possible, as there are many unknowns that will affect the result.

The problem

The image illustrates the problem as I understand it.

We have 3 ships (the minimum required to find a solution) marked with a red A,B,C. We know the latitude and longitude of each ship. As they are close there is no need to correct for any distortion due to converging longitudes.

The green lines represent the camera's view, the image is projected via a lens onto the CCD (green line above A) The twp gray lines then are projected onto the camera's screen below the ship.

Triangulation and triangles.

From the longitudes we can find the distance from each ship to the other, giving us the lengths of the sides of a triangle.

var ships = {
    A : { lat : ?, long : ? },
    B : { lat : ?, long : ? },
    C : { lat : ?, long : ? },
}
var AB = Math.hypot(ships.A.lat - ships.B.lat, ships.A.long - ships.B.long);
var BC = Math.hypot(ships.C.lat - ships.B.lat, ships.C.long - ships.B.long);
var CA = Math.hypot(ships.A.lat - ships.C.lat, ships.A.long - ships.C.long);

The inset triangle shows how to find the angle of a corner given the lengths of the sides.

For this we are after the angle pheta

var pheta = Math.acos(BC * BC - AB * AB + CA * CA) / (-2 * AB * CA));

The camera's field of view.

Now we need an extra bit of information. That is the field of view of the camera (in image as the green lines and red FOV). You will have to find those details for the camera you are using.

A typical phone camera has a focal length (fl) from 24-35mm equivalent and knowing the CCD size in relative terms you can find the FOV with var FOV = 2 * Math.atan((CCD.width / 2) / fl) But this is problematic as a modern phone is under 10mm thick and the CCD is tiny, what are the actual dimensions?

There is a long and complicated process you can use to determine the  FOV without knowing the internal dimensions of the camera, but easy to look up the phone specs.

For now let's assume the camera has a FOV of 67deg (1.17radians). If the camera has a resolution of 1280 and we ignore lens distortions, and keep the camera vertical and at the same level as the targets , we can calculate the distance in pixels between the two ships via the angle between them.

var FOV = 1.17; // radians the Field of View of the camera
var pixels = (1.17 / 1280) * pheta; // 1280 is horizontal resolution of display

So now we have the distance in pixels between the two ships on the camera. Assuming that they fit on the camera we are missing one more important bit of information.

Bearings

We need to know which way the camera is pointing as a bearing. Only when we have that can we find the ships. So lets assume the GPS on the phone gives you the live bearing. What we need is the bearing to one of the ships.

I had to dig deep into my archives to find this, It had no source or referance so  can only provide as is. All it had is Haversin so assuming that is the method used.

After some further digging I found a referance to what is likely the original source code that this was derived from Calculate distance, bearing and more between Latitude/Longitude points

function deg2rad(angle) {  return angle * 0.017453292519943295 }
function rad2deg(angle) {  return angle / 0.017453292519943295 }
//return bearing in radians.
function getBearing(lat1,lon1,lat2,lon2){
    var earth = 6371e3;
    var lat1 = lat1.toRadians();
    var lat2 = lat2.toRadians();
    var lon1 = lon1.toRadians();
    var lon2 = lon2.toRadians();
    var latD = lat2-lat1;
    var lonD = lon2-lon1;
    var a = Math.sin(latD / 2) * Math.sin(latD / 2) +  Math.cos(lat1 ) * Math.cos(lat2) *  Math.sin(lonD / 2) * Math.sin(lonD / 2);
    var c = 2 * Math.atan2( Math.sqrt(a),  Math.sqrt(1-a) );
    return earth * c;
}

So now you can get the bearing from you to one of the ships.  Use that and your bearing to find the difference in angle between you and it.

   var yourBearing = ?; // in radians
   var shipBBearing = getBearing(ships.A.lat, ships.A.long, ships.B.lat, ships.B.long);

Now get the differance in angle

   var shipBAt = yourBearing - shipBBearing

Knowing the pixel FOV

   var shipBPixelsFromCenter = (FOV / 1280) * shipBAt;

   var shipBXpos = 1280 / 2 - shipBPixelsFromCenter;
   // and from above the dif in pixels between ships is
   var shipCXpos = shipBXpos + pixels.

And done.


问:
Akka HTTP response html string with recurrent css or image link
I'm implementing a simple web server on Scala with akka http routes dsl and so on. I have (for instance):

```<code>val route = get {
    path("test") {
      complete((new ViewTemplate).response)
    }
}
</code>```

Where ViewTemplateis a class who reads some html template, injects it with some values probably makes some transformations and returns as HttpResponse...

```<code>class ViewTemplate(val filename: String = "test.html") {
    import scala.io.Source
    private val template = Source.fromResource(filename)
    override def toString: String = template.mkString
    def entity: ResponseEntity = HttpEntity(ContentTypes.`text/html(UTF-8)`, toString)
    def response: HttpResponse = HttpResponse(entity = entity)
}
</code>```

all this works fine until i add

```<code><link rel="stylesheet" href="style.css"/>
</code>```

into test.html's head. The browser just ignores this refs at all. The same situation with images and a's stuff. I suppose, that things like spray of play handle this case fine and I'm inventing another bicycle, but i'm just looking for roots. So what can you advice?

答:
To add an explanation, what you have there is only serving the generated template, it does not serve any other paths, which means that when your browser asks for "http://yourserver/style.css" the server will reply with 404 not found since there is no route defined for "/style.css".

In Akka HTTP (and Spray as well) you have to explicitly define routes for everything you want your web server to do. You can however define routes that extracts the path from a request and serves corresponding files from the filesystem.

You can see the various directives for doing this on this page of the docs: http://doc.akka.io/docs/akka-http/10.0.7/scala/http/routing-dsl/directives/file-and-resource-directives/index.html

Note that getFromResourceDirectory, which you have found yourself, serves files from the classpath and not directly from the filesystem, which may or may not suit your use case.

Body:
I'm implementing a simple web server on Scala with akka http routes dsl and so on. I have (for instance):

val route = get {
    path("test") {
      complete((new ViewTemplate).response)
    }
}

Where ViewTemplateis a class who reads some html template, injects it with some values probably makes some transformations and returns as HttpResponse...

class ViewTemplate(val filename: String = "test.html") {
    import scala.io.Source
    private val template = Source.fromResource(filename)
    override def toString: String = template.mkString
    def entity: ResponseEntity = HttpEntity(ContentTypes.`text/html(UTF-8)`, toString)
    def response: HttpResponse = HttpResponse(entity = entity)
}

all this works fine until i add

<link rel="stylesheet" href="style.css"/>

into test.html's head. The browser just ignores this refs at all. The same situation with images and a's stuff. I suppose, that things like spray of play handle this case fine and I'm inventing another bicycle, but i'm just looking for roots. So what can you advice?


问:
How to create a dynamic component from Javascript
I am trying to create a ComboBox in with html and Javascript. So I got to start the idea with this link. MultiSelect Combo (MultiSelect ComboBox)

In this link I take all the resources and placed in my local and got the desired result.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Custom Format in ComboBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="CSS/easyui.css">
    <script type="text/javascript" src="JS/jquery.min.js"></script>
    <script type="text/javascript" src="JS/jquery.easyui.min.js"></script>
</head>
<body>
    <h2>Custom Format in ComboBox</h2>
    <p>This sample shows how to custom the format of list item.</p>
    <div style="margin:20px 0"></div>
    <div style="margin-bottom:20px">
            <input class="easyui-combobox" name="language" style="width:26%;" data-options="
                    url: 'JSON/combobox_data1.json',
                    method: 'get',
                    valueField: 'id',
                    textField: 'text',
                    panelWidth: 350,
                    multiple:true,
                    formatter: formatItem,
                    label: 'Language:',
                    labelPosition: 'top'
                    ">
        </div>
    <script type="text/javascript">
        function formatItem(row){
            var s = '<span style="font-weight:bold">' + row.text + '</span><br/>' +
                    '<span style="color:#888">' + row.desc + '</span>';
            return s;
        }
    </script>
</body>
</html>
</code>```

Now I want my Inputbox to be Dynamic, So I can use it anywhere and any number of times by passing div and others required attributes.

What I tried here is

index.html

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Custom Format in ComboBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="CSS/easyui.css">
    <script type="text/javascript" src="JS/jquery.min.js"></script>
    <script type="text/javascript" src="JS/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="JS/NewCombo.js"></script>
</head>
<body>
    <h2>Custom Format in ComboBox</h2>
    <p>This sample shows how to custom the format of list item.</p>
    <div style="margin:20px 0"></div>
    <script type="text/javascript">
        var myCombo = new NewCombo({
            url: 'JSON/combobox_data1.json',
            method: 'get',
            valueField: 'id',
            textField: 'text',
            panelWidth: 350,
            multiple:true,
            //formatter: formatItem,
            label: 'Language:',
            });
    </script>
</body>
</html>
</code>```

And JS Code is
Js Code

```<code>NewCombo = function(args){
    var mydiv =   "<div style="margin-bottom:20px">"+"
            <input class="easyui-combobox" name="language" style="width:26%;" data-options="
                    url: 'JSON/combobox_data1.json',\
                    method: 'get',\
                    valueField: 'id',\
                    textField: 'text',\
                    panelWidth: 350,\
                    multiple:true,\
                    formatter: formatItem,\
                    label: 'Language:',\
                    labelPosition: 'top'\
                    ">"+"
        </div>"
}
</code>```

ut What chalanges I am facing is

Not able to create correct input tag element which causing error.

Here example :

In first case :

input tag is

```<code>"<input class="easyui-combobox" name="language" style="width:100%;" data-options="url: "JSON/combobox_data1.json",method: "get",valueField: "id",textField: "text",                    panelWidth: 350,multiple:true,label: "Language:",labelPosition: "top">"
</code>```

In second case input tag is :

```<code>"<div id="chart_line" style="width:26%; background-color: lightblue;"><input class="easyui-combobox" name="language" style="width:100%;" data-options="                    url: " json="" combobox_data1.json",="" method:="" "get",="" valuefield:="" "id",="" textfield:="" "text",="" panelwidth:="" 350,="" multiple:true,="" label:="" "language:",="" labelposition:="" "top"=""></div>"
</code>```

Now Please help me how to fix this.

答:
Try using the setAttribute method to add a data-options attribute dynamically:

```<code>document.getElementById('combobox1').setAttribute('data-options', '{GENERATED OPTIONS}');
</code>```

Body:
I am trying to create a ComboBox in with html and Javascript. So I got to start the idea with this link. MultiSelect Combo (MultiSelect ComboBox)

In this link I take all the resources and placed in my local and got the desired result.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Custom Format in ComboBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="CSS/easyui.css">

Custom Format in ComboBox

This sample shows how to custom the format of list item.

            <input class="easyui-combobox" name="language" style="width:26%;" data-options="
                    url: 'JSON/combobox_data1.json',
                    method: 'get',
                    valueField: 'id',
                    textField: 'text',
                    panelWidth: 350,
                    multiple:true,
                    formatter: formatItem,
                    label: 'Language:',
                    labelPosition: 'top'
                    ">

Now I want my Inputbox to be Dynamic, So I can use it anywhere and any number of times by passing div and others required attributes.

What I tried here is

index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Custom Format in ComboBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="CSS/easyui.css">

Custom Format in ComboBox

This sample shows how to custom the format of list item.

And JS Code is
Js Code

NewCombo = function(args){
    var mydiv =   "
"+"
            <input class="easyui-combobox" name="language" style="width:26%;" data-options="
                    url: 'JSON/combobox_data1.json',\
                    method: 'get',\
                    valueField: 'id',\
                    textField: 'text',\
                    panelWidth: 350,\
                    multiple:true,\
                    formatter: formatItem,\
                    label: 'Language:',\
                    labelPosition: 'top'\
                    ">"+"

"
}

ut What chalanges I am facing is

Not able to create correct input tag element which causing error.

Here example :

In first case :

input tag is

"<input class="easyui-combobox" name="language" style="width:100%;" data-options="url: "JSON/combobox_data1.json",method: "get",valueField: "id",textField: "text",                    panelWidth: 350,multiple:true,label: "Language:",labelPosition: "top">"

In second case input tag is :

"
<input class="easyui-combobox" name="language" style="width:100%;" data-options="                    url: " json="" combobox_data1.json",="" method:="" "get",="" valuefield:="" "id",="" textfield:="" "text",="" panelwidth:="" 350,="" multiple:true,="" label:="" "language:",="" labelposition:="" "top"="">
"

Now Please help me how to fix this.

Body:
Try using the setAttribute method to add a data-options attribute dynamically:

document.getElementById('combobox1').setAttribute('data-options', '{GENERATED OPTIONS}');


问:
Is there a windows utility similar to HTML Tidy for Javascript?
I want to cleanup some javascript files and reformat them with nice indents, etc,
Are there recommendations for utilities to do this under Windows?</p>

答:
Try the online JavaScript Tidy

Several attempts have been made to
  produce programs to reformat code, but
  these often fail to cope with
  situations such as '{', '}' or ';'
  characters inside strings, regular
  expressions, or comments, so virtually
  all of them end up with broken code.
  However, browsers already have their
  own parsers built in that deal with
  all of these situations. This script
  hooks into the browser's own parser,
  by wrapping the code in a function
  then using the native toString method
  to obtain the tidied code. As a
  result, it relies on the browser
  producing a tidied output, which there
  is no requirement for them to do. In
  fact, it relies on the browser
  decompiling to tidied code instead of
  just retaining the original, which is
  an expensive process in terms of
  performance, and leads to extra
  complexity when trying to make sure
  the decompiled code still works, so
  not all browsers choose to do it this
  way.

For best results, use Opera 9.2x- (not
  9.5+), Safari or Konqueror on this page. It partially works in Firefox
  (nested functions are not tidied,
  meaning that most scripts you want to
  tidy still end up unreadable), and
  fails to reformat code in IE and iCab
  3-. Since you can always keep a copy
  of Opera 9.2 on your computer (as well
  as whatever the current version is), I
  recommend you use Opera, and keep a
  copy of it around for use with JSTidy.

OwnerDisplayName: Noah

LastEditorDisplayName: Noah

OwnerDisplayName: Ates Goral

LastEditorDisplayName: Ates Goral


问:
How to remove empty values from multidimensional array in PHP?
I've been looking a lot of answers, but none of them are working for me.

This is the data assigned to my $quantities array:

```<code>Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array([35.00] => )
    [1] => Array([30.00] => )
    [2] => Array([30.00] => )
)
</code>```

I'm looking for a way to remove the subarrays with empty values like [12] [1] and [2] while keeping everything else.

The desired result:

```<code>Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
)
</code>```

I tried a lot of the functions on the official php docs and none of them worked.

I've used this one:

```<code>function array_filter_recursive($array, $callback = null) {
    foreach ($array as $key => & $value) {
        if (is_array($value)) {
            $value = array_filter_recursive($value, $callback);
        } else {
            if ( ! is_null($callback)) {
                if ( ! $callback($value)) {
                    unset($array[$key]);
                }
            } else {
                if ( ! (bool) $value) {
                    unset($array[$key]);
                }
            }
        }
    }
    unset($value);
    return $array;
}
</code>```

But it only removes the element in the subarrays; I need the subarrays to be removed entirely.

I don't want this:

```<code>Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array()
    [1] => Array()
    [2] => Array()
)
</code>```

答:
This removes all items with null values recursively on multideminsional arrays. Works on PHP >= 5.6. If you want to remove all "empty" values, replace !is_null($value) with !empty($value).

```<code>function recursivelyRemoveItemsWithNullValuesFromArray(array $data = []): array
{
    $data = array_map(function($value) {
        return is_array($value) ? recursivelyRemoveItemsWithNullValuesFromArray($value) : $value;
    }, $data);

    return array_filter($data, function($value) {
        return !is_null($value);
    });
}
</code>```

Body:
I've been looking a lot of answers, but none of them are working for me.

This is the data assigned to my $quantities array:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array([35.00] => )
    [1] => Array([30.00] => )
    [2] => Array([30.00] => )
)

I'm looking for a way to remove the subarrays with empty values like [12] [1] and [2] while keeping everything else.

The desired result:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
)

I tried a lot of the functions on the official php docs and none of them worked.

I've used this one:

function array_filter_recursive($array, $callback = null) {
    foreach ($array as $key => & $value) {
        if (is_array($value)) {
            $value = array_filter_recursive($value, $callback);
        } else {
            if ( ! is_null($callback)) {
                if ( ! $callback($value)) {
                    unset($array[$key]);
                }
            } else {
                if ( ! (bool) $value) {
                    unset($array[$key]);
                }
            }
        }
    }
    unset($value);
    return $array;
}

But it only removes the element in the subarrays; I need the subarrays to be removed entirely.

I don't want this:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array()
    [1] => Array()
    [2] => Array()
)

Body:
This removes all items with null values recursively on multideminsional arrays. Works on PHP >= 5.6. If you want to remove all "empty" values, replace !is_null($value) with !empty($value).

function recursivelyRemoveItemsWithNullValuesFromArray(array $data = []): array
{
    $data = array_map(function($value) {
        return is_array($value) ? recursivelyRemoveItemsWithNullValuesFromArray($value) : $value;
    }, $data);

    return array_filter($data, function($value) {
        return !is_null($value);
    });
}

ContentLicense: CC BY-SA 4.0


问:
How to solve Too many open files exception in flink when using elastic search connector to send stream data to elastic search index?
I am using flink elastic search connector to send data to elastic search index.

But I am unable to run the job and getting this exception. How to solve this issue?.Is there any setting or configurations I am missing? Could anyone guide me?

```<code>io.netty.channel.ChannelException: The operating system does not offer enough file handles to open the network connection. Please increase the number of of available file handles.
    at org.apache.flink.runtime.io.network.netty.NettyClient.connect(NettyClient.java:207)
    at org.apache.flink.runtime.io.network.netty.PartitionRequestClientFactory.createPartitionRequestClient(PartitionRequestClientFactory.java:81)
    at org.apache.flink.runtime.io.network.netty.NettyConnectionManager.createPartitionRequestClient(NettyConnectionManager.java:60)
    at org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel.requestSubpartition(RemoteInputChannel.java:112)
    at org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate.requestPartitions(SingleInputGate.java:419)
    at org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate.getNextBufferOrEvent(SingleInputGate.java:441)
    at org.apache.flink.streaming.runtime.io.BarrierTracker.getNextNonBlocked(BarrierTracker.java:85)
    at org.apache.flink.streaming.runtime.io.StreamInputProcessor.processInput(StreamInputProcessor.java:192)
    at org.apache.flink.streaming.runtime.tasks.OneInputStreamTask.run(OneInputStreamTask.java:63)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:261)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:665)
    at java.lang.Thread.run(Thread.java:748)
Caused by: io.netty.channel.ChannelException: Failed to open a socket.
    at io.netty.channel.socket.nio.NioSocketChannel.newSocket(NioSocketChannel.java:62)
    at io.netty.channel.socket.nio.NioSocketChannel.<init>(NioSocketChannel.java:72)
    at sun.reflect.GeneratedConstructorAccessor8.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at io.netty.bootstrap.AbstractBootstrap$BootstrapChannelFactory.newChannel(AbstractBootstrap.java:453)
    at io.netty.bootstrap.AbstractBootstrap.initAndRegister(AbstractBootstrap.java:306)
    at io.netty.bootstrap.Bootstrap.doConnect(Bootstrap.java:133)
    at io.netty.bootstrap.Bootstrap.connect(Bootstrap.java:115)
    at org.apache.flink.runtime.io.network.netty.NettyClient.connect(NettyClient.java:198)
    ... 11 more
Caused by: java.net.SocketException: Too many open files
    at sun.nio.ch.Net.socket0(Native Method)
    at sun.nio.ch.Net.socket(Net.java:411)
    at sun.nio.ch.Net.socket(Net.java:404)
    at sun.nio.ch.SocketChannelImpl.<init>(SocketChannelImpl.java:105)
    at sun.nio.ch.SelectorProviderImpl.openSocketChannel(SelectorProviderImpl.java:60)
    at io.netty.channel.socket.nio.NioSocketChannel.newSocket(NioSocketChannel.java:60)
    ... 21 more
</code>```

答: In order to increase the number of file handles in your system you can set them via ulimit -n for a process if you have root privileges. If you want to change the number of file handles system-wide, then change the value in /proc/sys/fs/file-max (on Linux).

Body:
I am using flink elastic search connector to send data to elastic search index.

But I am unable to run the job and getting this exception. How to solve this issue?.Is there any setting or configurations I am missing? Could anyone guide me?

io.netty.channel.ChannelException: The operating system does not offer enough file handles to open the network connection. Please increase the number of of available file handles.
    at org.apache.flink.runtime.io.network.netty.NettyClient.connect(NettyClient.java:207)
    at org.apache.flink.runtime.io.network.netty.PartitionRequestClientFactory.createPartitionRequestClient(PartitionRequestClientFactory.java:81)
    at org.apache.flink.runtime.io.network.netty.NettyConnectionManager.createPartitionRequestClient(NettyConnectionManager.java:60)
    at org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel.requestSubpartition(RemoteInputChannel.java:112)
    at org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate.requestPartitions(SingleInputGate.java:419)
    at org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate.getNextBufferOrEvent(SingleInputGate.java:441)
    at org.apache.flink.streaming.runtime.io.BarrierTracker.getNextNonBlocked(BarrierTracker.java:85)
    at org.apache.flink.streaming.runtime.io.StreamInputProcessor.processInput(StreamInputProcessor.java:192)
    at org.apache.flink.streaming.runtime.tasks.OneInputStreamTask.run(OneInputStreamTask.java:63)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:261)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:665)
    at java.lang.Thread.run(Thread.java:748)
Caused by: io.netty.channel.ChannelException: Failed to open a socket.
    at io.netty.channel.socket.nio.NioSocketChannel.newSocket(NioSocketChannel.java:62)
    at io.netty.channel.socket.nio.NioSocketChannel.<init>(NioSocketChannel.java:72)
    at sun.reflect.GeneratedConstructorAccessor8.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at io.netty.bootstrap.AbstractBootstrap$BootstrapChannelFactory.newChannel(AbstractBootstrap.java:453)
    at io.netty.bootstrap.AbstractBootstrap.initAndRegister(AbstractBootstrap.java:306)
    at io.netty.bootstrap.Bootstrap.doConnect(Bootstrap.java:133)
    at io.netty.bootstrap.Bootstrap.connect(Bootstrap.java:115)
    at org.apache.flink.runtime.io.network.netty.NettyClient.connect(NettyClient.java:198)
    ... 11 more
Caused by: java.net.SocketException: Too many open files
    at sun.nio.ch.Net.socket0(Native Method)
    at sun.nio.ch.Net.socket(Net.java:411)
    at sun.nio.ch.Net.socket(Net.java:404)
    at sun.nio.ch.SocketChannelImpl.<init>(SocketChannelImpl.java:105)
    at sun.nio.ch.SelectorProviderImpl.openSocketChannel(SelectorProviderImpl.java:60)
    at io.netty.channel.socket.nio.NioSocketChannel.newSocket(NioSocketChannel.java:60)
    ... 21 more


问:
Pass **kwargs through to inner function
I have a function

```<code>def wrapper_function(url, **kwargs)
   def foo():
      if kwargs:
          return do_something(url, kwargs)
      else:
          return do_something(url)
</code>```

The do_something() function can either have one or more parameters.

When I call the wrapper_function(), want to call it either like

```<code>wrapper_function('www.bar.com')
</code>```

or

```<code>wrapper_function('www.bar.com', selected_clients=clients)
</code>```

so that do_something('www.bar.com', selected_clients=clients).

However, when I approach it like this, I get an error
clients is not defined.

How can I pass on the params exactly like they are with the keyword into an inner function? Important, that keyword needs to be variable as well.

答:
When your function takes in kwargs in the form foo(**kwargs), you access the keyworded arguments as you would a python dict. Similarly, to pass the dict to a function in the form of several keyworded arguments, simply pass it as **kwargs again. So, in your case,

```<code>do_something(url, **kwargs)
</code>```

Title: Pass **kwargs through to inner function

Body:
I have a function

def wrapper_function(url, **kwargs)
   def foo():
      if kwargs:
          return do_something(url, kwargs)
      else:
          return do_something(url)

The do_something() function can either have one or more parameters.

When I call the wrapper_function(), want to call it either like

wrapper_function('www.bar.com')

or

wrapper_function('www.bar.com', selected_clients=clients)

so that do_something('www.bar.com', selected_clients=clients).

However, when I approach it like this, I get an error
clients is not defined.

How can I pass on the params exactly like they are with the keyword into an inner function? Important, that keyword needs to be variable as well.

Body:
When your function takes in kwargs in the form foo(**kwargs), you access the keyworded arguments as you would a python dict. Similarly, to pass the dict to a function in the form of several keyworded arguments, simply pass it as **kwargs again. So, in your case,

do_something(url, **kwargs)


问:
append Carbon to object Property - Javascript
I'm working with Pusher right now, and when a user sends a message, I append it to Pusher like this:

```<code>channel.bind('App\\Events\\MessageSent', function(data){
                $('#chat-box-message').empty(html);
                for (var i = 0; i< data.length; i++) {

                    for (var key in data) {  //empty the div for append does not repeat
                        var obj = data[key];
                        for (var prop in obj) {

                            $('#chat-box-message').append(
                                '<div class="comment">'+
                                    '<div class="content">'+
                                        '<div class="date">'+
                                            obj[prop]['created_at']+
                                        '</div>'+
                                        '<div class="text">' +
                                            obj[prop]['message']+
                                        '</div>'+
                                     '</div>'+
                                '</div>'
                            );
                        }
                    }
                }
            });
</code>```

But what I need to append is this:

```<code><div class="date">
  {{ $message->created_at->diffForHumans() }}
</div>
</code>```

to this:

```<code>  obj[prop]['created_at']+
</code>```

How do I append the diffForHumans() on the object property in the JavaScript section?

答:
As @Derek said:</p>

```<code>obj[prop]['message'] + '{{ $message->created_at->diffForHumans() }}'
</code>```

Body:
I'm working with Pusher right now, and when a user sends a message, I append it to Pusher like this:

channel.bind('App\\Events\\MessageSent', function(data){
                $('#chat-box-message').empty(html);
                for (var i = 0; i< data.length; i++) {

                    for (var key in data) {  //empty the div for append does not repeat
                        var obj = data[key];
                        for (var prop in obj) {

                            $('#chat-box-message').append(
                                '
'+
                                    '
'+
                                        '
'+
                                            obj[prop]['created_at']+
                                        '
'+
                                        '
' +
                                            obj[prop]['message']+
                                        '
'+
                                     '
'+
                                '
'
                            );
                        }
                    }
                }
            });

But what I need to append is this:

  {{ $message->created_at->diffForHumans() }}

to this:

  obj[prop]['created_at']+

How do I append the diffForHumans() on the object property in the JavaScript section?

Body:
As @Derek said:

obj[prop]['message'] + '{{ $message->created_at->diffForHumans() }}'


问:
Python requests dict as form-data
I have a python dict

```<code>x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}
</code>```

I'm trying to get my form-data to be

```<code>id=123
data[param1]=hello
data[param2]=world
</code>```

I cannot pass it as a json, because the API receiving it won't accept json objects

I've tried passing it like this

```<code>requests.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})
</code>```

The request goes out with form data looking like this

```<code>id=123
data=param1
data=param2
</code>```

Is there a way to get around this?

答:
Perhaps you can do it well. Let's try it

```<code>x = {
   'id': 123,
   'data[param1]': 'hello',
   'data[param2]': 'world',
}
</code>```

https://github.com/requests/requests/issues/2885

Title: Python requests dict as form-data

Body:
I have a python dict

x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}

I'm trying to get my form-data to be

id=123
data[param1]=hello
data[param2]=world

I cannot pass it as a json, because the API receiving it won't accept json objects

I've tried passing it like this

requests.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})

The request goes out with form data looking like this

id=123
data=param1
data=param2

Is there a way to get around this?

Body:
Perhaps you can do it well. Let's try it

x = {
   'id': 123,
   'data[param1]': 'hello',
   'data[param2]': 'world',
}

https://github.com/requests/requests/issues/2885


问:
Disable info window shadow in google maps (v2)
Is there any way to disable the automatically generated shadow for the info window for a marker?

I'm trying to get around the bug reported at http://www.google.com/support/forum/p/maps/thread?tid=69bcc3217ee1ac68&hl=en where the shadow has big black marks around it that obscure the view of the map when viewed in IE 8 at any zoom level other than 100%.

答:
Looks like, for IE 8 only, you'll have to traverse the dom, find the shadow images (iws3.png), and hide them. If you have jQuery at your disposal, then it's as simple as

```<code>$('img[src$="iws3.png"]').hide();
</code>```

after the map has loaded.

Or, if you don't have jQuery, something like...

```<code>var i, imgs = document.getElementsByTagName('img');
for (i = 0; i < imgs.length; i++) {
    if (/iws3\.png/.test(imgs[i].src)) {
        imgs[i].style.display = "none";
    }
}
</code>```

P.S. @Crescent Fresh, here's a screenshot:

Body:
Looks like, for IE 8 only, you'll have to traverse the dom, find the shadow images (iws3.png), and hide them. If you have jQuery at your disposal, then it's as simple as

$('img[src$="iws3.png"]').hide();

after the map has loaded.

Or, if you don't have jQuery, something like...

var i, imgs = document.getElementsByTagName('img');
for (i = 0; i < imgs.length; i++) {
    if (/iws3\.png/.test(imgs[i].src)) {
        imgs[i].style.display = "none";
    }
}

P.S. @Crescent Fresh, here's a screenshot: