问:
Pass variable set in PowerShell task to another task (YAML)
I have a yaml file with following tasks:

```<code>parameters:

 steps:
- task: AzurePowerShell@4
  displayName: 'script'
  inputs:
        azureSubscription:
        ScriptPath:
        ScriptArguments:
        azurePowerShellVersion: LatestVersion

 - task: AzureResourceGroupDeployment@2
   displayName: 'deployment'
   inputs:
         azureSubscription:
         resourceGroupName:
         location:
         overrideParameters: '-abc $(var1) -def $(var2)'
         deploymentMode: 'Incremental'

</code>```

In the Powershell Script, I'm setting 2 variables as follows:

```<code>    $ABC = 1
    $DEF = 2
    Write-Host "##vso[task.setvariable variable=var1;isOutput=true]$ABC"
    Write-Host "##vso[task.setvariable variable=var2;isOutput=true]$DEF"
</code>```

On trying to use these variables in the 2nd task (in overrideParameters section), I see the following error:

[error]InvalidContentLink: Unable to download deployment content from 'xxxx$(var1)'

[error]InvalidContentLink: Unable to download deployment content from 'xxxx$(var2)'

Am I setting variables in PowerShell script wrong?

答:
You can try to add a reference name to the first task. For example:

```<code>- task: AzurePowerShell@4
  displayName: 'script'
  inputs:
        azureSubscription:
        ScriptPath:
        ScriptArguments:
        azurePowerShellVersion: LatestVersion
  name: test
</code>```

Then in the second task, get the variable value in the form of $(test.var1).

This is because in definition editor, downstream tasks won't get variable name intellisense for output variables that were published by an ad-hoc script. You can refer to this document for details.

In addition, here is a blog with some examples on how to pass variables in Azure Pipelines YAML tasks.

Body:
I have a yaml file with following tasks:

parameters:

 steps:
- task: AzurePowerShell@4
  displayName: 'script'
  inputs:
        azureSubscription:
        ScriptPath:
        ScriptArguments:
        azurePowerShellVersion: LatestVersion

 - task: AzureResourceGroupDeployment@2
   displayName: 'deployment'
   inputs:
         azureSubscription:
         resourceGroupName:
         location:
         overrideParameters: '-abc $(var1) -def $(var2)'
         deploymentMode: 'Incremental'

In the Powershell Script, I'm setting 2 variables as follows:

    $ABC = 1
    $DEF = 2
    Write-Host "##vso[task.setvariable variable=var1;isOutput=true]$ABC"
    Write-Host "##vso[task.setvariable variable=var2;isOutput=true]$DEF"

On trying to use these variables in the 2nd task (in overrideParameters section), I see the following error:

[error]InvalidContentLink: Unable to download deployment content from 'xxxx$(var1)'

[error]InvalidContentLink: Unable to download deployment content from 'xxxx$(var2)'

Am I setting variables in PowerShell script wrong?

Body:
You can try to add a reference name to the first task. For example:

- task: AzurePowerShell@4
  displayName: 'script'
  inputs:
        azureSubscription:
        ScriptPath:
        ScriptArguments:
        azurePowerShellVersion: LatestVersion
  name: test

Then in the second task, get the variable value in the form of $(test.var1).

This is because in definition editor, downstream tasks won't get variable name intellisense for output variables that were published by an ad-hoc script. You can refer to this document for details.

In addition, here is a blog with some examples on how to pass variables in Azure Pipelines YAML tasks.


来源: stackexchange

问:
Function-wide exception handling in c++ - is it a bad style?
There is a try-catch thing about functions, which I think sometimes may be quite useful:

```<code>bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}
</code>```

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

```<code>bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
</code>```

after:

```<code>bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}
</code>```

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

答:
Really the only reason to function-level try blocks is for constructors, otherwise it's a somewhat obscure feature that doesn't buy you that much.  It's just as easy to do it this way:

```<code>bool readEntity(...)
{
   try
   {
      while(...)
      {
         if(...)
         {
            //lot's of code...
         }
      }
   }
   catch(XMLBaseException & ex)
   {
       //create our exception and throw
   }
}
</code>```

If you are having troubles with horizontal scrolling then the thing to do is to split up your code.  try/catches are complexity and this should be represented in the nesting level, not hidden.

In constructors, this is a different issue: there is no other way to catch exceptions in an initializer list:

```<code>SomeClass::SomeClass(parameter p1, parameter p2) : Member1(p1), Member2(p2)
try
{
}
catch(Exception &ex)
{
    // handle and rethrow
}
</code>```

Of course, if you have an exception mid-construction, there's not likely much you can do to recover except log and and rethrow (it's going to get rethrown anyway in the constructor case).  Your object isn't completely constructed yet and there's nothing you can really do with it.  The only thing that you can trust to be valid are the parameters (although if the initialization failed, that will likely be due to bad parameters).

See this GOTW for a discussion on this.

ContentLicense: CC BY-SA 2.5

Body:
There is a try-catch thing about functions, which I think sometimes may be quite useful:

bool function()
try
{
    //do something
}
catch(exception_type & t)
{
   //do something
}

So the first part of the question: is this style considered bad in general case?

And the concrete example I used this approach in:

We had project with quite a lot of code in c and c++. And there we had custom exception types (not std::exception derived). I needed to integrate XML library and cast all exception to our types. So, basically, the last step was to catch all exceptions from XML library and convert them.

Function before:

bool readEntity(...)
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}

after:

bool readEntity(...)
try
{
   while(...)
   {
      if(...)
      {
         //lot's of code...
      }
   }
}
catch(XMLBaseException & ex)
{
    //create our exception and throw
}

My thoughts went something like this: I clearly state my intentions to convert all exception derived from one type into custom type AND we keep our screen without horizontal scroll bar (cause horizontal scroll bars are bad).

Well, I actually was quite criticized for this approach as for non-clear one during code review.

So I'd like to hear you thoughts.

UPDATE: just to be clear: refactoring the function wasn't an option. And actually it was good written one.

Body:
Really the only reason to function-level try blocks is for constructors, otherwise it's a somewhat obscure feature that doesn't buy you that much.  It's just as easy to do it this way:

bool readEntity(...)
{
   try
   {
      while(...)
      {
         if(...)
         {
            //lot's of code...
         }
      }
   }
   catch(XMLBaseException & ex)
   {
       //create our exception and throw
   }
}

If you are having troubles with horizontal scrolling then the thing to do is to split up your code.  try/catches are complexity and this should be represented in the nesting level, not hidden.

In constructors, this is a different issue: there is no other way to catch exceptions in an initializer list:

SomeClass::SomeClass(parameter p1, parameter p2) : Member1(p1), Member2(p2)
try
{
}
catch(Exception &ex)
{
    // handle and rethrow
}

Of course, if you have an exception mid-construction, there's not likely much you can do to recover except log and and rethrow (it's going to get rethrown anyway in the constructor case).  Your object isn't completely constructed yet and there's nothing you can really do with it.  The only thing that you can trust to be valid are the parameters (although if the initialization failed, that will likely be due to bad parameters).

See this GOTW for a discussion on this.

OwnerDisplayName: Josh

LastEditorDisplayName: Josh


问:
Confused by a very simple if / else statement in perl
```<code>print "content-type: text/html \n\n";   #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}
</code>```

This is some code I picked up from tizag.  The part I don't understand is that the bool value for true is 1, and false is 0.  So why is it when I successfully delete the file I'm checking to see if it returns a 0?

答:
That seems like a mistake.. from perldoc perlfunc:

Deletes a list of files. On success,
  it returns the number of files it
  successfully deleted. On failure, it
  returns false and sets $! (errno):

If the return value is 0, you deleted 0 files.

The correct way to write it would be:

```<code>if (unlink($file)) { print "Success!" }
else { print "Unlink failed: $!" }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
print "content-type: text/html \n\n";   #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}

This is some code I picked up from tizag.  The part I don't understand is that the bool value for true is 1, and false is 0.  So why is it when I successfully delete the file I'm checking to see if it returns a 0?

Body:
That seems like a mistake.. from perldoc perlfunc:

Deletes a list of files. On success,
  it returns the number of files it
  successfully deleted. On failure, it
  returns false and sets $! (errno):

If the return value is 0, you deleted 0 files.

The correct way to write it would be:

if (unlink($file)) { print "Success!" }
else { print "Unlink failed: $!" }


问:
The event of the document is not triggered, when it is on a disabled element
When I give the document a mouseup event, if the mouse in a disabled element and I released the button. The document mouseup event handler can't fire.
How should I do let the handler be called?

Example:

document.addEventListener('mouseup', () => {
  console.log('mouseup')
}, true)

const changeBtn = document.getElementById('change')
const testBtn = document.getElementById('test')

changeBtn.onclick = () => {
  testBtn.setAttribute('disabled', true)
}
testBtn.onclick = () => {
  console.log('testBtn click')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="test">test</button>
<button id="change">change</button></code>```

答:
Using CSS set pointer-events: none on :disabled elements:

document.addEventListener('mouseup', () => {
  console.log('mouseup')
}, true)

const changeBtn = document.getElementById('change')
const testBtn = document.getElementById('test')

changeBtn.onclick = () => {
  testBtn.setAttribute('disabled', true)
}
testBtn.onclick = () => {
  console.log('testBtn click')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*:disabled {
  pointer-events: none;
}</code>```

<button id="test">test</button>
<button id="change">change</button>```

ContentLicense: CC BY-SA 4.0

Body:
When I give the document a mouseup event, if the mouse in a disabled element and I released the button. The document mouseup event handler can't fire.
How should I do let the handler be called?

Example:

document.addEventListener('mouseup', () => {
  console.log('mouseup')
}, true)

const changeBtn = document.getElementById('change')
const testBtn = document.getElementById('test')

changeBtn.onclick = () => {
  testBtn.setAttribute('disabled', true)
}
testBtn.onclick = () => {
  console.log('testBtn click')
}

<button id="test">test</button>
<button id="change">change</button>

Body:
Using CSS set pointer-events: none on :disabled elements:

document.addEventListener('mouseup', () => {
  console.log('mouseup')
}, true)

const changeBtn = document.getElementById('change')
const testBtn = document.getElementById('test')

changeBtn.onclick = () => {
  testBtn.setAttribute('disabled', true)
}
testBtn.onclick = () => {
  console.log('testBtn click')
}

*:disabled {
  pointer-events: none;
}

<button id="test">test</button>
<button id="change">change</button>


问:
How to get rid of blinking fields and cursor when hovering over this field?
There are 2 sections of code, first for the desktop version, the second for the mobile version. The first version works correctly (the first image)enter image description here, an error appears in the mobile version, when you hover over the list item hover, the effect does not work, border color appears (background (second image))enter image description here, if you move the cursor to this border, hover works, but the field itself starts blinking. If you enter in the code of the mobile version the dimensions of the list item, as in the version for large monitors, i.e. duplicate the rules, both the field and the cursor blink. How to solve this situation, so that instead of the appearance of a colored border, there is a hover effect without blinking? Below is the html and css of the problem place, and just for javascript.

if ('ontouchstart' in window) { var click = 'touchstart'; }
else { var click = 'click'; }

$('div.burger').on('click', function () {
  if (!$(this).hasClass('open')) { openMenu(); }
  else { closeMenu(); }
});

$('div.menu ul li a').on('click', function (e) {
  e.preventDefault();
  closeMenu();
});

function openMenu() {
  (document.getElementById("see").setAttribute("style", "display: block;"));
  $('div.menu-bg').addClass('animate');

  $('div.burger').addClass('open');
  $('div.x, div.z').addClass('collapse');

  setTimeout(function () {
    $('div.y').hide();
    $('div.x').addClass('rotate30');
    $('div.z').addClass('rotate150');
  }, 70);
  setTimeout(function () {
    $('div.x').addClass('rotate45');
    $('div.z').addClass('rotate135');
  }, 120);
}

function closeMenu() {

  $('.menu li').removeClass('animate');
  (document.getElementById("see").setAttribute("style", "display: none;"));
  setTimeout(function () {
    $('div.burger').removeClass('open');
    $('div.x').removeClass('rotate45').addClass('rotate30');
    $('div.z').removeClass('rotate135').addClass('rotate150');
    $('div.menu-bg').removeClass('animate');

    setTimeout(function () {
      $('div.x').removeClass('rotate30');
      $('div.z').removeClass('rotate150');
    }, 50);
    setTimeout(function () {
      $('div.y').show();
      $('div.x, div.z').removeClass('collapse');
    }, 70);
  }, 100);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 background: blue;
 }
.nav {
  height: 100vh;
  position: relative;
  outline: none;
}
.nav ul {
  list-style: none;
  padding: 0.5em 0;
  margin: 0;
}
.nav ul li {
  margin: 10px;
  width: 300px;
  height: 40px;
  line-height: 40px;
  background-color: white;
  padding: 0.5em 1em 0.5em 1em;
  font-size: 24px;
  background-repeat: no-repeat;
  background-position: left 15px center;
  background-size: auto 40px;
  transition: all 0.15s linear;
  border-radius: 5px;
  border: 1px solid black;
  opacity: 0.75;
}
.nav img {
  float: left;
}
.menu li:hover {
  background-color: #ffffff;
  opacity: 1;
}

@media screen and (max-width: 479px) {
.menu {
  display: none;
}
div.burger {
  height: 30px;
  width: 40px;
  position: absolute;
  top: 11px;
  left: 21px;
}
  div.x,
  div.y,
  div.z {
    position: absolute; margin: auto;
    top: 0px; bottom: 0px;
    background: #fff;
    border-radius:2px;
    -webkit-transition: all 200ms ease-out;
       -moz-transition: all 200ms ease-out;
        -ms-transition: all 200ms ease-out;
         -o-transition: all 200ms ease-out;
            transition: all 200ms ease-out;
  }
  div.x, div.y, div.z { height: 3px; width: 26px; }
  div.y {top: 18px;}
  div.z {top: 37px;}
  div.collapse {
    top: 20px;
    -webkit-transition: all 70ms ease-out;
       -moz-transition: all 70ms ease-out;
        -ms-transition: all 70ms ease-out;
         -o-transition: all 70ms ease-out;
            transition: all 70ms ease-out;
  }

  div.rotate30 {
    -ms-transform: rotate(30deg);
     -webkit-transform: rotate(30deg);
      transform: rotate(30deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }
  div.rotate150 {
    -ms-transform: rotate(150deg);
     -webkit-transform: rotate(150deg);
      transform: rotate(150deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }

  div.rotate45 {
    -ms-transform: rotate(45deg);
     -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
  div.rotate135 {
    -ms-transform: rotate(135deg);
     -webkit-transform: rotate(135deg);
      transform: rotate(135deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
div.menu-bg {
  width: 100%;
  height: 100%;
  position:absolute;
  top:0;
  left:0;
  background:#203d63;
  opacity:0;
  -webkit-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
}
div.menu-bg.animate{
  opacity:0.9;
  -webkit-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);

}
ul.menu {
  padding-top: 5em;
}
ul.menu li {
  width:300px;
  margin: 0 auto;
}
ul.menu span {
  text-align: right;
}
ul.menu li a {
  background-color: white;
  color:rgb(0, 0, 0);
  opacity: 0.75;
}
section > div {
  transition: transform 1s;
  transform: translateX(0px);
}}</code>```

      Главная

      Галерея

```

答:
You need to remove following line from openMenu function.

```<code>$('div.menu-bg').addClass('animate');
</code>```

Please look at the updated openMenu function.

if( 'ontouchstart' in window ){ var click = 'touchstart'; }
  else { var click = 'click'; }

  $('div.burger').on(click, function(){
      if( !$(this).hasClass('open') ){ openMenu(); }
      else { closeMenu(); }
    });

  $('div.menu ul li a').on(click, function(e){
    e.preventDefault();
    closeMenu();
  });

  function openMenu(){
        (document.getElementById("see").setAttribute("style", "display: block;"));

    //Remove this line
    // $('div.menu-bg').addClass('animate');

    $('div.burger').addClass('open');
    $('div.x, div.z').addClass('collapse');

    setTimeout(function(){
      $('div.y').hide();
      $('div.x').addClass('rotate30');
      $('div.z').addClass('rotate150');
    }, 70);
    setTimeout(function(){
      $('div.x').addClass('rotate45');
      $('div.z').addClass('rotate135');
    }, 120);
  }

  function closeMenu(){

        $('.menu li').removeClass('animate');
        (document.getElementById("see").setAttribute("style", "display: none;"));
    setTimeout(function(){
      $('div.burger').removeClass('open');
      $('div.x').removeClass('rotate45').addClass('rotate30');
      $('div.z').removeClass('rotate135').addClass('rotate150');
      $('div.menu-bg').removeClass('animate');

      setTimeout(function(){
        $('div.x').removeClass('rotate30');
        $('div.z').removeClass('rotate150');
      }, 50);
      setTimeout(function(){
        $('div.y').show();
        $('div.x, div.z').removeClass('collapse');
      }, 70);
    }, 100);

  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 background: blue;
 }
.nav {
  height: 100vh;
  position: relative;
  outline: none;
}
.nav ul {
  list-style: none;
  padding: 0.5em 0;
  margin: 0;
}
.nav ul li {
  margin: 10px;
  width: 300px;
  height: 40px;
  line-height: 40px;
  background-color: white;
  padding: 0.5em 1em 0.5em 1em;
  font-size: 24px;
  background-repeat: no-repeat;
  background-position: left 15px center;
  background-size: auto 40px;
  transition: all 0.15s linear;
  border-radius: 5px;
  border: 1px solid black;
  opacity: 0.75;
}
.nav img {
  float: left;
}
.menu li:hover {
  background-color: #ffffff;
  opacity: 1;
}

@media screen and (max-width: 900px) {
.menu {
  display: none;
}
div.burger {
  height: 30px;
  width: 40px;
  position: absolute;
  top: 11px;
  left: 21px;
}
  div.x,
  div.y,
  div.z {
    position: absolute; margin: auto;
    top: 0px; bottom: 0px;
    background: #fff;
    border-radius:2px;
    -webkit-transition: all 200ms ease-out;
       -moz-transition: all 200ms ease-out;
        -ms-transition: all 200ms ease-out;
         -o-transition: all 200ms ease-out;
            transition: all 200ms ease-out;
  }
  div.x, div.y, div.z { height: 3px; width: 26px; }
  div.y {top: 18px;}
  div.z {top: 37px;}
  div.collapse {
    top: 20px;
    -webkit-transition: all 70ms ease-out;
       -moz-transition: all 70ms ease-out;
        -ms-transition: all 70ms ease-out;
         -o-transition: all 70ms ease-out;
            transition: all 70ms ease-out;
  }

  div.rotate30 {
    -ms-transform: rotate(30deg);
     -webkit-transform: rotate(30deg);
      transform: rotate(30deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }
  div.rotate150 {
    -ms-transform: rotate(150deg);
     -webkit-transform: rotate(150deg);
      transform: rotate(150deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }

  div.rotate45 {
    -ms-transform: rotate(45deg);
     -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
  div.rotate135 {
    -ms-transform: rotate(135deg);
     -webkit-transform: rotate(135deg);
      transform: rotate(135deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
div.menu-bg {
  width: 100%;
  height: 100%;
  position:absolute;
  top:0;
  left:0;
  background:#203d63;
  opacity:0;
  -webkit-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
}
div.menu-bg.animate{
  opacity:0.9;
  -webkit-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);

}
ul.menu {
  padding-top: 5em;
}
ul.menu li {
  width:300px;
  margin: 0 auto;
}
ul.menu span {
  text-align: right;
}
ul.menu li a {
  background-color: white;
  color:rgb(0, 0, 0);
  opacity: 0.75;
}
section > div {
  transition: transform 1s;
  transform: translateX(0px);
}}</code>```

Главная

Галерея

```

Body:
There are 2 sections of code, first for the desktop version, the second for the mobile version. The first version works correctly (the first image)enter image description here, an error appears in the mobile version, when you hover over the list item hover, the effect does not work, border color appears (background (second image))enter image description here, if you move the cursor to this border, hover works, but the field itself starts blinking. If you enter in the code of the mobile version the dimensions of the list item, as in the version for large monitors, i.e. duplicate the rules, both the field and the cursor blink. How to solve this situation, so that instead of the appearance of a colored border, there is a hover effect without blinking? Below is the html and css of the problem place, and just for javascript.

if ('ontouchstart' in window) { var click = 'touchstart'; }
else { var click = 'click'; }

$('div.burger').on('click', function () {
  if (!$(this).hasClass('open')) { openMenu(); }
  else { closeMenu(); }
});

$('div.menu ul li a').on('click', function (e) {
  e.preventDefault();
  closeMenu();
});

function openMenu() {
  (document.getElementById("see").setAttribute("style", "display: block;"));
  $('div.menu-bg').addClass('animate');

  $('div.burger').addClass('open');
  $('div.x, div.z').addClass('collapse');

  setTimeout(function () {
    $('div.y').hide();
    $('div.x').addClass('rotate30');
    $('div.z').addClass('rotate150');
  }, 70);
  setTimeout(function () {
    $('div.x').addClass('rotate45');
    $('div.z').addClass('rotate135');
  }, 120);
}

function closeMenu() {

  $('.menu li').removeClass('animate');
  (document.getElementById("see").setAttribute("style", "display: none;"));
  setTimeout(function () {
    $('div.burger').removeClass('open');
    $('div.x').removeClass('rotate45').addClass('rotate30');
    $('div.z').removeClass('rotate135').addClass('rotate150');
    $('div.menu-bg').removeClass('animate');

    setTimeout(function () {
      $('div.x').removeClass('rotate30');
      $('div.z').removeClass('rotate150');
    }, 50);
    setTimeout(function () {
      $('div.y').show();
      $('div.x, div.z').removeClass('collapse');
    }, 70);
  }, 100);

}

body {
 background: blue;
 }
.nav {
  height: 100vh;
  position: relative;
  outline: none;
}
.nav ul {
  list-style: none;
  padding: 0.5em 0;
  margin: 0;
}
.nav ul li {
  margin: 10px;
  width: 300px;
  height: 40px;
  line-height: 40px;
  background-color: white;
  padding: 0.5em 1em 0.5em 1em;
  font-size: 24px;
  background-repeat: no-repeat;
  background-position: left 15px center;
  background-size: auto 40px;
  transition: all 0.15s linear;
  border-radius: 5px;
  border: 1px solid black;
  opacity: 0.75;
}
.nav img {
  float: left;
}
.menu li:hover {
  background-color: #ffffff;
  opacity: 1;
}

@media screen and (max-width: 479px) {
.menu {
  display: none;
}
div.burger {
  height: 30px;
  width: 40px;
  position: absolute;
  top: 11px;
  left: 21px;
}
  div.x,
  div.y,
  div.z {
    position: absolute; margin: auto;
    top: 0px; bottom: 0px;
    background: #fff;
    border-radius:2px;
    -webkit-transition: all 200ms ease-out;
       -moz-transition: all 200ms ease-out;
        -ms-transition: all 200ms ease-out;
         -o-transition: all 200ms ease-out;
            transition: all 200ms ease-out;
  }
  div.x, div.y, div.z { height: 3px; width: 26px; }
  div.y {top: 18px;}
  div.z {top: 37px;}
  div.collapse {
    top: 20px;
    -webkit-transition: all 70ms ease-out;
       -moz-transition: all 70ms ease-out;
        -ms-transition: all 70ms ease-out;
         -o-transition: all 70ms ease-out;
            transition: all 70ms ease-out;
  }

  div.rotate30 {
    -ms-transform: rotate(30deg);
     -webkit-transform: rotate(30deg);
      transform: rotate(30deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }
  div.rotate150 {
    -ms-transform: rotate(150deg);
     -webkit-transform: rotate(150deg);
      transform: rotate(150deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }

  div.rotate45 {
    -ms-transform: rotate(45deg);
     -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
  div.rotate135 {
    -ms-transform: rotate(135deg);
     -webkit-transform: rotate(135deg);
      transform: rotate(135deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
div.menu-bg {
  width: 100%;
  height: 100%;
  position:absolute;
  top:0;
  left:0;
  background:#203d63;
  opacity:0;
  -webkit-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
}
div.menu-bg.animate{
  opacity:0.9;
  -webkit-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);

}
ul.menu {
  padding-top: 5em;
}
ul.menu li {
  width:300px;
  margin: 0 auto;
}
ul.menu span {
  text-align: right;
}
ul.menu li a {
  background-color: white;
  color:rgb(0, 0, 0);
  opacity: 0.75;
}
section > div {
  transition: transform 1s;
  transform: translateX(0px);
}}

      Главная

      Галерея

Body:
You need to remove following line from openMenu function.

$('div.menu-bg').addClass('animate');

Please look at the updated openMenu function.

if( 'ontouchstart' in window ){ var click = 'touchstart'; }
  else { var click = 'click'; }

  $('div.burger').on(click, function(){
      if( !$(this).hasClass('open') ){ openMenu(); }
      else { closeMenu(); }
    });

  $('div.menu ul li a').on(click, function(e){
    e.preventDefault();
    closeMenu();
  });

  function openMenu(){
        (document.getElementById("see").setAttribute("style", "display: block;"));

    //Remove this line
    // $('div.menu-bg').addClass('animate');

    $('div.burger').addClass('open');
    $('div.x, div.z').addClass('collapse');

    setTimeout(function(){
      $('div.y').hide();
      $('div.x').addClass('rotate30');
      $('div.z').addClass('rotate150');
    }, 70);
    setTimeout(function(){
      $('div.x').addClass('rotate45');
      $('div.z').addClass('rotate135');
    }, 120);
  }

  function closeMenu(){

        $('.menu li').removeClass('animate');
        (document.getElementById("see").setAttribute("style", "display: none;"));
    setTimeout(function(){
      $('div.burger').removeClass('open');
      $('div.x').removeClass('rotate45').addClass('rotate30');
      $('div.z').removeClass('rotate135').addClass('rotate150');
      $('div.menu-bg').removeClass('animate');

      setTimeout(function(){
        $('div.x').removeClass('rotate30');
        $('div.z').removeClass('rotate150');
      }, 50);
      setTimeout(function(){
        $('div.y').show();
        $('div.x, div.z').removeClass('collapse');
      }, 70);
    }, 100);

  }

body {
 background: blue;
 }
.nav {
  height: 100vh;
  position: relative;
  outline: none;
}
.nav ul {
  list-style: none;
  padding: 0.5em 0;
  margin: 0;
}
.nav ul li {
  margin: 10px;
  width: 300px;
  height: 40px;
  line-height: 40px;
  background-color: white;
  padding: 0.5em 1em 0.5em 1em;
  font-size: 24px;
  background-repeat: no-repeat;
  background-position: left 15px center;
  background-size: auto 40px;
  transition: all 0.15s linear;
  border-radius: 5px;
  border: 1px solid black;
  opacity: 0.75;
}
.nav img {
  float: left;
}
.menu li:hover {
  background-color: #ffffff;
  opacity: 1;
}

@media screen and (max-width: 900px) {
.menu {
  display: none;
}
div.burger {
  height: 30px;
  width: 40px;
  position: absolute;
  top: 11px;
  left: 21px;
}
  div.x,
  div.y,
  div.z {
    position: absolute; margin: auto;
    top: 0px; bottom: 0px;
    background: #fff;
    border-radius:2px;
    -webkit-transition: all 200ms ease-out;
       -moz-transition: all 200ms ease-out;
        -ms-transition: all 200ms ease-out;
         -o-transition: all 200ms ease-out;
            transition: all 200ms ease-out;
  }
  div.x, div.y, div.z { height: 3px; width: 26px; }
  div.y {top: 18px;}
  div.z {top: 37px;}
  div.collapse {
    top: 20px;
    -webkit-transition: all 70ms ease-out;
       -moz-transition: all 70ms ease-out;
        -ms-transition: all 70ms ease-out;
         -o-transition: all 70ms ease-out;
            transition: all 70ms ease-out;
  }

  div.rotate30 {
    -ms-transform: rotate(30deg);
     -webkit-transform: rotate(30deg);
      transform: rotate(30deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }
  div.rotate150 {
    -ms-transform: rotate(150deg);
     -webkit-transform: rotate(150deg);
      transform: rotate(150deg);
    -webkit-transition: all 50ms ease-out;
       -moz-transition: all 50ms ease-out;
        -ms-transition: all 50ms ease-out;
         -o-transition: all 50ms ease-out;
            transition: all 50ms ease-out;
  }

  div.rotate45 {
    -ms-transform: rotate(45deg);
     -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
  div.rotate135 {
    -ms-transform: rotate(135deg);
     -webkit-transform: rotate(135deg);
      transform: rotate(135deg);
    -webkit-transition: all 100ms ease-out;
       -moz-transition: all 100ms ease-out;
        -ms-transition: all 100ms ease-out;
         -o-transition: all 100ms ease-out;
            transition: all 100ms ease-out;
  }
div.menu-bg {
  width: 100%;
  height: 100%;
  position:absolute;
  top:0;
  left:0;
  background:#203d63;
  opacity:0;
  -webkit-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 300ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
}
div.menu-bg.animate{
  opacity:0.9;
  -webkit-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
     -moz-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
      -ms-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
       -o-transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);
          transition: all 400ms cubic-bezier(0.000, 0.995, 0.990, 1.000);

}
ul.menu {
  padding-top: 5em;
}
ul.menu li {
  width:300px;
  margin: 0 auto;
}
ul.menu span {
  text-align: right;
}
ul.menu li a {
  background-color: white;
  color:rgb(0, 0, 0);
  opacity: 0.75;
}
section > div {
  transition: transform 1s;
  transform: translateX(0px);
}}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="nav" role="navigation">
<div class="menu-bg"></div>
<ul class="menu" id="see">
<li class="home"><a href="#"><img src="https://picsum.photos/200/300" alt="img" height="40px"><span>Главная</span></a></li>
<li class="gallery"><a href="#"><img src="https://picsum.photos/200/300" alt="img" height="40px"><span>Галерея</span></a></li>
</ul>
<div class="burger">
<div class="x"></div>
<div class="y"></div>
<div class="z"></div>
</div>
</nav>


问:
django.urls.exceptions.NoReverseMatch: Reverse for 'new_entry' with arguments '(1,)' not found. 1 pattern(s) tried: ['new_entry/$']
I am currently working on a tutorial in the "Python Crash course" Book.

The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics

I am currently stuck at editing an existing Entry form and receive an Error, when I run
http://127.0.0.1:8000/topics/2/

forms.py file

```<code>    from django import forms
    from .models import Topic,Entry
    class Topicform(forms.ModelForm):
         class Meta:
         model = Topic
         fields =['text']
         labels = {'text' :''}
    class Entryform(forms.ModelForm):
        class Meta:
        model = Entry
        fields =['text']
        labels = {'text' :''}
        widgets = {'text' : forms.Textarea(attrs={'cols':80})}
</code>```

urls.py file

```<code>    from django.conf.urls import url
    from . import views
    app_name='learning_logs'
    urlpatterns=[
      #Home page
    url(r'^$',views.index,name='index'),
      #Show all topics page
    url(r'^topics/$',views.topics,name='topics'),
      #Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'),
      #Page for adding a new topic
    url(r'^new_topic/$',views.new_topic,name='new_topic'),
      #Page for adding a new entry
    url(r'^new_entry/$',views.new_entry,name='new_entry'),
      #Page for editing an entry
    url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'),
</code>```

]

views.py file

```<code>    from django.http import HttpResponseRedirect
    from django.urls import reverse
    from django.shortcuts import render
    from .models import Topic,Entry
    from .forms import Topicform, Entryform
    --snip--
    def edit_entry(request,entry_id):
        entry = Entry.objects.get(id=entry_id)
        topic=entry.topic

        if request.method != 'POST':
        # No data submitted; create a blank form
           form = Entryform(instance = entry)
        else:
        # Post data submitted;process data
           form = Entryform(request.POST,instance=entry)
           if form.is_valid():
                form.save()
        return HttpResponseRedirect(reverse('learning_logs:topics',args=[topic.id]))

   context={'entry':entry,'topic':topic,'form':form}
   return render(request,'learning_logs/edit_entry.html',context)
</code>```

edit_entry.html file

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

    {% block content %}

    <p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p>

    <p>Edit Entry:</p>
    <form action= "{%url 'learning_logs:edit_entry' entry.id %}" method = 'post'>
        {%csrf_token %}
        {{form.as_p}}
    <button name="submit">save changes</button>
    </form>

   {% endblock content %}
</code>```

topic.html file

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

    {% block content %}
    <p> Topic: {{topic}} </p>
    <p> Entries:</p>
    <p>
       <a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a>
    </p>
    <ul>
         {%for entry in entries%}
       <li>
         <p> {{entry.date_added|date:'M d,Y H:i'}} </p>
         <p> {{entry.text|linebreaks}} </p>
         <p>
            <a href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a>
         </p>
      </li>
  {%empty%}
      <li>
         There are no entries for this topic yet.
      </li>
 {% endfor %}
 </ul>
{% endblock content %}
</code>```

答:
Your new_entry path does not take any parameter as from your urls.py. But you gave one, in topic.html:

```<code><a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a>
</code>```

Here, topic.id is what you gave. But should be:

```<code><a href="{% url 'learning_logs:new_entry' %}">Add new entry</a>
</code>```

EDIT

So, I ll try to explain. Firstly, Let you see the url for new_entry as you register in urls.py.

```<code>  #Page for adding a new topic
  url(r'^new_topic/$',views.new_topic,name='new_topic'),
</code>```

Here, you did not gave parameter to the path. See, first part of path. r'^new_topic/$'. And, see your url route where you gave the parameter:

```<code>  #Page for editing an entry
  url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'),
</code>```

Now, let's see the first part r'^edit_entry/(?P<entry_id>\d+)/$', here you  can see parameter, i.e, (?P<entry_id>\d+) with name, entry_id. Comparing both the urls, your practical urls will look like:

```<code>  #For adding new topic
  www.example.com/new_topic/

  #For url with parameter
  www.example.com/edit_entry/1/   # 1 is entry_id, parameter for route edit_entry
</code>```

Now, lets come in your template:

```<code><a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a>
</code>```

See, last part in django url tag, i.e, topic.id. As, in your urls.py you did not give parameter to new_entry. So, if you give parameter to the url which does not take parameter(does not take parameter, I mean to say url is registered but parameter is not set to them), then the url you are getting will be shown.

I hope you now understand what I was saying. For, further more explanation of what to do, you can see the second answer by W-liamx. Have a look at this beautiful documentation on urls by django.

Body:
I am currently working on a tutorial in the "Python Crash course" Book.

The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics

I am currently stuck at editing an existing Entry form and receive an Error, when I run
http://127.0.0.1:8000/topics/2/

forms.py file

    from django import forms
    from .models import Topic,Entry
    class Topicform(forms.ModelForm):
         class Meta:
         model = Topic
         fields =['text']
         labels = {'text' :''}
    class Entryform(forms.ModelForm):
        class Meta:
        model = Entry
        fields =['text']
        labels = {'text' :''}
        widgets = {'text' : forms.Textarea(attrs={'cols':80})}

urls.py file

    from django.conf.urls import url
    from . import views
    app_name='learning_logs'
    urlpatterns=[
      #Home page
    url(r'^$',views.index,name='index'),
      #Show all topics page
    url(r'^topics/$',views.topics,name='topics'),
      #Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'),
      #Page for adding a new topic
    url(r'^new_topic/$',views.new_topic,name='new_topic'),
      #Page for adding a new entry
    url(r'^new_entry/$',views.new_entry,name='new_entry'),
      #Page for editing an entry
    url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'),

]

views.py file

    from django.http import HttpResponseRedirect
    from django.urls import reverse
    from django.shortcuts import render
    from .models import Topic,Entry
    from .forms import Topicform, Entryform
    --snip--
    def edit_entry(request,entry_id):
        entry = Entry.objects.get(id=entry_id)
        topic=entry.topic

        if request.method != 'POST':
        # No data submitted; create a blank form
           form = Entryform(instance = entry)
        else:
        # Post data submitted;process data
           form = Entryform(request.POST,instance=entry)
           if form.is_valid():
                form.save()
        return HttpResponseRedirect(reverse('learning_logs:topics',args=[topic.id]))

   context={'entry':entry,'topic':topic,'form':form}
   return render(request,'learning_logs/edit_entry.html',context)

edit_entry.html file

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

    {% block content %}

{{ topic }}

Edit Entry:

    <form action= "{%url 'learning_logs:edit_entry' entry.id %}" method = 'post'>
        {%csrf_token %}
        {{form.as_p}}
    <button name="submit">save changes</button>
    </form>

   {% endblock content %}

topic.html file

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

    {% block content %}

 Topic: {{topic}}

 Entries:

       Add new entry

         {%for entry in entries%}

 {{entry.date_added|date:'M d,Y H:i'}}

 {{entry.text|linebreaks}}

            edit entry

  {%empty%}

         There are no entries for this topic yet.

 {% endfor %}

{% endblock content %}

Body:
Your new_entry path does not take any parameter as from your urls.py. But you gave one, in topic.html:

<a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a>

Here, topic.id is what you gave. But should be:

<a href="{% url 'learning_logs:new_entry' %}">Add new entry</a>

EDIT

So, I ll try to explain. Firstly, Let you see the url for new_entry as you register in urls.py.

  #Page for adding a new topic
  url(r'^new_topic/$',views.new_topic,name='new_topic'),

Here, you did not gave parameter to the path. See, first part of path. r'^new_topic/$'. And, see your url route where you gave the parameter:

  #Page for editing an entry
  url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'),

Now, let's see the first part r'^edit_entry/(?P<entry_id>\d+)/$', here you  can see parameter, i.e, (?P<entry_id>\d+) with name, entry_id. Comparing both the urls, your practical urls will look like:

  #For adding new topic
  www.example.com/new_topic/

  #For url with parameter
  www.example.com/edit_entry/1/   # 1 is entry_id, parameter for route edit_entry

Now, lets come in your template:

<a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a>

See, last part in django url tag, i.e, topic.id. As, in your urls.py you did not give parameter to new_entry. So, if you give parameter to the url which does not take parameter(does not take parameter, I mean to say url is registered but parameter is not set to them), then the url you are getting will be shown.

I hope you now understand what I was saying. For, further more explanation of what to do, you can see the second answer by W-liamx. Have a look at this beautiful documentation on urls by django.


问:
Reading XML Value Using Schema XSD
I am having XML tag as below.

My tries to read unitcode value using XSD Script and it's result are,

```<code>XML Tag: <AllocatedBaseUOMQuantity unitCode="EA">4.0</AllocatedBaseUOMQuantity>

Try1: <xsl:value-of select="*:AllocatedBaseUOMQuantity[@unitCode]/text()"/> : Result = 4.0
Try2: <xsl:value-of select="*:OpenBaseUOMQuantity/@unitCode/text()"/> : Resut = ""
Try3: <xsl:value-of select="*:OpenBaseUOMQuantity/unitCode/text()"/> : Resut = ""

</code>```

I want to get unitcode value "EA" as a output. Please advice.

Thanks in advance.

Regards,
MGP

答:
I'm afraid this question is very confused. I don't see any XSD "script" here. Are you confusing XSD with XSLT?

The XPath expression you are looking for is

```<code>select="*:AllocatedBaseUOMQuantity/@unitCode"
</code>```

Rather than just putting this in your code, I'd suggest you do some reading so that you understand why it works, and why your attempts don't. It looks very much as if you were trying a scatter-gun approach, trying out different constructs without understanding their meaning, and that's never going to be an efficient way of programming.

Title: Reading XML Value Using Schema XSD

Body:
I am having XML tag as below.

My tries to read unitcode value using XSD Script and it's result are,

XML Tag: <AllocatedBaseUOMQuantity unitCode="EA">4.0</AllocatedBaseUOMQuantity>

Try1: <xsl:value-of select="*:AllocatedBaseUOMQuantity[@unitCode]/text()"/> : Result = 4.0
Try2: <xsl:value-of select="*:OpenBaseUOMQuantity/@unitCode/text()"/> : Resut = ""
Try3: <xsl:value-of select="*:OpenBaseUOMQuantity/unitCode/text()"/> : Resut = ""

I want to get unitcode value "EA" as a output. Please advice.

Thanks in advance.

Regards,
MGP

Body:
I'm afraid this question is very confused. I don't see any XSD "script" here. Are you confusing XSD with XSLT?

The XPath expression you are looking for is

select="*:AllocatedBaseUOMQuantity/@unitCode"

Rather than just putting this in your code, I'd suggest you do some reading so that you understand why it works, and why your attempts don't. It looks very much as if you were trying a scatter-gun approach, trying out different constructs without understanding their meaning, and that's never going to be an efficient way of programming.


问:
Unable to Access New Linux Samba Share from Windows 10
I can't connect to the Linux Samba share just created from Windows 10.
I get the "You do not have permission to access..." error message on Windows.
Any help will be appreciated.  It looks like I am sooo close!  FYI, I can ping, ssh into the linux box, etc.  Network connectivity doesn't appear to be an issue.

Here's the smb.conf...

```<code>    [global]
        workgroup = SAMBA
        security = user

        passdb backend = tdbsam

        printing = cups
        log level = 2
        printcap name = cups
        load printers = yes
        cups options = raw
        hosts allow = 192.168.1.220 192.158.1.230 192.168.1.240 192.168.1.0/24

[homes]
        comment = Home Directories
        valid users = %S, %D%w%S
        browseable = No
        read only = No
        inherit acls = Yes

    [printers]
        comment = All Printers
        path = /var/tmp
        printable = Yes
        create mask = 0600
        browseable = No

[print$]
        comment = Printer Drivers
        path = /var/lib/samba/drivers
        write list = @printadmin root
        force group = @printadmin
        create mask = 0664
        directory mask = 0775

    [fshare]
        browseable = yes
        path = /home/fshare
        public = yes
        writeable = yes
        read only = no
        guest ok = yes
        guest only = yes
        create mode = 0777
        directory mode = 0777
        valid users = sambauser
</code>```

答:
In my case, I had to chmod the share folder. As root :

chmod -R 777 /home/shares/

Quite brutal, but enough for my home needs.

Body:
I can't connect to the Linux Samba share just created from Windows 10.
I get the "You do not have permission to access..." error message on Windows.
Any help will be appreciated.  It looks like I am sooo close!  FYI, I can ping, ssh into the linux box, etc.  Network connectivity doesn't appear to be an issue.

Here's the smb.conf...

    [global]
        workgroup = SAMBA
        security = user

        passdb backend = tdbsam

        printing = cups
        log level = 2
        printcap name = cups
        load printers = yes
        cups options = raw
        hosts allow = 192.168.1.220 192.158.1.230 192.168.1.240 192.168.1.0/24

[homes]
        comment = Home Directories
        valid users = %S, %D%w%S
        browseable = No
        read only = No
        inherit acls = Yes

    [printers]
        comment = All Printers
        path = /var/tmp
        printable = Yes
        create mask = 0600
        browseable = No

[print$]
        comment = Printer Drivers
        path = /var/lib/samba/drivers
        write list = @printadmin root
        force group = @printadmin
        create mask = 0664
        directory mask = 0775

    [fshare]
        browseable = yes
        path = /home/fshare
        public = yes
        writeable = yes
        read only = no
        guest ok = yes
        guest only = yes
        create mode = 0777
        directory mode = 0777
        valid users = sambauser


问:
How can I generate the external url for images in Sails?
Currently, Sails serves the images hosted in assets/images folder, however, I need a different approach because the images will be hosted in a CDN system (AWS Cloudfront), so the images' URLs follow a structure like this:

```<code>https://hdfhhfh.cloudtfront.net/images/image.jpg
</code>```

Therefore, How can I approach this?, How can I approach this in order to Sails automatically generate the URL for me?

For dev env, it's ok, for production env I need all the images in HTML/EJS to point to the CDN.

答:
After thinking about how to approach this, I decided to config a reverse proxy between the client and the backend.

With Nginx I configured a rule to redirect the /images/* to Cloudfront endpoint, this way I've avoided placing hard code in my project.  Moreover, I have css files which are pointing to /images/*, with this approach I don't care about it.

Body:
Currently, Sails serves the images hosted in assets/images folder, however, I need a different approach because the images will be hosted in a CDN system (AWS Cloudfront), so the images' URLs follow a structure like this:

https://hdfhhfh.cloudtfront.net/images/image.jpg

Therefore, How can I approach this?, How can I approach this in order to Sails automatically generate the URL for me?

For dev env, it's ok, for production env I need all the images in HTML/EJS to point to the CDN.


问:
Linking together two models in a Razor Pages/MVC asp application
So. I am working on a Razor based website that functions as a business manager.

I am trying to link an address to a printer in the creation page.

The Printer Model looks like this:
public class Printer
    {
        public int ID { get; set; }

```<code>    [StringLength(50)]
    [Display(Name = "Machine ID")]
    public string MachineID { get; set; }

    [Display(Name = "Log ID")]
    public int Log_ID { get; set; }

    [Display(Name = "Lease ID")]
    public int Lease_ID { get; set; }

    [Display(Name = "Serial Number")]
    [StringLength(50)]
    public string Serial_Number { get; set; }

    [StringLength(10)]
    public string Solution { get; set; }

    [StringLength(50)]
    [Display(Name = "Additional Info")]
    public string Additional_Info { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Installation Date")]
    public DateTime InstallationDate { get; set; }

    [Display(Name = "Mono Click")]
    public float Mono_Click { get; set; }

    [Display(Name = "Colour Click")]
    public float Colour_Click { get; set; }

    public int Minimum { get; set; }

    [Display(Name = "Parts Warranty")]
    public int Parts_Warranty { get; set; }

    [Display(Name = "IT Support")]
    public int IT_Support { get; set; }

    [StringLength(50)]
    [Display(Name = "Contract Type")]
    public string Contract_Type { get; set; }

    public Company_Site Site { get; set; }
    public Printer_Model Model { get; set; }
    public Address Previous_Address { get; set; }
}
</code>```

The Address Model looks like this:
public class Address
    {
        public int ID { get; set; }

```<code>    [StringLength(50)]
    [Display(Name = "Address")]
    public string Address_1 { get; set; }

    [Display(Name = "Address")]
    [StringLength(50)]
    public string Address_2 { get; set; }

    [StringLength(50)]
    [Display(Name = "City")]
    public string Town_City { get; set; }

    [StringLength(50)]
    public string County { get; set; }

    [Display(Name = "Post Code")]
    [StringLength(10)]
    public string Post_Code { get; set; }
}
</code>```

To try and link them together I have this in my Create.cshtml.cs file:

```<code>public List<SelectListItem> PrevAddress { get; set; }
public IActionResult OnGet()
   {
        PrevAddress = _context.Address.Select(a => new SelectListItem
        {
            Value = a.ID.ToString(),
            Text = a.Address_1 + " " + a.Town_City + " " + a.Post_Code
        }).ToList();
        return Page();
    }
</code>```

Create.cshtml:

```<code><div class="form-group">
                <label asp-for="Printer.Previous_Address.ID" class="control-label"></label>
                <select asp-for="Printer.Previous_Address.ID" name="PrevAddress" asp-items="Model.PrevAddress" class="form-control"><option value=""></option></select>
                <span asp-validation-for="Printer.Previous_Address.ID" class="text-danger"></span>
            </div>
</code>```

However, when I run it through my form no value gets sent to the foreign key field in the database even when I have explicitly selected one of my addresses from the dropdown box. Any help in this would be much appreciated.

答:
If you want to set an item as selected in the select tag helper, you can do so by assigning its value to the property specified by the asp-for attribute.

https://www.learnrazorpages.com/razor-pages/forms/select-lists#setting-selected-items1

1Disclosure - I own the Learn Razor Pages site

Body:
So. I am working on a Razor based website that functions as a business manager.

I am trying to link an address to a printer in the creation page.

The Printer Model looks like this:
public class Printer
    {
        public int ID { get; set; }

    [StringLength(50)]
    [Display(Name = "Machine ID")]
    public string MachineID { get; set; }

    [Display(Name = "Log ID")]
    public int Log_ID { get; set; }

    [Display(Name = "Lease ID")]
    public int Lease_ID { get; set; }

    [Display(Name = "Serial Number")]
    [StringLength(50)]
    public string Serial_Number { get; set; }

    [StringLength(10)]
    public string Solution { get; set; }

    [StringLength(50)]
    [Display(Name = "Additional Info")]
    public string Additional_Info { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Installation Date")]
    public DateTime InstallationDate { get; set; }

    [Display(Name = "Mono Click")]
    public float Mono_Click { get; set; }

    [Display(Name = "Colour Click")]
    public float Colour_Click { get; set; }

    public int Minimum { get; set; }

    [Display(Name = "Parts Warranty")]
    public int Parts_Warranty { get; set; }

    [Display(Name = "IT Support")]
    public int IT_Support { get; set; }

    [StringLength(50)]
    [Display(Name = "Contract Type")]
    public string Contract_Type { get; set; }

    public Company_Site Site { get; set; }
    public Printer_Model Model { get; set; }
    public Address Previous_Address { get; set; }
}

The Address Model looks like this:
public class Address
    {
        public int ID { get; set; }

    [StringLength(50)]
    [Display(Name = "Address")]
    public string Address_1 { get; set; }

    [Display(Name = "Address")]
    [StringLength(50)]
    public string Address_2 { get; set; }

    [StringLength(50)]
    [Display(Name = "City")]
    public string Town_City { get; set; }

    [StringLength(50)]
    public string County { get; set; }

    [Display(Name = "Post Code")]
    [StringLength(10)]
    public string Post_Code { get; set; }
}

To try and link them together I have this in my Create.cshtml.cs file:

public List<SelectListItem> PrevAddress { get; set; }
public IActionResult OnGet()
   {
        PrevAddress = _context.Address.Select(a => new SelectListItem
        {
            Value = a.ID.ToString(),
            Text = a.Address_1 + " " + a.Town_City + " " + a.Post_Code
        }).ToList();
        return Page();
    }

Create.cshtml:

                <select asp-for="Printer.Previous_Address.ID" name="PrevAddress" asp-items="Model.PrevAddress" class="form-control"><option value=""></option></select>

However, when I run it through my form no value gets sent to the foreign key field in the database even when I have explicitly selected one of my addresses from the dropdown box. Any help in this would be much appreciated.


问:
How to prevent NSManagedObjectContext from corrupting the database when a thread gets killed while saving?
In this question, octy wrote:

BTW, if you save on a background
  thread, you also need to consider what
  happens when your app is terminated
  while a save operation is in progress.
  Background threads get killed right
  away, whereas the watchdog waits 5
  seconds for the main thread to finish
  up.

Now I've spent all day implementing NSOperation and creating NSManagedObjectContext instances directly inside the NSOperation subclasses so every NSOperation owns it's own non-shared MOC. But now this is very bad news since a scenario like this, which likely happens all the time, would corrupt the Core Data database. I mean it can't start to write a half byte of something in the sqlite3 file and then just stop right away.

And then there's another problem: In my NSOperations I also do File I/O with NSFileManager.

So what can I do about this? Must I keep track of all running NSOperations and NSOperationQueues in my app und take care of them quickly in the App Delegate when the app gets terminated, so that I can tell the NSOperations to SFF (Save F*****g Fast) or cancel all operations, grab their MOC's and "hard-save" them immediately? What's best practice to solve this problem?

And why am I hearing about this the first time in my career? I mean none of the NSOperationQueue and Core Data mentioning books even talks about this but it seems it's a random app killer that forces the user to re-install (and possibly lose tons of data) if we don't take explicit care of this.

答:
The main power of MOC is that represents an abstract storage that is independent from the format. It stores all it's objects in the memory and uses the mechanism of transactions to commit any changes. So when you're inserting/deleting/editing some objects that in MOC they are only changed in memory and not in persistent store (whether it is SQLite database, XML file or whatever). The changes are only committed when you call save: method.

As for NSOperation and file handling: if you want to stop some operation, you should call cancel for that. From docs:

This method does not force your
  operation code to stop. Instead, it
  updates the object’s internal flags to
  reflect the change in state. If the
  operation has already finished
  executing, this method has no effect.
  Canceling an operation that is
  currently in an operation queue, but
  not yet executing, makes it possible
  to remove the operation from the queue
  sooner than usual.

It means that if there is some IO operation running when you're canceling an operation operation would wait until it is finished.

Also despite the Core Data transaction mechanism you should implement your own one for any data that is not managed by it (if needed).


问:
Pandas masking a specific column by date
I have a dataframe (df) with 2 main columns--one called 'TIMESTAMP' representing dates, and one called 'QC' reflecting quality control flags as ints. This df has about 40,000 rows so I do not want to iterate over each one.

I have a new dataframe (dfNew) with just two columns of several start and end date pairs. I want to go through my original df and for all rows where the TIMESTAMP falls in between any of the start-end date pairs listed in dfNew, I want to replace the QC value with -1. This dfNew has about 400 rows so I figured iterating here would not be too bad.

The df looks something like this:

```<code>TIMESTAMP       | QC
2019-05-04 00:22    5
2019-05-04 00:24    1
2019-05-09 03:30    3
</code>```

the dfNew looks something like this:

```<code>START         | END
20190504_0023   20190504_0024
</code>```

So I would want to replace QC=1 for the second row in df with QC=-1.

This is my code so far:

```<code>for index, row in dfNew.iterrows():
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'].mask(masked, -1)
</code>```

However for some reason, the mask is not working. No values get replaced with -1. I think it may have something to with the fact that I'm creating the mask using the TIMESTAMP column but trying to use that mask to replace values in the QC columns, but I cannot figure out what it is. Any thoughts would be appreciated!

答:
The main thing is that you need to set the column values equal to the applied mask: df['QC'] = df['QC'].mask(masked, -1).

You only need to convert the 'TIMESTAMP' column to datetimes once outside of the loop. Assuming you have multiple rows in dfNew, the start and end times change for each row, so this stays inside the loop.

```<code># this should be outside of the loop
df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])

for index, row in dfNew.iterrows():
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'] = df['QC'].mask(masked, -1)
</code>```

Body:
I have a dataframe (df) with 2 main columns--one called 'TIMESTAMP' representing dates, and one called 'QC' reflecting quality control flags as ints. This df has about 40,000 rows so I do not want to iterate over each one.

I have a new dataframe (dfNew) with just two columns of several start and end date pairs. I want to go through my original df and for all rows where the TIMESTAMP falls in between any of the start-end date pairs listed in dfNew, I want to replace the QC value with -1. This dfNew has about 400 rows so I figured iterating here would not be too bad.

The df looks something like this:

TIMESTAMP       | QC
2019-05-04 00:22    5
2019-05-04 00:24    1
2019-05-09 03:30    3

the dfNew looks something like this:

START         | END
20190504_0023   20190504_0024

So I would want to replace QC=1 for the second row in df with QC=-1.

This is my code so far:

for index, row in dfNew.iterrows():
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'].mask(masked, -1)

However for some reason, the mask is not working. No values get replaced with -1. I think it may have something to with the fact that I'm creating the mask using the TIMESTAMP column but trying to use that mask to replace values in the QC columns, but I cannot figure out what it is. Any thoughts would be appreciated!

Body:
The main thing is that you need to set the column values equal to the applied mask: df['QC'] = df['QC'].mask(masked, -1).

You only need to convert the 'TIMESTAMP' column to datetimes once outside of the loop. Assuming you have multiple rows in dfNew, the start and end times change for each row, so this stays inside the loop.

# this should be outside of the loop
df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])

for index, row in dfNew.iterrows():
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'] = df['QC'].mask(masked, -1)


问:
Add value of the already existing key in dict in a form of container in Python
Is there any built-in function that would do the following?

```<code>dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}
</code>```

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

答:
You could rewrite the update function by creating a new class:

In Python bulitins.py:

```<code>    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass
</code>```

So I write this(Inherit from UserDict, suggested by @timgeb):

```<code>from collections import UserDict

class CustomDict(UserDict):
    def __init__(self):
        super().__init__()

    def update(self, E=None, **F) -> None:
        if E:
            if isinstance(E, dict):
                for k in E:
                    self[k] = E[k]
            else:
                for k, v in E:
                    self[k] = v
        else:
            if isinstance(F, dict):
                for key in F:
                    if isinstance(self[key], list):
                        self[key].append(F[key])
                    else:
                        self[key] = [self[key], F[key]]

dictionary = CustomDict()
dictionary.update({'a': 1, 'b': 2, 'c': 3})
print(dictionary)
dictionary.update(a=3)
print(dictionary)
dictionary.update(a=4)
print(dictionary)
</code>```

Result:

```<code>{'a': 1, 'b': 2, 'c': 3}
{'a': [1, 3], 'b': 2, 'c': 3}
{'a': [1, 3, 4], 'b': 2, 'c': 3}
</code>```

Maybe there are some logic errors in my code,but welcome to point out.

Body:
Is there any built-in function that would do the following?

dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

Body:
You could rewrite the update function by creating a new class:

In Python bulitins.py:

    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

So I write this(Inherit from UserDict, suggested by @timgeb):

from collections import UserDict

class CustomDict(UserDict):
    def __init__(self):
        super().__init__()

    def update(self, E=None, **F) -> None:
        if E:
            if isinstance(E, dict):
                for k in E:
                    self[k] = E[k]
            else:
                for k, v in E:
                    self[k] = v
        else:
            if isinstance(F, dict):
                for key in F:
                    if isinstance(self[key], list):
                        self[key].append(F[key])
                    else:
                        self[key] = [self[key], F[key]]

dictionary = CustomDict()
dictionary.update({'a': 1, 'b': 2, 'c': 3})
print(dictionary)
dictionary.update(a=3)
print(dictionary)
dictionary.update(a=4)
print(dictionary)

Result:

{'a': 1, 'b': 2, 'c': 3}
{'a': [1, 3], 'b': 2, 'c': 3}
{'a': [1, 3, 4], 'b': 2, 'c': 3}

Maybe there are some logic errors in my code,but welcome to point out.


问:
constraintlayout baseline to baseline with autosize
I'm trying to align 2 textviews by baseline and use autosize for textsize at the same time.
Here is simplified code example. First textview has big size, so textsize auto set to some big value. Second textview smaller than first one so it has smaller auto determined textsize.

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

    <TextView
        android:id="@+id/text1"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:text="text1"
        android:maxLines="1"
        android:autoSizeTextType="uniform"
        android:autoSizeMaxTextSize="200sp"
        android:autoSizeMinTextSize="2sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/text2"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/text2"
        android:layout_width="50dp"
        android:layout_height="20dp"
        android:text="text2"
        android:maxLines="1"
        android:autoSizeTextType="uniform"
        android:autoSizeMaxTextSize="200sp"
        android:autoSizeMinTextSize="2sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/text1"
        app:layout_constraintBaseline_toBaselineOf="@id/text1"/>

</android.support.constraint.ConstraintLayout>
</code>```

result of example code

The problem is that seems layout_constraintBaseline_toBaselineOf stops working as soon as I use autoSizeTextType

It would be nice if someone can point me right direction. Am I understand wrong how to use constraintlayout? Or is it just baseline_tobaseline does not work with autosize?

答:
I fixed it as follows:

Kotlin:

```<code>text1.text = "This is text text text text"
text1.post{

text1.requestLayout()

}
</code>```

Body:
I'm trying to align 2 textviews by baseline and use autosize for textsize at the same time.
Here is simplified code example. First textview has big size, so textsize auto set to some big value. Second textview smaller than first one so it has smaller auto determined textsize.

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

    <TextView
        android:id="@+id/text1"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:text="text1"
        android:maxLines="1"
        android:autoSizeTextType="uniform"
        android:autoSizeMaxTextSize="200sp"
        android:autoSizeMinTextSize="2sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/text2"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/text2"
        android:layout_width="50dp"
        android:layout_height="20dp"
        android:text="text2"
        android:maxLines="1"
        android:autoSizeTextType="uniform"
        android:autoSizeMaxTextSize="200sp"
        android:autoSizeMinTextSize="2sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/text1"
        app:layout_constraintBaseline_toBaselineOf="@id/text1"/>

</android.support.constraint.ConstraintLayout>

result of example code

The problem is that seems layout_constraintBaseline_toBaselineOf stops working as soon as I use autoSizeTextType

It would be nice if someone can point me right direction. Am I understand wrong how to use constraintlayout? Or is it just baseline_tobaseline does not work with autosize?

Body:
I fixed it as follows:

Kotlin:

text1.text = "This is text text text text"
text1.post{

text1.requestLayout()

}


问:
How to delete a form from a cell in a Google Colab notebook?
I might be going crazy, but I believe I read all the existing documentation on Google Colab and I couldn't figure this one out. Maybe it's not possible, but I find this to be very weird.

I am aware that the form can be hidden, and that I can simply copy paste the contents of the cell and just paste it in a new cell that doesn't have a form, but these are hacks and not how a regular user would try to do it.

I am wondering if I'm going crazy and I just can't see the delete form button, or did someone at google colab UX simply forgot about the delete form menu? (or maybe they chose to not add it for a reason I can't understand)

答:
You specify the form with #@param. Forms are simply interpretable Python comments.

For example

```<code>i = 0 #@param {type:'slider', max: 10}
</code>```

To remove the form, just remove all #@param, including the initial #@title

```<code>i = 0
</code>```

The "Add a form" menu simply inserts the #@title parameter. There is no menu to remove this line.

Body:
You specify the form with #@param. Forms are simply interpretable Python comments.

For example

i = 0 #@param {type:'slider', max: 10}

To remove the form, just remove all #@param, including the initial #@title

i = 0

The "Add a form" menu simply inserts the #@title parameter. There is no menu to remove this line.


问:
how to Progress bar show before image load.?
I want to show a progress bar before image loading. I am getting an image from firebase storage. some time image taking more time to load and show .. ... That's why I am trying to input progressbar before load image..... I have tried but now working. Can anyone help me to solve this issue????

Please check my code below:-

```<code>  public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

        public Context mContext;
        private List <Post>mPost;
        private FirebaseUser firebaseUser;
        ProgressBar progressBar;

        public PostAdapter(Context mContext, List<Post> mPost) {
            this.mContext = mContext;
            this.mPost = mPost;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);

            return new PostAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {

            firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
            final Post post=mPost.get(position);

            try {
                Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(holder.post_image);

            }catch (Exception e)
            {

            }

            //holder.time.setText(post.getTime());
            Get_Time_ago getTimeAgo=new Get_Time_ago();

            long lastTime=Long.parseLong(String.valueOf(post.timestamp));
            String last_seen_time=getTimeAgo.getTimeAgo(lastTime,mContext);
           holder. time.setText(last_seen_time);
                       /*SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                       String time=sfd.format(new Date(lastseenonline));
                       mLast_seenview.setText(time);*/

            if(post.getDescription().equals("")){
                holder.description.setVisibility(View.GONE);

            }else {
                holder.description.setVisibility(View.VISIBLE);
                holder.description.setText(post.getDescription());

            }

            publisherInfo(holder.image_profile,holder.username,holder.blood,holder.publisher,post.getPublisher());

            if(post.getPublisher().equals(firebaseUser.getUid())){
                holder.delete.setVisibility(View.VISIBLE);

            }else {
                holder.delete.setVisibility(View.GONE);

            }

            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                        alertDialog.setTitle("Confirm Delete?");
                        alertDialog.setMessage("Do you want to delete your post?");
                        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
                                notify();

                            }
                        });
                        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        alertDialog.show();
                    }

            });

        }

        @Override
        public int getItemCount() {
            return mPost.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView image_profile,post_image,like,dislike,comment,save,delete;
            public TextView username,blood,likes,dislikes,comments, description,publisher,time;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                image_profile=itemView.findViewById(R.id.image_profile);
                post_image=itemView.findViewById(R.id.post_image);
                like=itemView.findViewById(R.id.like);
                comment=itemView.findViewById(R.id.comment);
                save=itemView.findViewById(R.id.save);
                delete=itemView.findViewById(R.id.delete);

                username=itemView.findViewById(R.id.username);
                blood=itemView.findViewById(R.id.blood);
                time=itemView.findViewById(R.id.time);

                likes=itemView.findViewById(R.id.likes);
                dislikes=itemView.findViewById(R.id.dislikes);
                dislike=itemView.findViewById(R.id.dislike);
                comments=itemView.findViewById(R.id.comments);
                description=itemView.findViewById(R.id.description);
                publisher=itemView.findViewById(R.id.publisher);
                progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);

            }
        }

        private void publisherInfo (final ImageView image_profile, final TextView username,final  TextView blood, final TextView publisher, final String userId ){
            DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    try {
                        User user=dataSnapshot.getValue(User.class);
                        Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);

                        username.setText(user.getUsername());
                        blood.setText(user.getBlood());

                        publisher.setText(user.getUsername());

                    }catch (Exception e){

                    }

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

    }
</code>```

答:
You can show a loading using a CircularProgressDrawable in the Glides´s placeholder.  I copied it from my little project, it is in Kotlin, but is easy:

```<code>fun AppCompatImageView.loadImage(imageUri: String) {
    val circularProgressDrawable = CircularProgressDrawable(context)
    circularProgressDrawable.strokeWidth = 5f
    circularProgressDrawable.centerRadius = 30f
    circularProgressDrawable.start()

    Glide.with(context)
            .load(imageUri)
            .placeholder(circularProgressDrawable)
            .error(R.drawable.ic_close_black)
            .override(200, 300)
            .into(this)
}
</code>```

Update after your comment... code in Java:

```<code> void loadImage(AppCompatImageView yourImageView, String imageUri) {
        CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(yourImageView.getContext())
        circularProgressDrawable.setStrokeWidth(5f);
        circularProgressDrawable.setCenterRadius(30f);
        circularProgressDrawable.start();

        Glide.with(yourImageView)
            .load(imageUri)
            .placeholder(circularProgressDrawable)
            .error(R.drawable.ic_close_black)
            .override(200, 300)
            .into(yourImageView);
    }
</code>```

Body:
I want to show a progress bar before image loading. I am getting an image from firebase storage. some time image taking more time to load and show .. ... That's why I am trying to input progressbar before load image..... I have tried but now working. Can anyone help me to solve this issue????

Please check my code below:-

  public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

        public Context mContext;
        private List <Post>mPost;
        private FirebaseUser firebaseUser;
        ProgressBar progressBar;

        public PostAdapter(Context mContext, List<Post> mPost) {
            this.mContext = mContext;
            this.mPost = mPost;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);

            return new PostAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {

            firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
            final Post post=mPost.get(position);

            try {
                Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(holder.post_image);

            }catch (Exception e)
            {

            }

            //holder.time.setText(post.getTime());
            Get_Time_ago getTimeAgo=new Get_Time_ago();

            long lastTime=Long.parseLong(String.valueOf(post.timestamp));
            String last_seen_time=getTimeAgo.getTimeAgo(lastTime,mContext);
           holder. time.setText(last_seen_time);
                       /*SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                       String time=sfd.format(new Date(lastseenonline));
                       mLast_seenview.setText(time);*/

            if(post.getDescription().equals("")){
                holder.description.setVisibility(View.GONE);

            }else {
                holder.description.setVisibility(View.VISIBLE);
                holder.description.setText(post.getDescription());

            }

            publisherInfo(holder.image_profile,holder.username,holder.blood,holder.publisher,post.getPublisher());

            if(post.getPublisher().equals(firebaseUser.getUid())){
                holder.delete.setVisibility(View.VISIBLE);

            }else {
                holder.delete.setVisibility(View.GONE);

            }

            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                        alertDialog.setTitle("Confirm Delete?");
                        alertDialog.setMessage("Do you want to delete your post?");
                        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
                                notify();

                            }
                        });
                        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        alertDialog.show();
                    }

            });

        }

        @Override
        public int getItemCount() {
            return mPost.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView image_profile,post_image,like,dislike,comment,save,delete;
            public TextView username,blood,likes,dislikes,comments, description,publisher,time;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                image_profile=itemView.findViewById(R.id.image_profile);
                post_image=itemView.findViewById(R.id.post_image);
                like=itemView.findViewById(R.id.like);
                comment=itemView.findViewById(R.id.comment);
                save=itemView.findViewById(R.id.save);
                delete=itemView.findViewById(R.id.delete);

                username=itemView.findViewById(R.id.username);
                blood=itemView.findViewById(R.id.blood);
                time=itemView.findViewById(R.id.time);

                likes=itemView.findViewById(R.id.likes);
                dislikes=itemView.findViewById(R.id.dislikes);
                dislike=itemView.findViewById(R.id.dislike);
                comments=itemView.findViewById(R.id.comments);
                description=itemView.findViewById(R.id.description);
                publisher=itemView.findViewById(R.id.publisher);
                progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);

            }
        }

        private void publisherInfo (final ImageView image_profile, final TextView username,final  TextView blood, final TextView publisher, final String userId ){
            DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    try {
                        User user=dataSnapshot.getValue(User.class);
                        Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);

                        username.setText(user.getUsername());
                        blood.setText(user.getBlood());

                        publisher.setText(user.getUsername());

                    }catch (Exception e){

                    }

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

    }

Body:
You can show a loading using a CircularProgressDrawable in the Glides´s placeholder.  I copied it from my little project, it is in Kotlin, but is easy:

fun AppCompatImageView.loadImage(imageUri: String) {
    val circularProgressDrawable = CircularProgressDrawable(context)
    circularProgressDrawable.strokeWidth = 5f
    circularProgressDrawable.centerRadius = 30f
    circularProgressDrawable.start()

    Glide.with(context)
            .load(imageUri)
            .placeholder(circularProgressDrawable)
            .error(R.drawable.ic_close_black)
            .override(200, 300)
            .into(this)
}

Update after your comment... code in Java:

 void loadImage(AppCompatImageView yourImageView, String imageUri) {
        CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(yourImageView.getContext())
        circularProgressDrawable.setStrokeWidth(5f);
        circularProgressDrawable.setCenterRadius(30f);
        circularProgressDrawable.start();

        Glide.with(yourImageView)
            .load(imageUri)
            .placeholder(circularProgressDrawable)
            .error(R.drawable.ic_close_black)
            .override(200, 300)
            .into(yourImageView);
    }


问:
Insert different HTML based on switch statement
I have this element in a form:

```<code><a id="dyLink" href="">
</code>```

Depending on calculation of the form the href tag changes depending on different cases:

switch (week) {
  case 1:
    link = "https://schwangerschaftswochen.ch/die-erste-schwangerschaftswoche/";
    break;
  case 2:
    link = "https://schwangerschaftswochen.ch/die-zweite-schwangerschaftswoche/";
    break;
  case 3:
    link = "https://schwangerschaftswochen.ch/die-dritte-schwangerschaftswoche/";
    break;
  case 4:
    link = "https://schwangerschaftswochen.ch/die-vierte-schwangerschaftswoche/";
    break;
  case 5:
    link = "https://schwangerschaftswochen.ch/geburtsterminrechner/#lepopup-Newsletteranmeldung";
}

jQuery("#dyLink").attr("href", link)
```

However I don't want to have different links, but different HTML elements for every case. I have no idea about coding. How can I do it?

答:
Since you are using jQuery you may replace your element with another using .replaceWith to completely replace an element with another one.

Using your code as base you may do something like this:

```<code>switch (week) {
  case 1:
    link = '<a href="anything" id="some-id">A link</a>';
    break;
  case 2:
    link = '<div class"clannName">The Content</div>';
    break;
  case 3:
    link = '<input type="text" name="inputName">';
    break;
  case 4:
    link = '```Preformatted test```';
    break;
  case 5:
    link = '<button type="button">Click!</button>';
}

jQuery("#dyLink").replaceWith(link);
</code>```

Body:
I have this element in a form:

Depending on calculation of the form the href tag changes depending on different cases:

switch (week) {
  case 1:
    link = "https://schwangerschaftswochen.ch/die-erste-schwangerschaftswoche/";
    break;
  case 2:
    link = "https://schwangerschaftswochen.ch/die-zweite-schwangerschaftswoche/";
    break;
  case 3:
    link = "https://schwangerschaftswochen.ch/die-dritte-schwangerschaftswoche/";
    break;
  case 4:
    link = "https://schwangerschaftswochen.ch/die-vierte-schwangerschaftswoche/";
    break;
  case 5:
    link = "https://schwangerschaftswochen.ch/geburtsterminrechner/#lepopup-Newsletteranmeldung";
}

jQuery("#dyLink").attr("href", link)

However I don't want to have different links, but different HTML elements for every case. I have no idea about coding. How can I do it?

Body:
Since you are using jQuery you may replace your element with another using .replaceWith to completely replace an element with another one.

Using your code as base you may do something like this:

switch (week) {
  case 1:
    link = '<a href="anything" id="some-id">A link</a>';
    break;
  case 2:
    link = '<div class"clannName">The Content</div>';
    break;
  case 3:
    link = '<input type="text" name="inputName">';
    break;
  case 4:
    link = '<pre>Preformatted test</pre>';
    break;
  case 5:
    link = '<button type="button">Click!</button>';
}

jQuery("#dyLink").replaceWith(link);