问:
UL act like an OL => including START value
It not usual to do so, but we are getting an unordered list from an external tool and have to deal with it. This is why I am asking here.

I need the ul to behave like an ol.
It's easy to say, list-style-type="decimal".
But I would need to have the START parameter as well.

If that is not possible to have in an easy way I would have to build something completly independant, aka

```<code><li>
  <span>1.</span>
  <p>Text</p>
</li>
</code>```

I would really like to avoid that, so my question is:

Is it possible to use an ul as an ol including the start value?

```<code><ul start="17">
</code>```

答:
You can use CSS Counters and define a starting point in the counter-reset` CSS.

ul.my-list {
  list-style: none;
  counter-reset: item 17;
  /* number should always be 1 LESS than your required starting number */
}

.my-list li::before {
  counter-increment: item;
  content: counters(item, ".") ". ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="my-list">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul></code>```

It should be easy to handle for a user on the other side of the desk. He should have a tool where he defines e.g. <list start="17"> That's it. He should not handle with css or whatever.

That being the case, this Q&A may offer a solution..the user merely has to apply a style="--start-xx"; inline style and CSS Custom properties can handle the rest.

ul.my-list {
  list-style: none;
  counter-reset: item calc(var(--start) - 1)
}

.my-list li::before {
  counter-increment: item;
  content: counters(item, ".") ". ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="my-list" style="--start:21">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul class="my-list" style="--start:10">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul></code>```

Body:
It not usual to do so, but we are getting an unordered list from an external tool and have to deal with it. This is why I am asking here.

I need the ul to behave like an ol.
It's easy to say, list-style-type="decimal".
But I would need to have the START parameter as well.

If that is not possible to have in an easy way I would have to build something completly independant, aka

  1.

Text

I would really like to avoid that, so my question is:

Is it possible to use an ul as an ol including the start value?

Body:
You can use CSS Counters and define a starting point in the counter-reset` CSS.

ul.my-list {
  list-style: none;
  counter-reset: item 17;
  /* number should always be 1 LESS than your required starting number */
}

.my-list li::before {
  counter-increment: item;
  content: counters(item, ".") ". ";
}

<ul class="my-list">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

It should be easy to handle for a user on the other side of the desk. He should have a tool where he defines e.g. <list start="17"> That's it. He should not handle with css or whatever.

That being the case, this Q&A may offer a solution..the user merely has to apply a style="--start-xx"; inline style and CSS Custom properties can handle the rest.

ul.my-list {
  list-style: none;
  counter-reset: item calc(var(--start) - 1)
}

.my-list li::before {
  counter-increment: item;
  content: counters(item, ".") ". ";
}

<ul class="my-list" style="--start:21">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul class="my-list" style="--start:10">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>


来源: stackexchange

问:
|| operator in c++ for vector norm
I'm trying to write a own "library" for vectors where I can define operators such as "*" for scalar multiplication and "+" for vector addition etc. I think I got most of it right, but now I'm trying to define a operator for the l2 norm of a vector using "| |", meaning this:

```<code>Vector v;
// let v be (3, 4)
double a = |v|;
// then a should be 5 (sqrt(16 + 9))
</code>```

but then I get this error:

```<code>main.cpp:11:17: error: no match for 'operator|' (operand types are 'Vector' and 'int')
     double a = v|2|;
               ~^~
main.cpp:11:20: error: expected primary-expression before ';' token
     double a = v|2|;
</code>```

Now here I'm struggling to define the operator ||...

I tried doing something like this:

```<code>double Vector::operator||(int){
//  here I used the scalar product to calculate the norm
    double d = (*this) * (*this);
    return sqrt(d);
}
</code>```

or I tried defining it as friend function with two parameters. I think the main problem is what parameters I have to give the operator because it always requiers two (or one if its a member function). I just cant figure out a way to do it...

Has anyone of you an idea how solve this or is there no solution for this and I have to use a normal function?

Thanks in advance :)

答: Regardless of how much you abuse C++'s syntax, I'm afraid there's no way to turn double a = |v|; into valid code, because | can only be a binary infix operator.

ContentLicense: CC BY-SA 4.0

Title: || operator in c++ for vector norm

Body:
I'm trying to write a own "library" for vectors where I can define operators such as "*" for scalar multiplication and "+" for vector addition etc. I think I got most of it right, but now I'm trying to define a operator for the l2 norm of a vector using "| |", meaning this:

Vector v;
// let v be (3, 4)
double a = |v|;
// then a should be 5 (sqrt(16 + 9))

but then I get this error:

main.cpp:11:17: error: no match for 'operator|' (operand types are 'Vector' and 'int')
     double a = v|2|;
               ~^~
main.cpp:11:20: error: expected primary-expression before ';' token
     double a = v|2|;

Now here I'm struggling to define the operator ||...

I tried doing something like this:

double Vector::operator||(int){
//  here I used the scalar product to calculate the norm
    double d = (*this) * (*this);
    return sqrt(d);
}

or I tried defining it as friend function with two parameters. I think the main problem is what parameters I have to give the operator because it always requiers two (or one if its a member function). I just cant figure out a way to do it...

Has anyone of you an idea how solve this or is there no solution for this and I have to use a normal function?

Thanks in advance :)


问:
File pattern for Publish Pipeline Artifact in Azure DevOps
Recently just built an Azure Pipeline where in one stage there are different zip files in the artifact staging directory. What I'm trying to achieve is publish to the drop folder all the zip files from the staging folder with PublishPipelineArtifact task.

I have 2 archived zip files in artifact staging directory:

$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip

$(Build.ArtifactStagingDirectory)/cli_scripts_$(Build.BuildId).zip

In my azure-pipelines.yml file please find the publish task:

```<code>- task: PublishPipelineArtifact@0
  displayName: 'Publish pipeline artifacts'
  inputs:
    targetPath: $(Build.ArtifactStagingDirectory)/**
</code>```

This gives the following error:

[error] Path does not exist: d:\a\1\a**

I have already tried with the following as well but none of them working:

```<code>$(Build.ArtifactStagingDirectory)/**
$(Build.ArtifactStagingDirectory)/**/*.zip
$(Build.ArtifactStagingDirectory)/*.zip
</code>```

Question:

What is the pattern for targetPath to move all the zip files from that folder?

Any help is appreciated!

答:
What finally resolved the issue is including a pattern with archiveFilePatterns in the task and not combining with the targetPath as I originally tried.

The solution which worked well is the following:

```<code>- task: PublishPipelineArtifact@0
  displayName: 'Publish pipeline artifacts'
  inputs:
    targetPath: $(Build.ArtifactStagingDirectory)/
    archiveFilePatterns: '**/*.zip'
</code>```

The official documentation does not really states this but it was giving the idea using the pattern attribute: Publish and download artifacts

I hope that helps someone in the future.

Body:
Recently just built an Azure Pipeline where in one stage there are different zip files in the artifact staging directory. What I'm trying to achieve is publish to the drop folder all the zip files from the staging folder with PublishPipelineArtifact task.

I have 2 archived zip files in artifact staging directory:

$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip

$(Build.ArtifactStagingDirectory)/cli_scripts_$(Build.BuildId).zip

In my azure-pipelines.yml file please find the publish task:

- task: PublishPipelineArtifact@0
  displayName: 'Publish pipeline artifacts'
  inputs:
    targetPath: $(Build.ArtifactStagingDirectory)/**

This gives the following error:

[error] Path does not exist: d:\a\1\a**

I have already tried with the following as well but none of them working:

$(Build.ArtifactStagingDirectory)/**
$(Build.ArtifactStagingDirectory)/**/*.zip
$(Build.ArtifactStagingDirectory)/*.zip

Question:

What is the pattern for targetPath to move all the zip files from that folder?

Any help is appreciated!

Body:
What finally resolved the issue is including a pattern with archiveFilePatterns in the task and not combining with the targetPath as I originally tried.

The solution which worked well is the following:

- task: PublishPipelineArtifact@0
  displayName: 'Publish pipeline artifacts'
  inputs:
    targetPath: $(Build.ArtifactStagingDirectory)/
    archiveFilePatterns: '**/*.zip'

The official documentation does not really states this but it was giving the idea using the pattern attribute: Publish and download artifacts

I hope that helps someone in the future.


问:
nashorn call java from script 4 hour I did not expect to waste
This works:

```<code>interpreter.eval("var myCls = Java.type('java.io.File');\n"+"myCls.createTempFile('nashorn','.tmp');", sc1 );
</code>```

But this does not:

```<code>interpreter.eval("var myCls = Java.type('mypkg.MyClass');\n"+"myCls.play('misty');", sc1 );
</code>```

Why?

P

答:
Okay after 6 or so hours of faffing, it turns out that
not only does the method need to be public and static, the
class itself needs to be public.

More relevant error messages would be nice.

Body:
This works:

interpreter.eval("var myCls = Java.type('java.io.File');\n"+"myCls.createTempFile('nashorn','.tmp');", sc1 );

But this does not:

interpreter.eval("var myCls = Java.type('mypkg.MyClass');\n"+"myCls.play('misty');", sc1 );

Why?

P


问:
How to fix "AttributeError: module 'tensorflow' has no attribute 'get_default_graph'"?
I am trying to run some code to create an LSTM model but i get an error:

AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

My code is as follows:

```<code>from keras.models import Sequential

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

I have found someone else with a similar problem and they updated tensorflow and it works; but mine is up to date and still does not work. I am new to using keras and machine learning so I apologise if this is something silly!

答:
To solve the problem I used the code below:</p>
```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy
</code>```

Body:
I am trying to run some code to create an LSTM model but i get an error:

AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

My code is as follows:

from keras.models import Sequential

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

I have found someone else with a similar problem and they updated tensorflow and it works; but mine is up to date and still does not work. I am new to using keras and machine learning so I apologise if this is something silly!

Body:
To solve the problem I used the code below:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy


问:
Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P<pk>\\d+)/delete/$']
I am getting:

django.urls.exceptions.NoReverseMatch: Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P\d+)/delete/$']

and in my console it is showing:

- Failed to load resource: the server responded with a status of 500 (Internal Server Error)

My views.py

```<code>def company_delete(request,pk):
    data = dict()
    company = get_object_or_404(Company,pk=pk)
    if request.method == "POST":
        company.delete()
        data['form_is_valid'] = True
        companies = Company.objects.all()
        data['company_list'] = render_to_string('company_list_2.html',{'companies': companies})
    else:
        context = {'company': company}
        data['html_form'] = render_to_string('company_delete.html',context,request=request)

    return JsonResponse(data)
</code>```

my urls.py

```<code>urlpatterns = [
    url(r'^company/$', views.company_list, name='company_list'),
    url(r'^company/create/$', views.company_create, name='company_create'),
    url(r'^company/(?P<pk>\d+)/update/$', views.company_update, name='company_update'),
    url(r'^company/(?P<pk>\d+)/delete/$', views.company_delete, name='company_delete'),
]
</code>```

my company_list_2.html

```<code>{% for c in companies %}
  <tr>
    <td>{{ c.name }}</td>
    <td>{{ c.description }}</td>
    <td>{{ c.website }}</td>
    <td>{{ c.address }}</td>
    <td>{{ c.phone }}</td>
    <td>{{ c.email }}</td>
    <td>{{ c.contact }}</td>
    <td>
      <button class="btn btn-warning show-form-update" data-url="{% url 'company_update' c.pk %}">
        <span class="glyphicon glyphicon-pencil"></span>
        Edit
      </button>
    </td>
    <td>
      <button class="btn btn-danger show-form-delete" data-url="{% url 'company_delete' c.pk %}">
        <span class="glyphicon glyphicon-trash"></span>
        Delete
      </button>
    </td>
  </tr>
{% empty %}
  <tr>
    <td colspan="7" class="text-center bg-warning">No Company</td>
  </tr>
{% endfor %}
</code>```

my company_delete.html

```<code>{% load crispy_forms_tags %}
<form method="post" data-url="{% url 'company_delete' c.pk %}" class="delete-form">
    {% csrf_token %}
    <div class="modal-header">
        <h3 class="modal-title" >Delete Company</h3>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
        </button>
    </div>
    <div class="modal-body">
        <p class="lead"> Are you sure you want to delete this company <strong>{{ c.name }}</strong></p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-danger">Delete Company</button>
    </div>
</form>
</code>```

答:
As say @Ivan Starostin just put company.pk instance c.pk in your url form

```<code><form method="post" data-url="{% url 'company_delete' company.pk %}" class="delete-form">
    ...
</form>
</code>```

Body:
I am getting:

django.urls.exceptions.NoReverseMatch: Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P\d+)/delete/$']

and in my console it is showing:

- Failed to load resource: the server responded with a status of 500 (Internal Server Error)

My views.py

def company_delete(request,pk):
    data = dict()
    company = get_object_or_404(Company,pk=pk)
    if request.method == "POST":
        company.delete()
        data['form_is_valid'] = True
        companies = Company.objects.all()
        data['company_list'] = render_to_string('company_list_2.html',{'companies': companies})
    else:
        context = {'company': company}
        data['html_form'] = render_to_string('company_delete.html',context,request=request)

    return JsonResponse(data)

my urls.py

urlpatterns = [
    url(r'^company/$', views.company_list, name='company_list'),
    url(r'^company/create/$', views.company_create, name='company_create'),
    url(r'^company/(?P<pk>\d+)/update/$', views.company_update, name='company_update'),
    url(r'^company/(?P<pk>\d+)/delete/$', views.company_delete, name='company_delete'),
]

my company_list_2.html

{% for c in companies %}

    {{ c.name }}
    {{ c.description }}
    {{ c.website }}
    {{ c.address }}
    {{ c.phone }}
    {{ c.email }}
    {{ c.contact }}

      <button class="btn btn-warning show-form-update" data-url="{% url 'company_update' c.pk %}">

        Edit
      </button>

      <button class="btn btn-danger show-form-delete" data-url="{% url 'company_delete' c.pk %}">

        Delete
      </button>

{% empty %}

    No Company

{% endfor %}

my company_delete.html

{% load crispy_forms_tags %}
<form method="post" data-url="{% url 'company_delete' c.pk %}" class="delete-form">
    {% csrf_token %}

Delete Company

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
        </button>

 Are you sure you want to delete this company {{ c.name }}

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-danger">Delete Company</button>

</form>

Body:
As say @Ivan Starostin just put company.pk instance c.pk in your url form

<form method="post" data-url="{% url 'company_delete' company.pk %}" class="delete-form">
    ...
</form>


问:
can i Highlight specific days - like all mondays tuesdays etc in datepicker js
I am trying to highlight days in datepicker. I am using the folowwing code to highlight them.BUt this highlights all the days of the datepicker.</p>

```<code>  dates.data = ['0','1','2'] // days of week
 beforeShowDay: function (date) {
     if($.inArray(date.getDay(), dates.data)) {
          // if it is return the following.
              return [true, 'ui-state-error', 'tooltip text'];
              } else {
                             // default
               return [true, '', ''];
              }
}
</code>```

答:
 var highlight_dates = {};
    highlight_dates[ new Date( '03/10/2020' )] = new Date( '03/10/2020' );
    highlight_dates[ new Date( '02/21/2020' )] = new Date( '02/21/2020' );

    $('#datepicker').datepicker({
       beforeShowDay: function(date) {
          var highlight = highlight_dates[date];
            if( highlight ) {
                 return [true, "class-to-highlight", 'Special Event'];
            } else {
                 return [true, '', ''];
            }
       }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .class-to-highlight{
           background-color: #ff0;
       }</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

Date: <input type="text" id="datepicker">
```

Body:
I am trying to highlight days in datepicker. I am using the folowwing code to highlight them.BUt this highlights all the days of the datepicker.

  dates.data = ['0','1','2'] // days of week
 beforeShowDay: function (date) {
     if($.inArray(date.getDay(), dates.data)) {
          // if it is return the following.
              return [true, 'ui-state-error', 'tooltip text'];
              } else {
                             // default
               return [true, '', ''];
              }
}

Body:
 var highlight_dates = {};
    highlight_dates[ new Date( '03/10/2020' )] = new Date( '03/10/2020' );
    highlight_dates[ new Date( '02/21/2020' )] = new Date( '02/21/2020' );

    $('#datepicker').datepicker({
       beforeShowDay: function(date) {
          var highlight = highlight_dates[date];
            if( highlight ) {
                 return [true, "class-to-highlight", 'Special Event'];
            } else {
                 return [true, '', ''];
            }
       }
    });

 .class-to-highlight{
           background-color: #ff0;
       }

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Date: <input type="text" id="datepicker"></p>


问:
Varnish throws 503 errors
I have managed to set up Redis, nginx and varnish for magento 2 in Ubuntu without SSL.

Performed all the necessary steps required to configured varnish with nginx.

There following are the configuration files.

/etc/default/varnish

/lib/systemd/system/varnish.service

/etc/varnish/default.vcl

/etc/nginx/sites-available/magento

Error log: varnishlog -q 'RespStatus == 503' -g request

```<code>-   Begin          req 32779 rxreq
-   Timestamp      Start: 1582114572.814013 0.000000 0.000000
-   Timestamp      Req: 1582114572.814013 0.000000 0.000000
-   ReqStart       122.170.13.29 49606
-   ReqMethod      GET
-   ReqURL         /
-   ReqProtocol    HTTP/1.1
-   ReqHeader      Host: 13.126.114.136
-   ReqHeader      User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0
-   ReqHeader      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
-   ReqHeader      Accept-Language: en-US,en;q=0.5
-   ReqHeader      Accept-Encoding: gzip, deflate
-   ReqHeader      Connection: keep-alive
-   ReqHeader      Cookie: PHPSESSID=8hie1n4ddjurjoup67keoblubv; form_key=pKBGXC2YzDcWL6pi; mage-cache-storage=%7B%7D; mage-cache-storage-section-invalidation=%7B%7D; mage-cache-sessid=true; mage-messages=; recently_viewed_product=%7B%7D; recently_viewed_product_previous=%
-   ReqHeader      Upgrade-Insecure-Requests: 1
-   ReqHeader      Cache-Control: max-age=0
-   ReqHeader      X-Forwarded-For: 122.170.13.29
-   VCL_call       RECV
-   ReqHeader      grace: none
-   ReqURL         /
-   ReqUnset       Accept-Encoding: gzip, deflate
-   ReqHeader      Accept-Encoding: gzip
-   VCL_return     hash
-   VCL_call       HASH
-   VCL_return     lookup
-   VCL_call       MISS
-   VCL_return     fetch
-   Link           bereq 32781 fetch
-   Timestamp      Fetch: 1582114572.814245 0.000232 0.000232
-   RespProtocol   HTTP/1.1
-   RespStatus     503
-   RespReason     Backend fetch failed
-   RespHeader     Date: Wed, 19 Feb 2020 12:16:12 GMT
-   RespHeader     Server: Varnish
-   RespHeader     Content-Type: text/html; charset=utf-8
-   RespHeader     Retry-After: 5
-   RespHeader     X-Varnish: 32780
-   RespHeader     Age: 0
-   RespHeader     Via: 1.1 varnish (Varnish/5.2)
-   VCL_call       DELIVER
-   RespUnset      Age: 0
-   RespHeader     Pragma: no-cache
-   RespHeader     Expires: -1
-   RespHeader     Cache-Control: no-store, no-cache, must-revalidate, max-age=0
-   RespUnset      Server: Varnish
-   RespUnset      X-Varnish: 32780
-   RespUnset      Via: 1.1 varnish (Varnish/5.2)
-   VCL_return     deliver
-   Timestamp      Process: 1582114572.814265 0.000252 0.000019
-   RespHeader     Content-Length: 282
-   RespHeader     Connection: keep-alive
-   Timestamp      Resp: 1582114572.814298 0.000285 0.000033
-   ReqAcct        1095 0 1095 269 282 551
-   End
**  << BeReq    >> 32781
--  Begin          bereq 32780 fetch
--  Timestamp      Start: 1582114572.814101 0.000000 0.000000
--  BereqMethod    GET
--  BereqURL       /
--  BereqProtocol  HTTP/1.1
--  BereqHeader    Host: 13.126.114.136
--  BereqHeader    User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0
--  BereqHeader    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
--  BereqHeader    Accept-Language: en-US,en;q=0.5
--  BereqHeader    Cookie: PHPSESSID=8hie1n4ddjurjoup67keoblubv; form_key=pKBGXC2YzDcWL6pi; mage-cache-storage=%7B%7D; mage-cache-storage-section-invalidation=%7B%7D; mage-cache-sessid=true; mage-messages=; recently_viewed_product=%7B%7D; recently_viewed_product_previous=%
--  BereqHeader    Upgrade-Insecure-Requests: 1
--  BereqHeader    X-Forwarded-For: 122.170.13.29
--  BereqHeader    grace: none
--  BereqHeader    Accept-Encoding: gzip
--  BereqHeader    X-Varnish: 32781
--  VCL_call       BACKEND_FETCH
--  VCL_return     fetch
--  FetchError     no backend connection
--  Timestamp      Beresp: 1582114572.814144 0.000042 0.000042
--  Timestamp      Error: 1582114572.814148 0.000046 0.000004
--  BerespProtocol HTTP/1.1
--  BerespStatus   503
--  BerespReason   Service Unavailable
--  BerespReason   Backend fetch failed
--  BerespHeader   Date: Wed, 19 Feb 2020 12:16:12 GMT
--  BerespHeader   Server: Varnish
--  VCL_call       BACKEND_ERROR
--  BerespHeader   Content-Type: text/html; charset=utf-8
--  BerespHeader   Retry-After: 5
--  VCL_return     deliver
--  Storage        malloc Transient
--  ObjProtocol    HTTP/1.1
--  ObjStatus      503
--  ObjReason      Backend fetch failed
--  ObjHeader      Date: Wed, 19 Feb 2020 12:16:12 GMT
--  ObjHeader      Server: Varnish
--  ObjHeader      Content-Type: text/html; charset=utf-8
--  ObjHeader      Retry-After: 5
--  Length         282
--  BereqAcct      0 0 0 0 0 0
--  End
</code>```

Tried several solutions found here but none seems to be working.

答:
The varnishlog tells you no backend connection, which would likely mean a failed health check.

To confirm, run varnishlog -g raw -i Backend_Health

A side note: It is best to set the pub directory of Magento to be the webroot (root directive in NGINX) for security reasons. Subsequently, edit the VCL file to remove pub from the health check, because all the web-accessible paths will be relative to the webroot.

It may be also misconfiguration of the stack. In your configs, NGINX listens on the loopback interface 127.0.0.1. But in Varnish you set the backend to localhost. In some situations, this may resolve to IPv6's loopback interface ::1 and Varnish may be failing connection to NGINX because it does not listen on ::1. So it helps to be consistent and put 127.0.0.1 in the VCL file to ensure it is talking to the right interface where NGINX listens on.

Once that this is corrected, confirm the NGINX listen interface is accessible, by e.g. trying to telnet in:

```<code>telnet 127.0.0.1 8080
</code>```

If you don't get connection refused messages, NGINX's listen interface is accessible. Otherwise, there are further corrections to be made.

Title: Varnish throws 503 errors

Body:
I have managed to set up Redis, nginx and varnish for magento 2 in Ubuntu without SSL.

Performed all the necessary steps required to configured varnish with nginx.

There following are the configuration files.

/etc/default/varnish

/lib/systemd/system/varnish.service

/etc/varnish/default.vcl

/etc/nginx/sites-available/magento

Error log: varnishlog -q 'RespStatus == 503' -g request

-   Begin          req 32779 rxreq
-   Timestamp      Start: 1582114572.814013 0.000000 0.000000
-   Timestamp      Req: 1582114572.814013 0.000000 0.000000
-   ReqStart       122.170.13.29 49606
-   ReqMethod      GET
-   ReqURL         /
-   ReqProtocol    HTTP/1.1
-   ReqHeader      Host: 13.126.114.136
-   ReqHeader      User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0
-   ReqHeader      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
-   ReqHeader      Accept-Language: en-US,en;q=0.5
-   ReqHeader      Accept-Encoding: gzip, deflate
-   ReqHeader      Connection: keep-alive
-   ReqHeader      Cookie: PHPSESSID=8hie1n4ddjurjoup67keoblubv; form_key=pKBGXC2YzDcWL6pi; mage-cache-storage=%7B%7D; mage-cache-storage-section-invalidation=%7B%7D; mage-cache-sessid=true; mage-messages=; recently_viewed_product=%7B%7D; recently_viewed_product_previous=%
-   ReqHeader      Upgrade-Insecure-Requests: 1
-   ReqHeader      Cache-Control: max-age=0
-   ReqHeader      X-Forwarded-For: 122.170.13.29
-   VCL_call       RECV
-   ReqHeader      grace: none
-   ReqURL         /
-   ReqUnset       Accept-Encoding: gzip, deflate
-   ReqHeader      Accept-Encoding: gzip
-   VCL_return     hash
-   VCL_call       HASH
-   VCL_return     lookup
-   VCL_call       MISS
-   VCL_return     fetch
-   Link           bereq 32781 fetch
-   Timestamp      Fetch: 1582114572.814245 0.000232 0.000232
-   RespProtocol   HTTP/1.1
-   RespStatus     503
-   RespReason     Backend fetch failed
-   RespHeader     Date: Wed, 19 Feb 2020 12:16:12 GMT
-   RespHeader     Server: Varnish
-   RespHeader     Content-Type: text/html; charset=utf-8
-   RespHeader     Retry-After: 5
-   RespHeader     X-Varnish: 32780
-   RespHeader     Age: 0
-   RespHeader     Via: 1.1 varnish (Varnish/5.2)
-   VCL_call       DELIVER
-   RespUnset      Age: 0
-   RespHeader     Pragma: no-cache
-   RespHeader     Expires: -1
-   RespHeader     Cache-Control: no-store, no-cache, must-revalidate, max-age=0
-   RespUnset      Server: Varnish
-   RespUnset      X-Varnish: 32780
-   RespUnset      Via: 1.1 varnish (Varnish/5.2)
-   VCL_return     deliver
-   Timestamp      Process: 1582114572.814265 0.000252 0.000019
-   RespHeader     Content-Length: 282
-   RespHeader     Connection: keep-alive
-   Timestamp      Resp: 1582114572.814298 0.000285 0.000033
-   ReqAcct        1095 0 1095 269 282 551
-   End
**  << BeReq    >> 32781
--  Begin          bereq 32780 fetch
--  Timestamp      Start: 1582114572.814101 0.000000 0.000000
--  BereqMethod    GET
--  BereqURL       /
--  BereqProtocol  HTTP/1.1
--  BereqHeader    Host: 13.126.114.136
--  BereqHeader    User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0
--  BereqHeader    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
--  BereqHeader    Accept-Language: en-US,en;q=0.5
--  BereqHeader    Cookie: PHPSESSID=8hie1n4ddjurjoup67keoblubv; form_key=pKBGXC2YzDcWL6pi; mage-cache-storage=%7B%7D; mage-cache-storage-section-invalidation=%7B%7D; mage-cache-sessid=true; mage-messages=; recently_viewed_product=%7B%7D; recently_viewed_product_previous=%
--  BereqHeader    Upgrade-Insecure-Requests: 1
--  BereqHeader    X-Forwarded-For: 122.170.13.29
--  BereqHeader    grace: none
--  BereqHeader    Accept-Encoding: gzip
--  BereqHeader    X-Varnish: 32781
--  VCL_call       BACKEND_FETCH
--  VCL_return     fetch
--  FetchError     no backend connection
--  Timestamp      Beresp: 1582114572.814144 0.000042 0.000042
--  Timestamp      Error: 1582114572.814148 0.000046 0.000004
--  BerespProtocol HTTP/1.1
--  BerespStatus   503
--  BerespReason   Service Unavailable
--  BerespReason   Backend fetch failed
--  BerespHeader   Date: Wed, 19 Feb 2020 12:16:12 GMT
--  BerespHeader   Server: Varnish
--  VCL_call       BACKEND_ERROR
--  BerespHeader   Content-Type: text/html; charset=utf-8
--  BerespHeader   Retry-After: 5
--  VCL_return     deliver
--  Storage        malloc Transient
--  ObjProtocol    HTTP/1.1
--  ObjStatus      503
--  ObjReason      Backend fetch failed
--  ObjHeader      Date: Wed, 19 Feb 2020 12:16:12 GMT
--  ObjHeader      Server: Varnish
--  ObjHeader      Content-Type: text/html; charset=utf-8
--  ObjHeader      Retry-After: 5
--  Length         282
--  BereqAcct      0 0 0 0 0 0
--  End

Tried several solutions found here but none seems to be working.

Body:
The varnishlog tells you no backend connection, which would likely mean a failed health check.

To confirm, run varnishlog -g raw -i Backend_Health

A side note: It is best to set the pub directory of Magento to be the webroot (root directive in NGINX) for security reasons. Subsequently, edit the VCL file to remove pub from the health check, because all the web-accessible paths will be relative to the webroot.

It may be also misconfiguration of the stack. In your configs, NGINX listens on the loopback interface 127.0.0.1. But in Varnish you set the backend to localhost. In some situations, this may resolve to IPv6's loopback interface ::1 and Varnish may be failing connection to NGINX because it does not listen on ::1. So it helps to be consistent and put 127.0.0.1 in the VCL file to ensure it is talking to the right interface where NGINX listens on.

Once that this is corrected, confirm the NGINX listen interface is accessible, by e.g. trying to telnet in:

telnet 127.0.0.1 8080

If you don't get connection refused messages, NGINX's listen interface is accessible. Otherwise, there are further corrections to be made.


问:
Plpgsql seems to be deleting and inserting instead of updating - Why?
I am using postgreSQL 7.4.

I have a large table , call it table_a:

```<code>key1 INT NOT NULL,
key2 INT NOT NULL,
data INT NOT NULL,
itstamp INT NOT NULL DEFAULT (date_part('EPOCH'::text, (timeofday())::timestamp without time zone))::INTEGER
</code>```

and a table that summaries the last update time for key1, call it table_b:

```<code>key1        INT NOT NULL,
max_itstamp INT NOT NULL
</code>```

I created a trigger function in plpgsql to update or insert rows in table_b as necessary:

```<code>CREATE OR REPLACE FUNCTION table_b_update() RETURNS TRIGGER AS '
 DECLARE
  l_key1 INT;
  l_itstamp INT;
 BEGIN
  l_key1 := new.key1;
  l_itstamp := new.itstamp;
  PERFORM TRUE FROM table_b WHERE key1=l_key1;
  IF NOT FOUND THEN
   INSERT INTO table_b(key1, max_itstamp) values (l_key1, l_itstamp);
  ELSE
   UPDATE table_b SET max_itstamp=l_itstamp WHERE key1=l_key1;
  END IF;
  RETURN NULL;
 END'
LANGUAGE plpgsql IMMUTABLE;
</code>```

and then I attached a trigger to table_a:

```<code>CREATE TRIGGER table_a_trigger1 AFTER INSERT OR UPDATE ON table_a FOR EACH ROW
EXECUTE PROCEDURE table_b_upate();
</code>```

Now, the time to insert new data into table_a grows incrementally.  The file footprint of table_b grows steadily.

I have used RAISE NOTICE commands in the function to confirm that the If statement causes an UPDATE and not an INSERT after the first call per key.

Since the insert time grows for each INSERT, I tried a VACUUM FULL on table_b. The insert time changed back to the approximate time of the early inserts. The file size for table_b was reduced considerably. After the VACUUM FULL the insert time started to grow again. I don't want to do a VACUUM FULL after every INSERT though.

Is it possible that the UPDATE is actually doing a DELETE and INSERT in table_b?

答:
7.4 is extremely old. You really need to upgrade to a recent version, which has good autovacuum, and will handle this automatically.

Do not use VACUUM FULL (try CLUSTER instead).

ContentLicense: CC BY-SA 3.0

Body:
I am using postgreSQL 7.4.

I have a large table , call it table_a:

key1 INT NOT NULL,
key2 INT NOT NULL,
data INT NOT NULL,
itstamp INT NOT NULL DEFAULT (date_part('EPOCH'::text, (timeofday())::timestamp without time zone))::INTEGER

and a table that summaries the last update time for key1, call it table_b:

key1        INT NOT NULL,
max_itstamp INT NOT NULL

I created a trigger function in plpgsql to update or insert rows in table_b as necessary:

CREATE OR REPLACE FUNCTION table_b_update() RETURNS TRIGGER AS '
 DECLARE
  l_key1 INT;
  l_itstamp INT;
 BEGIN
  l_key1 := new.key1;
  l_itstamp := new.itstamp;
  PERFORM TRUE FROM table_b WHERE key1=l_key1;
  IF NOT FOUND THEN
   INSERT INTO table_b(key1, max_itstamp) values (l_key1, l_itstamp);
  ELSE
   UPDATE table_b SET max_itstamp=l_itstamp WHERE key1=l_key1;
  END IF;
  RETURN NULL;
 END'
LANGUAGE plpgsql IMMUTABLE;

and then I attached a trigger to table_a:

CREATE TRIGGER table_a_trigger1 AFTER INSERT OR UPDATE ON table_a FOR EACH ROW
EXECUTE PROCEDURE table_b_upate();

Now, the time to insert new data into table_a grows incrementally.  The file footprint of table_b grows steadily.

I have used RAISE NOTICE commands in the function to confirm that the If statement causes an UPDATE and not an INSERT after the first call per key.

Since the insert time grows for each INSERT, I tried a VACUUM FULL on table_b. The insert time changed back to the approximate time of the early inserts. The file size for table_b was reduced considerably. After the VACUUM FULL the insert time started to grow again. I don't want to do a VACUUM FULL after every INSERT though.

Is it possible that the UPDATE is actually doing a DELETE and INSERT in table_b?


问:
Refactoring Array.prototype.concat.apply([], [x]) to [].concat(x) throws error
Refactoring Array.prototype.concat.apply([], [x]) to [].concat(x) throws this error:

No overload matches this call.
  Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'Moment | [Moment, Moment]' is not assignable to parameter of type 'ConcatArray<never>'.
      Type 'Moment' is missing the following properties from type 'ConcatArray<never>': length, join, slice
  Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'Moment | [Moment, Moment]' is not assignable to parameter of type 'ConcatArray<never>'.
      Type 'Moment' is not assignable to type 'ConcatArray<never>'.ts(2769)
```

What's the problem I'm missing and how can I refactor this effectively?

答:
This is because the [] is typed as never[]. But since you call concat in the first example on Array.prototype which is any[], the concatenation happens between any[] and (typeof x)[]

Argument of type 'Moment | [Moment, Moment]'

so you want to normalize that to Moment[]?
You can do:

```<code>let y:Moment[];

y = ([] as any[]).concat(x);

// or something like

y = "length" in x ? x: [x];

// or something completely different, as you are already refactoring.

const [
  from = x,
  to = x
] = x as any;
</code>```

or you put that into a function

```<code>function foo<T>(arg: T|T[]): T[] {
  return Array.isArray(arg) ? arg : [arg];
}
</code>```

Body:
Refactoring Array.prototype.concat.apply([], [x]) to [].concat(x) throws this error:

No overload matches this call.
  Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'Moment | [Moment, Moment]' is not assignable to parameter of type 'ConcatArray<never>'.
      Type 'Moment' is missing the following properties from type 'ConcatArray<never>': length, join, slice
  Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'Moment | [Moment, Moment]' is not assignable to parameter of type 'ConcatArray<never>'.
      Type 'Moment' is not assignable to type 'ConcatArray<never>'.ts(2769)

What's the problem I'm missing and how can I refactor this effectively?

Body:
This is because the [] is typed as never[]. But since you call concat in the first example on Array.prototype which is any[], the concatenation happens between any[] and (typeof x)[]

Argument of type 'Moment | [Moment, Moment]'

so you want to normalize that to Moment[]?
You can do:

let y:Moment[];

y = ([] as any[]).concat(x);

// or something like

y = "length" in x ? x: [x];

// or something completely different, as you are already refactoring.

const [
  from = x,
  to = x
] = x as any;

or you put that into a function

function foo<T>(arg: T|T[]): T[] {
  return Array.isArray(arg) ? arg : [arg];
}


问:
navigator.mediaDevices.enumerateDevices() returns empty labels
Background

The machine I am trying to implement this on contains multiple cameras, I want to select the camera in the code. (all machines have the same hardware)

Issue

I am trying to implement a custom function before requesting video access where I manually set which device that should be used to prevent selection of wrong camera, but when I use

await navigator.mediaDevices.enumerateDevices()

I get empty labels for available video camera devices.

答:
navigator.mediaDevices.enumerateDevices() will return an empty label attribute value if the permission for accessing the mediadevice is not given. Try using it after getUserMedia.</p>

```<code>(async () => {
  await navigator.mediaDevices.getUserMedia({audio: true, video: true});
  let devices = await navigator.mediaDevices.enumerateDevices();
  console.log(devices);
})();
</code>```

Body:
navigator.mediaDevices.enumerateDevices() will return an empty label attribute value if the permission for accessing the mediadevice is not given. Try using it after getUserMedia.

(async () => {
  await navigator.mediaDevices.getUserMedia({audio: true, video: true});
  let devices = await navigator.mediaDevices.enumerateDevices();
  console.log(devices);
})();


问:
Easiest way to dynamically get/set properties of c# objects by name
I have several objects of different types and the name of a property that I need to get and set on these. In languages like javascript this is trivial as I can get and set values with indexor syntax.

```<code>obj2[propertyName] = obj1[propertyName];
</code>```

In c# it's not so easy. I know I can use reflection but that's a lot of code. I know there's dynamic objects, but they don't automatically have a way to reference properties by name. What's the easiest way to get and set properties dynamically by name on objects of arbitrary types (ie they have the property but don't all share a common interface or base class)?

Update: Upon further research it seems like FastMember, Impromptu, Dynamitey, or maybe FSharp.Dynamic can help here if anyone has any thoughts...

答:
dynamic value in property object:

```<code>public dynamic propertyName {
   get; set;
}
</code>```

to get a property by name, you need to implement an indexer in the class
https://www.geeksforgeeks.org/c-sharp-indexers/

Body:
I have several objects of different types and the name of a property that I need to get and set on these. In languages like javascript this is trivial as I can get and set values with indexor syntax.

obj2[propertyName] = obj1[propertyName];

In c# it's not so easy. I know I can use reflection but that's a lot of code. I know there's dynamic objects, but they don't automatically have a way to reference properties by name. What's the easiest way to get and set properties dynamically by name on objects of arbitrary types (ie they have the property but don't all share a common interface or base class)?

Update: Upon further research it seems like FastMember, Impromptu, Dynamitey, or maybe FSharp.Dynamic can help here if anyone has any thoughts...

Body:
dynamic value in property object:

public dynamic propertyName {
   get; set;
}

to get a property by name, you need to implement an indexer in the class
https://www.geeksforgeeks.org/c-sharp-indexers/


问:
How to create/update a LastModified field in EF Code First
I want to add a column that stores the current DateTime when a record is saved to disk. What would be the best way to accomplish this?

I know it's not a very complex problem, but I wondered if there is any best practice or any feature of EF that would simplify the task.
For example:

Is there any way to include the logic for this field inside the table Class, so that it's automatically updated whenever it's saved to disk?

Is there any event to capture when an object is modified or saved?

答:
one option would be to create repository layer and implement your own SaveChanges</p>

```<code>public void SaveChanges()
{
    foreach (var entry in Context.ChangeTracker.Entries<ICreatedAt>().Where(x => x.State == EntityState.Added && x.Entity.CreatedAt == default(DateTime)))
            entry.Entity.CreatedAt = DateTime.Now;

    foreach (var entry in Context.ChangeTracker.Entries<ICreatedBy>().Where(x => x.State == EntityState.Added && x.Entity.CreatedBy == null))
        entry.Entity.CreatedBy = ContextManager.CurrentUser;

    foreach (var entry in Context.ChangeTracker.Entries<IModifiedAt>().Where(x => x.State == EntityState.Modified))
        entry.Entity.ModifiedAt = DateTime.Now;

    foreach (var entry in Context.ChangeTracker.Entries<IModifiedBy>().Where(x => x.State == EntityState.Modified))
        entry.Entity.ModifiedBy = ContextManager.CurrentUser;

    Context.SaveChanges();
}
</code>```

Body:
one option would be to create repository layer and implement your own SaveChanges

public void SaveChanges()
{
    foreach (var entry in Context.ChangeTracker.Entries<ICreatedAt>().Where(x => x.State == EntityState.Added && x.Entity.CreatedAt == default(DateTime)))
            entry.Entity.CreatedAt = DateTime.Now;

    foreach (var entry in Context.ChangeTracker.Entries<ICreatedBy>().Where(x => x.State == EntityState.Added && x.Entity.CreatedBy == null))
        entry.Entity.CreatedBy = ContextManager.CurrentUser;

    foreach (var entry in Context.ChangeTracker.Entries<IModifiedAt>().Where(x => x.State == EntityState.Modified))
        entry.Entity.ModifiedAt = DateTime.Now;

    foreach (var entry in Context.ChangeTracker.Entries<IModifiedBy>().Where(x => x.State == EntityState.Modified))
        entry.Entity.ModifiedBy = ContextManager.CurrentUser;

    Context.SaveChanges();
}


问:
SSRS Is there a way to set a dropdown null check mark as default?
enter image description hereI have 3 dropdowns and i want 1 dropdown set null check mark by default.
So only when needed to filter with marriedname the check mark can be removed.
Dropdown are Names, Firstnames and Marriedname.

Dataset Marriedname:

Select distinct [Name3]
from Patient
ORDER BY [Name3]

答:
Go to your parameter properties (Marriedname). If you tick the checkbox "Allow null value", there will be a null check mark and it will be checked by default when you run the report.

edit: The "null" checkbox will not show up if the parameter available values are populated from a dataset. Workaround is to include the "null" value as one of the options in the dropdown list from the dataset results. This query will add a null value to your result set in the dropdown and you can specify the null value by default.

```<code>Select distinct [Name3]
into #temptable
from PatientenNAW
ORDER BY [Name3]

insert into #temptable ([Name3]) values (null) --you might need to put this null value in single quotes depending on how you reference default value

drop table #temptable
</code>```

Body:
Go to your parameter properties (Marriedname). If you tick the checkbox "Allow null value", there will be a null check mark and it will be checked by default when you run the report.

edit: The "null" checkbox will not show up if the parameter available values are populated from a dataset. Workaround is to include the "null" value as one of the options in the dropdown list from the dataset results. This query will add a null value to your result set in the dropdown and you can specify the null value by default.

Select distinct [Name3]
into #temptable
from PatientenNAW
ORDER BY [Name3]

insert into #temptable ([Name3]) values (null) --you might need to put this null value in single quotes depending on how you reference default value

drop table #temptable


问:
How can i redirect unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei) using .htaccess?
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

```<code>RewriteEngine On
ErrorDocument 404 /example.com
</code>```

答:
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

I assume /digital-marketing.php is a file on your filesystem. In which case /ercbierubcrei is additional pathname information (or path-info). By default, the PHP handler allows path-info, so /digital-marketing.php is still served but at the different URL (if that's what you mean by "unstructured link"?).

You can simply disable path-info on these URLs by setting the following at the top of your .htaccess file:

```<code>AcceptPathInfo Off
</code>```

Now, any URL that contains path-info will trigger a 404 instead and your custom 404 error document will be called. (You can still override this behaviour with mod_rewrite if you wish.)

Alternatively, if you wanted to redirect /digital-marketing.php/ercbierubcrei to /digital-marketing.php (is that what you mean by "redirect its to main root"?*1) then you can do something like the following near the top of your .htaccess file using mod_rewrite:

```<code>RewriteEngine On
RewriteRule ^(.+?\.php)/ /$1 [R=302,L]
</code>```

This redirects a URL of the form /<something>.php/<anything> to /<something.php, effectively discarding the path-info portion of the URL.

(*1 - If by "main root" you do literally mean the document root of the site then that is not recommended. Google would likely treat this as a soft-404 anyway. A custom 404 with a meaningful message would be preferable.)

```<code>ErrorDocument 404 /example.com
</code>```

This does not look "valid". The 2nd argument to the ErrorDocument directive should ideally be a local URL-path to the document that handles the error response.

For example:

```<code>ErrorDocument 404 /error-documents/my-404-error-document.php
</code>```

Body:
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

RewriteEngine On
ErrorDocument 404 /example.com

Body:
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

I assume /digital-marketing.php is a file on your filesystem. In which case /ercbierubcrei is additional pathname information (or path-info). By default, the PHP handler allows path-info, so /digital-marketing.php is still served but at the different URL (if that's what you mean by "unstructured link"?).

You can simply disable path-info on these URLs by setting the following at the top of your .htaccess file:

AcceptPathInfo Off

Now, any URL that contains path-info will trigger a 404 instead and your custom 404 error document will be called. (You can still override this behaviour with mod_rewrite if you wish.)

Alternatively, if you wanted to redirect /digital-marketing.php/ercbierubcrei to /digital-marketing.php (is that what you mean by "redirect its to main root"?*1) then you can do something like the following near the top of your .htaccess file using mod_rewrite:

RewriteEngine On
RewriteRule ^(.+?\.php)/ /$1 [R=302,L]

This redirects a URL of the form /<something>.php/<anything> to /<something.php, effectively discarding the path-info portion of the URL.

(*1 - If by "main root" you do literally mean the document root of the site then that is not recommended. Google would likely treat this as a soft-404 anyway. A custom 404 with a meaningful message would be preferable.)

ErrorDocument 404 /example.com

This does not look "valid". The 2nd argument to the ErrorDocument directive should ideally be a local URL-path to the document that handles the error response.

For example:

ErrorDocument 404 /error-documents/my-404-error-document.php


问:
how to compare type of an object's instance to a generic type?
how can i write this code in java?

```<code>public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public <U extends IComponent> U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}
</code>```

but i cant perform instanceof on generic types. how should i do it?
thanks.

答:
General rule with java - if a generic class needs to know its generic type(s), then you have to pass a hint. A common approach for the problem is using the constructor:

```<code>public class ComponentsManager<U extends IComponent> {
  private Class<U extends IComponentManeger> genericType = null;
  public ComponentsManager<U extends IComponent>(
                       Class<U extends IComponent> genericType) {
    this.genericType = genericType;
  }

}
</code>```

Now the class knows it's generic type class and you can uses the generic type class instance to verify, if a component in your collection matches the classes generic type.

Body:
how can i write this code in java?

public class ComponentsManager
    {
        private List<IComponent> list = new ArrayList<IComponent>();

        public  U GetComponent() {

            for (IComponent component : list) {

                if(component instanceof U)
                {
                    return component;
                }
            }
        }
}

but i cant perform instanceof on generic types. how should i do it?
thanks.

Body:
General rule with java - if a generic class needs to know its generic type(s), then you have to pass a hint. A common approach for the problem is using the constructor:

public class ComponentsManager<U extends IComponent> {
  private Class<U extends IComponentManeger> genericType = null;
  public ComponentsManager<U extends IComponent>(
                       Class<U extends IComponent> genericType) {
    this.genericType = genericType;
  }

}

Now the class knows it's generic type class and you can uses the generic type class instance to verify, if a component in your collection matches the classes generic type.


问:
How do I fix it so that my text label isn't cut off at the top when programmatically adding a text label?
I have added a label programmatically, and it works fine, except that local characters like å, ä, ö gets cut off att the top. This is true even if I change _nothingToShow.lineBreakMode = NSLineBreakByClipping; to NSLineBreakByCharWrapping.

I set up the label like this:

```<code>-(void)setupNoOldExcursionsView {
    _myView = [[UIView alloc] initWithFrame:self.view.frame];
    _myView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: _myView];

    [self.view bringSubviewToFront: _myView];

    if (@available(iOS 11.0, *)) {
        _nothingToShow = [[UILabel alloc] init];

        [self generalLabelSetUp];

        _myView.translatesAutoresizingMaskIntoConstraints = NO;
        _nothingToShow.translatesAutoresizingMaskIntoConstraints = NO;

        UILayoutGuide *g = self.view.safeAreaLayoutGuide;

        [NSLayoutConstraint activateConstraints:@[
               [_myView.topAnchor constraintEqualToAnchor:g.topAnchor constant:0.0],
               [_myView.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant:0.0],
               [_myView.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:0.0],
               [_myView.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:0.0],

               [_nothingToShow.centerXAnchor constraintEqualToAnchor: _myView.centerXAnchor],
               [_nothingToShow.centerYAnchor constraintEqualToAnchor: _myView.centerYAnchor],
               [_nothingToShow.leadingAnchor constraintEqualToAnchor: _myView.leadingAnchor constant:0],
               [_nothingToShow.trailingAnchor constraintEqualToAnchor: _myView.trailingAnchor constant:0]
           ]];
    }
}
</code>```

and setting up the label:

```<code>-(void)generalLabelSetUp {
      _nothingToShow.text = NSLocalizedString(@"NoExcursions", @"");
      _nothingToShow.textColor = [UIColor blackColor];
      _nothingToShow.textAlignment = NSTextAlignmentCenter;
      [_nothingToShow setNumberOfLines: 0];
//      _nothingToShow.lineBreakMode = NSLineBreakByClipping;
        _nothingToShow.lineBreakMode = NSLineBreakByCharWrapping;

      [_nothingToShow setCenter: CGPointMake(_noOldExcursions.center.x, _noOldExcursions.center.y - 40)];

      _nothingToShow.font = [UIFont apolloNoExperiences];
      _nothingToShow.textColor = [UIColor apolloBlueColor];

      [_noOldExcursions addSubview:_nothingToShow];
  }
</code>```

How do I make sure the text is not cut off? Do I set the height of the label in some way? Or shrink the text to fit the label?

答:
Try adding a top and bottom constraint constant value like:

```<code>   [_myView.topAnchor constraintEqualToAnchor:g.topAnchor constant:10.0],
   [_myView.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant: -10.0],
</code>```

if this didn't work for you then your issue is with the continer that you use to add the lable, just make the hight bigger.

Body:
I have added a label programmatically, and it works fine, except that local characters like å, ä, ö gets cut off att the top. This is true even if I change _nothingToShow.lineBreakMode = NSLineBreakByClipping; to NSLineBreakByCharWrapping.

I set up the label like this:

-(void)setupNoOldExcursionsView {
    _myView = [[UIView alloc] initWithFrame:self.view.frame];
    _myView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: _myView];

    [self.view bringSubviewToFront: _myView];

    if (@available(iOS 11.0, *)) {
        _nothingToShow = [[UILabel alloc] init];

        [self generalLabelSetUp];

        _myView.translatesAutoresizingMaskIntoConstraints = NO;
        _nothingToShow.translatesAutoresizingMaskIntoConstraints = NO;

        UILayoutGuide *g = self.view.safeAreaLayoutGuide;

        [NSLayoutConstraint activateConstraints:@[
               [_myView.topAnchor constraintEqualToAnchor:g.topAnchor constant:0.0],
               [_myView.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant:0.0],
               [_myView.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:0.0],
               [_myView.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:0.0],

               [_nothingToShow.centerXAnchor constraintEqualToAnchor: _myView.centerXAnchor],
               [_nothingToShow.centerYAnchor constraintEqualToAnchor: _myView.centerYAnchor],
               [_nothingToShow.leadingAnchor constraintEqualToAnchor: _myView.leadingAnchor constant:0],
               [_nothingToShow.trailingAnchor constraintEqualToAnchor: _myView.trailingAnchor constant:0]
           ]];
    }
}

and setting up the label:

-(void)generalLabelSetUp {
      _nothingToShow.text = NSLocalizedString(@"NoExcursions", @"");
      _nothingToShow.textColor = [UIColor blackColor];
      _nothingToShow.textAlignment = NSTextAlignmentCenter;
      [_nothingToShow setNumberOfLines: 0];
//      _nothingToShow.lineBreakMode = NSLineBreakByClipping;
        _nothingToShow.lineBreakMode = NSLineBreakByCharWrapping;

      [_nothingToShow setCenter: CGPointMake(_noOldExcursions.center.x, _noOldExcursions.center.y - 40)];

      _nothingToShow.font = [UIFont apolloNoExperiences];
      _nothingToShow.textColor = [UIColor apolloBlueColor];

      [_noOldExcursions addSubview:_nothingToShow];
  }

How do I make sure the text is not cut off? Do I set the height of the label in some way? Or shrink the text to fit the label?

Body:
Try adding a top and bottom constraint constant value like:

   [_myView.topAnchor constraintEqualToAnchor:g.topAnchor constant:10.0],
   [_myView.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant: -10.0],

if this didn't work for you then your issue is with the continer that you use to add the lable, just make the hight bigger.


问:
Firebase Push notifications don't work on iOS 13
Firebase push notifications aren't working on iOS 13. But works fine in iOS 12.4. Any solution?

Edited: 04.10.19

Silent push notification not working iOS 13

答:
Quick Fix Solution:

If you are facing issue to receive push notification on iOS version 13.2.X, then do below change in device settings and check again:

Device > Settings > Search your AppName > Notifications > Banner Style > Change it to "Persistent" from "Temporary" or vise-versa one time.

Now send push notification again and its start receiving.


问:
How do I completely delete Cloud Datastore from a project?
I want to create a Firestore in Native mode in an existing project.
I don't have any data in Cloud Datastore, but it blocks me, saying

This project uses another database service
  Your current project is set up to use Cloud Datastore or Cloud Firestore in Datastore mode. You can access data for this project from the Cloud Datastore console.

when going through https://console.cloud.google.com/firestore/
and

Cannot enable Firestore for this project
  Currently Firestore cannot be enabled in projects already using Cloud Datastore or App Engine

when going through https://console.firebase.google.com/

I've tried it with writes to datastore enabled and disabled

I just want to completely purge the Cloud Datastore product from my project.

答:
If you have an empty Datastore database and you never executed a write to the database, you can upgrade to Firestore in Datastore mode or Native mode.

If you do not receive this option, then your database instance will be automatically upgraded at a future date.

If you upgrade from Datastore to Firestore in Datastore mode or from Datastore mode to Native mode, you cannot undo the operation.

See this page for additional details:
https://cloud.google.com/datastore/docs/upgrade-to-firestore


问:
Missing colors in my Chart.js, my data looks fine, but no color
I made my first bar with Chart.js library.
My data looks nice, but I can't give my valuest some color.

enter image description here

My function looks like this:

```<code>var $barData =
{
    type: 'bar',
    labels: ['Super mad', 'Middel', 'Ikke ok', 'Gennemsnit'],
    datasets:
    [
        {
            label: 'Antal stemmer',
            data: [
            [$arrStemmer[0]],
            [$arrStemmer[1]],
            [$arrStemmer[2]],
            [$Snit_Vaerdi]
            ],

            backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }

    ]
}

// Hent graf initialiserings setup
var $Stemmer = document.getElementById("can_afstemning_graf").getContext("2d");
// Tegn graf, men data fra barData objektet
new Chart($Stemmer).Bar($barData);
</code>```

What am I missing?
I am looking here in the documentation and it look fine: https://www.chartjs.org/docs/latest/.

Thanks,
Nenad

答:
This should work. if the $arrStemmer and $snit_Vaerdi are filled.

```<code>let $stemmer = document.getElementById('can_afstemning_graf').getContext('2d');

let myChart = new Chart($stemmer, {
    type: 'bar',
    data: {
        labels: ['Super mad', 'Middel', 'Ikke ok', 'Gennemsnit'],
        datasets: [{
            label: 'Antal stemmer',
            data: [
                $arrStemmer[0],
                $arrStemmer[1],
                $arrStemmer[2],
                $Snit_Vaerdi
            ],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
</code>```

Body:
I made my first bar with Chart.js library.
My data looks nice, but I can't give my valuest some color.

enter image description here

My function looks like this:

var $barData =
{
    type: 'bar',
    labels: ['Super mad', 'Middel', 'Ikke ok', 'Gennemsnit'],
    datasets:
    [
        {
            label: 'Antal stemmer',
            data: [
            [$arrStemmer[0]],
            [$arrStemmer[1]],
            [$arrStemmer[2]],
            [$Snit_Vaerdi]
            ],

            backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }

    ]
}

// Hent graf initialiserings setup
var $Stemmer = document.getElementById("can_afstemning_graf").getContext("2d");
// Tegn graf, men data fra barData objektet
new Chart($Stemmer).Bar($barData);

What am I missing?
I am looking here in the documentation and it look fine: https://www.chartjs.org/docs/latest/.

Thanks,
Nenad

Body:
This should work. if the $arrStemmer and $snit_Vaerdi are filled.

let $stemmer = document.getElementById('can_afstemning_graf').getContext('2d');

let myChart = new Chart($stemmer, {
    type: 'bar',
    data: {
        labels: ['Super mad', 'Middel', 'Ikke ok', 'Gennemsnit'],
        datasets: [{
            label: 'Antal stemmer',
            data: [
                $arrStemmer[0],
                $arrStemmer[1],
                $arrStemmer[2],
                $Snit_Vaerdi
            ],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});


问:
Elasticsearch query to search from different fields non-strictly
I'm relatively new with elasticsearch and have been working with elasticsearch in python. What I had was people's data in csv format which I had converted to json and had added to elasticsearch index.
The fields are the following:

```<code>'Last Name (Legal Name)',
'First Name',
'Middle Name',
'Other Last Name',
'Business Mailing Address City Name',
'Business Mailing Address State Name',
'Business Practice Location Address City Name',
'Business Practice Location Address State Name',
'Authorized Official Last Name',
'Authorized Official First Name',
'Authorized Official Middle Name',
'Authorized Official Title or Position'
</code>```

What I want to put in the query is something like "Name City". For Example, "Clinton Adams Hamilton" where Clinton Adams is the name and Hamilton is the city. In most of the cases I won't be sure which is the first name or which is the last, so I will need to match from all the fields.

What I've used till now is something like this:

```<code>"query":{
                "query_string":{
                    "fields": ['Last Name (Legal Name)', 'First Name', 'Middle Name',
                             'Other Last Name', 'Business Mailing Address City Name',
                             'Business Mailing Address State Name',
                             'Business Practice Location Address City Name', 'Business Practice
                              Location Address State Name',
                             'Authorized Official Last Name', 'Authorized Official First Name',
                             'Authorized Official Middle Name',
                             'Authorized Official Title or Position'],
                    "query": "(Clinton) AND (Adams) AND (Hamilton)",
                    }
                }

</code>```

The following query works fine if I search the exact name and City from the database but if I have a spelling mistake in the name or if in some name the first name is abbreviated, it doesn't give the expected results. For example if the query is something like "Clinton A Hamilton", it wouldn't match with any documents. I can't use the ORoperator as there are multiple people with similar names, so all of the parts of the query - first name/last name and city are important. I would want the query to fetch the most relevant record from the index.

I tried my best to explain the situation. In any case, feel free to ask if anything isn't really clear. Appreciate your suggestions. Thanks.

答:
first of all, you should give a try to the multi-match query, especially the cross_field type that is suited for your use case. Documentation here.

It will handle all your searched fields as one blended field.

But if you keep your operator "AND" a query for "Clinton A Hamilton" will not match a "Clinton Adams / Hamilton" document.
I think you should go for the standard OR operator. It will give you the first relevant document in first position. Exact matches first and partial ones after.

If you know for sure that a lot of your users will use diminutive form for the first name you should consider creating a special analyzer to index the diminutive form.

Here is an example in a standalone index :

```<code>PUT diminutive
{
  "settings": {
    "analysis": {
      "filter": {
        "diminutive": {
          "type": "edge_ngram",
          "min_gram": 1,
          "max_gram": 3
        }
      },
      "analyzer": {
        "diminutive": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "asciifolding",
            "diminutive"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "firstname": {
        "type": "text",
        "analyzer": "diminutive",
        "search_analyzer": "standard"
      }
    }
  }
}
</code>```

You could then use your diminutive analyzer in a field for 'First Name' ( see documentation here) and add the subfield in the multi-match query.

It's maybe a lot of informations / concept to handle, but I think it should be a good start for your use case.

Body:
I'm relatively new with elasticsearch and have been working with elasticsearch in python. What I had was people's data in csv format which I had converted to json and had added to elasticsearch index.
The fields are the following:

'Last Name (Legal Name)',
'First Name',
'Middle Name',
'Other Last Name',
'Business Mailing Address City Name',
'Business Mailing Address State Name',
'Business Practice Location Address City Name',
'Business Practice Location Address State Name',
'Authorized Official Last Name',
'Authorized Official First Name',
'Authorized Official Middle Name',
'Authorized Official Title or Position'

What I want to put in the query is something like "Name City". For Example, "Clinton Adams Hamilton" where Clinton Adams is the name and Hamilton is the city. In most of the cases I won't be sure which is the first name or which is the last, so I will need to match from all the fields.

What I've used till now is something like this:

"query":{
                "query_string":{
                    "fields": ['Last Name (Legal Name)', 'First Name', 'Middle Name',
                             'Other Last Name', 'Business Mailing Address City Name',
                             'Business Mailing Address State Name',
                             'Business Practice Location Address City Name', 'Business Practice
                              Location Address State Name',
                             'Authorized Official Last Name', 'Authorized Official First Name',
                             'Authorized Official Middle Name',
                             'Authorized Official Title or Position'],
                    "query": "(Clinton) AND (Adams) AND (Hamilton)",
                    }
                }

The following query works fine if I search the exact name and City from the database but if I have a spelling mistake in the name or if in some name the first name is abbreviated, it doesn't give the expected results. For example if the query is something like "Clinton A Hamilton", it wouldn't match with any documents. I can't use the ORoperator as there are multiple people with similar names, so all of the parts of the query - first name/last name and city are important. I would want the query to fetch the most relevant record from the index.

I tried my best to explain the situation. In any case, feel free to ask if anything isn't really clear. Appreciate your suggestions. Thanks.

Body:
first of all, you should give a try to the multi-match query, especially the cross_field type that is suited for your use case. Documentation here.

It will handle all your searched fields as one blended field.

But if you keep your operator "AND" a query for "Clinton A Hamilton" will not match a "Clinton Adams / Hamilton" document.
I think you should go for the standard OR operator. It will give you the first relevant document in first position. Exact matches first and partial ones after.

If you know for sure that a lot of your users will use diminutive form for the first name you should consider creating a special analyzer to index the diminutive form.

Here is an example in a standalone index :

PUT diminutive
{
  "settings": {
    "analysis": {
      "filter": {
        "diminutive": {
          "type": "edge_ngram",
          "min_gram": 1,
          "max_gram": 3
        }
      },
      "analyzer": {
        "diminutive": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "asciifolding",
            "diminutive"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "firstname": {
        "type": "text",
        "analyzer": "diminutive",
        "search_analyzer": "standard"
      }
    }
  }
}

You could then use your diminutive analyzer in a field for 'First Name' ( see documentation here) and add the subfield in the multi-match query.

It's maybe a lot of informations / concept to handle, but I think it should be a good start for your use case.


问:
Importing Bootstrap css in app.js breaks current styles vuejs
I have a current VueJS project and in attempting to add a bootstrap modal I am running into an issue where importing the bootstrap scss breaks/overrides the css of the project.  How can I include Bootstrap css without overriding my current css?

I'm importing bootstrap into the top of my app.js file

```<code>import Vue from 'vue';

import { BootstrapVue } from 'bootstrap-vue'
Vue.use(BootstrapVue)

import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
</code>```

答:
Just went through this so I can provide the specific code as of bootstrap-vue v.2.5.0. This is from the docs, but as mentioned, it will take a little digging to uncover where all the paths are so I've included them all here.

create a _custom.scss file (I put mine in src/assets/):

```<code>// required:
@import "./node_modules/bootstrap/scss/functions";
@import "./node_modules/bootstrap/scss/variables";
@import "./node_modules/bootstrap/scss/mixins";
// optional
@import "./node_modules/bootstrap/scss/root";
@import "./node_modules/bootstrap/scss/reboot";
// @import "./node_modules/bootstrap/scss/type";
@import "./node_modules/bootstrap/scss/images";
// @import "./node_modules/bootstrap/scss/code";
@import "./node_modules/bootstrap/scss/grid";
// @import "./node_modules/bootstrap/scss/tables";
@import "./node_modules/bootstrap/scss/forms";
@import "./node_modules/bootstrap/scss/buttons";
@import "./node_modules/bootstrap/scss/transitions";
@import "./node_modules/bootstrap/scss/dropdown";
@import "./node_modules/bootstrap/scss/button-group";
@import "./node_modules/bootstrap/scss/input-group";
// @import "./node_modules/bootstrap/scss/custom-forms";
@import "./node_modules/bootstrap/scss/nav";
@import "./node_modules/bootstrap/scss/navbar";
@import "./node_modules/bootstrap/scss/card";
// @import "./node_modules/bootstrap/scss/breadcrumb";
// @import "./node_modules/bootstrap/scss/pagination";
// @import "./node_modules/bootstrap/scss/badge";
// @import "./node_modules/bootstrap/scss/jumbotron";
@import "./node_modules/bootstrap/scss/alert";
// @import "./node_modules/bootstrap/scss/progress";
// @import "./node_modules/bootstrap/scss/media";
@import "./node_modules/bootstrap/scss/list-group";
// @import "./node_modules/bootstrap/scss/close";
// @import "./node_modules/bootstrap/scss/toasts";
// @import "./node_modules/bootstrap/scss/modal";
// @import "./node_modules/bootstrap/scss/tooltip";
// @import "./node_modules/bootstrap/scss/popover";
// @import "./node_modules/bootstrap/scss/carousel";
// @import "./node_modules/bootstrap/scss/spinners";
@import "./node_modules/bootstrap/scss/utilities";
// @import "./node_modules/bootstrap/scss/print";

@import './node_modules/bootstrap-vue/src/variables';
@import './node_modules/bootstrap-vue/src/utilities';
@import "./node_modules/bootstrap-vue/src/components/card/index";
@import "./node_modules/bootstrap-vue/src/components/dropdown/index";
// @import "./node_modules/bootstrap-vue/src/components/form-checkbox/index";
// @import "./node_modules/bootstrap-vue/src/components/form-file/index";
@import "./node_modules/bootstrap-vue/src/components/form-input/index";
// @import "./node_modules/bootstrap-vue/src/components/form-radio/index";
// @import "./node_modules/bootstrap-vue/src/components/form-tags/index";
@import "./node_modules/bootstrap-vue/src/components/input-group/index";
// @import "./node_modules/bootstrap-vue/src/components/modal/index";
@import "./node_modules/bootstrap-vue/src/components/nav/index";
@import "./node_modules/bootstrap-vue/src/components/navbar/index";
// @import "./node_modules/bootstrap-vue/src/components/pagination/index";
// @import "./node_modules/bootstrap-vue/src/components/pagination-nav/index";
// @import "./node_modules/bootstrap-vue/src/components/popover/index";
// @import "./node_modules/bootstrap-vue/src/components/table/index";
// @import "./node_modules/bootstrap-vue/src/components/toast/index";
// @import "./node_modules/bootstrap-vue/src/components/tooltip/index";
</code>```

As you can see, I commented out what I wasn't using. Then simply:

```<code>// in main.js:
import "./assets/_custom.scss";
</code>```

Do not forget to include node-sass and sass-loader to use scss in Vue:

```<code>npm install --save-dev node-sass sass-loader
</code>```

Note: You may need to adjust the SCSS import paths based on your build environment.

Body:
I have a current VueJS project and in attempting to add a bootstrap modal I am running into an issue where importing the bootstrap scss breaks/overrides the css of the project.  How can I include Bootstrap css without overriding my current css?

I'm importing bootstrap into the top of my app.js file

import Vue from 'vue';

import { BootstrapVue } from 'bootstrap-vue'
Vue.use(BootstrapVue)

import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

Body:
Just went through this so I can provide the specific code as of bootstrap-vue v.2.5.0. This is from the docs, but as mentioned, it will take a little digging to uncover where all the paths are so I've included them all here.

create a _custom.scss file (I put mine in src/assets/):

// required:
@import "./node_modules/bootstrap/scss/functions";
@import "./node_modules/bootstrap/scss/variables";
@import "./node_modules/bootstrap/scss/mixins";
// optional
@import "./node_modules/bootstrap/scss/root";
@import "./node_modules/bootstrap/scss/reboot";
// @import "./node_modules/bootstrap/scss/type";
@import "./node_modules/bootstrap/scss/images";
// @import "./node_modules/bootstrap/scss/code";
@import "./node_modules/bootstrap/scss/grid";
// @import "./node_modules/bootstrap/scss/tables";
@import "./node_modules/bootstrap/scss/forms";
@import "./node_modules/bootstrap/scss/buttons";
@import "./node_modules/bootstrap/scss/transitions";
@import "./node_modules/bootstrap/scss/dropdown";
@import "./node_modules/bootstrap/scss/button-group";
@import "./node_modules/bootstrap/scss/input-group";
// @import "./node_modules/bootstrap/scss/custom-forms";
@import "./node_modules/bootstrap/scss/nav";
@import "./node_modules/bootstrap/scss/navbar";
@import "./node_modules/bootstrap/scss/card";
// @import "./node_modules/bootstrap/scss/breadcrumb";
// @import "./node_modules/bootstrap/scss/pagination";
// @import "./node_modules/bootstrap/scss/badge";
// @import "./node_modules/bootstrap/scss/jumbotron";
@import "./node_modules/bootstrap/scss/alert";
// @import "./node_modules/bootstrap/scss/progress";
// @import "./node_modules/bootstrap/scss/media";
@import "./node_modules/bootstrap/scss/list-group";
// @import "./node_modules/bootstrap/scss/close";
// @import "./node_modules/bootstrap/scss/toasts";
// @import "./node_modules/bootstrap/scss/modal";
// @import "./node_modules/bootstrap/scss/tooltip";
// @import "./node_modules/bootstrap/scss/popover";
// @import "./node_modules/bootstrap/scss/carousel";
// @import "./node_modules/bootstrap/scss/spinners";
@import "./node_modules/bootstrap/scss/utilities";
// @import "./node_modules/bootstrap/scss/print";

@import './node_modules/bootstrap-vue/src/variables';
@import './node_modules/bootstrap-vue/src/utilities';
@import "./node_modules/bootstrap-vue/src/components/card/index";
@import "./node_modules/bootstrap-vue/src/components/dropdown/index";
// @import "./node_modules/bootstrap-vue/src/components/form-checkbox/index";
// @import "./node_modules/bootstrap-vue/src/components/form-file/index";
@import "./node_modules/bootstrap-vue/src/components/form-input/index";
// @import "./node_modules/bootstrap-vue/src/components/form-radio/index";
// @import "./node_modules/bootstrap-vue/src/components/form-tags/index";
@import "./node_modules/bootstrap-vue/src/components/input-group/index";
// @import "./node_modules/bootstrap-vue/src/components/modal/index";
@import "./node_modules/bootstrap-vue/src/components/nav/index";
@import "./node_modules/bootstrap-vue/src/components/navbar/index";
// @import "./node_modules/bootstrap-vue/src/components/pagination/index";
// @import "./node_modules/bootstrap-vue/src/components/pagination-nav/index";
// @import "./node_modules/bootstrap-vue/src/components/popover/index";
// @import "./node_modules/bootstrap-vue/src/components/table/index";
// @import "./node_modules/bootstrap-vue/src/components/toast/index";
// @import "./node_modules/bootstrap-vue/src/components/tooltip/index";

As you can see, I commented out what I wasn't using. Then simply:

// in main.js:
import "./assets/_custom.scss";

Do not forget to include node-sass and sass-loader to use scss in Vue:

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

Note: You may need to adjust the SCSS import paths based on your build environment.


问:
jQuery new Object .bind
I've come across a code snippet that i am trying to understand. I did not find it anywhere. The code still works fine. Its about the .bind function of jQuery:

```<code>$(new Object()).bind()
</code>```

what does the bind function of jQuery do with " new Object() ". Can someone elaborate?! Thanks.

答:
I've got it solved. For someone who is interested-> There are two parts to it:

```<code><a id="refButton" href="#">Click Me !!</a>

**Part 1:**

    $(new Object()).bind("pressMe", function(event, data){
             $(document).ready(function(){
                   $('#refButton').bind("click",function(){
                      alert("Hi There !!");
                    });
             });
        });

**Part 2**

    if(some condition == TRUE){
      $.event.trigger("pressMe");
    }
</code>```

So, everybody knows that "$(document).ready(function(){" gets executed first - but - in this way only when Part2 condition is TRUE than it triggers the "pressMe" event defined in Part1 which ultimately listens to the click event of the #refButton Id.

But it still remains a mistery to me how the empty new Object() - disables the "$(document).ready(function(){" functionality till the trigger is activated.

But thanks to all who answered.

Title: jQuery new Object .bind

Body:
I've come across a code snippet that i am trying to understand. I did not find it anywhere. The code still works fine. Its about the .bind function of jQuery:

$(new Object()).bind()

what does the bind function of jQuery do with " new Object() ". Can someone elaborate?! Thanks.

Body:
I've got it solved. For someone who is interested-> There are two parts to it:

<a id="refButton" href="#">Click Me !!</a>

**Part 1:**

    $(new Object()).bind("pressMe", function(event, data){
             $(document).ready(function(){
                   $('#refButton').bind("click",function(){
                      alert("Hi There !!");
                    });
             });
        });

**Part 2**

    if(some condition == TRUE){
      $.event.trigger("pressMe");
    }

So, everybody knows that "$(document).ready(function(){" gets executed first - but - in this way only when Part2 condition is TRUE than it triggers the "pressMe" event defined in Part1 which ultimately listens to the click event of the #refButton Id.

But it still remains a mistery to me how the empty new Object() - disables the "$(document).ready(function(){" functionality till the trigger is activated.

But thanks to all who answered.


问:
Need properties in Configuration class
I have spring boot application and application.properties file in resources folder.
I need some properties in a configuration class. I cant use getClass().getClassLoader().getResourceAsStream() because null pointer. How do I get the properties in configuration class?
Property class:

@Configuration
@PropertySource("classpath:application.properties")
public class AppProperties {
    @Value("${server.ssl.key-store}")
    private String serverSSLKeyStore;

    @Value("${server.ssl.trust-store}")
    private String serverSSLTrustStore;

    @Value("${server.ssl.key-store-password}")
    private String serverSSLKeyStorePwd;

    @Value("${server.ssl.trust-store-password}")
    private String serverSSLTrustStorePwd;

    @Value("${rabo.api.url}")
    private String raboApiUrl;

    @Value("${tpp.certificate}")
    private String TPPCertificate;

    @Value("${rabo.client.id}")
    private String raboClientId;

    @Value("${rabo.key.id}")
    private String raboKeyId;

    @Value("${rabo.private.key}")
    private String raboPrivateKey;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("application.properties"));
        return propertySourcesPlaceholderConfigurer;

    }
// Getters

}
```

<p>Configuration class:</p>

<pre class="lang-java prettyprint-override"><code>@Configuration
public class RetrofitConfiguration {
    private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class);

    @Bean
    SSLTrustManagerHelper provideSSLTrustManagerHelper(AppProperties properties) {
        try {
            LOG.error(properties.getServerSSLKeyStore()); // PRINTS NULL
            InputStream keystore = new FileInputStream(properties.getServerSSLKeyStore());
            InputStream truststore = new FileInputStream(properties.getServerSSLTrustStore());
            String keystorePwd = properties.getServerSSLKeyStorePwd();
            String truststorePwd = properties.getServerSSLTrustStorePwd();
            SSLTrustManagerHelper ssl = null;
            try {
                ssl = new SSLTrustManagerHelper(keystore, keystorePwd, truststore, truststorePwd);
            } catch (Exception e) {
                LOG.error("error occured while creating ssl trust manager helper!", e);
            }
            return ssl;
        } catch (FileNotFoundException e) {
            LOG.error("file not found ", e);
            return null;
        }
    }

// Other config
}
</code>```

The AppProperties class is created but properties return null.

答:
What you want to do is setup a @ConfigurationProperties rather than a property source. This feature of Spring Boot allows you to read properties into a POJO that can be used elsewhere in code.

So the AppProperties would be something like:

```<code>@Configuration
@ConfigurationProperties
class AppProperties {
   private String serverSSLKeyStore;
   // the other properties

   public void setServerSslKeyStore(String value) {
     this.serverSSLKeyStore = value;
   }

   public String getServerSslKeyStore() {
     return this.serverSSLKeyStore;
   }
}
</code>```

Every field must have a corresponding property with the same name in the application.properties file. Note that each field should have getter and setter methods for this to work.

You can then initialize it in your Spring boot application using:

```<code>@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class) // not needed in later spring version
class MyApplication {
   public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
   }
}
</code>```

Title: Need properties in Configuration class

Body:
I have spring boot application and application.properties file in resources folder.
I need some properties in a configuration class. I cant use getClass().getClassLoader().getResourceAsStream() because null pointer. How do I get the properties in configuration class?
Property class:

@Configuration
@PropertySource("classpath:application.properties")
public class AppProperties {
    @Value("${server.ssl.key-store}")
    private String serverSSLKeyStore;

    @Value("${server.ssl.trust-store}")
    private String serverSSLTrustStore;

    @Value("${server.ssl.key-store-password}")
    private String serverSSLKeyStorePwd;

    @Value("${server.ssl.trust-store-password}")
    private String serverSSLTrustStorePwd;

    @Value("${rabo.api.url}")
    private String raboApiUrl;

    @Value("${tpp.certificate}")
    private String TPPCertificate;

    @Value("${rabo.client.id}")
    private String raboClientId;

    @Value("${rabo.key.id}")
    private String raboKeyId;

    @Value("${rabo.private.key}")
    private String raboPrivateKey;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("application.properties"));
        return propertySourcesPlaceholderConfigurer;

    }
// Getters

}

Configuration class:

@Configuration
public class RetrofitConfiguration {
    private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class);

    @Bean
    SSLTrustManagerHelper provideSSLTrustManagerHelper(AppProperties properties) {
        try {
            LOG.error(properties.getServerSSLKeyStore()); // PRINTS NULL
            InputStream keystore = new FileInputStream(properties.getServerSSLKeyStore());
            InputStream truststore = new FileInputStream(properties.getServerSSLTrustStore());
            String keystorePwd = properties.getServerSSLKeyStorePwd();
            String truststorePwd = properties.getServerSSLTrustStorePwd();
            SSLTrustManagerHelper ssl = null;
            try {
                ssl = new SSLTrustManagerHelper(keystore, keystorePwd, truststore, truststorePwd);
            } catch (Exception e) {
                LOG.error("error occured while creating ssl trust manager helper!", e);
            }
            return ssl;
        } catch (FileNotFoundException e) {
            LOG.error("file not found ", e);
            return null;
        }
    }

// Other config
}

The AppProperties class is created but properties return null.

Body:
What you want to do is setup a @ConfigurationProperties rather than a property source. This feature of Spring Boot allows you to read properties into a POJO that can be used elsewhere in code.

So the AppProperties would be something like:

@Configuration
@ConfigurationProperties
class AppProperties {
   private String serverSSLKeyStore;
   // the other properties

   public void setServerSslKeyStore(String value) {
     this.serverSSLKeyStore = value;
   }

   public String getServerSslKeyStore() {
     return this.serverSSLKeyStore;
   }
}

Every field must have a corresponding property with the same name in the application.properties file. Note that each field should have getter and setter methods for this to work.

You can then initialize it in your Spring boot application using:

@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class) // not needed in later spring version
class MyApplication {
   public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
   }
}


问:
Grid dashboard with Plotly dash
I'm trying to build a dashboard with Dash from Plotly composed of a series of tiles (Text) like in the picture below.

I'm trying to build a component to reuse it an build the layout below. Each box will contain a Title, a value and a description as shown below.

Is there a component available? Can someone help me with any basic idea/code ?

Thanks in advance!

答:
I would recommend checking out Dash Bootstrap Components (dbc).

You can use dbc.Col (columns) components nested into dbc.Row (rows) components to produce your layout. You can check them out here.

Then for the actual 'cards' as I'll call them, you can use the dbc.Card component. Here's the link.

Here's some example code replicating your layout:

```<code>import dash_bootstrap_components as dbc
import dash_html_components as html

card = dbc.Card(
    dbc.CardBody(
        [
            html.H4("Title", id="card-title"),
            html.H2("100", id="card-value"),
            html.P("Description", id="card-description")
        ]
    )
)

layout = html.Div([
    dbc.Row([
        dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
    ]),
    dbc.Row([
        dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
    ]),
    dbc.Row([
        dbc.Col([card]), dbc.Col([card])
    ])
])

</code>```

Best thing would probably be to have a function which creates those cards with parameters for ids, titles and descriptions to save the hassle of creating different cards:

```<code>def create_card(card_id, title, description):
    return dbc.Card(
        dbc.CardBody(
            [
                html.H4(title, id=f"{card_id}-title"),
                html.H2("100", id=f"{card_id}-value"),
                html.P(description, id=f"{card_id}-description")
            ]
        )
    )
</code>```

You can then just replace each card with create_card('id', 'Title', 'Description') as you please.

Another quick tip is that the col component has a parameter, width. You can give each column in a row a different value to adjust the relative widths. You can read more about that in the docs I linked above.

Hope this helps,

Ollie

Title: Grid dashboard with Plotly dash

Body:
I would recommend checking out Dash Bootstrap Components (dbc).

You can use dbc.Col (columns) components nested into dbc.Row (rows) components to produce your layout. You can check them out here.

Then for the actual 'cards' as I'll call them, you can use the dbc.Card component. Here's the link.

Here's some example code replicating your layout:

import dash_bootstrap_components as dbc
import dash_html_components as html

card = dbc.Card(
    dbc.CardBody(
        [
            html.H4("Title", id="card-title"),
            html.H2("100", id="card-value"),
            html.P("Description", id="card-description")
        ]
    )
)

layout = html.Div([
    dbc.Row([
        dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
    ]),
    dbc.Row([
        dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
    ]),
    dbc.Row([
        dbc.Col([card]), dbc.Col([card])
    ])
])

Best thing would probably be to have a function which creates those cards with parameters for ids, titles and descriptions to save the hassle of creating different cards:

def create_card(card_id, title, description):
    return dbc.Card(
        dbc.CardBody(
            [
                html.H4(title, id=f"{card_id}-title"),
                html.H2("100", id=f"{card_id}-value"),
                html.P(description, id=f"{card_id}-description")
            ]
        )
    )

You can then just replace each card with create_card('id', 'Title', 'Description') as you please.

Another quick tip is that the col component has a parameter, width. You can give each column in a row a different value to adjust the relative widths. You can read more about that in the docs I linked above.

Hope this helps,

Ollie


问:
How to apply new changes to current database in code fist EF core?
I have a project that coded with DotNet Core code first.

Now, there is a lot of real data on the database and i have to add some features with many tables and new relations to this project.

How can I apply these tables and their relations to the Database without adding manually?

Is there any way to use Add-Migratiosn and Update-Database to apply new changes via EF core instead of manually applying?

答:
If you have not many changes to your DBContext you can remove it and use Scaffolding to create new DbContext from the existing database schema. You can find more information in the official Microsoft documentation here.

It is better to use only one entity framework database approach either Database-First or Code-First.