问:
javascript count black spaces as 0?
I am building a script that is embedded in HTML to generate a report that extracts information from an internal company system.

The objective is to build some kind of a funnel, making the sum of records in each of the stages. For example, I have:

Processes in stage 1 = "3"

Processes in stage 2 = "5"

Processes in stage 3 = " "

Processes at stage 4 = "2"

Processes in stage 5 = " "

However, I have a problem when one of the stages is empty (it is not 0) because there is no stage in that specific process. When I try to add, for example, Stage 1 and Stage 3, it always returns an empty value, while it should give result 3 (3 + 0).

```<code><p id="global_calc"></p>
<script>
{
var A = Stage1.system.count;
var B = Stage2.system.count;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
</script>
</code>```

The Stage.system.count is the internal system's variable that has the number I want to eventually sum with var total.

But, for example, if Stage1.system.count = 3 and Stage2.system.count = " ", total result in " " instead of 3. How can I make this to count the black space as a 0?

答:
First it's probably worth checking what variables you have; any number + " " will always give you a string:

const x = 123 + " "; // "123 ";
const y = 123 + "" // "123"
```

<p>We can see that in practice in your example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
var A = 3;
var B = " ";
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;

console.log(("The total of this stage is: " + total).replace(/ /g, '*'))</code>```

```
</div>
</div>
</p>

<p>It seems like you're using <code>undefined</code> as part of the addition, which returns the value <code>NaN</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
var A = 3;
var B = undefined;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;

console.log(("The total of this stage is: " + total).replace(/ /g, '*'))</code>```

```
</div>
</div>
</p>

<p>We'll need more details to figure out exactly why you're getting <code>" "</code> for total.</p>

<p>If you want a function which converts <code>number -> number</code> and <code>" " -> 0</code> then <code>Number</code> would do:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const x = 3;
const y = " ";

console.log(Number(x));
console.log(Number(y));</code>```

Title: javascript count black spaces as 0?

Body:
I am building a script that is embedded in HTML to generate a report that extracts information from an internal company system.

The objective is to build some kind of a funnel, making the sum of records in each of the stages. For example, I have:

Processes in stage 1 = "3"

Processes in stage 2 = "5"

Processes in stage 3 = " "

Processes at stage 4 = "2"

Processes in stage 5 = " "

However, I have a problem when one of the stages is empty (it is not 0) because there is no stage in that specific process. When I try to add, for example, Stage 1 and Stage 3, it always returns an empty value, while it should give result 3 (3 + 0).

The Stage.system.count is the internal system's variable that has the number I want to eventually sum with var total.

But, for example, if Stage1.system.count = 3 and Stage2.system.count = " ", total result in " " instead of 3. How can I make this to count the black space as a 0?

Body:
First it's probably worth checking what variables you have; any number + " " will always give you a string:

const x = 123 + " "; // "123 ";
const y = 123 + "" // "123"

We can see that in practice in your example:

{
var A = 3;
var B = " ";
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;

console.log(("The total of this stage is: " + total).replace(/ /g, '*'))

<div id="global_calc"></div>

It seems like you're using undefined as part of the addition, which returns the value NaN:

{
var A = 3;
var B = undefined;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;

console.log(("The total of this stage is: " + total).replace(/ /g, '*'))

<div id="global_calc"></div>

We'll need more details to figure out exactly why you're getting " " for total.

If you want a function which converts number -> number and " " -> 0 then Number would do:

const x = 3;
const y = " ";

console.log(Number(x));
console.log(Number(y));


来源: stackexchange

问:
How do I get a volatile function argument working?
I am completely unexperienced in C++, I use C all the time. In my recent hobby project I need to mix in a C++ library with my C code thus forcing me to have a C++ main.cpp.

I am right now meddling my C code to compile as C++. This even works pretty well except for one problem I simply cannot solve.

This is an interrupt service incrementing my unix time variable every second and also doing a conversion into spli-up time format afterwards. Since this happens in an interrupt I set the variables as volatile.

```<code>volatile time_t UNIX_TIME = 0;
volatile struct tm TIME_CUR_LOCALTIME;

if (htim == &htim2){
    UNIX_TIME++;
    TIME_CUR_LOCALTIME = *localtime(&UNIX_TIME);
}
</code>```

From library time.h:

```<code>struct tm *localtime (const time_t *_timer);
</code>```

With gcc this compiles flawless.

g++ is a different story. It gives me the error:

error: passing 'volatile tm' as 'this' argument discards qualifiers [-fpermissive]

I tried multiple casts and stuff, the only way this starts working by itself is when I drop both volatile qualifiers. But I don't want that.

What is the correct way to get this working? I am out of ideas.

答:
Copy the time first into a non-volatile instance:</p>

```<code>time_t t = UNIX_TIME;
tm local = *localtime(&t);
TIME_CUR_LOCALTIME.tm_sec   = local.tm_sec;
TIME_CUR_LOCALTIME.tm_min   = local.tm_min;
TIME_CUR_LOCALTIME.tm_hour  = local.tm_hour;
TIME_CUR_LOCALTIME.tm_mday  = local.tm_mday;
TIME_CUR_LOCALTIME.tm_mon   = local.tm_mon;
TIME_CUR_LOCALTIME.tm_year  = local.tm_year;
TIME_CUR_LOCALTIME.tm_wday  = local.tm_wday;
TIME_CUR_LOCALTIME.tm_yday  = local.tm_yday;
TIME_CUR_LOCALTIME.tm_isdst = local.tm_isdst;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am completely unexperienced in C++, I use C all the time. In my recent hobby project I need to mix in a C++ library with my C code thus forcing me to have a C++ main.cpp.

I am right now meddling my C code to compile as C++. This even works pretty well except for one problem I simply cannot solve.

This is an interrupt service incrementing my unix time variable every second and also doing a conversion into spli-up time format afterwards. Since this happens in an interrupt I set the variables as volatile.

volatile time_t UNIX_TIME = 0;
volatile struct tm TIME_CUR_LOCALTIME;

if (htim == &htim2){
    UNIX_TIME++;
    TIME_CUR_LOCALTIME = *localtime(&UNIX_TIME);
}

From library time.h:

struct tm *localtime (const time_t *_timer);

With gcc this compiles flawless.

g++ is a different story. It gives me the error:

error: passing 'volatile tm' as 'this' argument discards qualifiers [-fpermissive]

I tried multiple casts and stuff, the only way this starts working by itself is when I drop both volatile qualifiers. But I don't want that.

What is the correct way to get this working? I am out of ideas.

Body:
Copy the time first into a non-volatile instance:

time_t t = UNIX_TIME;
tm local = *localtime(&t);
TIME_CUR_LOCALTIME.tm_sec   = local.tm_sec;
TIME_CUR_LOCALTIME.tm_min   = local.tm_min;
TIME_CUR_LOCALTIME.tm_hour  = local.tm_hour;
TIME_CUR_LOCALTIME.tm_mday  = local.tm_mday;
TIME_CUR_LOCALTIME.tm_mon   = local.tm_mon;
TIME_CUR_LOCALTIME.tm_year  = local.tm_year;
TIME_CUR_LOCALTIME.tm_wday  = local.tm_wday;
TIME_CUR_LOCALTIME.tm_yday  = local.tm_yday;
TIME_CUR_LOCALTIME.tm_isdst = local.tm_isdst;


问:
Is it possible to create a function where [[prototype]] refers to another function
I would like to create function objects (yes, all functions are objects) with some control over the prototypal inheritance, that is, I would like one function to inherit from another.

I can make objects that have prototypal inheritance, and know to set the prototype property of a function performing as a constructor to initialize the [[prototype]] property of the object.

However, when creating a function, I must use the function operator or the Function constructor. I could try to swizzle Function.prototype, but (1) don't know if that is writable, and (2) that just seems quite dangerous [still, I should try doing that].

btw: I only care to do this for V8 within node.JS, so if there are means that work only for that environment, that would be acceptable.

For the record, I have seen this:
Is it possible to create a function with another prototype than Function.prototype?

答:
I think I understand what you're trying to do.  In short, there's no way to really do it natively.  You'd have to access the Function constructor, which for function expressions and definitions (i.e. anything using the 'function' keyword), isn't possible as far as I can tell.  You could overwrite Function and just always use new Function([args], string) but I doubt you (or any JS programmer) want to do that.

Your best bet would probably be to send your function expressions to another function that returns the function object with your custom methods dynamically added:

```<code>wrapFunc = function(f){
  f.customFunc = someCustomFunc;
  return f;
}

var myNewFunc = wrapFunc(
  function(){
    //do something
  }
);

myNewFunc.customFunc();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think I understand what you're trying to do.  In short, there's no way to really do it natively.  You'd have to access the Function constructor, which for function expressions and definitions (i.e. anything using the 'function' keyword), isn't possible as far as I can tell.  You could overwrite Function and just always use new Function([args], string) but I doubt you (or any JS programmer) want to do that.

Your best bet would probably be to send your function expressions to another function that returns the function object with your custom methods dynamically added:

wrapFunc = function(f){
  f.customFunc = someCustomFunc;
  return f;
}

var myNewFunc = wrapFunc(
  function(){
    //do something
  }
);

myNewFunc.customFunc();


问:
Loading css file in django allauth login page
I can't seem to be able to change the css of my allauth login page. I would like to add some custom css to change a few things.

I created a base.css file

```<code>div_id_login.form-group{
    font-weight:200;
}
</code>```

That is loaded in my login.html file

```<code>{% extends "account/base.html" %}

{% load i18n %}
{% load account socialaccount %}
{%  load crispy_forms_tags %}
{%  load static %}

{% block head_title %}{% trans "Sign In" %}{% endblock %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<head>
    <link rel="stylesheet" href="{% static 'css/base.css' %}">
</head>
{% block content %}

<h1 style = "text-align: center;">{% trans "Sign In" %}</h1>
...
</code>```

The div class mentioned in the base.css file should be this:

I have made changes to my base.html file according to the answer suggested:

```<code>{%  load static %}
<!DOCTYPE html>
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <head>
    <title>{% block head_title %}{% endblock %}</title>
    {% block extra_head %}
    {% endblock %}
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="{% static 'css/base.css' %}">
  </head>
</code>```

However, still the css changes I made are still not appearing in login.html

答:
Maybe it's because Django can't find your base.css. Do you get a 404 error when you access the CSS upon visiting the webpage? The error would appear like this in the console while running the server:

```GET /static/account/style.css HTTP/1.1" <strong>404</strong> 1677```

In my case, my CSS file is located in <project directory>/static/account/style.css

Django can't seem to find my style.css so I added this in the project's settings.py:

```<code>STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
</code>```

And the CSS file is working now. Django's static file searching is kind of tricky.

Body:
I can't seem to be able to change the css of my allauth login page. I would like to add some custom css to change a few things.

I created a base.css file

div_id_login.form-group{
    font-weight:200;
}

That is loaded in my login.html file

{% extends "account/base.html" %}

{% load i18n %}
{% load account socialaccount %}
{%  load crispy_forms_tags %}
{%  load static %}

{% block head_title %}{% trans "Sign In" %}{% endblock %}

    <link rel="stylesheet" href="{% static 'css/base.css' %}">

{% block content %}

{% trans "Sign In" %}

...

The div class mentioned in the base.css file should be this:

I have made changes to my base.html file according to the answer suggested:

{%  load static %}
<!DOCTYPE html>

    <title>{% block head_title %}{% endblock %}</title>
    {% block extra_head %}
    {% endblock %}
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="{% static 'css/base.css' %}">

However, still the css changes I made are still not appearing in login.html

Body:
Maybe it's because Django can't find your base.css. Do you get a 404 error when you access the CSS upon visiting the webpage? The error would appear like this in the console while running the server:

GET /static/account/style.css HTTP/1.1" 404 1677

In my case, my CSS file is located in <project directory>/static/account/style.css

Django can't seem to find my style.css so I added this in the project's settings.py:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

And the CSS file is working now. Django's static file searching is kind of tricky.


问:
How can Azure Data Factory access a Custom Data Connector
I've just started to look at Azure Data Factory as a possible way to get data we are currently consuming for Power BI via custom connectors, primarily to access Graph APIs. I can't see if the same data is available to Azure Data Factory. Is there any way to achieve this?</p>

答:
We decided to use Logic Apps, rather than Data Factory, which offer a convenient means to access Graph APIs, as Logic Apps support OAuth well i.e. we're not using Data Connectors any more

In addition, we put some of the more complicated logic into Stored Procedures, as Logic Apps, despite their name, can only handle basic logic


问:
Disable config edit in solr
I am trying to disable the configApi in solr and i read it in a blog stating that "Disable the ConfigAPI if not in use, by running Solr with the system property disable.configEdit=true" .Can someone please explain a little bit on how actually we do it ?</p>

答:
Adding the below line in solr.in.cmd and restarting SOLR worked for me,

```<code>set SOLR_OPTS=%SOLR_OPTS% -Ddisable.configEdit=true
</code>```

We could also validate if the Config API is disabled by executing the following curl command which should result in 403 Forbidden Error,

```<code>curl https://localhost:8983/solr/<core_name>/config -H "Accept: application/json" -H "Content-type:application/json" -d "{'set-user-property' : {'variable_name':'some_value'}}"
</code>```

Title: Disable config edit in solr

Body:
Adding the below line in solr.in.cmd and restarting SOLR worked for me,

set SOLR_OPTS=%SOLR_OPTS% -Ddisable.configEdit=true

We could also validate if the Config API is disabled by executing the following curl command which should result in 403 Forbidden Error,

curl https://localhost:8983/solr/<core_name>/config -H "Accept: application/json" -H "Content-type:application/json" -d "{'set-user-property' : {'variable_name':'some_value'}}"


问:
Active checkbox changes table background color except for a cell
When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red.
That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html></code>```

Thanks already for the help.

答:
Add the following code to your CSS:

#checkbox_id:checked+table #red {
  background-color: red;
}
```

<p>Here is a code snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}

#checkbox_id:checked+table {
  background-color: yellow;
}

#checkbox_id:checked+table #red {
  background-color: red;
}

/*Table styles*/

.tg {
  border-collapse: collapse;
  border-spacing: 0;
}

.tg td {
  border-color: black;
  border-style: solid;
  border-width: 1px;
  font-family: Arial, sans-serif;
  font-size: 14px;
  overflow: hidden;
  padding: 10px 5px;
  word-break: normal;
  width: 50px;
  height: 50px;
}

.tg th {
  border-color: black;
  border-style: solid;
  border-width: 1px;
  font-family: Arial, sans-serif;
  font-size: 14px;
  font-weight: normal;
  overflow: hidden;
  padding: 10px 5px;
  word-break: normal;
  width: 50px;
  height: 50px;
}

.tg .tg-0lax {
  text-align: left;
  vertical-align: top
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Check6</title>

  CLICCA
  <input type="checkbox" id="checkbox_id">

```

Body:
When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red.
That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Check6</title>

    CLICCA
    <input type="checkbox" id="checkbox_id">

Thanks already for the help.

Body:
Add the following code to your CSS:

#checkbox_id:checked+table #red {
  background-color: red;
}

Here is a code snippet:

label {
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
  display: inline-block;
  cursor: pointer;
  margin: 5px;
}

#checkbox_id:checked+table {
  background-color: yellow;
}

#checkbox_id:checked+table #red {
  background-color: red;
}

/*Table styles*/

.tg {
  border-collapse: collapse;
  border-spacing: 0;
}

.tg td {
  border-color: black;
  border-style: solid;
  border-width: 1px;
  font-family: Arial, sans-serif;
  font-size: 14px;
  overflow: hidden;
  padding: 10px 5px;
  word-break: normal;
  width: 50px;
  height: 50px;
}

.tg th {
  border-color: black;
  border-style: solid;
  border-width: 1px;
  font-family: Arial, sans-serif;
  font-size: 14px;
  font-weight: normal;
  overflow: hidden;
  padding: 10px 5px;
  word-break: normal;
  width: 50px;
  height: 50px;
}

.tg .tg-0lax {
  text-align: left;
  vertical-align: top
}

<!DOCTYPE html>
<html lang="it" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Check6</title>
</head>

<body>
  <label for="checkbox_id">CLICCA</label>
  <input type="checkbox" id="checkbox_id">
  <table class="tg">
    <thead>
      <tr>
        <th class="tg-0lax"></th>
        <th class="tg-0lax"></th>
        <th class="tg-0lax"></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="tg-0lax"></td>
        <td id="red"></td>
        <td class="tg-0lax"></td>
      </tr>
      <tr>
        <td class="tg-0lax"></td>
        <td class="tg-0lax"></td>
        <td class="tg-0lax"></td>
      </tr>
    </tbody>
  </table>
</body>

</html>


问:
Gitlab Maven Package Registry. Install a package with artifact dependency
I need to connect Package Registry in Gitlab using Maven Repository. I did everything according to: https://gitlab.com/help/user/packages/maven_repository/index.md. I have a problem with "Installing a package".

I have added dependency in my pom.xml and then tried to mvn install. But I have an error. As far as I know, Maven should use the repository from pom.xml to search for my artifact, but it doesn't

```<code>[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.479 s
[INFO] Finished at: 2020-05-28T20:23:59+07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Error resolving version for plugin '.upprpo:budget-planner_' from the repositories [local (C:\Users\User\.m2\repository), central (https://repo.maven.apache.org/maven2)]: Plugin not found in any plugin repository -> [Help 1]
org.apache.maven.plugin.version.PluginVersionResolutionException: Error resolving version for plugin '.upprpo:budget-planner_' from the repositories [local (C:\Users\User\.m2\repository), central (https://repo.maven.apache.org/maven2)]: Plugin not found in any plugin repository
at org.apache.maven.plugin.version.internal.DefaultPluginVersionResolver.selectVersion (DefaultPluginVersionResolver.java:236)
at org.apache.maven.plugin.version.internal.DefaultPluginVersionResolver.resolveFromRepository (DefaultPluginVersionResolver.java:146)
at org.apache.maven.plugin.version.internal.DefaultPluginVersionResolver.resolve (DefaultPluginVersionResolver.java:94)
at org.apache.maven.lifecycle.internal.MojoDescriptorCreator.resolvePluginVersion (MojoDescriptorCreator.java:281)
at org.apache.maven.lifecycle.internal.MojoDescriptorCreator.getMojoDescriptor (MojoDescriptorCreator.java:236)
at org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalculator.calculateTaskSegments (DefaultLifecycleTaskSegmentCalculator.java:104)
at org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalculator.calculateTaskSegments (DefaultLifecycleTaskSegmentCalculator.java:83)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:89)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:567)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginVersionResolutionException
PS D:\JavaLabs\budget-planner gitlab> mvn dependency:get -Dartifact=nsu.upprpo:budget-planner_:2.0
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] 'dependencies.dependency[nsu.upprpo:budget-planner_:2.0]' for nsu.upprpo:budget-planner_:2.0 is referencing itself. @ line 158, column 21
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project nsu.upprpo:budget-planner_:2.0 (D:\JavaLabs\budget-planner gitlab\pom.xml) has 1 error
[ERROR]     'dependencies.dependency[nsu.upprpo:budget-planner_:2.0]' for nsu.upprpo:budget-planner_:2.0 is referencing itself. @ line 158, column 21
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
</code>```

And there is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>nsu.upprpo</groupId>
<artifactId>budget-planner_</artifactId>
<version>2.0</version>
<packaging>jar</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <sonar.host.url>http://84.237.50.237:9000/</sonar.host.url>
    <sonar.login>9508b619882a5709e02a1902a6361249c8e65db6</sonar.login>
    <sonar.jacoco.reportPaths>${project.build.directory}/coverage-reports/jacoco.exec</sonar.jacoco.reportPaths>
    <sonar.coverage.exclusions>**/gui/*, **/application/*</sonar.coverage.exclusions>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>11</source>
                <target>11</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.5</version>
            <executions>

                <execution>
                    <id>pre-unit-test</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                    <configuration>
                        <destFile>${project.build.directory}/coverage-reports/jacoco.exec</destFile>
                        <propertyName>surefireArgLine</propertyName>
                    </configuration>
                </execution>

                <execution>
                    <id>post-unit-test</id>
                    <phase>test</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                    </configuration>
                </execution>

            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.15</version>
            <configuration>
                <argLine>${surefireArgLine}</argLine>
            </configuration>
        </plugin>

    </plugins>
</build>

<repositories>
    <repository>
        <id>gitlab-maven</id>
        <url>https://gitlab.com/api/v4/projects/19026178/packages/maven</url>
    </repository>
</repositories>

<distributionManagement>
    <repository>
        <id>gitlab-maven</id>
        <url>https://gitlab.com/api/v4/projects/19026178/packages/maven</url>
    </repository>

    <snapshotRepository>
        <id>gitlab-maven</id>
        <url>https://gitlab.com/api/v4/projects/19026178/packages/maven</url>
    </snapshotRepository>
</distributionManagement>

<dependencies>

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>6.2.3</version>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.10</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.14.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.4.Final</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.intellij</groupId>
        <artifactId>forms_rt</artifactId>
        <version>7.0.3</version>
    </dependency>

    <dependency>
        <groupId>org.jdatepicker</groupId>
        <artifactId>jdatepicker</artifactId>
        <version>1.3.4</version>
    </dependency>

    <dependency>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.8.5</version>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.3.3</version>
    </dependency>

    <dependency>
        <groupId>nsu.upprpo</groupId>
        <artifactId>budget-planner_</artifactId>
        <version>2.0</version>
    </dependency>

</dependencies>
</code>```

I found information that I should use Artifactory or something similar, but I would like to do without it

答:
Is the plugin '.upprpo:budget-planner_' something you are building?  If so you'll need to build it and put it in the projects' repository first.  I appear that your project is still looking for that dependency on https://repo.maven.apache.org/maven2.

If that's an external dependency you're not building, check the spelling of the name and if it is in the main Maven repository.

Body:
I need to connect Package Registry in Gitlab using Maven Repository. I did everything according to: https://gitlab.com/help/user/packages/maven_repository/index.md. I have a problem with "Installing a package".

I have added dependency in my pom.xml and then tried to mvn install. But I have an error. As far as I know, Maven should use the repository from pom.xml to search for my artifact, but it doesn't

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.479 s
[INFO] Finished at: 2020-05-28T20:23:59+07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Error resolving version for plugin '.upprpo:budget-planner_' from the repositories [local (C:\Users\User\.m2\repository), central (https://repo.maven.apache.org/maven2)]: Plugin not found in any plugin repository -> [Help 1]
org.apache.maven.plugin.version.PluginVersionResolutionException: Error resolving version for plugin '.upprpo:budget-planner_' from the repositories [local (C:\Users\User\.m2\repository), central (https://repo.maven.apache.org/maven2)]: Plugin not found in any plugin repository
at org.apache.maven.plugin.version.internal.DefaultPluginVersionResolver.selectVersion (DefaultPluginVersionResolver.java:236)
at org.apache.maven.plugin.version.internal.DefaultPluginVersionResolver.resolveFromRepository (DefaultPluginVersionResolver.java:146)
at org.apache.maven.plugin.version.internal.DefaultPluginVersionResolver.resolve (DefaultPluginVersionResolver.java:94)
at org.apache.maven.lifecycle.internal.MojoDescriptorCreator.resolvePluginVersion (MojoDescriptorCreator.java:281)
at org.apache.maven.lifecycle.internal.MojoDescriptorCreator.getMojoDescriptor (MojoDescriptorCreator.java:236)
at org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalculator.calculateTaskSegments (DefaultLifecycleTaskSegmentCalculator.java:104)
at org.apache.maven.lifecycle.internal.DefaultLifecycleTaskSegmentCalculator.calculateTaskSegments (DefaultLifecycleTaskSegmentCalculator.java:83)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:89)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:567)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginVersionResolutionException
PS D:\JavaLabs\budget-planner gitlab> mvn dependency:get -Dartifact=nsu.upprpo:budget-planner_:2.0
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] 'dependencies.dependency[nsu.upprpo:budget-planner_:2.0]' for nsu.upprpo:budget-planner_:2.0 is referencing itself. @ line 158, column 21
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project nsu.upprpo:budget-planner_:2.0 (D:\JavaLabs\budget-planner gitlab\pom.xml) has 1 error
[ERROR]     'dependencies.dependency[nsu.upprpo:budget-planner_:2.0]' for nsu.upprpo:budget-planner_:2.0 is referencing itself. @ line 158, column 21
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException

And there is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>nsu.upprpo</groupId>
<artifactId>budget-planner_</artifactId>
<version>2.0</version>
<packaging>jar</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <sonar.host.url>http://84.237.50.237:9000/</sonar.host.url>
    <sonar.login>9508b619882a5709e02a1902a6361249c8e65db6</sonar.login>
    <sonar.jacoco.reportPaths>${project.build.directory}/coverage-reports/jacoco.exec</sonar.jacoco.reportPaths>
    <sonar.coverage.exclusions>**/gui/*, **/application/*</sonar.coverage.exclusions>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>11</source>
                <target>11</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.5</version>
            <executions>

                <execution>
                    <id>pre-unit-test</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                    <configuration>
                        <destFile>${project.build.directory}/coverage-reports/jacoco.exec</destFile>
                        <propertyName>surefireArgLine</propertyName>
                    </configuration>
                </execution>

                <execution>
                    <id>post-unit-test</id>
                    <phase>test</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                    </configuration>
                </execution>

            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.15</version>
            <configuration>
                <argLine>${surefireArgLine}</argLine>
            </configuration>
        </plugin>

    </plugins>
</build>

<repositories>
    <repository>
        <id>gitlab-maven</id>
        <url>https://gitlab.com/api/v4/projects/19026178/packages/maven</url>
    </repository>
</repositories>

<distributionManagement>
    <repository>
        <id>gitlab-maven</id>
        <url>https://gitlab.com/api/v4/projects/19026178/packages/maven</url>
    </repository>

    <snapshotRepository>
        <id>gitlab-maven</id>
        <url>https://gitlab.com/api/v4/projects/19026178/packages/maven</url>
    </snapshotRepository>
</distributionManagement>

<dependencies>

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>6.2.3</version>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.10</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.14.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.4.Final</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.intellij</groupId>
        <artifactId>forms_rt</artifactId>
        <version>7.0.3</version>
    </dependency>

    <dependency>
        <groupId>org.jdatepicker</groupId>
        <artifactId>jdatepicker</artifactId>
        <version>1.3.4</version>
    </dependency>

    <dependency>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.8.5</version>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.3.3</version>
    </dependency>

    <dependency>
        <groupId>nsu.upprpo</groupId>
        <artifactId>budget-planner_</artifactId>
        <version>2.0</version>
    </dependency>

</dependencies>

I found information that I should use Artifactory or something similar, but I would like to do without it


问:
How to ignore safe area for a background with a linear gradient in swiftUI?
With SwiftUI, I know how to set a background with a simple color all over screen. So only background ignore the safe area. But when I want to do this with a linear gradient, I don't know do this.

My view with a simple background :

```<code>import SwiftUI

struct Settings : View {
  var body: some View {
    ScrollView {
        VStack {
          Text("Boussole")
            .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
            .multilineTextAlignment(.leading)
            .font(.system(size: 28))
            .padding(.top, 15)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
          Toggle(isOn: .constant(false)) {
            Text("Afficher le vrai nord")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          Toggle(isOn: .constant(true)) {
            Text("Activer la vibration")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          .padding(.bottom, 20)
          Divider()
        }
      .padding(.leading, 25)
      .padding(.trailing, 25)
    }
    .background(Color.gray.edgesIgnoringSafeArea(.all))
  }
}
</code>```

So in this case, the safe area is ignored only for the background.

But how can I do this with this type of background ?

```<code>.background(LinearGradient(gradient: Gradient(colors: [Color(red: 189/255, green: 195/255, blue: 199/255, opacity: 1.0), .white]), startPoint: .topTrailing, endPoint: .bottomLeading), cornerRadius: 0)
</code>```

I don't know how to place .edgesIgnoringSafeArea(.all)

答:
This should fix the bottom trail for iPhone X, XS, 11 and so on</p>

```<code>struct ContentView: View {
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.black,.blue]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
            Text("The only label")
        }
    }
}
</code>```

Body:
With SwiftUI, I know how to set a background with a simple color all over screen. So only background ignore the safe area. But when I want to do this with a linear gradient, I don't know do this.

My view with a simple background :

import SwiftUI

struct Settings : View {
  var body: some View {
    ScrollView {
        VStack {
          Text("Boussole")
            .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
            .multilineTextAlignment(.leading)
            .font(.system(size: 28))
            .padding(.top, 15)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
          Toggle(isOn: .constant(false)) {
            Text("Afficher le vrai nord")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          Toggle(isOn: .constant(true)) {
            Text("Activer la vibration")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          .padding(.bottom, 20)
          Divider()
        }
      .padding(.leading, 25)
      .padding(.trailing, 25)
    }
    .background(Color.gray.edgesIgnoringSafeArea(.all))
  }
}

So in this case, the safe area is ignored only for the background.

But how can I do this with this type of background ?

.background(LinearGradient(gradient: Gradient(colors: [Color(red: 189/255, green: 195/255, blue: 199/255, opacity: 1.0), .white]), startPoint: .topTrailing, endPoint: .bottomLeading), cornerRadius: 0)

I don't know how to place .edgesIgnoringSafeArea(.all)

Body:
This should fix the bottom trail for iPhone X, XS, 11 and so on

struct ContentView: View {
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.black,.blue]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
            Text("The only label")
        }
    }
}


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
The | and '+` are different mathematical operations.

Given the equations:

```<code>  unsigned int y = 2 + 2;
  unsigned int z = 2 | 2;
</code>```

will yield different answers.

Technically, the `|' operation is faster since it only uses OR gates inside the processor.  The addition operation requires more gates.

The performance gained by using '|' over '+' is usually wasted by the time required to fetch data into and out of the processor.  In otherwords, the net performance is negligible. (The time difference is usually in the range of nanoseconds.)

However, the maintenance time between the two forms may be greater.  When one is needing arithmetic rather than bit twiddling (or vice versa), trying to find this runtime error can be great.

Use the proper operator for the proper purpose.  Give the testing and maintenance groups a break.  This kind of micro-optimization is not worthwhile.

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.

Body:
The | and '+` are different mathematical operations.

Given the equations:

  unsigned int y = 2 + 2;
  unsigned int z = 2 | 2;

will yield different answers.

Technically, the `|' operation is faster since it only uses OR gates inside the processor.  The addition operation requires more gates.

The performance gained by using '|' over '+' is usually wasted by the time required to fetch data into and out of the processor.  In otherwords, the net performance is negligible. (The time difference is usually in the range of nanoseconds.)

However, the maintenance time between the two forms may be greater.  When one is needing arithmetic rather than bit twiddling (or vice versa), trying to find this runtime error can be great.

Use the proper operator for the proper purpose.  Give the testing and maintenance groups a break.  This kind of micro-optimization is not worthwhile.


问:
Lighthouse Performance values are different in report vs Profile
When running a Lighthouse (e.g. v6) via NPM package, for example:

lighthouse --view --save-assets https://example.com

Getting these numbers in the browser:

Then using Dev Tools > Performance > Load Profile to load the saved trace JSON, getting:

Question

Largest Contentful Paint 2.3s in the report vs 408.0ms in the profile. How to correlate this?

答:
The Lighthouse works as expected.

One would have to check-out the Simulated throttling:

After checked-out clicking View Trace will show the actual data in the Performance panel.

By default Simulated throttling is checked-in, it would run the page without any throttling and then apply throttling manually to the result. In this case clicking View Trace shows the original (unthrottled) data.


问:
Existence of a permutation under constraints (Interview Street - Manipulative Numbers)
I am trying to solve this problem: https://www.interviewstreet.com/challenges/dashboard/#problem/4f9a33ec1b8ea

Suppose that A is a list of n numbers ( A1, A2, A3, ... , An) and B ( B1, B2, B3, .. ,Bn ) is a permutation of these numbers. We say B is K-Manipulative if and only if its following value:

M(B) = min( B1 Xor B2, B2 Xor B3, B3 Xor B4, ... , Bn-1 Xor Bn, Bn Xor B1 ) is not less than 2^K.
You are given n number A1 to An, You have to find the biggest K such that there exists a permutation B of these numbers which is K-Manipulative.

Input:

In the first line of the input there is an integer N.
In the second line of input there are N integers A1 to An
N is not more than 100.
Ai is non-negative and will fit in 32-bit integer.

Output:

Print an integer to the output being the answer to the test. If there is no such K print -1 to the output.

Sample Input

3
13 3 10

Sample Output

2

Sample Input

4
1 2 3 4

Sample Output

1

Explanation

First Sample test
Here the list A is {13, 3, 10}. One possible permutation of A is, B = (10, 3, 13).

For B,  min( B1 xor B2, B2 xor B3, B3 xor B1 ) = min( 10 xor 3, 3 xor 13, 13 xor 10 ) = min( 9, 14, 7 ) = 7.

So there exist a permutation B of A such that M(B) is not less than 4 i.e 2^2. However there does not exist any permutation B of A such that M(B) is not less than 8 ie 2^3. So the maximum possible value of K is 2.

==================================================================================

Here are the attempts I have made so far.

Attempt 1: Greedy Algorithm

Place the input in an array A[1..n]

Compute the value M(A). This gives the location of the min XOR value (i, (i + 1) % n)

Check whether swapping A[i] or A[(i + 1) % n] with any other element of the array increases the value of M(A). If such an element exists, make the swap.

Repeat steps 2 & 3 until the value M(A) cannot be improved.

This gives a local maxima for sure, but I am not sure whether this gives the global maxima.

Attempt 2: Checking for the existence of a permutation given neighbor constraints

Given input A[1..n], For i = 1..n and j = (i+1)..n compute x_ij = A[i] XOR A[j]

Compute the max(x_ij). Note that 2^p <= max(x_ij) < 2^(p+1) for some p.

Collect all x_ij such that x_ij >= 2^p. Note that this collection can be treated as a graph G with nodes {1, 2, .. n} and nodes i and j have an undirected edge between them if x_ij >= 2^p.

Check whether the graph G has a cycle which visits each node exactly once. If such a cycle exists, k = p. Otherwise, let p = p - 1, goto step 3.

This gives the correct answer, but note that in step 4 we are essentially checking whether a graph has a hamiltonian cycle which is a very hard problem.

Any hints or suggestions?

答:
Greedy Approach #priority_queue

firstly insert all pairs xor value and consecutive index i and j ->pq.push(tuple(v[i]^v[j],i,j))
now pop the first maxm xor value and set the both index i and j
now again pop that maxm xor value which is comes from the i or j
this operation perform up to 1 to n
then return nth poped xor value


问:
Minikube Error "loading cached images: Docker load'
I'm trying to start minikube in Windows 10 using below command. minikube version v1.10.1

```<code>minikube start --vm-driver=virtualbox --no-vtx-check
</code>```

But i'm getting below error

```<code> Creating virtualbox VM (CPUs=2, Memory=4096MB, Disk=20000MB) ...
    * Preparing Kubernetes v1.18.2 on Docker 19.03.8 ...
    * Unable to load cached images: loading cached images: Docker load /var/lib/minikube/images/pause_3.2: loadimage docker.: docker load -i /var/lib/minikube/images/pause_3.2: Process exited with status 1
    stdout:

    stderr:
    Error processing tar file(exit status 1): archive/tar: invalid tar header

    *
    * [OOM_KILL_SCP] Failed to update cluster updating node: downloading binaries: NewSession: new client: new client: ssh: handshake failed: read tcp 127.0.0.1:2506->127.0.0.1:2427: wsarecv: An existing connection was forcibly closed by the remote host.
    * Suggestion: Disable dynamic memory in your VM manager, or pass in a larger --memory value
    * Related issue: https://github.com/kubernetes/minikube/issues/1766
</code>```

So i thought of degrading the minikube version. so i used v1.7.2 version and then v1.3.0 version but in both cases i got the same above mentioned error. Kindly suggest

Regards

答:
It worked. Below are the steps which i have done as part of change for minikube in Windows 10 Home edition where hyper-v is not supported

Step 1: Enable virtualization and install virtualbox

step 2: add kutectl and minikube installer

step 3:

Run below command

```<code>minikube start --vm-driver=virtualbox --memory 4096
</code>```

If it fails then

minikube delete and delete .minikube and .kubectl folders

Enable WSL 2

Open PowerShell as Administrator and run:

Enable WSL1

```<code>dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
</code>```

Enable WSL2

```<code>dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
</code>```

Restart the system

Install Linux Distribution Package

Click here!

Disable hypervisorlaunchtype

Open CMD

Run bcdedit to check hypervisor status

```<code>bcdedit
</code>```

If hypervisorlaunchtype is set to auto then disable it:

```<code>bcdedit /set hypervisorlaunchtype off
</code>```

Reboot

Again run minikube

```<code>minikube start --vm-driver=virtualbox --memory 4096
</code>```

Body:
I'm trying to start minikube in Windows 10 using below command. minikube version v1.10.1

minikube start --vm-driver=virtualbox --no-vtx-check

But i'm getting below error

 Creating virtualbox VM (CPUs=2, Memory=4096MB, Disk=20000MB) ...
    * Preparing Kubernetes v1.18.2 on Docker 19.03.8 ...
    * Unable to load cached images: loading cached images: Docker load /var/lib/minikube/images/pause_3.2: loadimage docker.: docker load -i /var/lib/minikube/images/pause_3.2: Process exited with status 1
    stdout:

    stderr:
    Error processing tar file(exit status 1): archive/tar: invalid tar header

    *
    * [OOM_KILL_SCP] Failed to update cluster updating node: downloading binaries: NewSession: new client: new client: ssh: handshake failed: read tcp 127.0.0.1:2506->127.0.0.1:2427: wsarecv: An existing connection was forcibly closed by the remote host.
    * Suggestion: Disable dynamic memory in your VM manager, or pass in a larger --memory value
    * Related issue: https://github.com/kubernetes/minikube/issues/1766

So i thought of degrading the minikube version. so i used v1.7.2 version and then v1.3.0 version but in both cases i got the same above mentioned error. Kindly suggest

Regards

Body:
It worked. Below are the steps which i have done as part of change for minikube in Windows 10 Home edition where hyper-v is not supported

Step 1: Enable virtualization and install virtualbox

step 2: add kutectl and minikube installer

step 3:

Run below command

minikube start --vm-driver=virtualbox --memory 4096

If it fails then

minikube delete and delete .minikube and .kubectl folders

Enable WSL 2

Open PowerShell as Administrator and run:

Enable WSL1

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Enable WSL2

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Restart the system

Install Linux Distribution Package

Click here!

Disable hypervisorlaunchtype

Open CMD

Run bcdedit to check hypervisor status

bcdedit

If hypervisorlaunchtype is set to auto then disable it:

bcdedit /set hypervisorlaunchtype off

Reboot

Again run minikube

minikube start --vm-driver=virtualbox --memory 4096


问:
Hidden Features of VHDL
The original question was:

What are some really useful but esoteric language features in VHDL that you've actually been able to employ to do useful work?

The original question was deleted, and I was just answering. I think this is an interesting question, especially when you compare VHDL to other (normal) programming languages.

Disclaimer: I only did few trivial examples in VHDL.

But what I especially liked, when compared to other programming languages (which is probably not what you are asking about, but I think just for these things every programmer should know VHDL a bit):

The ability to have several different implementations (architectures) of a single interface, and exchange them easily.

The low-overhead parallelism inherent to the language model. It sort of reminds me of dataflow languages.

答:
Conditional signal assignment is the same as a case statement - i.e. equal weight branches. Selected signal assignment is a priority encoder structure  - i.e. equivalent to nested if/then/else statements. Note that all concurrent assignment statements in vhdl are identically equivalent to a process with a sensitivity list composed of the signals on the right hand side of the assignment operator.

My favourite esoteric features are configurations (which are especially useful when you have multiple architectures of the same entity) and access types. These allow one to create dynamic data structures. Not useful for hardware design, but very useful for testbench creation. Method overloading my argument type signature also makes for very readable code - and is a feature sadly lacking in SystemVerilog.

Paul.

ContentLicense: CC BY-SA 2.5

Title: Hidden Features of VHDL


问:
how to apply dcc interval on the selected drop down value
I would like user to first select an patient id from the drop down menu, that selected id will then be refreshed using dcc.Interval to obtain his current blood pressure live in text output (real time via database).

However, I can only obtain the blood pressure of a patient but still have to refresh it by f5 for new reading pressure.
How do I modify my second callback and its relevant function?

I tried lookup those tutorials but still not sure how to mash things up. Thanks.

My app.layout:

```<code>app.layout = html.Div([

                html.Div([dcc.Dropdown(id='dropdown',
                                    options=[{'label': i, 'value': i} for i in x],
                                    value='x',
                                    clearable=False),
                        html.Div(id='table-container')]),

                html.Div([html.Div(id='live-update-text'),
                          dcc.Interval(id='interval-component', interval=2000, n_intervals=0)])

])
</code>```

Respective callback:

```<code>#First callback and its function [working as expected]
@app.callback(
    dash.dependencies.Output('dropdown', 'options'),
    [dash.dependencies.Input('dropdown', 'value')])
def get_update_db_dropdown(value):
    #connect to database and then return the results.

#Second callback and its pseudo function; I want this to be self refresh/live updating via dcc interval process
@app.callback(
    Output('live-update-text', 'children'),
    [dash.dependencies.Input('dropdown', 'value')])
def set_display_livedata(value):
    #connect to database and obtain blood pressure where id=value
    return f'selected {id} has {bloodPressure}'
</code>```

答:
To trigger the callback periodically, you must add the Interval component as an input. Hence, your second callback should be

```<code>@app.callback(
    Output('live-update-text', 'children'),
    [dash.dependencies.Input('dropdown', 'value'), dash.dependencies.Input('interval-component', 'n_intervals')])
def set_display_livedata(value, n_intervals):
    #connect to database and obtain blood pressure where id=value
    return f'selected {id} has {bloodPressure}'
</code>```

Body:
I would like user to first select an patient id from the drop down menu, that selected id will then be refreshed using dcc.Interval to obtain his current blood pressure live in text output (real time via database).

However, I can only obtain the blood pressure of a patient but still have to refresh it by f5 for new reading pressure.
How do I modify my second callback and its relevant function?

I tried lookup those tutorials but still not sure how to mash things up. Thanks.

My app.layout:

app.layout = html.Div([

                html.Div([dcc.Dropdown(id='dropdown',
                                    options=[{'label': i, 'value': i} for i in x],
                                    value='x',
                                    clearable=False),
                        html.Div(id='table-container')]),

                html.Div([html.Div(id='live-update-text'),
                          dcc.Interval(id='interval-component', interval=2000, n_intervals=0)])

])

Respective callback:

#First callback and its function [working as expected]
@app.callback(
    dash.dependencies.Output('dropdown', 'options'),
    [dash.dependencies.Input('dropdown', 'value')])
def get_update_db_dropdown(value):
    #connect to database and then return the results.

#Second callback and its pseudo function; I want this to be self refresh/live updating via dcc interval process
@app.callback(
    Output('live-update-text', 'children'),
    [dash.dependencies.Input('dropdown', 'value')])
def set_display_livedata(value):
    #connect to database and obtain blood pressure where id=value
    return f'selected {id} has {bloodPressure}'

Body:
To trigger the callback periodically, you must add the Interval component as an input. Hence, your second callback should be

@app.callback(
    Output('live-update-text', 'children'),
    [dash.dependencies.Input('dropdown', 'value'), dash.dependencies.Input('interval-component', 'n_intervals')])
def set_display_livedata(value, n_intervals):
    #connect to database and obtain blood pressure where id=value
    return f'selected {id} has {bloodPressure}'


问:
Error while creating a new app in reactjs
PS D:\React\counter-app> create-react-app tower
create-react-app : File C:\Users\ee209495\AppData\Roaming\npm\create-react-app.ps1 cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ create-react-app tower
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess</p>

答:
Try executing the console with admin credentials.
You might not have permissons while trying to execute npm commands.
i would also recommend to use npx create-reaact-app myapp.
This provides a previous check to see if you had already installed react packages, if not, it will install them for you.</p>


问:
How to style an element created with JavaScript by using the HTML id attribute
I am trying to style an element created with JavaScript like this:

```<code>  const h1 = document.createElement("h1");
  h1.textContent = data.name;
  h1.setAttribute("id", "heading");
  window.data.appendChild(h1);
</code>```

This is my CSS code:

```<code>#heading{
  padding-right: 100px;
  colour: red;
}
</code>```

The element appears on the page since i have an async function which takes data from a JSON file, but i don't see a difference in the style of the element. I can't seem to find the issue in the code since I am new to JavaScript too.

答:
color instead of colour.
window.data is undifined

```<code>const h1 = document.createElement("h1");
h1.textContent = data.name;
h1.setAttribute("id", "heading");
document.getElementById("content").appendChild(h1);
</code>```

demo :
https://jsfiddle.net/smaha/gx71y63h/3/

Body:
I am trying to style an element created with JavaScript like this:

  const h1 = document.createElement("h1");
  h1.textContent = data.name;
  h1.setAttribute("id", "heading");
  window.data.appendChild(h1);

This is my CSS code:

#heading{
  padding-right: 100px;
  colour: red;
}

The element appears on the page since i have an async function which takes data from a JSON file, but i don't see a difference in the style of the element. I can't seem to find the issue in the code since I am new to JavaScript too.

Body:
color instead of colour.
window.data is undifined

const h1 = document.createElement("h1");
h1.textContent = data.name;
h1.setAttribute("id", "heading");
document.getElementById("content").appendChild(h1);

demo :
https://jsfiddle.net/smaha/gx71y63h/3/


问:
How to check whether a pandas DataFrame is empty?
How to check whether a pandas DataFrame is empty? In my case I want to print some message in terminal if the DataFrame is empty.

答:
If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.

when this situation can happen?
This situation happens when a single function is used to plot more than one DataFrame
which are passed as parameter.In such a situation the function try to plot the data even
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.

why?
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message
if a DataFrame is empty(instead of plotting):

```<code>df1                     df2
col1 col2           col1 col2
Nan   2              Nan  Nan
2     Nan            Nan  Nan
</code>```

and the function:

```<code>def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')
</code>```

Body:
If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.

when this situation can happen?
This situation happens when a single function is used to plot more than one DataFrame
which are passed as parameter.In such a situation the function try to plot the data even
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.

why?
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message
if a DataFrame is empty(instead of plotting):

df1                     df2
col1 col2           col1 col2
Nan   2              Nan  Nan
2     Nan            Nan  Nan

and the function:

def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')


问:
For input string: "Mat [ 0*0*CV_32FC1, isCont=true, isSubmat=false, nativeObj=0x78a0dff700, dataAddr=0x0 ]" - Error filling matrix
I am working with opencv on android for the development of an image segmentation application, but with the watershed algorithm. I am opening an image and creating a mask with the same image size and passing 0 for all the rows and columns of that mask. However, in the next step, which is to go through an array of 0 and add as coordinates in that array, I have the error:

```<code>java.lang.NumberFormatException: For input string: "Mat [0 * 0 * CV_32FC1, isCont = true, isSubmat = false, nativeObj = 0x78a0dff700, dataAddr = 0x0] "
</code>```

With that, it is not possible to pass the new values to an array, can someone help me with this?

Code:

```<code>// Load the image
val srcOriginal = Imgcodecs.imread(currentPhotoPath)

// Create a blank image of zeros (same dimension as img)
val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

// Example assigning a new value to a matrix index
for (i in 0 until markers.toInt()) {
   markers.put(my_canvas.pointsToDrawY.get(i).toInt(), my_canvas.pointsToDrawY.get(i).toInt(), intArrayOf(0,0,255))
}
</code>```

Error:

答: I don't think you can use markers.toInt() in the for loop.  Markers is a multidimensional array and can not be converted to an Integer.</p>

Body:
I am working with opencv on android for the development of an image segmentation application, but with the watershed algorithm. I am opening an image and creating a mask with the same image size and passing 0 for all the rows and columns of that mask. However, in the next step, which is to go through an array of 0 and add as coordinates in that array, I have the error:

java.lang.NumberFormatException: For input string: "Mat [0 * 0 * CV_32FC1, isCont = true, isSubmat = false, nativeObj = 0x78a0dff700, dataAddr = 0x0] "

With that, it is not possible to pass the new values to an array, can someone help me with this?

Code:

// Load the image
val srcOriginal = Imgcodecs.imread(currentPhotoPath)

// Create a blank image of zeros (same dimension as img)
val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

// Example assigning a new value to a matrix index
for (i in 0 until markers.toInt()) {
   markers.put(my_canvas.pointsToDrawY.get(i).toInt(), my_canvas.pointsToDrawY.get(i).toInt(), intArrayOf(0,0,255))
}

Error:


答:
Try following steps:

Go to Start Menu and search for "Windows PowerShell ISE".

Right click the x86 version and choose "Run as administrator".

In the top part, paste Set-ExecutionPolicy RemoteSigned; run the script. Choose "Yes".

Repeat these steps for the 64-bit version of Powershell ISE too (the non x86 version).

Title: Error while creating a new app in reactjs

Body:
PS D:\React\counter-app> create-react-app tower
create-react-app : File C:\Users\ee209495\AppData\Roaming\npm\create-react-app.ps1 cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ create-react-app tower
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess


问:
Garbage collection for a simple python class
I am writing a python class like this:

```<code>class MyImageProcessor:
   def __init__ (self, image, metadata):
     self.image=image
     self.metadata=metadata
</code>```

Both image and metadata are objects of a class written by a
colleague. Now I need to  make sure there is no waste of memory.  I am thinking of defining a quit() method like this,

```<code>  def quit():
    self.image=None
    self.metadata=None
    import gc
    gc.collect()
</code>```

and suggest users to call quit() systematically. I would like to know whether this is the right way. In particular, do the instructions in quit() above guarantee that unused memories being well collected?

Alternatively, I could rename quit() to the build-in __exit__(), and suggest users to use the "with" syntax. But my question is
more about whether the instructions in quit() indeed fulfill the garbage collection work one would need in this situation.

Thank you for your help.

答:
In python every object has a built-in reference_count, the variables(names) you create are only pointers to the objects. There are mutable and unmutable variables (for example if you change the value of an integer, the name will be pointed to another integer object, while changing a list element will not cause changing of the list name).

Reference count basically counts how many variable uses that data, and it is incremented/decremented automatically.
The garbage collector will destroy the objects with zero references (actually not always, it takes extra steps to save time). You should check out this article.

Similarly to object constructors (__init__()), which are called on object creation, you can define destructors (__del__()), which are executed on object deletion (usually when the reference count drops to 0). According to this article, in python they are not needed as much needed in C++ because Python has a garbage collector that handles memory management automatically. You can check out those examples too.

Hope it helps :)

Body:
I am writing a python class like this:

class MyImageProcessor:
   def __init__ (self, image, metadata):
     self.image=image
     self.metadata=metadata

Both image and metadata are objects of a class written by a
colleague. Now I need to  make sure there is no waste of memory.  I am thinking of defining a quit() method like this,

  def quit():
    self.image=None
    self.metadata=None
    import gc
    gc.collect()

and suggest users to call quit() systematically. I would like to know whether this is the right way. In particular, do the instructions in quit() above guarantee that unused memories being well collected?

Alternatively, I could rename quit() to the build-in __exit__(), and suggest users to use the "with" syntax. But my question is
more about whether the instructions in quit() indeed fulfill the garbage collection work one would need in this situation.

Thank you for your help.


问:
RecursionError:maximum recursion depth exceeded
i'm building an e-commerece and when i try to add more than one orderitems to the order but i get this error enter image description here .
Any help is appreciated .

```<code>   def Cart(request):
        `enter code here`    customer=request.user.customer
            if request.user.is_authenticated:
                 order,status=Order.objects.get_or_create(customer=customer,complete=False)
                 items=order.orderitem_set.all()
            else:
                items=[]

            context={"items":items}
            return render(request,'store/Cart.html',context)
</code>```

and  this the tree models

```<code>   class Customer(models.Model):
        user=models.OneToOneField(User,null=True,on_delete=models.CASCADE,blank=True)
        name=models.CharField(max_length=200,null=True)
        email=models.EmailField(null=True,help_text='A valid email address,please.')
        objects = models.Manager()

        def __str__(self):
            return  self.name

    class Order(models.Model):
        customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True)
        date_orderd=models.DateField(auto_now_add=True)
        complete=models.BooleanField(default=True,null=True,blank=False)
        transaction_id=models.CharField(max_length=200,null=True)
        objects = models.Manager()

        def __str__(self):
            return str(self.pk)

    class OrderItem(models.Model):
        product=models.ForeignKey(Product,on_delete=models.CASCADE,null=True)
        order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True)
        quantity=models.IntegerField(default=1,null=True,blank=True)
        date_added=models.DateField(auto_now_add=True)
        objects = models.Manager()

        def __str__(self):
             return self.product.name

        @property
        def get_total(self):
            total=self.product.price*self.quantity
            return self.get_total
</code>```

答:
This error usually occurs when you add an app's urls in itself.
check your app's url.py you mayhave included itself in it.</p>

Body:
i'm building an e-commerece and when i try to add more than one orderitems to the order but i get this error enter image description here .
Any help is appreciated .

   def Cart(request):
        `enter code here`    customer=request.user.customer
            if request.user.is_authenticated:
                 order,status=Order.objects.get_or_create(customer=customer,complete=False)
                 items=order.orderitem_set.all()
            else:
                items=[]

            context={"items":items}
            return render(request,'store/Cart.html',context)

and  this the tree models

   class Customer(models.Model):
        user=models.OneToOneField(User,null=True,on_delete=models.CASCADE,blank=True)
        name=models.CharField(max_length=200,null=True)
        email=models.EmailField(null=True,help_text='A valid email address,please.')
        objects = models.Manager()

        def __str__(self):
            return  self.name

    class Order(models.Model):
        customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True)
        date_orderd=models.DateField(auto_now_add=True)
        complete=models.BooleanField(default=True,null=True,blank=False)
        transaction_id=models.CharField(max_length=200,null=True)
        objects = models.Manager()

        def __str__(self):
            return str(self.pk)

    class OrderItem(models.Model):
        product=models.ForeignKey(Product,on_delete=models.CASCADE,null=True)
        order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True)
        quantity=models.IntegerField(default=1,null=True,blank=True)
        date_added=models.DateField(auto_now_add=True)
        objects = models.Manager()

        def __str__(self):
             return self.product.name

        @property
        def get_total(self):
            total=self.product.price*self.quantity
            return self.get_total


问:
How to bundle install gemfile with specific version of bundler
I am trying to bundle install a project running gem 'rails', '4.2.0'.
Running Bundle install, I get :

```<code>Bundler could not find compatible versions for gem "bundler":
  In Gemfile:
    rails (= 4.2.0) was resolved to 4.2.0, which depends on
      bundler (>= 1.3.0, < 2.0)

  Current Bundler version:
    bundler (2.1.4)
This Gemfile requires a different version of Bundler.
Perhaps you need to update Bundler by running `gem install bundler`?

Could not find gem 'bundler (>= 1.3.0, < 2.0)', which is required by gem 'rails (= 4.2.0)', in any of the sources.
</code>```

Thus I then try to install bundler v 1.3.0 to successfully bundle this gemfile : gem install bundler -v 1.3.0

```<code>gem list bundler shows me that I successfully installed bundler at v 1.3.0
</code>```

Then when trying to bundle install with v 1.3.0 like this bundle _1.3.0_ install, I get Could not find command "_1.3.0_".

How can I successfully run bundle install with that specific version of bundler ?

答:
There was a bug with bundler previously, if you're using the wrong version of ruby gems. Try</p>

```<code>gem update --system
</code>```

Body:
I am trying to bundle install a project running gem 'rails', '4.2.0'.
Running Bundle install, I get :

Bundler could not find compatible versions for gem "bundler":
  In Gemfile:
    rails (= 4.2.0) was resolved to 4.2.0, which depends on
      bundler (>= 1.3.0, < 2.0)

  Current Bundler version:
    bundler (2.1.4)
This Gemfile requires a different version of Bundler.
Perhaps you need to update Bundler by running `gem install bundler`?

Could not find gem 'bundler (>= 1.3.0, < 2.0)', which is required by gem 'rails (= 4.2.0)', in any of the sources.

Thus I then try to install bundler v 1.3.0 to successfully bundle this gemfile : gem install bundler -v 1.3.0

gem list bundler shows me that I successfully installed bundler at v 1.3.0

Then when trying to bundle install with v 1.3.0 like this bundle _1.3.0_ install, I get Could not find command "_1.3.0_".

How can I successfully run bundle install with that specific version of bundler ?

Body:
There was a bug with bundler previously, if you're using the wrong version of ruby gems. Try

gem update --system


问:
SQL Duplicate Key Help
I have a statement that looks something like this:

```<code>insert table_name(...)
select .... from ... join ...
</code>```

How can I use where not exists or something of that effect with this insert and select statement so that if this exact code is reran with the same values, it won't throw an error. I don't want to have to copy and paste the select/joins in a check as it is a pretty big block of code, so is there any way to do something like

```<code>if not exists (insert table_name(...)
              select ... from...join)
</code>```

or would it be something else like

```<code>insert table_name(...)
if not exists(select ... from ... join)
</code>```

答:
Try using the sql server MERGE command.

http://technet.microsoft.com/en-us/library/bb510625.aspx

Title: SQL Duplicate Key Help

Body:
I have a statement that looks something like this:

insert table_name(...)
select .... from ... join ...

How can I use where not exists or something of that effect with this insert and select statement so that if this exact code is reran with the same values, it won't throw an error. I don't want to have to copy and paste the select/joins in a check as it is a pretty big block of code, so is there any way to do something like

if not exists (insert table_name(...)
              select ... from...join)

or would it be something else like

insert table_name(...)
if not exists(select ... from ... join)


问:
CEF sharp browser wait till website fully loaded
I am using CEFsharp browser and determine the page finish loading with LoadingStateChanged event but it fires many times.

I need it to fire only once the page has fully loaded, how can this be done?

```<code>private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
    if (!e.Browser.IsLoading)
    {
        await Task.Run(async () =>
        {
            await Task.Delay(3000);
        });

        try
        {
            MessageBox.Show("Page has been loaded");
        }
        catch (Exception ex)
        {

        }
    }
}
</code>```

答:
These days its really simple. Put for example these 2 lines of Code in ur Form_Load:

```<code>  browser = new ChromiumWebBrowser();
  (browser).FrameLoadEnd += Browser_FrameLoadEnd;
</code>```

Then add the required methode:

```<code>async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{ // Jumps in here when the page is fully loaded:
    if (e.Frame.IsMain)
    {
        if (e.Url.Contains("whatever you need"))
        {
            // Call a methode or something else.
        }
    }
}
</code>```

Body:
I am using CEFsharp browser and determine the page finish loading with LoadingStateChanged event but it fires many times.

I need it to fire only once the page has fully loaded, how can this be done?

private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
    if (!e.Browser.IsLoading)
    {
        await Task.Run(async () =>
        {
            await Task.Delay(3000);
        });

        try
        {
            MessageBox.Show("Page has been loaded");
        }
        catch (Exception ex)
        {

        }
    }
}

Body:
These days its really simple. Put for example these 2 lines of Code in ur Form_Load:

  browser = new ChromiumWebBrowser();
  (browser).FrameLoadEnd += Browser_FrameLoadEnd;

Then add the required methode:

async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{ // Jumps in here when the page is fully loaded:
    if (e.Frame.IsMain)
    {
        if (e.Url.Contains("whatever you need"))
        {
            // Call a methode or something else.
        }
    }
}


问:
VSCode + Go keeps toggles go.mod dependencies, sets root ownership
There is a project that uses Go modules. There is a recent version of VSCode with the official Go extension installed.

Problem 1

Every time the focus moves out of VSCode - it would update the modules files. E.g.:

becomes:

Problem 2

Sometimes the ownership of go.mod would be set to root - breaking shell-scripts and overall working routines.

答:
The solution would be to keep in mind 2 things:

Make sure to update mod dependencies on a regular basis.

Make sure to set the user for Docker Compose fiels (by default Docker will use the 0:0 - root permission, modifying the files on the host system).


答:
You may be able to just put it in a TRY CATCH block to just eat an exception if this insert fails.

http://geekswithblogs.net/ram/archive/2006/10/12/93829.aspx

On that note I must say that this is considered BAD PRACTICE to use exceptions to control logic flow.

I am more concerned about why this situation exists, I am having a hard time thinking of a legitimate situation in a GOOD DESIGN where this problem would occur?

Title: SQL Duplicate Key Help


问:
How to use Microsoft OCR Library ( Microsoft.Windows.Ocr ) in an ASP.Net MVC4 Web API Project?

TL;DR:

Does anyone know of a way to reference Microsoft.Windows.Ocr (/ WindowsPreview.Media.Ocr.dll ) Assembly on a server-side ASP.Net Web application like MV4 Web API and make use of the OCR Functionality in that assembly to take a photo image as input and extract the text content out of it ? If yes, please provide detailed instructions in your answer.

Question Details (and what I have tried so far)

I am building a web application that takes an image uploaded to the Server (via a file upload UI screen) and then reads the text using OCR and displays the text on the next page, right next to the image that was uploaded.

Since most commercial OCR Libraries cost an arm and length (over $1,300 last time I checked) I thought I can try and use the Microsoft OCR Library Microsoft.Windows.Ocr that is FREE and seems to be very simple and straightforward to use.

So I tried to install the Microsoft.Windows.Ocr Nuget Package to my ASP.Net MVC4 Web API Project and that succeeded.

After that, I looked through my MVC4 Web API Project References, and to my surprise, did not find a reference to Microsoft.Windows.Ocr.dll Assembly.

So then I tried to add a reference to the x86 version of the Microsoft.Windows.Ocr.dll Assembly by browsing to that Assembly in the \packages folder, and selected the WindowsPreview.Media.Ocr.dll from \lib\win81\x86 folder

Note: The Assembly name is WindowsPreview.Media.Ocr.dll and not  Microsoft.Windows.Ocr.dll , not sure why!

When I did that and clicked OK, I got the following Error Message.

```<code>---------------------------
Microsoft Visual Studio
---------------------------
A reference to
'D:\TestProjects\packages\Microsoft.Windows.Ocr.1.0.0\lib\win81\x86\
 WindowsPreview.Media.Ocr.dll' could not be added. Please make sure
 that the file is accessible, and that it is a valid assembly
 or COM component.
---------------------------
OK
---------------------------
</code>```

I then found out from the Nuget Page that the "Supported Platforms" are only Windows Phone 8, Windows Phone 8.1, Windows 8.1 (Windows Store apps only).

But surely, there must be a way to use this OCR dll on the Server-side in an ASP.Net Application?

Does anyone know of a way to reference Microsoft.Windows.Ocr (/ WindowsPreview.Media.Ocr.dll ) Assembly on a server-side ASP.Net Web application like MV4 Web API and make use of the OCR Functionality in that assembly to take a photo image as input and extract the text content out of it ?** If yes, please provide detailed instructions in your answer.

Any "hacks" and/or Sample code would be much appreciated!!

Thank you!!

答:
I managed to invoke the OCR from Web API by invoking the DLL from powershell. I found also that you cannot invoke this DLL in parallel.

It took me a few days, but here is the repo. Available both as nuget and web API with Windows docker https://github.com/MihaiTheCoder/ocr-all-in-one

I developed Web API project mostly for this question, so hopefully somebody will find it useful.

The powershell that is invoking Windows OCR is here: https://github.com/MihaiTheCoder/ocr-all-in-one/blob/master/Ocr.Wrapper/Resources/Get-Text-Win-OCR.ps1

It is a 2 stage process because the initialization of the OCR engine takes more time, and it is better to have it cached.

Body:
TL;DR:

Does anyone know of a way to reference Microsoft.Windows.Ocr (/ WindowsPreview.Media.Ocr.dll ) Assembly on a server-side ASP.Net Web application like MV4 Web API and make use of the OCR Functionality in that assembly to take a photo image as input and extract the text content out of it ? If yes, please provide detailed instructions in your answer.

Question Details (and what I have tried so far)

I am building a web application that takes an image uploaded to the Server (via a file upload UI screen) and then reads the text using OCR and displays the text on the next page, right next to the image that was uploaded.

Since most commercial OCR Libraries cost an arm and length (over $1,300 last time I checked) I thought I can try and use the Microsoft OCR Library Microsoft.Windows.Ocr that is FREE and seems to be very simple and straightforward to use.

So I tried to install the Microsoft.Windows.Ocr Nuget Package to my ASP.Net MVC4 Web API Project and that succeeded.

After that, I looked through my MVC4 Web API Project References, and to my surprise, did not find a reference to Microsoft.Windows.Ocr.dll Assembly.

So then I tried to add a reference to the x86 version of the Microsoft.Windows.Ocr.dll Assembly by browsing to that Assembly in the \packages folder, and selected the WindowsPreview.Media.Ocr.dll from \lib\win81\x86 folder

Note: The Assembly name is WindowsPreview.Media.Ocr.dll and not  Microsoft.Windows.Ocr.dll , not sure why!

When I did that and clicked OK, I got the following Error Message.

---------------------------
Microsoft Visual Studio
---------------------------
A reference to
'D:\TestProjects\packages\Microsoft.Windows.Ocr.1.0.0\lib\win81\x86\
 WindowsPreview.Media.Ocr.dll' could not be added. Please make sure
 that the file is accessible, and that it is a valid assembly
 or COM component.
---------------------------
OK
---------------------------

I then found out from the Nuget Page that the "Supported Platforms" are only Windows Phone 8, Windows Phone 8.1, Windows 8.1 (Windows Store apps only).

But surely, there must be a way to use this OCR dll on the Server-side in an ASP.Net Application?

Does anyone know of a way to reference Microsoft.Windows.Ocr (/ WindowsPreview.Media.Ocr.dll ) Assembly on a server-side ASP.Net Web application like MV4 Web API and make use of the OCR Functionality in that assembly to take a photo image as input and extract the text content out of it ?** If yes, please provide detailed instructions in your answer.

Any "hacks" and/or Sample code would be much appreciated!!

Thank you!!


问:
How to add mappings by namespace in Fluent NHibernate
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

```<code>    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()
</code>```

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?

答:
```<code>... AutoMap.AssemblyOf<Person>().Where(x => x.Namespace.EndsWith("Domain")) ...
</code>```

Body:
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?