问:
Vectorized matrix and array multiplication in R
I could not figure out, how to write a vectorized version of the following matrix and array multiplication:

```<code>v = rep(0.1, 2)
v2 = matrix(0, nrow = 2, ncol = 3)
A = matrix(0.25, nrow = 2, ncol = 3)
R = matrix(- 1, nrow = 2, ncol = 3)
P = array(1:12, dim = c(2, 2, 3))
for (i in 1:3) {
  v2[, i] = A[, i] * (R[, i] + P[, , i] %*%  v)
}
v = rowSums(v2)
</code>```

Can someone help?

答:
The problem that we are faced with is that we want to do matrix multiplication over P, a 3d array. As this is not efficiently possible, it is better to transform this array to a 2d column matrix.

```<code>P <- array(1:12, dim = c(2, 2, 3))
P <- matrix(P, nrow = 2)
</code>```

The A and R matrices don't have to be adjusted for this to work

```<code>A <- matrix(0.25, nrow = 2, ncol = 3)
R <- matrix(-1, nrow = 2, ncol = 3)
</code>```

Matrix multiplication with the v vector can then be accomplished by transforming the column vector into a sparse block diagonal matrix with the bdiag(...) function from the Matrix package.

```<code>library(Matrix)

v <- rep(0.1, 2)
v <- bdiag(v, v, v)

## [1,] 0.1 .   .
## [2,] 0.1 .   .
## [3,] .   0.1 .
## [4,] .   0.1 .
## [5,] .   .   0.1
## [6,] .   .   0.1
</code>```

This gives the same result as before, however, this time in a vectorized manner.

```<code>v <- rowSums(A * (R + (P %*% v)))
## [1] 0.15 0.30
</code>```

Edit: In the above equation I use two types of multiplication: *, the dot-product, which computes the element-wise products between two matrices of equal size, and %*%, the ordinary matrix product, which computes the matrix product of two conformable matrices, or in other words, the number of columns of the first, and the number of rows of the second matrix should be equal.

Edit2: As requested I have included how to transform the given P array to a matrix.

Edit3: This method can be generalized by introducing a variable n for the number of groups. The key adjustment is in the declaration of the block diagonal matrix, as next to individual matrices, this function also takes a list of matrices as input. This results in the following solution

```<code>library(Matrix)
n <- 3
P <- array(1:12, dim = c(2, 2, n))
P <- matrix(P, nrow = 2)
A <- matrix(0.25, nrow = 2, ncol = n)
R <- matrix(-1, nrow = 2, ncol = n)
v <- rep(0.1, 2)
v <- bdiag(rep(list(v),n))
v <- rowSums(A * (R + (P %*% v)))
## [1] 0.15 0.30
</code>```

Body:
I could not figure out, how to write a vectorized version of the following matrix and array multiplication:

v = rep(0.1, 2)
v2 = matrix(0, nrow = 2, ncol = 3)
A = matrix(0.25, nrow = 2, ncol = 3)
R = matrix(- 1, nrow = 2, ncol = 3)
P = array(1:12, dim = c(2, 2, 3))
for (i in 1:3) {
  v2[, i] = A[, i] * (R[, i] + P[, , i] %*%  v)
}
v = rowSums(v2)

Can someone help?

Body:
The problem that we are faced with is that we want to do matrix multiplication over P, a 3d array. As this is not efficiently possible, it is better to transform this array to a 2d column matrix.

P <- array(1:12, dim = c(2, 2, 3))
P <- matrix(P, nrow = 2)

The A and R matrices don't have to be adjusted for this to work

A <- matrix(0.25, nrow = 2, ncol = 3)
R <- matrix(-1, nrow = 2, ncol = 3)

Matrix multiplication with the v vector can then be accomplished by transforming the column vector into a sparse block diagonal matrix with the bdiag(...) function from the Matrix package.

library(Matrix)

v <- rep(0.1, 2)
v <- bdiag(v, v, v)

## [1,] 0.1 .   .
## [2,] 0.1 .   .
## [3,] .   0.1 .
## [4,] .   0.1 .
## [5,] .   .   0.1
## [6,] .   .   0.1

This gives the same result as before, however, this time in a vectorized manner.

v <- rowSums(A * (R + (P %*% v)))
## [1] 0.15 0.30

Edit: In the above equation I use two types of multiplication: *, the dot-product, which computes the element-wise products between two matrices of equal size, and %*%, the ordinary matrix product, which computes the matrix product of two conformable matrices, or in other words, the number of columns of the first, and the number of rows of the second matrix should be equal.

Edit2: As requested I have included how to transform the given P array to a matrix.

Edit3: This method can be generalized by introducing a variable n for the number of groups. The key adjustment is in the declaration of the block diagonal matrix, as next to individual matrices, this function also takes a list of matrices as input. This results in the following solution

library(Matrix)
n <- 3
P <- array(1:12, dim = c(2, 2, n))
P <- matrix(P, nrow = 2)
A <- matrix(0.25, nrow = 2, ncol = n)
R <- matrix(-1, nrow = 2, ncol = n)
v <- rep(0.1, 2)
v <- bdiag(rep(list(v),n))
v <- rowSums(A * (R + (P %*% v)))
## [1] 0.15 0.30


来源: stackexchange

问:
how to merge two strings using c?
```<code>#include<stdio.h>

/* a function to merge two strings */

void stringMerge(char* f, char* s){

while(*f++);

while((*f++ = *s++));

}

int main(){

char s1[] = "Hello ";

char s2[] = "World";

stringMerge(s1,s2);

printf("%s",s1);

return 0;

}
</code>```

答:
Taking into account the declarations of strings that you are going to concatenate then it seems you mean the following function implementation.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        strcpy(p, s1);
        strcpy(p + n, s2);
    }

    return p;
}

int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}
</code>```

Or the following

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        char *t = p;
        while (*t = *s1++) ++t;
        do { *t = *s2++; } while (*t++);
    }

    return p;
}

int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}
</code>```

In the both programs the output is

```<code>Hello World
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to merge two strings using c?

Body:
Taking into account the declarations of strings that you are going to concatenate then it seems you mean the following function implementation.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        strcpy(p, s1);
        strcpy(p + n, s2);
    }

    return p;
}

int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}

Or the following

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        char *t = p;
        while (*t = *s1++) ++t;
        do { *t = *s2++; } while (*t++);
    }

    return p;
}

int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}

In the both programs the output is

Hello World


问:
best way to include header and footer on HTML using any client side framework
Having HTML project want to include header and footer , so it will reduce rework.
Please suggest any good way.

I tried AngularJS with ng-include and below code

```<code>var app = angular.module("arstlApp", []);
app.controller("arstlCtrl", function($scope, $rootScope,$timeout) {
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         _autoload();
    });
  });
});
</code>```

but <ng-include increase number of call JS function.

答:
If you truly don't care about the which framework: Consider using pug.

Example from link:

```<code>doctype html
html
  include includes/head.pug
  body
    h1 My Site
    p Welcome to my super lame site.
    include includes/foot.pug
</code>```

Other options:

Use a component based client framework like AngularX or React

pug is just one of the many Html template libraries out there (Handlebars, Vue, ...)

If you have a semi-static website, Jekyll will create static html from your source files with support for html includes

Use PHP or another server side language which supports includes. Or use some MVC framework in said language (ex PHP has Laravel)

Body:
Having HTML project want to include header and footer , so it will reduce rework.
Please suggest any good way.

I tried AngularJS with ng-include and below code

var app = angular.module("arstlApp", []);
app.controller("arstlCtrl", function($scope, $rootScope,$timeout) {
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         _autoload();
    });
  });
});

but <ng-include increase number of call JS function.

Body:
If you truly don't care about the which framework: Consider using pug.

Example from link:

doctype html
html
  include includes/head.pug
  body
    h1 My Site
    p Welcome to my super lame site.
    include includes/foot.pug

Other options:

Use a component based client framework like AngularX or React

pug is just one of the many Html template libraries out there (Handlebars, Vue, ...)

If you have a semi-static website, Jekyll will create static html from your source files with support for html includes

Use PHP or another server side language which supports includes. Or use some MVC framework in said language (ex PHP has Laravel)


问:
Ruby on Rails: How to add a form text field if the corresponding filed in the model doesn't exist?
I have the following models:

```<code>Product: name, shop_id (foreign key)
Shop:    name
</code>```

The associations are:

```<code>Product: belongs_to :shop
Shop:    has_many   :products
</code>```

In the form that creates a new Product I have:

```<code><%= f.label(:shop, "Shop:") %>
<%= f.select(...) %>
</code>```

This is a select box with all existing shops. The last option in this select box is Create New Shop. When user clicks this option, Javascript shows an extra field:

```<code><div id="new_shop_wrapper">
    <label for="new_shop">New shop:</label>
    <input id="new_shop" name="new_shop" type="text" />
</div>
</code>```

(This div is hidden by default with display: none.)

How should I add this div in the Rails form creation ?

I tried:

```<code><%= f.label(:new_shop, "New Shop:") %>
<%= f.text_field(:new_shop) %>
</code>```

but it doesn't work because new_shop is not Product's field.

I thought to use:

```<code><%= text_field(<object>, :new_shop) %>
</code>```

but I don't know what  to use.

Please advise.

答:
In fact, you could add your method in the model:</p>

```<code>class Product < ActiveRecord::Base
  def new_show=(val)
    self.shop = Shop.new({:name => val})
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following models:

Product: name, shop_id (foreign key)
Shop:    name

The associations are:

Product: belongs_to :shop
Shop:    has_many   :products

In the form that creates a new Product I have:

<%= f.label(:shop, "Shop:") %>
<%= f.select(...) %>

This is a select box with all existing shops. The last option in this select box is Create New Shop. When user clicks this option, Javascript shows an extra field:

    New shop:
    <input id="new_shop" name="new_shop" type="text" />

(This div is hidden by default with display: none.)

How should I add this div in the Rails form creation ?

I tried:

<%= f.label(:new_shop, "New Shop:") %>
<%= f.text_field(:new_shop) %>

but it doesn't work because new_shop is not Product's field.

I thought to use:

<%= text_field(<object>, :new_shop) %>

but I don't know what  to use.

Please advise.

Body:
In fact, you could add your method in the model:

class Product < ActiveRecord::Base
  def new_show=(val)
    self.shop = Shop.new({:name => val})
  end
end


问:
How to determine if a character is alphanumeric using comparison operator?
I'm taking freecodecamp challenge "Check for Palindromes". Write a function to check if a given string is palindrome. Here is my code:

```<code>    function palindrome(str) {
      str = str.toLowerCase();
      for(var i=0; i<str.length; i++){
        if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
          str = str.replace(str[i], '');
        }
      }
      for(i=0; i<str.length/2; i++){
        if(str[i] != str[str.length-1-i]){
        return false;
        }
      }
      return true;
    }
</code>```

But it not worked properly. When I use replace(/[\W_]/g, ''); :

```<code>    function palindrome(str) {
      str = str.toLowerCase().replace(/[\W_]/g, '');
 //   for(var i=0; i<str.length; i++){
 //     if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
 //       str = str.replace(str[i], '');
 //     }
 //   }
      for(i=0; i<str.length/2; i++){
      if(str[i] != str[str.length-1-i]){
          return false;
        }
      }
      return true;
    }
</code>```

The function worked properly. Is my first method not correct?

答:
Palindromes ignore capitalization, spaces, punctuation and newlines and so on.

So:

A man. A plan. A canal: Panama!

Is a valid palindrome.

As such, you need to strip all punctuation and whitespace out of your string before trying to evaluate it, such that the string you're actually evaluating is:

amanaplanacanalpanama

Then it's easy to do whatever comparator you'd like on the remaining characters.

I did one of these a while ago and included some tests, it might be worth looking at: https://github.com/pvencill/palindrome

Body:
I'm taking freecodecamp challenge "Check for Palindromes". Write a function to check if a given string is palindrome. Here is my code:

    function palindrome(str) {
      str = str.toLowerCase();
      for(var i=0; i<str.length; i++){
        if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
          str = str.replace(str[i], '');
        }
      }
      for(i=0; i<str.length/2; i++){
        if(str[i] != str[str.length-1-i]){
        return false;
        }
      }
      return true;
    }

But it not worked properly. When I use replace(/[\W_]/g, ''); :

    function palindrome(str) {
      str = str.toLowerCase().replace(/[\W_]/g, '');
 //   for(var i=0; i<str.length; i++){
 //     if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
 //       str = str.replace(str[i], '');
 //     }
 //   }
      for(i=0; i<str.length/2; i++){
      if(str[i] != str[str.length-1-i]){
          return false;
        }
      }
      return true;
    }

The function worked properly. Is my first method not correct?


问:
Android "Error inflating class ImageView" on older devices?
I have a recycler view where each element has an image. Sometimes this is blank, sometimes this has a placeholder, sometimes this has an image retrieved via Picasso. Works perfectly fine in simulators and on two devices running Marshmallow. Not working at all on two devices on 4.3 and 4.4.2 respectively (a Samsung S3 and Galaxy Tab 3 8.0). I get the following error:

```<code>android.view.InflateException: Binary XML file line #103: Error inflating class ImageView
                                                                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
                                                                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
                                                                      at com.rhls.directrepairs.AgentListViewAdapter.onCreateViewHolder(AgentListViewAdapter.java:43)
                                                                      at com.rhls.directrepairs.AgentListViewAdapter.onCreateViewHolder(AgentListViewAdapter.java:20)
                                                                      at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5779)
                                                                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5003)
                                                                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
                                                                      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
                                                                      at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
                                                                      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
                                                                      at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
                                                                      at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
                                                                      at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
                                                                      at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
                                                                      at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                      at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1319)
                                                                      at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:817)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
                                                                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
                                                                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
                                                                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
                                                                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2260)
                                                                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2007)
                                                                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
                                                                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
                                                                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
                                                                      at android.view.Choreographer.doCallbacks(Choreographer.java:591)
                                                                      at android.view.Choreographer.doFrame(Choreographer.java:561)
                                                                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
                                                                      at android.os.Handler.handleCallback(Handler.java:730)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                    at android.os.Loope
</code>```

I am currently unable to make this work. I have tried removing the placeholder image (a drawable .png file) from the src field in the XML, but still get the crash. Any ideas as to why this isn't working?

答:
It's maybe because you are using vectors as background in your ImageView
Take a look at this answer</p>

Body:
I have a recycler view where each element has an image. Sometimes this is blank, sometimes this has a placeholder, sometimes this has an image retrieved via Picasso. Works perfectly fine in simulators and on two devices running Marshmallow. Not working at all on two devices on 4.3 and 4.4.2 respectively (a Samsung S3 and Galaxy Tab 3 8.0). I get the following error:

android.view.InflateException: Binary XML file line #103: Error inflating class ImageView
                                                                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
                                                                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
                                                                      at com.rhls.directrepairs.AgentListViewAdapter.onCreateViewHolder(AgentListViewAdapter.java:43)
                                                                      at com.rhls.directrepairs.AgentListViewAdapter.onCreateViewHolder(AgentListViewAdapter.java:20)
                                                                      at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5779)
                                                                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5003)
                                                                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
                                                                      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
                                                                      at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
                                                                      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
                                                                      at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
                                                                      at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
                                                                      at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
                                                                      at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
                                                                      at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                      at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1319)
                                                                      at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:817)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
                                                                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
                                                                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
                                                                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
                                                                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
                                                                      at android.view.View.layout(View.java:15204)
                                                                      at android.view.ViewGroup.layout(ViewGroup.java:4793)
                                                                      at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2260)
                                                                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2007)
                                                                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
                                                                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
                                                                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
                                                                      at android.view.Choreographer.doCallbacks(Choreographer.java:591)
                                                                      at android.view.Choreographer.doFrame(Choreographer.java:561)
                                                                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
                                                                      at android.os.Handler.handleCallback(Handler.java:730)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                    at android.os.Loope

I am currently unable to make this work. I have tried removing the placeholder image (a drawable .png file) from the src field in the XML, but still get the crash. Any ideas as to why this isn't working?


问:
Sending estimate HTTP Content-Length from Servlet etc
I often need to generate content dynamically from a servlet / restlet or whatever, and don't know the length ahead of time. If the client is a browser, the progress bar doesn't work properly, because I haven't set the Content-Length header. Is there any way of setting an estimated content length, so the progress bar works "more or less"?</p>

答:
While I wouldn't recommend doing it you can set the content-length to an estimate of what the content is, and you will get a progress bar.  As long as you can guarantee that your estimate is equal to or greater than the actual content this will generally work.  If your actual content is greater than the estimate than the content will be truncated to the specified content-length.

I tested this in Firefox, IE, and Chrome without issue.  The HTTP spec states that users agents MUST notify the user if the specified length doesn't match the actual length, but I have not observed this behavior with any browser I've tested.

I investigated this as an option but abandoned it due to the potential unforeseen conflicts for playing outside the bounds of the specification.


问:
How to remove object from array in local storage?
I have array like this:

```<code>var myMovie = [];
</code>```

And object like this:

```<code>var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
</code>```

I added object into local storage array via OnClick() on button.

```<code>$(document).ready(function() {
   $(".btn.btn-outline-success").click(function () {

    myMovie.push(first);

    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));
</code>```

After adding object into local storage, local storage looks like this:

```<code>[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]
</code>```

My question here is, how could I remove whole object via variable name? I want to remove object first from myMovie. Index position of object may be different each time.

```<code>[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]
</code>```

答:
Best would be a function, that not only changes the array but also stores it in localStorage.

To find the right index to remove, you could find the object with the right title:

    var myMovie=[] //JSON.parse(localStorage.getItem('myMovie')||"[]");

    function push(el){
    myMovie.push(el);
    //localStorage.setItem('myMovie', JSON.stringify(myMovie));
    }

    function remove(title){
     var i=myMovie.findIndex(movie=>movie.title===title);
     if(i!==-1){
       myMovie.splice(i,1);
       //localStorage.setItem('myMovie', JSON.stringify(myMovie));
     }
    }

    push({id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"});
    console.log(myMovie);
    remove("La La Land");
    console.log(myMovie);```

To make a running stackSnippet, i had to remove the localStorage functionality, it is commented out.

Body:
I have array like this:

var myMovie = [];

And object like this:

var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}

I added object into local storage array via OnClick() on button.

$(document).ready(function() {
   $(".btn.btn-outline-success").click(function () {

    myMovie.push(first);

    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));

After adding object into local storage, local storage looks like this:

[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]

My question here is, how could I remove whole object via variable name? I want to remove object first from myMovie. Index position of object may be different each time.

[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]

Body:
Best would be a function, that not only changes the array but also stores it in localStorage.

To find the right index to remove, you could find the object with the right title:

    var myMovie=[] //JSON.parse(localStorage.getItem('myMovie')||"[]");

    function push(el){
    myMovie.push(el);
    //localStorage.setItem('myMovie', JSON.stringify(myMovie));
    }

    function remove(title){
     var i=myMovie.findIndex(movie=>movie.title===title);
     if(i!==-1){
       myMovie.splice(i,1);
       //localStorage.setItem('myMovie', JSON.stringify(myMovie));
     }
    }

    push({id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"});
    console.log(myMovie);
    remove("La La Land");
    console.log(myMovie);

To make a running stackSnippet, i had to remove the localStorage functionality, it is commented out.


问:
variable indise html in wordpress plugin
I am doing my first every plugin to Wordpress.

How can i insert variable between HTML? I want to insert $today_output between divs?

Have tried all sort of things, but this is too confusing to me.

```<code>      $today_post_id = 82;
      $post_content = get_post($today_post_id);
      $today_output = wpautop( $post_content->post_content);

    $output = sprintf(
        '<div%2$s class="et_pb_code et_pb_module%3$s">
            want to add today_output variable here
        </div> <!-- .et_pb_today -->',
        $this->shortcode_content,
        ( '' !== $module_id ? sprintf( ' id="%1$s"', esc_attr( $module_id ) ) : '' ),
        ( '' !== $module_class ? sprintf( ' %1$s', esc_attr( $module_class ) ) : '' )
    );

    return  $output;
</code>```

Thanks,
Ville

答:
Maybe try it using string concatenation instead like this:</p>

```<code><?php

    $output = '<div class="' . $classname . '">' .
                '<div>' . $content . '</div>' .
              '</div>';

?>
</code>```

Body:
I am doing my first every plugin to Wordpress.

How can i insert variable between HTML? I want to insert $today_output between divs?

Have tried all sort of things, but this is too confusing to me.

      $today_post_id = 82;
      $post_content = get_post($today_post_id);
      $today_output = wpautop( $post_content->post_content);

    $output = sprintf(
        '

            want to add today_output variable here

 ',
        $this->shortcode_content,
        ( '' !== $module_id ? sprintf( ' id="%1$s"', esc_attr( $module_id ) ) : '' ),
        ( '' !== $module_class ? sprintf( ' %1$s', esc_attr( $module_class ) ) : '' )
    );

    return  $output;

Thanks,
Ville

Body:
Maybe try it using string concatenation instead like this:

<?php

    $output = '<div class="' . $classname . '">' .
                '<div>' . $content . '</div>' .
              '</div>';

?>


问:
Can i use alias in where clause?
```<code>SELECT sum(st.stock_in) - sum(st.stock_out) as'stock_qty',
p.product_name,p.product_limit
FROM stock  as st
join products as p
on p.product_id=st.product_id
where 'stock_qty' < 'p.product_limit'
GROUP BY st.product_id
</code>```

I Have two Tables Products and Stock.

Products Table: Product_id, Product_name and Product_limit

Stock: stock_id, Product_id, stock_in, stock_out

From above query i get all the records, but I want to get only those records who product limit is reached or below.

if product 1 has 50 product_limit and stock reached the 50 limit or below the 50 so get me those records.

Suggest me best solution.

答:
You cannot:

Use an alias in a where clause.

Use aggregation functions in the where clause.

Although comparing two strings is pretty much not ever recommended, it is allowed.

But, you want a having clause anyway, so the question in your title is irrelevant.  Try this:

```<code>select sum(st.stock_in) - sum(st.stock_out) as stock_qty,
       p.product_name, p.product_limit
from stock st join
     products p
     on p.product_id = st.product_id
group by p.product_name, p.product_limit
having stock_qty < p.product_limit  ;
</code>```

Note that I changed the group by to match the columns being selected in the select.  That is also a good practice.

Title: Can i use alias in where clause?

Body:
SELECT sum(st.stock_in) - sum(st.stock_out) as'stock_qty',
p.product_name,p.product_limit
FROM stock  as st
join products as p
on p.product_id=st.product_id
where 'stock_qty' < 'p.product_limit'
GROUP BY st.product_id

I Have two Tables Products and Stock.

Products Table: Product_id, Product_name and Product_limit

Stock: stock_id, Product_id, stock_in, stock_out

From above query i get all the records, but I want to get only those records who product limit is reached or below.

if product 1 has 50 product_limit and stock reached the 50 limit or below the 50 so get me those records.

Suggest me best solution.

Body:
You cannot:

Use an alias in a where clause.

Use aggregation functions in the where clause.

Although comparing two strings is pretty much not ever recommended, it is allowed.

But, you want a having clause anyway, so the question in your title is irrelevant.  Try this:

select sum(st.stock_in) - sum(st.stock_out) as stock_qty,
       p.product_name, p.product_limit
from stock st join
     products p
     on p.product_id = st.product_id
group by p.product_name, p.product_limit
having stock_qty < p.product_limit  ;

Note that I changed the group by to match the columns being selected in the select.  That is also a good practice.


问:
Python subprocess module equivalent for double-click in Windows
I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?

I tried the following line:

```<code>subprocess.call("C:/myfile.csv", shell=True)
</code>```

which throws an error saying:

The syntax of the command is
  incorrect.

  'C:\' is not recognized as
  an internal or external command,
  operable program or batch file.

How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.

答:
```<code>os.startfile(r'C:\myfile.csv')
</code>```

(Win32 only. For Mac, run a process with 'open filename'; on Linux/freedesktop-in-general, 'xdg-open filename'.)

Body:
I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?

I tried the following line:

subprocess.call("C:/myfile.csv", shell=True)

which throws an error saying:

The syntax of the command is
  incorrect.

  'C:\' is not recognized as
  an internal or external command,
  operable program or batch file.

How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.

Body:
os.startfile(r'C:\myfile.csv')

(Win32 only. For Mac, run a process with 'open filename'; on Linux/freedesktop-in-general, 'xdg-open filename'.)


问:
new ObjectInputStream blocks despite flushing OutputStream
At the moment i am trying to make some experiences with networking but i can't get past some point in the connection establishing process while using ObjectIn/OutputStreams.

I read in several Threads (like this one: Java Creating a new ObjectInputStream Blocks )on problems about the constructor of ObjectInputStream blocking and many suggest flushing the output first, so i came up with this:

```<code>out = new ObjectOutputStream(socket.getOutputStream());
String test = "test";
out.writeObject(test);
out.flush();
InputStream is = socket.getInputStream();
in = new ObjectInputStream(is);
</code>```

The blocking line is the last one.
Any suggestions why it is still failing to complete? Any help is appreciated.

答: The line of code you indicate will block until the peer has created an ObjectOutputStream on its socket, or written something else to the socket (which will cause a StreamCorruptedException).

Body:
At the moment i am trying to make some experiences with networking but i can't get past some point in the connection establishing process while using ObjectIn/OutputStreams.

I read in several Threads (like this one: Java Creating a new ObjectInputStream Blocks )on problems about the constructor of ObjectInputStream blocking and many suggest flushing the output first, so i came up with this:

out = new ObjectOutputStream(socket.getOutputStream());
String test = "test";
out.writeObject(test);
out.flush();
InputStream is = socket.getInputStream();
in = new ObjectInputStream(is);

The blocking line is the last one.
Any suggestions why it is still failing to complete? Any help is appreciated.


问:
Align Buttons with videoView using Constraint layout
I've been trying to make a similar login screen like Snapchat where the two buttons are at the bottom and theres a small video playing on the background layer. When I did everything the buttons do not position themselves where they are rather they go all over the emulator, and the video player is also misaligned.

The code for the login page is given below

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.test.Login">

<Button
    android:id="@+id/btnSignUp"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:text="SIGN UP"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#FFD54F"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-24dp"
    tools:layout_editor_absoluteY="397dp" />

<Button
    android:id="@+id/btnLogin"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:fontFamily="sans-serif"
    android:lineSpacingExtra="10sp"
    android:text="Login"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#80DEEA"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-15dp"
    tools:layout_editor_absoluteY="486dp" />

<VideoView
    android:id="@+id/bgVideoView"
    android:layout_width="394dp"
    android:layout_height="410dp"
    tools:layout_editor_absoluteX="-5dp"
    tools:layout_editor_absoluteY="0dp" />
</android.support.constraint.ConstraintLayout>
</code>```

What I want it to look like

Emulator Capture

答:
I think you should use a RelativeLayout instead.
See sample implementation below:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.test.Login">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <VideoView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btnSignUp"
            android:layout_width="414dp"
            android:layout_height="89dp"
            android:text="SIGN UP"
            android:textSize="40sp"
            android:textStyle="bold"
            android:background="#FFD54F"
            android:textColor="#FAFAFA" />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="414dp"
            android:layout_height="89dp"
            android:fontFamily="sans-serif"
            android:lineSpacingExtra="10sp"
            android:text="Login"
            android:textSize="40sp"
            android:textStyle="bold"
            android:background="#80DEEA"
            android:textColor="#FAFAFA"
            />
    </LinearLayout>

</RelativeLayout>
</code>```

Body:
I've been trying to make a similar login screen like Snapchat where the two buttons are at the bottom and theres a small video playing on the background layer. When I did everything the buttons do not position themselves where they are rather they go all over the emulator, and the video player is also misaligned.

The code for the login page is given below

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.test.Login">

<Button
    android:id="@+id/btnSignUp"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:text="SIGN UP"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#FFD54F"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-24dp"
    tools:layout_editor_absoluteY="397dp" />

<Button
    android:id="@+id/btnLogin"
    android:layout_width="414dp"
    android:layout_height="89dp"
    android:fontFamily="sans-serif"
    android:lineSpacingExtra="10sp"
    android:text="Login"
    android:textSize="40sp"
    android:textStyle="bold"
    android:background="#80DEEA"
    android:textColor="#FAFAFA"
    tools:layout_editor_absoluteX="-15dp"
    tools:layout_editor_absoluteY="486dp" />

<VideoView
    android:id="@+id/bgVideoView"
    android:layout_width="394dp"
    android:layout_height="410dp"
    tools:layout_editor_absoluteX="-5dp"
    tools:layout_editor_absoluteY="0dp" />
</android.support.constraint.ConstraintLayout>

What I want it to look like

Emulator Capture

Body:
I think you should use a RelativeLayout instead.
See sample implementation below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.test.Login">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <VideoView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btnSignUp"
            android:layout_width="414dp"
            android:layout_height="89dp"
            android:text="SIGN UP"
            android:textSize="40sp"
            android:textStyle="bold"
            android:background="#FFD54F"
            android:textColor="#FAFAFA" />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="414dp"
            android:layout_height="89dp"
            android:fontFamily="sans-serif"
            android:lineSpacingExtra="10sp"
            android:text="Login"
            android:textSize="40sp"
            android:textStyle="bold"
            android:background="#80DEEA"
            android:textColor="#FAFAFA"
            />
    </LinearLayout>

</RelativeLayout>


问:
Write string with newline to a text file c++
First I don't know if my question already asked but I searched a lot and didn't find a straight forward answer to this question yet.
I want to create a program to read a string wich has newlines \n in it and write the contents back to a text file on SD card with fprintf() function. My compiler is ARM_GCC and I'm using a specific library which only has fprintf() and fwrite() to write a string, so I preferred to only use these functions, but If you think there is another way I would appreciate if you say so.
I can easily use this program to write a string to file:

```<code>void sd_open(string sd_value)
{
  printf("Writing to Sd card...");
  FILE* fd = fopen("/sd/numbers.txt", "w+");
  fprintf(fd, "%s",sd_value.c_str());
  fclose(fd);
  printf("writed this value to sd: %s\r\n", sd_value.c_str());
  printf("Done\n");
}
</code>```

The problem is this code write the values of sd_value to one line only, I tought about using a for loop to search for newline in string and write line by line to a file but I dont know how to implement that.
Thanks.

EDIT...
suppose that sd_value is something like this:

```<code>string sd_value="Hello\nWelcome\nBye"
</code>```

which must be stored as the following to the text file:

```<code>Hello
Welcome
Bye
</code>```

Actually, sd_value is not handling in my program and a user types a value in another application and I receive it as a string. I can tell the user to use \n in his text box to enter a newline but don't know how to treat it as a newline in my code.

答:
There are differences between operating system which symbol(s) is chosen for EOL (end-of-line), e. g.

Windows: \r\n

Linux:       \n

MacOS:   \r

It means that if you have in you sd_value the EOL symbols from one operating system (e. g. MacOS) and you will use your command

```<code>fprintf(fd, "%s",sd_value.c_str());
</code>```

in other operating system (e. g. Windows), it is possible that this EOL symbol will not be interpreted as EOL in the target operating system and your whole string will be written in a single line.

Body:
First I don't know if my question already asked but I searched a lot and didn't find a straight forward answer to this question yet.
I want to create a program to read a string wich has newlines \n in it and write the contents back to a text file on SD card with fprintf() function. My compiler is ARM_GCC and I'm using a specific library which only has fprintf() and fwrite() to write a string, so I preferred to only use these functions, but If you think there is another way I would appreciate if you say so.
I can easily use this program to write a string to file:

void sd_open(string sd_value)
{
  printf("Writing to Sd card...");
  FILE* fd = fopen("/sd/numbers.txt", "w+");
  fprintf(fd, "%s",sd_value.c_str());
  fclose(fd);
  printf("writed this value to sd: %s\r\n", sd_value.c_str());
  printf("Done\n");
}

The problem is this code write the values of sd_value to one line only, I tought about using a for loop to search for newline in string and write line by line to a file but I dont know how to implement that.
Thanks.

EDIT...
suppose that sd_value is something like this:

string sd_value="Hello\nWelcome\nBye"

which must be stored as the following to the text file:

Hello
Welcome
Bye

Actually, sd_value is not handling in my program and a user types a value in another application and I receive it as a string. I can tell the user to use \n in his text box to enter a newline but don't know how to treat it as a newline in my code.

Body:
There are differences between operating system which symbol(s) is chosen for EOL (end-of-line), e. g.

Windows: \r\n

Linux:       \n

MacOS:   \r

It means that if you have in you sd_value the EOL symbols from one operating system (e. g. MacOS) and you will use your command

fprintf(fd, "%s",sd_value.c_str());

in other operating system (e. g. Windows), it is possible that this EOL symbol will not be interpreted as EOL in the target operating system and your whole string will be written in a single line.


问:
Delphi anonymous function passed to inlined function
I have stumbled upon an unexpected Delphi 2009 behaviour. After investigating a strange bug in my code, I managed to narrow down the issue and create a minimal example which I present below.

Of course, the following code prints the value 1:

```<code>program Example1;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer; inline;
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 1;
    end, 0));

end.
</code>```

Similarly, this program prints the value 2:

```<code>program Example2;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer; inline;
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 2;
    end, 0));

end.
</code>```

"Obviously", this third program prints the same value as the first one, namely, 1:

```<code>program Produce;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer; inline;
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 1;
    end, 0));

  fcn(function(const X: integer): integer
    begin
      result := 2;
    end, 0); // discard the output

end.
</code>```

However, the output isn't 1, but 2. It seems like the compiler uses the second anonymous function in the call to fcn in writeln.

To me this seems like a bug in the Delphi 2009 compiler, but it could also simply be my not understanding the more subtle details about anonymous functions in Delphi. What do you think?

答:
This certainly appears to be a bug, and according to the comments received on the question, this has been fixed in Delphi XE. Probably the simplest workaround is to skip asking for inlining if the compiler cannot handle it correctly:

```<code>program Solve;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer;
  {$IF CompilerVersion >= 22}inline;{$IFEND} {Warning: Horrible bug in Delphi 2009}
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 1;
    end, 0));

  fcn(function(const X: integer): integer
    begin
      result := 2;
    end, 0); // discard the output

end.
</code>```

In most cases, the loss of performance should be negligible in Delphi 2009, and you do request inlining in XE and later. Of course, if you don't think inlining is important at all, you can simply remove the request altogether.

Body:
I have stumbled upon an unexpected Delphi 2009 behaviour. After investigating a strange bug in my code, I managed to narrow down the issue and create a minimal example which I present below.

Of course, the following code prints the value 1:

program Example1;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer; inline;
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 1;
    end, 0));

end.

Similarly, this program prints the value 2:

program Example2;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer; inline;
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 2;
    end, 0));

end.

"Obviously", this third program prints the same value as the first one, namely, 1:

program Produce;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer; inline;
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 1;
    end, 0));

  fcn(function(const X: integer): integer
    begin
      result := 2;
    end, 0); // discard the output

end.

However, the output isn't 1, but 2. It seems like the compiler uses the second anonymous function in the call to fcn in writeln.

To me this seems like a bug in the Delphi 2009 compiler, but it could also simply be my not understanding the more subtle details about anonymous functions in Delphi. What do you think?

Body:
This certainly appears to be a bug, and according to the comments received on the question, this has been fixed in Delphi XE. Probably the simplest workaround is to skip asking for inlining if the compiler cannot handle it correctly:

program Solve;

{$APPTYPE CONSOLE}

type
  TIntFcn = reference to function(const X: integer): integer;

function fcn(AFunction: TIntFcn; a: integer): integer;
  {$IF CompilerVersion >= 22}inline;{$IFEND} {Warning: Horrible bug in Delphi 2009}
begin
  result := AFunction(a);
end;

begin

  writeln(fcn(function(const X: integer): integer
    begin
      result := 1;
    end, 0));

  fcn(function(const X: integer): integer
    begin
      result := 2;
    end, 0); // discard the output

end.

In most cases, the loss of performance should be negligible in Delphi 2009, and you do request inlining in XE and later. Of course, if you don't think inlining is important at all, you can simply remove the request altogether.


问:
Creating swift framework in AppCode
It is possible to create Swift frameworks (modules) like in XCode: [File] -> [New target] but using AppCode?
If I doing this using Xcode all working perfectly but if I try to do this in AppCode (in project settings) then I receive errors like: 'No such module [name]' after import. </p>

<p>What receipt is for this? </p>

答: This was not possible to do before and I still don´t think AppCode has support to add targets unfortunately. Could not find any information that they support this on their site either. So the answer will be no.

Title: Creating swift framework in AppCode

Body:
It is possible to create Swift frameworks (modules) like in XCode: [File] -> [New target] but using AppCode?
If I doing this using Xcode all working perfectly but if I try to do this in AppCode (in project settings) then I receive errors like: 'No such module [name]' after import.

What receipt is for this?


问:
program that determines if array is ascending, descending, or random(C language)
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

```<code>int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}
</code>```

i'd appreciate some guidance.

答:
Your code has some errors:

Breaking the array bounds

Incorrect use of = instead of ==

and seems over-complicated. Here is my solution.

```<code>#include <stdio.h>

int UpOrDown(int *arr, int size)
// return -1 (falling), 0 (unknown), +1 (rising)
{
    int rising = 0, falling = 0;
    for(int i = 1; i < size; i++) {
        if(arr[i] > arr[i-1]) {
            rising = 1;
        }
        else if(arr[i] < arr[i-1]) {
            falling = 1;
        }
    }
    return rising - falling;
}

int main(void)
{
    int arr1[1] = { 1 };
    int arr2[2] = { 1, 2 };
    int arr3[2] = { 2, 1 };
    int arr4[3] = { 1, 2, 1 };
    int arr5[3] = { 2, 1, 2 };

    printf("%d\n", UpOrDown(arr1, 1));
    printf("%d\n", UpOrDown(arr2, 2));
    printf("%d\n", UpOrDown(arr3, 2));
    printf("%d\n", UpOrDown(arr4, 3));
    printf("%d\n", UpOrDown(arr5, 3));

    return 0;
}
</code>```

Program output:

```
0
1
-1
0
0
```

Body:
i have to build a program that scans "size", then array in the size of "size".
returns 1 if ascending, -1 if descending, and 0 if neither.

so for I've came up with this, and its not working.

int UpOrDown(int *arr,int size)
{
int i,j,flag;
if(arr[0]<arr[1])// ascending or random
{
    flag=1;
    {
        for(i=1;i<size;i++)
            if(arr[i]>arr[i+1])
                flag=0;
    }
    if (flag=0) return 0;
    else return 1;
}
else //descending or random
{
    flag=-1;
        if(arr[0]>arr[1])
        {
            for(i=1;i<size;i++)
                if(arr[i]<arr[i+1])
                    flag=0;
        }
        if (flag=0) return 0;
        else return -1;
}

i'd appreciate some guidance.

Body:
Your code has some errors:

Breaking the array bounds

Incorrect use of = instead of ==

and seems over-complicated. Here is my solution.

#include <stdio.h>

int UpOrDown(int *arr, int size)
// return -1 (falling), 0 (unknown), +1 (rising)
{
    int rising = 0, falling = 0;
    for(int i = 1; i < size; i++) {
        if(arr[i] > arr[i-1]) {
            rising = 1;
        }
        else if(arr[i] < arr[i-1]) {
            falling = 1;
        }
    }
    return rising - falling;
}

int main(void)
{
    int arr1[1] = { 1 };
    int arr2[2] = { 1, 2 };
    int arr3[2] = { 2, 1 };
    int arr4[3] = { 1, 2, 1 };
    int arr5[3] = { 2, 1, 2 };

    printf("%d\n", UpOrDown(arr1, 1));
    printf("%d\n", UpOrDown(arr2, 2));
    printf("%d\n", UpOrDown(arr3, 2));
    printf("%d\n", UpOrDown(arr4, 3));
    printf("%d\n", UpOrDown(arr5, 3));

    return 0;
}

Program output:

0
1
-1
0
0


问:
VBA Cannot Subtract Days From Date
I’m trying to get the date 4 days older than now. Here is my code

```<code>Sub calcdate()
Dim nDateTime, oDateTime As Date
nDateTime = Format(Now, "YYMMDD")
oDateTime = Format(DateAdd("d", -4, nDateTime), "YYMMDD")
MsgBox ("Today is " & nDateTime & " And OldDate is " & oDateTime)
End Sub
</code>```

But output is ‘Today is 170604 And OldDate is 02-10-3734”

I Tried to do it without DateAdd

```<code>nDateTime = Format(Now, "YYMMDD")
oDateTime = nDateTime - 4
</code>```

*Output is ‘Today is 170604 And OldDate is 170604’

I tried these changes

```<code>nDateTime = Format(Now, "YYMMDD")
oDateTime = DateAdd("d", -4, nDateTime)
</code>```

*Output is ‘Today is 170604 And OldDate is 31-01-2367’

```<code>nDateTime = Format(Now, "YY-MM-DD")
oDateTime = Format(DateAdd("d", -4, nDateTime), "YY-MM-DD")
</code>```

*Output is ‘Today is 17-06-04 And OldDate is 04-06-2013’

So it seems here it is subtracting years although I put “d”.

last thing i tried:

```<code>nDateTime = Format(Now, "DD-MM-YY")
oDateTime = Format(DateAdd("d", -4, nDateTime), "DD-MM-YY")
</code>```

*Output is ‘Today is 04-06-17 And OldDate is 31-05-2017’
i want this date, in format 170531, also why did it give me 2017 while i choose format YY only?

答:
Format creates a string so you can no longer sensibly perform calculations on it. Do your formatting afterwards instead:

```<code>Dim nDateTime As Date, oDateTime As Date
nDateTime = Now
oDateTime = nDateTime - 4
MsgBox "Today is " & Format(nDateTime, "YYMMDD") & " And OldDate is " & Format(oDateTime, "YYMMDD")
</code>```

Also, you need to declare the variable type for each variable so, as I've done.

Title: VBA Cannot Subtract Days From Date

Body:
I’m trying to get the date 4 days older than now. Here is my code

Sub calcdate()
Dim nDateTime, oDateTime As Date
nDateTime = Format(Now, "YYMMDD")
oDateTime = Format(DateAdd("d", -4, nDateTime), "YYMMDD")
MsgBox ("Today is " & nDateTime & " And OldDate is " & oDateTime)
End Sub

But output is ‘Today is 170604 And OldDate is 02-10-3734”

I Tried to do it without DateAdd

nDateTime = Format(Now, "YYMMDD")
oDateTime = nDateTime - 4

*Output is ‘Today is 170604 And OldDate is 170604’

I tried these changes

nDateTime = Format(Now, "YYMMDD")
oDateTime = DateAdd("d", -4, nDateTime)

*Output is ‘Today is 170604 And OldDate is 31-01-2367’

nDateTime = Format(Now, "YY-MM-DD")
oDateTime = Format(DateAdd("d", -4, nDateTime), "YY-MM-DD")

*Output is ‘Today is 17-06-04 And OldDate is 04-06-2013’

So it seems here it is subtracting years although I put “d”.

last thing i tried:

nDateTime = Format(Now, "DD-MM-YY")
oDateTime = Format(DateAdd("d", -4, nDateTime), "DD-MM-YY")

*Output is ‘Today is 04-06-17 And OldDate is 31-05-2017’
i want this date, in format 170531, also why did it give me 2017 while i choose format YY only?

Body:
Format creates a string so you can no longer sensibly perform calculations on it. Do your formatting afterwards instead:

Dim nDateTime As Date, oDateTime As Date
nDateTime = Now
oDateTime = nDateTime - 4
MsgBox "Today is " & Format(nDateTime, "YYMMDD") & " And OldDate is " & Format(oDateTime, "YYMMDD")

Also, you need to declare the variable type for each variable so, as I've done.


问:
Regex not matching all hyphens
In the following example, only the third string is matched, even though there are hyphens in all three strings:

```<code>grep("-", c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015"))
[1] 3
</code>```

How can I match all three hyphens with grep?

答:
To match any type of dash use a \p{Pd} PCRE regex:

```<code>grep("\\p{Pd}", v1, perl=TRUE)
</code>```

The perl=TRUE forces R to parse the pattern with a PCRE regex engine and \p{Pd} matches any type of a Unicode dash/hyphen.

ContentLicense: CC BY-SA 4.0

Title: Regex not matching all hyphens

Body:
In the following example, only the third string is matched, even though there are hyphens in all three strings:

grep("-", c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015"))
[1] 3

How can I match all three hyphens with grep?

Body:
To match any type of dash use a \p{Pd} PCRE regex:

grep("\\p{Pd}", v1, perl=TRUE)

The perl=TRUE forces R to parse the pattern with a PCRE regex engine and \p{Pd} matches any type of a Unicode dash/hyphen.


问:
Flex center vertically and to right horizontally
I would like to achieve this: .right must be aligned vertically to center, but must be placed at the very end of the .wrap just like below.

Here is my code:

.wrap {
  display: flex;
  box-shadow: 0 0 0 1px black;
  height: 400px;
  align-items: center;
}
.wrap > * {
  box-shadow: 0 0 0 1px black;
  padding: 20px;
}
.right {
  align-self: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="left">1</div>
  <div class="nextToLeft">2</div>
  <div class="right">3</div>
</div></code>```

Codepen

Body:
I would like to achieve this: .right must be aligned vertically to center, but must be placed at the very end of the .wrap just like below.

Here is my code:

.wrap {
  display: flex;
  box-shadow: 0 0 0 1px black;
  height: 400px;
  align-items: center;
}
.wrap > * {
  box-shadow: 0 0 0 1px black;
  padding: 20px;
}
.right {
  align-self: flex-end;
}

1

2

3

Codepen

Body:
<html>
<head>

<style>

.wrap {
display: flex;
box-shadow: 0 0 0 1px black;
height: 400px;
align-items: center;
justify-content: space-between;
}

.wrap > * {
box-shadow: 0 0 0 1px black;
padding: 20px;
}

.nextToLeft {
margin-right: auto;
}

</style>
</head>

<body>
<div class="wrap">
<div class="left">1</div>
<div class="nextToLeft">2</div>
<div class="right">3</div>
</div>
</body>

</html>


问:
Adding a dropdown box in Datagridview
I have a Datagridview which is showing some records from DB. Now I want to add a dropdown menu in between the columns of this Datagridview.

How could I achieve that? My DGrid is bound in runtime so I am not initializing every column here!

Help?

答:
Use below code to add your Combobox Column at specific index of DataGridView</p>

```<code>        DataGridViewComboBoxColumn myCombo=new DataGridViewComboBoxColumn();
        myCombo.HeaderText = "My Combo";
        myCombo.Name = "myCombo";
        this.dataGridView1.Columns.Insert(n, myCombo); // n is index
</code>```

Title: Adding a dropdown box in Datagridview

Body:
Use below code to add your Combobox Column at specific index of DataGridView

        DataGridViewComboBoxColumn myCombo=new DataGridViewComboBoxColumn();
        myCombo.HeaderText = "My Combo";
        myCombo.Name = "myCombo";
        this.dataGridView1.Columns.Insert(n, myCombo); // n is index


问:
RTCPeerConnectionFactory.peerConnectionWithConfiguration causes IOS simulator crash
I'm experimenting with WebTRC IOS library.
I've tried https://cocoapods.org/pods/webrtc-framework and https://cocoapods.org/pods/WebRTC

Whenever I try to initialize a RTCPeerConnection and assign it to a local variable, the app crashes. with EXC_BAD_ACCESS error code.

Here is my code:

```<code>@interface WebRTCDelegate ()

@property (nonatomic, strong) SRWebSocket* webSocket;
@property(nonatomic) RTCPeerConnection *peerConnection;

@end

@implementation WebRTCDelegate
...
- (void)initRTCPeerConnection
{
    NSArray<RTCIceServer *> *iceServers = [NSArray arrayWithObjects:[[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.services.mozilla.com", nil]], [[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.l.google.com:19302", nil]] , nil];

    RTCConfiguration *config = [[RTCConfiguration alloc] init];
    [config setIceServers:iceServers];

    NSDictionary *mandatoryConstraints = @{
                                           @"OfferToReceiveAudio" : @"true",
                                           @"OfferToReceiveVideo" : @"true",
                                           };
    RTCMediaConstraints* constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints optionalConstraints:nil];

    RTCPeerConnectionFactory *pcFactory = [[RTCPeerConnectionFactory alloc] init];
    _peerConnection = [pcFactory peerConnectionWithConfiguration:config constraints:constraints delegate:self];
}

...

@end
</code>```

This is the error:

```<code>0x108895cbd <+115>: movq   0x38(%rax), %r13
0x108895cc1 <+119>: leaq   0x4f1891(%rip), %rsi      ; "OnMessage"
0x108895cc8 <+126>: leaq   0x4f1894(%rip), %rdx      ; "../../webrtc/base/rtccertificategenerator.cc:69"
</code>```

Is there anything wrong with my code?

Thanks!

答:
Try to keep factory object alive.</p>

```<code>@interface WebRTCDelegate ()

@property (nonatomic) SRWebSocket *webSocket;
@property (nonatomic) RTCPeerConnectionFactory *factory;
@property (nonatomic) RTCPeerConnection *peerConnection;

@end

@implementation WebRTCDelegate

...

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        factory = [[RTCPeerConnectionFactory alloc] init];
    }
    return self;
}

- (void)initRTCPeerConnection
{
    NSArray<RTCIceServer *> *iceServers = [NSArray arrayWithObjects:[[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.services.mozilla.com", nil]], [[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.l.google.com:19302", nil]] , nil];

    RTCConfiguration *config = [[RTCConfiguration alloc] init];
    [config setIceServers:iceServers];

    NSDictionary *mandatoryConstraints = @{
                                           @"OfferToReceiveAudio" : @"true",
                                           @"OfferToReceiveVideo" : @"true",
                                           };
    RTCMediaConstraints* constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints optionalConstraints:nil];
    _peerConnection = [_factory peerConnectionWithConfiguration:config constraints:constraints delegate:self];
}

...

@end
</code>```

Body:
I'm experimenting with WebTRC IOS library.
I've tried https://cocoapods.org/pods/webrtc-framework and https://cocoapods.org/pods/WebRTC

Whenever I try to initialize a RTCPeerConnection and assign it to a local variable, the app crashes. with EXC_BAD_ACCESS error code.

Here is my code:

@interface WebRTCDelegate ()

@property (nonatomic, strong) SRWebSocket* webSocket;
@property(nonatomic) RTCPeerConnection *peerConnection;

@end

@implementation WebRTCDelegate
...
- (void)initRTCPeerConnection
{
    NSArray<RTCIceServer *> *iceServers = [NSArray arrayWithObjects:[[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.services.mozilla.com", nil]], [[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.l.google.com:19302", nil]] , nil];

    RTCConfiguration *config = [[RTCConfiguration alloc] init];
    [config setIceServers:iceServers];

    NSDictionary *mandatoryConstraints = @{
                                           @"OfferToReceiveAudio" : @"true",
                                           @"OfferToReceiveVideo" : @"true",
                                           };
    RTCMediaConstraints* constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints optionalConstraints:nil];

    RTCPeerConnectionFactory *pcFactory = [[RTCPeerConnectionFactory alloc] init];
    _peerConnection = [pcFactory peerConnectionWithConfiguration:config constraints:constraints delegate:self];
}

...

@end

This is the error:

0x108895cbd <+115>: movq   0x38(%rax), %r13
0x108895cc1 <+119>: leaq   0x4f1891(%rip), %rsi      ; "OnMessage"
0x108895cc8 <+126>: leaq   0x4f1894(%rip), %rdx      ; "../../webrtc/base/rtccertificategenerator.cc:69"

Is there anything wrong with my code?

Thanks!

Body:
Try to keep factory object alive.

@interface WebRTCDelegate ()

@property (nonatomic) SRWebSocket *webSocket;
@property (nonatomic) RTCPeerConnectionFactory *factory;
@property (nonatomic) RTCPeerConnection *peerConnection;

@end

@implementation WebRTCDelegate

...

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        factory = [[RTCPeerConnectionFactory alloc] init];
    }
    return self;
}

- (void)initRTCPeerConnection
{
    NSArray<RTCIceServer *> *iceServers = [NSArray arrayWithObjects:[[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.services.mozilla.com", nil]], [[RTCIceServer alloc] initWithURLStrings:[NSArray arrayWithObjects:@"stun:stun.l.google.com:19302", nil]] , nil];

    RTCConfiguration *config = [[RTCConfiguration alloc] init];
    [config setIceServers:iceServers];

    NSDictionary *mandatoryConstraints = @{
                                           @"OfferToReceiveAudio" : @"true",
                                           @"OfferToReceiveVideo" : @"true",
                                           };
    RTCMediaConstraints* constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints optionalConstraints:nil];
    _peerConnection = [_factory peerConnectionWithConfiguration:config constraints:constraints delegate:self];
}

...

@end


问:
Is it possible to have multiple strings in one position of an array?
For example if my array is

```<code>var cars = ["Saab", "Volvo", "BMW"];
var answer = cars[1];
</code>```

and I create a function where if I type 'Volvo' it says 'Correct'. Is it possible to do something like this:

```<code>var cars = ["Saab", "Volvo|volkswagen", "BMW"];
</code>```

So when I type what is at position 1, I can type Volvo or volkswagen and it will say 'correct'? (But not both)

答:
Split the string using String#split method( with seperator | ) and check value using Array#indexOf method or Array#includes method.

```<code>// split the string by `|`  symbol
var answer = cars[1].split('|');

// check value by checking index in array
if(answer.indexOf(val) > -1){
   // do the rest here
}
</code>```

Body:
For example if my array is

var cars = ["Saab", "Volvo", "BMW"];
var answer = cars[1];

and I create a function where if I type 'Volvo' it says 'Correct'. Is it possible to do something like this:

var cars = ["Saab", "Volvo|volkswagen", "BMW"];

So when I type what is at position 1, I can type Volvo or volkswagen and it will say 'correct'? (But not both)

Body:
Split the string using String#split method( with seperator | ) and check value using Array#indexOf method or Array#includes method.

// split the string by `|`  symbol
var answer = cars[1].split('|');

// check value by checking index in array
if(answer.indexOf(val) > -1){
   // do the rest here
}


答:
because Format(Now, "YYMMDD") result  is string</p>

```<code>Dim myDate As Date
Dim nDatetime As String, oDateTime As String

myDate = Now
nDatetime = Format(myDate, "yymmdd")
oDateTime = Format(DateAdd("d", -4, myDate), "YY-MM-DD")
</code>```

Title: VBA Cannot Subtract Days From Date

Body:
because Format(Now, "YYMMDD") result  is string

Dim myDate As Date
Dim nDatetime As String, oDateTime As String

myDate = Now
nDatetime = Format(myDate, "yymmdd")
oDateTime = Format(DateAdd("d", -4, myDate), "YY-MM-DD")


问:
How to @import external SCSS properly with webpack and Vue.js?
As in Material Component Web's example, I want to be able to import SCSS from my node_modules like this:

```<code>@import '@material/elevation/mdc-elevation';
</code>```

However, I'm getting this error message when trying to run the webpack build:

```<code>File to import not found or unreadable: @material/elevation/mdc-elevation.
</code>```

@import './~/@material/elevation/mdc-elevation.scss'; doesn't work either.

I'm pretty sure the issue is somewhere in my webpack config, but I can't figure out where.

What did they do in Material Components Web's Vue.js example in order to make it work?

Here's my npm-debug.log in case you need it.
And here's the corresponding Git repository: sk22/spg-tinf-sem03/proj01

Thanks in advance!

Edit: I want to be able to import the scss files, not the compiled css.

答:
EDIT: Webpack has a section on sass-loader now: https://webpack.js.org/loaders/sass-loader/ also mentioning includepaths.

I had the same issue with @material and Vue. I managed to resolve the problem without adjusting the use property directly.

Solution

Step 1: First create a default Vue 2.1 project using the CLI.
  Your file structure will have a ./build directory.

Step 2: Open the file 'utils' you will see a cssLoaders() function which returns an object/map for the languages vue-loader supports.

You will see both sass and scss in that map.

Step 3: Change the values of sass and scss to:

```<code>  sass:    generateLoaders('sass', {
    indentedSyntax: true,
    includePaths:   [path.resolve(__dirname, '../node_modules')]
  }),
    scss:    generateLoaders('sass', {
  includePaths: [path.resolve(__dirname, '../node_modules')]
}),
</code>```

Step 4: Go to the .vue file you're using and change the lang attribute in your

Body:
As in Material Component Web's example, I want to be able to import SCSS from my node_modules like this:

@import '@material/elevation/mdc-elevation';

However, I'm getting this error message when trying to run the webpack build:

File to import not found or unreadable: @material/elevation/mdc-elevation.

@import './~/@material/elevation/mdc-elevation.scss'; doesn't work either.

I'm pretty sure the issue is somewhere in my webpack config, but I can't figure out where.

What did they do in Material Components Web's Vue.js example in order to make it work?

Here's my npm-debug.log in case you need it.
And here's the corresponding Git repository: sk22/spg-tinf-sem03/proj01

Thanks in advance!

Edit: I want to be able to import the scss files, not the compiled css.

Body:
EDIT: Webpack has a section on sass-loader now: https://webpack.js.org/loaders/sass-loader/ also mentioning includepaths.

I had the same issue with @material and Vue. I managed to resolve the problem without adjusting the use property directly.

Solution

Step 1: First create a default Vue 2.1 project using the CLI.
  Your file structure will have a ./build directory.

Step 2: Open the file 'utils' you will see a cssLoaders() function which returns an object/map for the languages vue-loader supports.

You will see both sass and scss in that map.

Step 3: Change the values of sass and scss to:

  sass:    generateLoaders('sass', {
    indentedSyntax: true,
    includePaths:   [path.resolve(__dirname, '../node_modules')]
  }),
    scss:    generateLoaders('sass', {
  includePaths: [path.resolve(__dirname, '../node_modules')]
}),

Step 4: Go to the .vue file you're using and change the lang attribute in your <style> element to either sass or scss.

Step 5: After you've done that go to the terminal/console and install sass-loader with:

npm install sass-loader node-sass webpack --save-dev

Step 6: Then run npm run dev and it should work.

Why does this work?

Libraries

I dug around a bit and it turns out sass-loader uses node-sass which has some options such asincludePaths one mentioned by @22samuelk. IncludePaths tells node-sass or rather the underlying library LibSass to include sass files from that directory/path.

Vue

Sass-loader options

By default Vue expects your assets to be in your projects src/assets folder (correct me if I'm wrong). You can however use ~ to indicat you want to start at your projects root which would look like `~/node_modules/@material/smth/mdc-smth.scss.

Now if you want your sass-loader to use something other than those options you need to explicitly tell them.

Hence path.resolve(__dirname, '../node_modules' since the utils file is in ./build and you need to use an absolute path for sass-loader to understand where to look.

Vue-loader config

This is not really specific to the question but the vue-loader config defined in vue-loader.conf.js works as follows:

It uses the map returned by cssLoaders() to build the loaders expected by webpack.
  The returned map ({key:value}) is then used by providing key as a file extension used in test: for a loader object. The value is used as the loader  object.
  Which would like like this:

{
  test: /\.(key)$/,
    use: [
  {
    loader: '//ld//-loader',
    options: {
      /*Options passed to generateLoaders('//ld//', options)*/
    },
  },
],
}

Where key is the file extention. In this case that would be either sass or scss. And //ld//is the loader you which to use. Which is shown in Step 3 as 'sass'.

Hopefully this clears up some stuff. Took me a while because I just started using Vue.


问:
How to check when camera autofocus is done android?
I would like to know if there is a way to know when the autofocus is done?

I have a app that doing some  image processing on video. My first thing that I need to do is to turn on the flash and the autofocus, my problem is that I don't know if the autofocus is done or not (I need to know it programmatically) so I can start all the image processing only after the auto focus is done.

This is how I configure the camera settings :

```<code>@Override
public void surfaceCreated(SurfaceHolder arg0) {
 try {
    camera = Camera.open();

    parameters = camera.getParameters();
    parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
    parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
    camera.setParameters(parameters);
    camera.setPreviewDisplay(holder);
    camera.startPreview();

    recorder = new MediaRecorder();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
</code>```

I just want to be clear, everything is working good, I just want to know when exactly the autofocus is done.

Thanks!

答:
The "autoFocus" method in the (now deprecated) Camera class just triggers a single auto focus event and the callback only relates to that single event. It will not be triggered again for future auto focus events.

To know when auto focus starts and stops each time you need to call the setAutoFocusMoveCallback method instead and pass in your AutoFocusMoveCallback instance. The "start" parameter in the callback is true when auto focus begins and false when auto focus completes.

```<code>camera.setAutoFocusMoveCallback(new AutoFocusMoveCallback() {
    @Override
    public void onAutoFocusMoving(boolean start, Camera camera) {
        // Do whatever you need to respond to auto focus starting and stopping
    }
});
</code>```

Body:
I would like to know if there is a way to know when the autofocus is done?

I have a app that doing some  image processing on video. My first thing that I need to do is to turn on the flash and the autofocus, my problem is that I don't know if the autofocus is done or not (I need to know it programmatically) so I can start all the image processing only after the auto focus is done.

This is how I configure the camera settings :

@Override
public void surfaceCreated(SurfaceHolder arg0) {
 try {
    camera = Camera.open();

    parameters = camera.getParameters();
    parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
    parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
    camera.setParameters(parameters);
    camera.setPreviewDisplay(holder);
    camera.startPreview();

    recorder = new MediaRecorder();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

I just want to be clear, everything is working good, I just want to know when exactly the autofocus is done.

Thanks!

Body:
The "autoFocus" method in the (now deprecated) Camera class just triggers a single auto focus event and the callback only relates to that single event. It will not be triggered again for future auto focus events.

To know when auto focus starts and stops each time you need to call the setAutoFocusMoveCallback method instead and pass in your AutoFocusMoveCallback instance. The "start" parameter in the callback is true when auto focus begins and false when auto focus completes.

camera.setAutoFocusMoveCallback(new AutoFocusMoveCallback() {
    @Override
    public void onAutoFocusMoving(boolean start, Camera camera) {
        // Do whatever you need to respond to auto focus starting and stopping
    }
});


问:
Is there any way to perform a batched request in Asp.net core?
We have an API built using ASP.Net Core, and we would like to consolidate multiple requests into one HTTP requests for performance reasons.

In previous versions of asp.net you could allow for batch requests via the DefaultHttpBatchHandler.

Unfortunately, no such thing seems to exist in Asp.net Core.

Is anyone aware of any way to do HTTP batches in core?

答:
After doing my research on the matter, this seems fairly simple to implement. However, I think it should be supported by the official asp.net core team.

To me it seems like it requires a middleware creating multiple RouteContext according to the inputted text, and just invoking their Handlers - and modifying their response. it might be a little bit more difficult, because it would require support for multiple responses for an HttpContext (as far as I know it seems like it will be shared across Controllers).

Anyway, There is an open issue in the official repository that I have risen from the dead, hoping it will move things along. I might work on an implementation in the future if there are no changes soon.

Update

Seems like the asp.net team responded to the request, and created a new issue that is set to 2.0 milestone, so I am guessing this feature will be available during asp.net 2.0 release.


答:
You can split element at | and use includes to check value.

var cars = ["Saab", "Volvo|volkswagen", "BMW"];

function check(value, pos) {
  return cars[pos].split('|').includes(value)
}

console.log(check('Volvo', 1))
console.log(check('volkswagen', 1))
console.log(check('Saab', 0))```

Title: Is it possible to have multiple strings in one position of an array?


问:
How to show current object inside template used with class based FormView
Having this urls.py snippet:

```<code>url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required(
    StorageItemTransactionAddView.as_view()),
    name='storage_item_transaction'),
</code>```

I'm wondering what is the correct way to make the object beihind pk available inside a template to show it e.g. with

```<code><h1>{{ object.name }}</h1>
</code>```

I tried to configure a query set

```<code>...
queryset = StorageItem.objects.get
    pk=get_from_kwargs()['object'])

def get_form_kwargs(self):
    kwargs = super(ItemCreate, self).get_form_kwargs()
    kwargs.update({
        'object' : self.kwargs['pk']
    })
    return kwargs
</code>```

but the method is not access able at this point. So I'm wondering how could one do it the correct way? All I need would be something like

```<code>self.object = StorageItem.objects.get(pk='my pk')
</code>```

答:
Why not simply do the following:

```<code>class StorageItemTransactionAddView(View):

    def post(self, request, pk):
        storage_item = StorageItem.objects.get(pk=pk)
        ...
        return render(request, 'myapp/index.html', {'object': storage_item})
</code>```

Now in your template, you can do the following:

```<code><h1>{{ object.name }}</h1>
</code>```

Hope it helps

Body:
Having this urls.py snippet:

url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required(
    StorageItemTransactionAddView.as_view()),
    name='storage_item_transaction'),

I'm wondering what is the correct way to make the object beihind pk available inside a template to show it e.g. with

{{ object.name }}

I tried to configure a query set

...
queryset = StorageItem.objects.get
    pk=get_from_kwargs()['object'])

def get_form_kwargs(self):
    kwargs = super(ItemCreate, self).get_form_kwargs()
    kwargs.update({
        'object' : self.kwargs['pk']
    })
    return kwargs

but the method is not access able at this point. So I'm wondering how could one do it the correct way? All I need would be something like

self.object = StorageItem.objects.get(pk='my pk')

Body:
Why not simply do the following:

class StorageItemTransactionAddView(View):

    def post(self, request, pk):
        storage_item = StorageItem.objects.get(pk=pk)
        ...
        return render(request, 'myapp/index.html', {'object': storage_item})

Now in your template, you can do the following:

<h1>{{ object.name }}</h1>

Hope it helps


问:
Correct way to override default template in Sonata
I'm a bit confused as I've seen a few varying methods posted online.

I have a bundle created with easyextends in src/Application/Sonata/SonataMediaBundle, which extends the SonataMediaBundle in the vendors.

The default template displays

```<code>   This is the gallery index template. Feel free to override it.
   This file can be found in SonataMediaBundle:Gallery:index.html.twig.
</code>```

so I've added src/Application/Sonata/SonataMediaBundle/Resources/views/Gallery/index.html.twig in my bundle

and this works and overrides, so why all these various other ways like How to override Sonata Media Bundle templates?

答:
You are using the correct way. To quote from symfonys How to Override Templates from Third-Party Bundles

To override the bundle template, just copy index.html.twig template from the bundle to app/Resources/AcmeBlogBundle/views/Blog/index.html.twig (the app/Resources/AcmeBlogBundle directory won't exist, so you'll need to create it). You're now free to customize the template.

And for more detailed/ complex overriding behaviour have a look at How to Use Bundle Inheritance to Override Parts of a Bundle

I wouldn't worry to much about other solutions unless you are not able to get the results you require using this method but I cant think of one.

Body:
I'm a bit confused as I've seen a few varying methods posted online.

I have a bundle created with easyextends in src/Application/Sonata/SonataMediaBundle, which extends the SonataMediaBundle in the vendors.

The default template displays

   This is the gallery index template. Feel free to override it.
   This file can be found in SonataMediaBundle:Gallery:index.html.twig.

so I've added src/Application/Sonata/SonataMediaBundle/Resources/views/Gallery/index.html.twig in my bundle

and this works and overrides, so why all these various other ways like How to override Sonata Media Bundle templates?


问:
how to resume wget mirroring website?
I use wget to download an entire website.

I used the follwing command (in windows 7):

```<code>wget ^
 --recursive ^
 -A "*thread*, *label*" ^
 --no-clobber ^
 --page-requisites ^
 --html-extension ^
 --domains example.com ^
 --random-wait ^
 --no-parent ^
 --background ^
 --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ^
     http://example.com/
</code>```

After 2 days my little brother restarted the PC

so I tried to resume the stopped process

I added the following to the command

```<code>--continue ^
</code>```

so the code looks like

```<code>wget ^
     --recursive ^
     -A "*thread*, *label*" ^
     --no-clobber ^
     --page-requisites ^
     --html-extension ^
     --domains example.com ^
     --random-wait ^
     --no-parent ^
     --background ^
     --continue ^
     --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ^
         http://example.com/
</code>```

unfortunately it started a new job it downloads the same files again and write a new log file named

```<code>wget-log.1
</code>```

Is there anyway to resume mirroring site with wget or do have I to start the whole thing over again?

答:
Try -nc option.  It checks everything once again, but doesn't download it.

I'm using this code to download one website:
    wget -r -t1 domain.com -o log

I've stopped the process, I wanted to resume it, so I changed the code:
    wget -nc -r -t1 domain.com -o log

In the logs there is  something like this:
    File .... already there; not retrieving. etc.

I checked logs before this and it seems that after maybe 5 minutes of this kind of checking it begins to download new files.

I'm using this manual for wget: http://www.linux.net.pl/~wkotwica/doc/wget/wget_8.html

Title: how to resume wget mirroring website?

Body:
I use wget to download an entire website.

I used the follwing command (in windows 7):

wget ^
 --recursive ^
 -A "*thread*, *label*" ^
 --no-clobber ^
 --page-requisites ^
 --html-extension ^
 --domains example.com ^
 --random-wait ^
 --no-parent ^
 --background ^
 --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ^
     http://example.com/

After 2 days my little brother restarted the PC

so I tried to resume the stopped process

I added the following to the command

--continue ^

so the code looks like

wget ^
     --recursive ^
     -A "*thread*, *label*" ^
     --no-clobber ^
     --page-requisites ^
     --html-extension ^
     --domains example.com ^
     --random-wait ^
     --no-parent ^
     --background ^
     --continue ^
     --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ^
         http://example.com/

unfortunately it started a new job it downloads the same files again and write a new log file named

wget-log.1

Is there anyway to resume mirroring site with wget or do have I to start the whole thing over again?