问:
Powershell script - wait for RoboCopy to finish
So I've got the following block of code to robocopy some user data over the network:

```<code>$localFiles = "C:\Users\"
$netFiles = "\\netLocation\migration\Users\"

Start-Process "RoboCopy.exe" -NoNewWindow -argumentlist " `"$localFiles\`" `"$netFiles\`" /s /r:1 /w:5 /mt:16"
</code>```

I have another, similar block of code directly underneath it that copies the same files to an external USB drive. What happens is, the first RoboCopy runs and immediately after the second one runs in unison. What I'd like to do is have the first function wait for RoboCopy to complete before it runs the second function. I have tried the -Wait argument, and that does not appear to work.

Thank you for your time!

答:
Per @mklement0:

I have no explanation for why -Wait doesn't work, but if you want to wait i.e. execute synchronously, just invoke robocopy directly: Robocopy.exe $localFiles $netFiles /s /r:1 /w:5 /mt:16 – mklement0

Resolved

Body:
So I've got the following block of code to robocopy some user data over the network:

$localFiles = "C:\Users\"
$netFiles = "\\netLocation\migration\Users\"

Start-Process "RoboCopy.exe" -NoNewWindow -argumentlist " `"$localFiles\`" `"$netFiles\`" /s /r:1 /w:5 /mt:16"

I have another, similar block of code directly underneath it that copies the same files to an external USB drive. What happens is, the first RoboCopy runs and immediately after the second one runs in unison. What I'd like to do is have the first function wait for RoboCopy to complete before it runs the second function. I have tried the -Wait argument, and that does not appear to work.

Thank you for your time!


来源: stackexchange

问:
how can i safely convert an ascii integer back to its associated ascii character using curses in c++?
I have not been able to find a reliable solution for my problem, what i'm simply trying to do is create some function which:

takes an rows and columns position in the terminal.

calls mvinch(window_object , rows, cols), which returns an unsigned int which corresponds to the character in the terminal at that position.

returns the ascii character associated with that unsigned int, effectively casting it back to a char.

Here is an example of my code in c++11:

```<code>char Kmenu::getChrfromW(size_t const y, size_t const x,
                        bool const save_cursor) const {
  size_t curr_y, curr_x;
  getyx(_win, curr_y, curr_x);
  char ich = mvwinch(_win, y, x);
  char ch = ich;
  if (save_cursor)
    wmove(_win, curr_y, curr_x);
  return ch;
}
</code>```

If for example the character in the terminal  at position 2,3 is the letter 'a', i want this function to return the letter 'a'.

I tried the solution described here:

Convert ASCII number to ASCII Character in C

which effectively casts an integer as char.

unfortunately what i get back is still the integer: testing with a screen filled with 'w's, i get back the integer 119.

the man page for the curses function mvwinch() describes the function to return chtype, which the compiler recognises as unsigned int.

Is there a built in a curses function which gives the char back directly without casting to unsigned int, or some other way i can achieve this?

Edit: ch to ich, as in the actual code

答:
A chtype contains a character along with other data.  The curses.h header has several symbols which are useful for extracting those bits.  If you mask it with A_CHARTEXT and cast that to a char, you will get a character:

```<code>char c = (char)((A_CHARTEXT) & n);
</code>```

Your example should not compile, since it declares ch twice.  You may have meant this:

```<code>char Kmenu::getChrfromW(size_t const y, size_t const x,
                        bool const save_cursor) const {
  int curr_y, curr_x;  // size_t is inappropriate...
  getyx(_win, curr_y, curr_x);
  char ch = (char)((A_CHARTEXT) & mvwinch(_win, y, x));
  // char ch = ich;
  if (save_cursor)
    wmove(_win, curr_y, curr_x);
  return ch;
}
</code>```

The manual page for mvwinch mentions the A_CHARTEXT mask in the Attributes section, assuming the reader is familiar with things like that:

```<code>   The following bit-masks may  be  AND-ed  with  characters  returned  by
   winch.

   A_CHARTEXT     Bit-mask to extract character
   A_ATTRIBUTES   Bit-mask to extract attributes
   A_COLOR        Bit-mask to extract color-pair field information
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have not been able to find a reliable solution for my problem, what i'm simply trying to do is create some function which:

takes an rows and columns position in the terminal.

calls mvinch(window_object , rows, cols), which returns an unsigned int which corresponds to the character in the terminal at that position.

returns the ascii character associated with that unsigned int, effectively casting it back to a char.

Here is an example of my code in c++11:

char Kmenu::getChrfromW(size_t const y, size_t const x,
                        bool const save_cursor) const {
  size_t curr_y, curr_x;
  getyx(_win, curr_y, curr_x);
  char ich = mvwinch(_win, y, x);
  char ch = ich;
  if (save_cursor)
    wmove(_win, curr_y, curr_x);
  return ch;
}

If for example the character in the terminal  at position 2,3 is the letter 'a', i want this function to return the letter 'a'.

I tried the solution described here:

Convert ASCII number to ASCII Character in C

which effectively casts an integer as char.

unfortunately what i get back is still the integer: testing with a screen filled with 'w's, i get back the integer 119.

the man page for the curses function mvwinch() describes the function to return chtype, which the compiler recognises as unsigned int.

Is there a built in a curses function which gives the char back directly without casting to unsigned int, or some other way i can achieve this?

Edit: ch to ich, as in the actual code

Body:
A chtype contains a character along with other data.  The curses.h header has several symbols which are useful for extracting those bits.  If you mask it with A_CHARTEXT and cast that to a char, you will get a character:

char c = (char)((A_CHARTEXT) & n);

Your example should not compile, since it declares ch twice.  You may have meant this:

char Kmenu::getChrfromW(size_t const y, size_t const x,
                        bool const save_cursor) const {
  int curr_y, curr_x;  // size_t is inappropriate...
  getyx(_win, curr_y, curr_x);
  char ch = (char)((A_CHARTEXT) & mvwinch(_win, y, x));
  // char ch = ich;
  if (save_cursor)
    wmove(_win, curr_y, curr_x);
  return ch;
}

The manual page for mvwinch mentions the A_CHARTEXT mask in the Attributes section, assuming the reader is familiar with things like that:

   The following bit-masks may  be  AND-ed  with  characters  returned  by
   winch.

   A_CHARTEXT     Bit-mask to extract character
   A_ATTRIBUTES   Bit-mask to extract attributes
   A_COLOR        Bit-mask to extract color-pair field information


问:
How can I keep a while loop going if the string contains a letter
```<code>while (firstName.//includes a,b,c,d,e,f,g.etc)
{
  //other code here
}
</code>```

I want the while loop to keep going if it includes a letter, please help.

Body:
while (firstName.//includes a,b,c,d,e,f,g.etc)
{
  //other code here
}

I want the while loop to keep going if it includes a letter, please help.

Body: Try firstName.matches(matches(".*[A-Za-z].*"));


问:
How to make this chart easier to read?
I want to know how to get my x axis labels to display bigger so that the team labels aren't overlapping. I'm sure it's just a matter of configuring the chart size

My code:

```<code>plt.plot(prem_data.Team, prem_data.attack_scored,'o')
plt.plot(prem_data.Team, prem_data.defence_saves)

plt.xlabel("Team")
plt.ylabel("Attack goals scored & Defence tackles")
plt.legend(["attack scored", "defence saved"])

plt.show()
</code>```

答:
I can imagine there being two mutually non-exclusive solutions.

Directly alter the size of the font. This can be achieved via calling plt.rcParams.update({'font.size': <font_size>}), assuming that you have imported matplotlib.pyplot under the alias plt, as you have done in the source code provided. You would probably want to set the <font_size> to be small to prevent overlapping labels, but this would require some experimentation.

Increase the size of the figure. This can be done in a number of ways, but perhaps the simplest method you can implement with minimal edits to your current code would be to use the command plt.rcParams["figure.figsize"] = <fig_size> where <fig_size> is a tuple specifying the size of the figure in inches, such as (10, 5).

With some trial and error, you should be able to manipulate the size of the font and the figure to produce a plot with improved readability.

Note: The method for altering figure size I introduced above is not the most conventional way to go about this problem. Instead, it is much more common to use matplotlib.pyplot.figure or similar variants. For more information, I recommend that you check out this thread and the documentation.

Title: How to make this chart easier to read?

Body:
I want to know how to get my x axis labels to display bigger so that the team labels aren't overlapping. I'm sure it's just a matter of configuring the chart size

My code:

plt.plot(prem_data.Team, prem_data.attack_scored,'o')
plt.plot(prem_data.Team, prem_data.defence_saves)

plt.xlabel("Team")
plt.ylabel("Attack goals scored & Defence tackles")
plt.legend(["attack scored", "defence saved"])

plt.show()


问:
Flask-User /user/sign-in view, where is it?
This is prolly a stupid question but I am experimenting with Flask-User.  I see the venv/.../flask_user/user_manager__settings.py file and see

```<code>USER_LOGIN_URL = '/user/sign-in' #:
</code>```

I do not see a method for this though.  Something is rendering a view for the sign-in page but I am not seeing the connection.  What part am I missing?

Edit

What am I asking?  I have copied the flask-user templates from site-packages into my test.  I have slightly tweaked them.  However, when I click the default Signin link I get an untweaked login template.  I am wondering if something has a hardwired template path?  I am just not finding that url->view->template linkage.

答:
There are config options to change the templates, for example:

```<code>USER_LOGIN_TEMPLATE = 'your/path'`

</code>```

Found here: https://flask-user.readthedocs.io/en/latest/configuring_settings.html

Body:
This is prolly a stupid question but I am experimenting with Flask-User.  I see the venv/.../flask_user/user_manager__settings.py file and see

USER_LOGIN_URL = '/user/sign-in' #:

I do not see a method for this though.  Something is rendering a view for the sign-in page but I am not seeing the connection.  What part am I missing?

Edit

What am I asking?  I have copied the flask-user templates from site-packages into my test.  I have slightly tweaked them.  However, when I click the default Signin link I get an untweaked login template.  I am wondering if something has a hardwired template path?  I am just not finding that url->view->template linkage.

Body:
There are config options to change the templates, for example:

USER_LOGIN_TEMPLATE = 'your/path'`

Found here: https://flask-user.readthedocs.io/en/latest/configuring_settings.html


问:
Using Custom Style sheet for browser - How to hide specific shows on netflix?
I recently learnt that we can use custom style sheets to manipulate elements of websites on the internet.

I have a problem where in I end up killing a lot of time binge watching shows on netflix and then I later regret doing that. So I'd like to hide the shows I get addicted to - in this instance "Arrow".

I'm sure there will be another one in near future I get hooked on, and I'll use the same technique to hide it until I get over it.

The CSS from Netflix for Arrow is:

```<code><a aria-label="Arrow" class="bob-jaw-hitzone" href="/title/70242081"></a>
</code>```

This is nested inside several divs and the outer most div could be different as the shows can be displayed multiple times under different sliders.

The immediate parent of this CSS selector I mentioned above is:

```<code><div class="bob-overlay bob-overlay-hidden">
<div class="bob-play-hitzone"></div>
<a aria-label="Arrow" class="bob-jaw-hitzone" href="/title/70242081"></a>
<div class="bob-overview-wrapper">
    <div class="bob-overview">
        <a tabindex="0" data-uia="play-button" role="link" aria-label="Resume" class="bob-play-button playLink" href="/watch/80140962?trackId=14170286&tctx=1%2C0%2Cb9a98838-f436-4b89-ac66-7190b45402e6-32766795%2Ccf1e7866-0b59-41c4-96bd-b10d5ca4cf61_77601417X3XX1581889779290%2Ccf1e7866-0b59-41c4-96bd-b10d5ca4cf61_ROOT">
            <span class="play-button">
                <svg class="svg-icon svg-icon-play-with-ring" focusable="true">
                    <use filter="" xlink:href="#play-with-ring">
                    </use>
                </svg>
            </span>
        </a>
        <div class="bob-title">
            Arrow
        </div>
        <div class="bob-overview-resume-title-wrapper">
        <div class="watched-title watched-title--bob-overview watched-title--no-wrap">
            <span><b>S5:E7</b> "Vigilante"</span>
        </div>
    </div>
    <div class="bob-content-warning-wrapper"></div>
</div>
</code>```

I tried adding the following in that Custom Style sheet but it didn't make any difference.

```<code>a[aria-label="Arrow"] { display: none; }
</code>```

any advice on how to write css selector that will match and hide this show ?

答:
It sounds like you might be looking to hide the whole bob-overlay container that contains the element with aria-label="Arrow". CSS can't select a parent from a child, but you can do that pretty easily with Javascript. Install a userscript manager like Tampermonkey, then search for elements matching a[aria-label="Arrow"], find their ancestor .bob-overlays, and remove them (or set their display to none):

for (const a of document.querySelectorAll('a[aria-label="Arrow"]')) {
  a.closest('.bob-overlay').remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bob-overlay bob-overlay-hidden">
  arrow - hide me
  <div class="bob-play-hitzone"></div>

  <div class="bob-overview-wrapper">
    <div class="bob-overview">

        <span class="play-button">
                <svg class="svg-icon svg-icon-play-with-ring" focusable="true">
                    <use filter="" xlink:href="#play-with-ring">
                    </use>
                </svg>
            </span>

      <div class="bob-title">
        Arrow
      </div>
      <div class="bob-overview-resume-title-wrapper">
        <div class="watched-title watched-title--bob-overview watched-title--no-wrap">
          <span><b>S5:E7</b> "Vigilante"</span>
        </div>
      </div>
      <div class="bob-content-warning-wrapper"></div>
    </div>
  </div>
</div>

<div class="bob-overlay bob-overlay-hidden">
  not arrow, don't hide me
  <div class="bob-play-hitzone"></div>

  <div class="bob-overview-wrapper">
    <div class="bob-overview">

        <span class="play-button">
                <svg class="svg-icon svg-icon-play-with-ring" focusable="true">
                    <use filter="" xlink:href="#play-with-ring">
                    </use>
                </svg>
            </span>

      <div class="bob-title">
        something else
      </div>
      <div class="bob-overview-resume-title-wrapper">
        <div class="watched-title watched-title--bob-overview watched-title--no-wrap">
          <span><b>S5:E7</b> "Vigilante"</span>
        </div>
      </div>
      <div class="bob-content-warning-wrapper"></div>
    </div>
  </div>
</div></code>```

If the elements are loaded dynamically and not present on initial pageload, you might have to run the JS after a setTimeout or (or setInterval polling, or MutationObserver).

The whole userscript will probably look something like

```<code>// ==UserScript==
// @name             Hide Arrow
// @include          https://www.netflix.com/*
// @grant            none
// ==/UserScript==

for (const a of document.querySelectorAll('a[aria-label="Arrow"]')) {
  a.closest('.bob-overlay').remove();
}
</code>```

Body:
I recently learnt that we can use custom style sheets to manipulate elements of websites on the internet.

I have a problem where in I end up killing a lot of time binge watching shows on netflix and then I later regret doing that. So I'd like to hide the shows I get addicted to - in this instance "Arrow".

I'm sure there will be another one in near future I get hooked on, and I'll use the same technique to hide it until I get over it.

The CSS from Netflix for Arrow is:

This is nested inside several divs and the outer most div could be different as the shows can be displayed multiple times under different sliders.

The immediate parent of this CSS selector I mentioned above is:

                <svg class="svg-icon svg-icon-play-with-ring" focusable="true">
                    <use filter="" xlink:href="#play-with-ring">
                    </use>
                </svg>

            Arrow

            S5:E7 "Vigilante"

I tried adding the following in that Custom Style sheet but it didn't make any difference.

a[aria-label="Arrow"] { display: none; }

any advice on how to write css selector that will match and hide this show ?

Body:
It sounds like you might be looking to hide the whole bob-overlay container that contains the element with aria-label="Arrow". CSS can't select a parent from a child, but you can do that pretty easily with Javascript. Install a userscript manager like Tampermonkey, then search for elements matching a[aria-label="Arrow"], find their ancestor .bob-overlays, and remove them (or set their display to none):

for (const a of document.querySelectorAll('a[aria-label="Arrow"]')) {
  a.closest('.bob-overlay').remove();
}

<div class="bob-overlay bob-overlay-hidden">
  arrow - hide me
  <div class="bob-play-hitzone"></div>
  <a aria-label="Arrow" class="bob-jaw-hitzone" href="/title/70242081"></a>
  <div class="bob-overview-wrapper">
    <div class="bob-overview">
      <a tabindex="0" data-uia="play-button" role="link" aria-label="Resume" class="bob-play-button playLink" href="/watch/80140962?trackId=14170286&amp;tctx=1%2C0%2Cb9a98838-f436-4b89-ac66-7190b45402e6-32766795%2Ccf1e7866-0b59-41c4-96bd-b10d5ca4cf61_77601417X3XX1581889779290%2Ccf1e7866-0b59-41c4-96bd-b10d5ca4cf61_ROOT">
        <span class="play-button">
                <svg class="svg-icon svg-icon-play-with-ring" focusable="true">
                    <use filter="" xlink:href="#play-with-ring">
                    </use>
                </svg>
            </span>
      </a>
      <div class="bob-title">
        Arrow
      </div>
      <div class="bob-overview-resume-title-wrapper">
        <div class="watched-title watched-title--bob-overview watched-title--no-wrap">
          <span><b>S5:E7</b> "Vigilante"</span>
        </div>
      </div>
      <div class="bob-content-warning-wrapper"></div>
    </div>
  </div>
</div>

<div class="bob-overlay bob-overlay-hidden">
  not arrow, don't hide me
  <div class="bob-play-hitzone"></div>
  <a aria-label="Foobar" class="bob-jaw-hitzone" href="/title/70242081"></a>
  <div class="bob-overview-wrapper">
    <div class="bob-overview">
      <a tabindex="0" data-uia="play-button" role="link" aria-label="Resume" class="bob-play-button playLink" href="/watch/80140962?trackId=14170286&amp;tctx=1%2C0%2Cb9a98838-f436-4b89-ac66-7190b45402e6-32766795%2Ccf1e7866-0b59-41c4-96bd-b10d5ca4cf61_77601417X3XX1581889779290%2Ccf1e7866-0b59-41c4-96bd-b10d5ca4cf61_ROOT">
        <span class="play-button">
                <svg class="svg-icon svg-icon-play-with-ring" focusable="true">
                    <use filter="" xlink:href="#play-with-ring">
                    </use>
                </svg>
            </span>
      </a>
      <div class="bob-title">
        something else
      </div>
      <div class="bob-overview-resume-title-wrapper">
        <div class="watched-title watched-title--bob-overview watched-title--no-wrap">
          <span><b>S5:E7</b> "Vigilante"</span>
        </div>
      </div>
      <div class="bob-content-warning-wrapper"></div>
    </div>
  </div>
</div>

If the elements are loaded dynamically and not present on initial pageload, you might have to run the JS after a setTimeout or (or setInterval polling, or MutationObserver).

The whole userscript will probably look something like

// ==UserScript==
// @name             Hide Arrow
// @include          https://www.netflix.com/*
// @grant            none
// ==/UserScript==

for (const a of document.querySelectorAll('a[aria-label="Arrow"]')) {
  a.closest('.bob-overlay').remove();
}


问:
Basic testing system implementation
I've written a BaseTestCase class (which is meant to be inherited by all test cases) and a number of TestCase<Number>(BaseTestCase) classes (each in its own .py file).

The project structure is:

BaseTestCase.py

TestCase1.py

TestCase2.py

Example:

```<code>class TestCase2(BaseTestCase):
    # methods

    def execute(self):
        self.method1()
        self.method2()
        self.method3()

</code>```

The execute method should be called on an instance of TestCase<Number> to run a specific test. What is the proper way to run all test cases, i.e. to orchestrate them all?

答:
I'm assuming you are using Unittest framework and want to run tests programmatically and have the ability to select which tests you run. If that's the correct assumption, here is the answer.

Lets assume you have those tests:

class TestExample1(unittest.TestCase):

    def test_something(self):
        pass

    def test_something_else(self):
        pass
```

<pre class="lang-py prettyprint-override"><code>class TestExample2(unittest.TestCase):

    def test_something(self):
        pass

    def test_something_else(self):
        pass
</code>```

If those are in the same file, you can simply run them like this

# assuming your tests are above in this same file
unittest.main()
```

<p>However, if they are in different files, you will have to extract the tests from them like so</p>

<pre class="lang-py prettyprint-override"><code>for example in [TestExample1, TestExample2]:
    tests = unittest.TestLoader().loadTestsFromTestCase(example)
    unittest.TextTestRunner().run(tests)
</code>```

This will result in two different executions like this

```<code>..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
</code>```

If you are considering other frameworks for running your tests, I recommend to take a look at Test Junkie: https://www.test-junkie.com/get-started/ as its much easier to get started with and is very powerful. (disclaimer: I'm the author!).

Title: Basic testing system implementation

Body:
I've written a BaseTestCase class (which is meant to be inherited by all test cases) and a number of TestCase<Number>(BaseTestCase) classes (each in its own .py file).

The project structure is:

BaseTestCase.py

TestCase1.py

TestCase2.py

Example:

class TestCase2(BaseTestCase):
    # methods

    def execute(self):
        self.method1()
        self.method2()
        self.method3()

The execute method should be called on an instance of TestCase<Number> to run a specific test. What is the proper way to run all test cases, i.e. to orchestrate them all?

Body:
I'm assuming you are using Unittest framework and want to run tests programmatically and have the ability to select which tests you run. If that's the correct assumption, here is the answer.

Lets assume you have those tests:

class TestExample1(unittest.TestCase):

    def test_something(self):
        pass

    def test_something_else(self):
        pass

class TestExample2(unittest.TestCase):

    def test_something(self):
        pass

    def test_something_else(self):
        pass

If those are in the same file, you can simply run them like this

# assuming your tests are above in this same file
unittest.main()

However, if they are in different files, you will have to extract the tests from them like so

for example in [TestExample1, TestExample2]:
    tests = unittest.TestLoader().loadTestsFromTestCase(example)
    unittest.TextTestRunner().run(tests)

This will result in two different executions like this

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

If you are considering other frameworks for running your tests, I recommend to take a look at Test Junkie: https://www.test-junkie.com/get-started/ as its much easier to get started with and is very powerful. (disclaimer: I'm the author!).


问:
Combining form input column data with just created id autoincrement data on the fly
I have a table with cases in which on HTML form POST I create an INT case_id autoincrement number. In this table I would like to have a filed nas_br witch will be a varchar column in whom I would like to combine the ID field from form input + case_id just created on insert.

Example: When I create a new case I pass the ID filed of let's say number 3, case_id is created on an insert with number 4. I need to pass that info automatically to field nas_br so it would be 34. (I will add a dot in between but that's easy I guess).

My question is is this even possible to do on the fly because case_id is made on the insert, or I need separate process. How can I do this automatically on form input?

EDIT:
Generated Columns are not supported in MARIADB on primary key/autoincrement.

```<code>$sql = "INSERT INTO PREDMETIF (ID, NAZIV, PROTUSTRANKA, SUD, SUDBROJ, PREDMET, VPS, grad, post_br, adresa, jb, upr_tj, sudac, datum, status) VALUES ('$STRANKAFID','$STRANKAFNAZ','$PROTUSTRANKA', '$SUD', '$SUDBROJ', '$PREDMET', '$VPS', '$grad', '$post_br', '$adresa', '$jb', '$upr_tj', '$sudac', '$datum', '$status')";
            $query = mysqli_query($conn, $sql);
</code>```

EDIT
As using Generated Columns is not supported on primary keys and AUTO_INCREMENT, found the other solution here: What is the alternative for generated column in MySQL 5.6.
This creates a new table in Views and copy the table PREDMETIF with added column nas_br and does the adding. It's not in the original table but it gets to job done.

```<code>CREATE VIEW PREDMETIFView AS (
    SELECT ID, case_id, COALESCE(CONCAT(ID, '.', case_id)) AS nas_br
    FROM PREDMETIF
)
</code>```

答:
As using Generated Columns is not supported on primary keys and AUTO_INCREMENT, found the other solution here: What is the alternative for generated column in MySQL 5.6.
This creates a new table in Views and copy the table PREDMETIF with added column nas_br and does the adding. It's not in the original table but it gets to job done. </p>

```<code>CREATE VIEW PREDMETIFView AS (
    SELECT ID, case_id, COALESCE(CONCAT(ID, '.', case_id)) AS nas_br
    FROM PREDMETIF
)
</code>```

Body:
I have a table with cases in which on HTML form POST I create an INT case_id autoincrement number. In this table I would like to have a filed nas_br witch will be a varchar column in whom I would like to combine the ID field from form input + case_id just created on insert.

Example: When I create a new case I pass the ID filed of let's say number 3, case_id is created on an insert with number 4. I need to pass that info automatically to field nas_br so it would be 34. (I will add a dot in between but that's easy I guess).

My question is is this even possible to do on the fly because case_id is made on the insert, or I need separate process. How can I do this automatically on form input?

EDIT:
Generated Columns are not supported in MARIADB on primary key/autoincrement.

$sql = "INSERT INTO PREDMETIF (ID, NAZIV, PROTUSTRANKA, SUD, SUDBROJ, PREDMET, VPS, grad, post_br, adresa, jb, upr_tj, sudac, datum, status) VALUES ('$STRANKAFID','$STRANKAFNAZ','$PROTUSTRANKA', '$SUD', '$SUDBROJ', '$PREDMET', '$VPS', '$grad', '$post_br', '$adresa', '$jb', '$upr_tj', '$sudac', '$datum', '$status')";
            $query = mysqli_query($conn, $sql);

EDIT
As using Generated Columns is not supported on primary keys and AUTO_INCREMENT, found the other solution here: What is the alternative for generated column in MySQL 5.6.
This creates a new table in Views and copy the table PREDMETIF with added column nas_br and does the adding. It's not in the original table but it gets to job done.

CREATE VIEW PREDMETIFView AS (
    SELECT ID, case_id, COALESCE(CONCAT(ID, '.', case_id)) AS nas_br
    FROM PREDMETIF
)


问:
Can I create a new object with the results of a query?
If there's a better way to do this, let me know, but this is kind of how i envisioned it. Can it be done?

Customer is a table in the database/datacontext. What I want is to query that table and build a new object with it.

If i were to insert a record, I would do something like this:

```<code>Customer cust = new Customer(){ FirstName = "A", LastName = "B", Age = 31 }
db.Customers.InsertOnSubmit(cust);
db.SubmitChanges();
</code>```

What I want to do is instantiate that object with a query result. Something like this:

```<code>var query =
     from a in db.Customers
     where a.FirstName == "A"
     select a;

Customer cust = new Customer(){ query };
</code>```

or maybe even

```<code>Customer cust = new Customer(){
     from a in db.Customers
     where a.FistName == "A"
     select a;
}
</code>```

is there some way to do this?

答:
yes, like this:

```<code>var query =  from c in db.Customers
     where c.FirstName == "somecriteria"
     select new Customer()
     {
        FirstName = "somevalue",
     };
</code>```

you can also make totally anonymous objects as well...

```<code>var query =  from c in db.Customers
     where c.FirstName == "somecriteria"
     select new()
     {
        FirstName = c.SomeProperty,
        AnotherProperty=c.AnotherProperty,
     };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If there's a better way to do this, let me know, but this is kind of how i envisioned it. Can it be done?

Customer is a table in the database/datacontext. What I want is to query that table and build a new object with it.

If i were to insert a record, I would do something like this:

Customer cust = new Customer(){ FirstName = "A", LastName = "B", Age = 31 }
db.Customers.InsertOnSubmit(cust);
db.SubmitChanges();

What I want to do is instantiate that object with a query result. Something like this:

var query =
     from a in db.Customers
     where a.FirstName == "A"
     select a;

Customer cust = new Customer(){ query };

or maybe even

Customer cust = new Customer(){
     from a in db.Customers
     where a.FistName == "A"
     select a;
}

is there some way to do this?

Body:
yes, like this:

var query =  from c in db.Customers
     where c.FirstName == "somecriteria"
     select new Customer()
     {
        FirstName = "somevalue",
     };

you can also make totally anonymous objects as well...

var query =  from c in db.Customers
     where c.FirstName == "somecriteria"
     select new()
     {
        FirstName = c.SomeProperty,
        AnotherProperty=c.AnotherProperty,
     };


问:
recursion compilation error in Standard ML
I am making a function that recurses over a string and replaces each instance of a user-specified character. However, I get a compilation error of :

```<code>Error: operator and operand do not agree [tycon mismatch]
  operator domain: string * string
  operand:         char * 'Z
</code>```

I would like to know what this error means for my program and what I could be doing wrong. I'm new to SML and have been trying to research this for some time now. Thanks.

This is my code:

```<code>fun remCharR(expr, letter) =
    if String.sub(expr, 0) = letter
    then remCharR(String.substring(expr, 0, 1), letter)
    else String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter);
</code>```

答:
I am making a function that recurses over a string and replaces each instance of a user-specified character.

A function that corresponds to this description is String.map. Example:

```<code>- String.map (fn c => if c = #"l" then #"k" else c) "hello";
> val it = "hekko" : string
</code>```

Since this function can't remove characters, this suggests that "replace" is an ambiguous word.

I would like to know what this error means for my program and what I could be doing wrong.

```<code>Error: operator and operand do not agree [tycon mismatch]
operator domain: string * string
operand:         char * 'Z
</code>```

Venkatesh-Prasad Ranganath already answered this and showed how to fix it.

So instead I will show an alternative way to implement this.

This is my code:

```<code>fun remCharR(expr, letter) =
   if String.sub(expr, 0) = letter
   then remCharR(String.substring(expr, 0, 1), letter)
   else String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter);
</code>```

Since the sole task of this function appears to remove characters, use String.translate:

```<code>fun remChar (c1, s) =
    String.translate (fn c2 => if c1 = c2 then "" else str c2) s
</code>```

Body:
I am making a function that recurses over a string and replaces each instance of a user-specified character. However, I get a compilation error of :

Error: operator and operand do not agree [tycon mismatch]
  operator domain: string * string
  operand:         char * 'Z

I would like to know what this error means for my program and what I could be doing wrong. I'm new to SML and have been trying to research this for some time now. Thanks.

This is my code:

fun remCharR(expr, letter) =
    if String.sub(expr, 0) = letter
    then remCharR(String.substring(expr, 0, 1), letter)
    else String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter);

Body:
I am making a function that recurses over a string and replaces each instance of a user-specified character.

A function that corresponds to this description is String.map. Example:

- String.map (fn c => if c = #"l" then #"k" else c) "hello";
> val it = "hekko" : string

Since this function can't remove characters, this suggests that "replace" is an ambiguous word.

I would like to know what this error means for my program and what I could be doing wrong.

Error: operator and operand do not agree [tycon mismatch]
operator domain: string * string
operand:         char * 'Z

Venkatesh-Prasad Ranganath already answered this and showed how to fix it.

So instead I will show an alternative way to implement this.

This is my code:

fun remCharR(expr, letter) =
   if String.sub(expr, 0) = letter
   then remCharR(String.substring(expr, 0, 1), letter)
   else String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter);

Since the sole task of this function appears to remove characters, use String.translate:

fun remChar (c1, s) =
    String.translate (fn c2 => if c1 = c2 then "" else str c2) s


问:
Java RMI, an interface is published as remote on the webserver, while it shouldn't
I'm having a nasty problem, but first let me explain the context.

The project is just a simple project so I get familiar with RMI. The project is a stockmarket server and a client that pulls data about the funds from the server.

I've divided the project in 3 java projects. The server (having MockStockMarket and Fund), the client (having GUI classes and a class to talk to the server: BannerController) and a project with the interfaces which both the client and server need (IStockMarket and IFund).

I want my bannerController to talk with the StockMarket so that the bannercontroller gets the funds. This is done using getFunds() : ArrayList.

As you can see, StockMarket should be Remote, and the Fund should be Serializable.

The problem is, for some reason when I use the following code:

```<code>IStockMarket market = new MockStockMarket();
Naming.rebind("rmi://localhost/StockMarket", market);
</code>```

Both IStockMarket (as intended) AND IFund (not as intended) become remote. Which is not what I want.

For the record: Fund implements IFund, which extends Serializable (so nothing remote) and MockStockMarket extends UnicastRemoteObject and implements IStockMarket, which extends Remote.

Here is a screenshot for the Webserver publishing both interfaces: http://imageshack.us/m/194/4755/rmibothinterfacespublis.png.

For the soure code: https://rapidshare.com/files/2085773800/stockmarket.zip

答:
Both IStockMarket (as intended) AND
  IFund (not as intended) become remote.

No they don't. Objects only 'become remote' by being exported, and interfaces don't 'become remote' at all. IFund is needed by the client, presumably because it appears in the IStockMarket interface. You appear to be using the codebase feature. From the point of view of codebase the Registry is a client too. So the Registry downloaded IFund.class and IStockMarket.class. That doesn't make IFund 'become remote' in any way shape or form.

Body:
I'm having a nasty problem, but first let me explain the context.

The project is just a simple project so I get familiar with RMI. The project is a stockmarket server and a client that pulls data about the funds from the server.

I've divided the project in 3 java projects. The server (having MockStockMarket and Fund), the client (having GUI classes and a class to talk to the server: BannerController) and a project with the interfaces which both the client and server need (IStockMarket and IFund).

I want my bannerController to talk with the StockMarket so that the bannercontroller gets the funds. This is done using getFunds() : ArrayList.

As you can see, StockMarket should be Remote, and the Fund should be Serializable.

The problem is, for some reason when I use the following code:

IStockMarket market = new MockStockMarket();
Naming.rebind("rmi://localhost/StockMarket", market);

Both IStockMarket (as intended) AND IFund (not as intended) become remote. Which is not what I want.

For the record: Fund implements IFund, which extends Serializable (so nothing remote) and MockStockMarket extends UnicastRemoteObject and implements IStockMarket, which extends Remote.

Here is a screenshot for the Webserver publishing both interfaces: http://imageshack.us/m/194/4755/rmibothinterfacespublis.png.

For the soure code: https://rapidshare.com/files/2085773800/stockmarket.zip


问:
JS Encryption w/ HTML
This should add the encoded text to the HTML but doesn't seem to work.

```<code><script>
var i=0,j=0,k=0;
var letters=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
function gibberish(string, list) {
document.innerHTML +="<p>";
for(var j=0;j<string.length;j++){
document.innerHTML += letters[(letters.indexOf(string.charAt(k))*list[(j%8)]+list[((j+1)%8)])%8];
k++;
}
document.innerHTML += "</p>";
}
var array = [];
var ptxt;
for(i=1;i<9;i++) {
array.push(prompt("enter a number (less than 10 preferably!)"));
}
ptxt = prompt("ok now enter a string");
gibberish(ptxt,array);
</script>
</code>```

What am I doing incorrectly, et cetera?

答: document not have innerHTML property. try to use document.body.innerHTML

Title: JS Encryption w/ HTML

Body:
This should add the encoded text to the HTML but doesn't seem to work.

What am I doing incorrectly, et cetera?


问:
Can I keep alpha or beta version when I release productive one?
I have uploaded a new alpha version of my Android app in the developer console, which provides a new database version. Now I also have to update the productive release, because of an error - but do not want to include the other stuff of the alpha version into it yet (espacially the database changes).

But if I update the productive track, it normaly replaces the alpha version and this will make the testing version no more available for the testers. Is there any way to release an productive version and keep the alpha one? Or is the only way to relase a new alpha version after the production version and hope that it will be earlier available for the testers than the productive one?

答:
It is possible but requires to assign the new production versionCode to be both higher than the current production versionCode and lower than the alpha versionCode.

Example:

Prod versionCode: 100

Alpha versionCode: 105

=> Use 101 for the new prod versionCode.

If you used consecutive numbers between the production track and the alpha track, then you'll first need to upload a new version on the alpha track with a versionCode a few numbers higher to leave enough room to then assign a lower versionCode for your next version on the production track.

Example:

Prod versionCode: 100

Alpha versionCode: 101

=> Publish new APK on alpha track with versionCode 103, then publish new APK on prod track with versionCode 102.


答:
The document does not have an innerHTML property. You have to select an element inside it - perhaps the document.body. You also shouldn't concatenate unbalanced tags - concatenate a balanced HTML string all at once, when it's ready:

var i = 0,
  j = 0,
  k = 0;
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function gibberish(string, list) {
  let str = "
";
  for (var j = 0; j < string.length; j++) {
    str += letters[(letters.indexOf(string.charAt(k)) * list[(j % 8)] + list[((j + 1) % 8)]) % 8];
    k++;
  }
  document.body.innerHTML += str + "
";
}
var array = [];
var ptxt;
for (i = 1; i < 9; i++) {
  array.push(prompt("enter a number (less than 10 preferably!)"));
}
ptxt = prompt("ok now enter a string");
gibberish(ptxt, array);```
</div>
</div>
</p>

<p>But concatenating with the <code>innerHTML</code> of an element is usually a bad idea - it'll force the whole container to be re-parsed, and will corrupt any listeners the container may have inside it. To avoid those problems, it might be better to create a <code><p></code> and use <code>appendChild</code> instead.</p>

<p>You can also create the <code>letters</code> array less repetitively by iterating over key codes.</p>

<p>It would also be good to make sure that the inputted numbers are actually numbers - you can use a <code>do</code>-<code>while</code> loop to verify them:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const letters = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i));
function gibberish(string, list) {
  let k = 0;
  const p = document.createElement('p');
  for (let j = 0; j < string.length; j++) {
    p.textContent += letters[(letters.indexOf(string.charAt(k)) * list[(j % 8)] + list[((j + 1) % 8)]) % 8];
    k++;
  }
  document.body.appendChild(p);
}
var array = [];
for (let i = 1; i < 9; i++) {
  let num = null;
  do {
    prompt("enter a number (less than 10 preferably!)");
  } while (num === null);
  array.push(num);
}
gibberish(prompt("ok now enter a string"), array);</code>```

Title: JS Encryption w/ HTML

Body:
The document does not have an innerHTML property. You have to select an element inside it - perhaps the document.body. You also shouldn't concatenate unbalanced tags - concatenate a balanced HTML string all at once, when it's ready:

var i = 0,
  j = 0,
  k = 0;
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function gibberish(string, list) {
  let str = "<p>";
  for (var j = 0; j < string.length; j++) {
    str += letters[(letters.indexOf(string.charAt(k)) * list[(j % 8)] + list[((j + 1) % 8)]) % 8];
    k++;
  }
  document.body.innerHTML += str + "</p>";
}
var array = [];
var ptxt;
for (i = 1; i < 9; i++) {
  array.push(prompt("enter a number (less than 10 preferably!)"));
}
ptxt = prompt("ok now enter a string");
gibberish(ptxt, array);

But concatenating with the innerHTML of an element is usually a bad idea - it'll force the whole container to be re-parsed, and will corrupt any listeners the container may have inside it. To avoid those problems, it might be better to create a <p> and use appendChild instead.

You can also create the letters array less repetitively by iterating over key codes.

It would also be good to make sure that the inputted numbers are actually numbers - you can use a do-while loop to verify them:

const letters = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i));
function gibberish(string, list) {
  let k = 0;
  const p = document.createElement('p');
  for (let j = 0; j < string.length; j++) {
    p.textContent += letters[(letters.indexOf(string.charAt(k)) * list[(j % 8)] + list[((j + 1) % 8)]) % 8];
    k++;
  }
  document.body.appendChild(p);
}
var array = [];
for (let i = 1; i < 9; i++) {
  let num = null;
  do {
    prompt("enter a number (less than 10 preferably!)");
  } while (num === null);
  array.push(num);
}
gibberish(prompt("ok now enter a string"), array);


问:
How can I set bazel option --output_user_root for Angular CLI
My user root contains a space in it so I get the following error when trying to run ng serve with bazel enabled:

WARNING: Output user root "C:/Users/Simon Weaver/_bazel_Simon Weaver"
  contains a space. This will probably break the build. You should set a
  different --output_user_root.

I just cannot find where to put this option - everywhere I've tried - such as angular.json file under options, or directly on the command line - either complains or fails.

答:
Create (or modify) the .bazelrc file in your project root with the following content:

```<code>startup --output_user_root=<path/to/new/root>
</code>```

This is equivalent to running $ bazel --output_user_root=<path/to/new/root> build ...

See this page for more information on .bazelrc files.

Body:
Create (or modify) the .bazelrc file in your project root with the following content:

startup --output_user_root=<path/to/new/root>

This is equivalent to running $ bazel --output_user_root=<path/to/new/root> build ...

See this page for more information on .bazelrc files.


问:
Count if current row and next row meet the criteria
For example, I have a table in with thousands of row:

```<code>      | col
row 1 | NN
row 2 | NNP
row 3 | VB
row 4 | NNP
row 5 | NN
row 6 | NNP
row 7 | JJ
row 8 | NUM
row 9 | CW
.....
row 10000 | NNP
</code>```

Can I count with condition :
IF (row 1 = NN AND row 2= NNP) AND (row 2 = NN AND row 3= NNP) AND ... AND (row 9999 = NN and row 10000 = NNP) THEN count?

Body:
For example, I have a table in with thousands of row:

      | col
row 1 | NN
row 2 | NNP
row 3 | VB
row 4 | NNP
row 5 | NN
row 6 | NNP
row 7 | JJ
row 8 | NUM
row 9 | CW
.....
row 10000 | NNP

Can I count with condition :
IF (row 1 = NN AND row 2= NNP) AND (row 2 = NN AND row 3= NNP) AND ... AND (row 9999 = NN and row 10000 = NNP) THEN count?

Body:
Try -

=SUMPRODUCT((A1:A10000="NN")*(A2:A10001="NNP"))


问:
how Backslash \ joins printf strings when written on separate lines in C?
Using Dev C++ I was doing some fun with C and got this :

```<code>#include<stdio.h>
main()
{
printf("Hello
      world" );
}
</code>```

^^^^ here I thought output would be like "Hello (with spaces) World" but
Errors :

```<code>C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c In function 'main':
5   10  C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
5   3   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   8   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] 'world' undeclared (first use in this function)
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Note] each undeclared identifier is reported only once for each function it appears in
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ')' before '}' token
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ';' before '}' token
</code>```

but when i added a \ it worked :

```<code>#include<stdio.h>
main()
{
printf("Hello \
   World" );
}
</code>```

Without any warnings and errors.
What Magic of '\' is this ?
And do any other soccery exists , please let me know .

答:
The C pre-processor will line splice, so one could have written,

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

int main(void) {
    printf("Hello\n"
        "World\n");
    return 0;
}
</code>```

Arguably nicer syntax with long strings. Note that the maximum length is still enforced. From a theoretical point-of-view, the C pre-processor is a language unto itself, see a discussion on Turing-completeness. For a practical example, x-macros are very useful in some cases.

Body:
Using Dev C++ I was doing some fun with C and got this :

#include<stdio.h>
main()
{
printf("Hello
      world" );
}

^^^^ here I thought output would be like "Hello (with spaces) World" but
Errors :

C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c In function 'main':
5   10  C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
5   3   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   8   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] 'world' undeclared (first use in this function)
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Note] each undeclared identifier is reported only once for each function it appears in
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ')' before '}' token
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ';' before '}' token

but when i added a \ it worked :

#include<stdio.h>
main()
{
printf("Hello \
   World" );
}

Without any warnings and errors.
What Magic of '\' is this ?
And do any other soccery exists , please let me know .

Body:
The C pre-processor will line splice, so one could have written,

#include <stdio.h>

int main(void) {
    printf("Hello\n"
        "World\n");
    return 0;
}

Arguably nicer syntax with long strings. Note that the maximum length is still enforced. From a theoretical point-of-view, the C pre-processor is a language unto itself, see a discussion on Turing-completeness. For a practical example, x-macros are very useful in some cases.


问:
React Hooks: Too many re-renders on switch mode
I'm trying to improve my switch theme code but I have the following error:

Error: Too many re-renders. React limits the number of renders to
  prevent an infinite loop.

My code:

```<code>export default function App() {
  const theme = useTheme();

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={theme.setTheme(
            theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
          )}
        >
          a
        </button>
      </div>
    </ThemeProvider>
  );
}
</code>```

My hook:

```<code>   export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    return savedTheme === 'dark' ? darkTheme : defaultTheme;
  }
  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}
</code>```

I would also like to know how I could get what was sent on my setTheme.

答:
Change

```<code>onClick={theme.setTheme(
        theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
      )}
</code>```

To

```<code>onClick={() => theme.setTheme(theme.type === 'dark' ? { type: 'light' } : { type: 'dark' })}
</code>```

In your code, you are immediately executing setTheme during render and it is causing  another render and recursively endless rendering, which is stopped by react. onClick prop expects a function as the value, that function will be executed during click.

Body:
I'm trying to improve my switch theme code but I have the following error:

Error: Too many re-renders. React limits the number of renders to
  prevent an infinite loop.

My code:

export default function App() {
  const theme = useTheme();

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={theme.setTheme(
            theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
          )}
        >
          a
        </button>

    </ThemeProvider>
  );
}

My hook:

   export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    return savedTheme === 'dark' ? darkTheme : defaultTheme;
  }
  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}

I would also like to know how I could get what was sent on my setTheme.

Body:
Change

onClick={theme.setTheme(
        theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
      )}

To

onClick={() => theme.setTheme(theme.type === 'dark' ? { type: 'light' } : { type: 'dark' })}

In your code, you are immediately executing setTheme during render and it is causing  another render and recursively endless rendering, which is stopped by react. onClick prop expects a function as the value, that function will be executed during click.


问:
Cannot feed image data of DICOM into image data generator
So i have preprocessed some dicom images to feed a neural network, and in image augmentation step, the image data generator expects a 4d input while my data is 3d (200, 420, 420)

i tried reshaping the array and expanding dimensions, but in both cases i cannot plot the individual images in the array (expects image with shape 420, 420 and instead my new images have shape 420, 420, 1)

and here are my codes;

I have three functions to convert DICOM images into images with good contrast;

This one takes housefield units

```<code>def transform_to_hu(medical_image, image):
    intercept = medical_image.RescaleIntercept
    slope = medical_image.RescaleSlope
    hu_image = image * slope + intercept

    return hu_image
</code>```

This one sets window image values;

```<code>def window_image(image, window_center, window_width):
    img_min = window_center - window_width // 2
    img_max = window_center + window_width // 2
    window_image = image.copy()
    window_image[window_image < img_min] = img_min
    window_image[window_image > img_max] = img_max

    return window_image
</code>```

And this function loads the image:

```<code>def load_image(file_path):
    medical_image = dicom.read_file(file_path)
    image = medical_image.pixel_array

    hu_image = transform_to_hu(medical_image, image)
    brain_image = window_image(hu_image, 40, 80)
    return brain_image
</code>```

Then i load my images:

```<code>files = sorted(glob.glob('F:\CT_Data_Classifier\*.dcm'))
images = np.array([load_image(path) for path in files])
</code>```

images.shape returns (200, 512, 512)
and everything is fine about the data, for example i can plot 100th image by
plt.imshow(images[100]) and it plots an image

i then feed the data into image data generator

```<code>train_image_data = ImageDataGenerator(
    rescale=1./255,
    shear_range=0.,
    zoom_range=0.05,
    rotation_range=180,
    width_shift_range=0.05,
    height_shift_range=0.05,
    horizontal_flip=True,
    vertical_flip=True,
    fill_mode='constant',
    cval=0
</code>```

but then, when i try to plot, with this code:

```<code>plt.figure(figsize=(12, 12))
for X_batch, y_batch in train_image_data.flow(trainX, trainY, batch_size=9):
    for i in range(0, 9):
        plt.subplot(330 + 1 + i)
        plt.imshow(X_batch[i])
    plt.show()
    break
</code>```

it returns

(ValueError: ('Input data in "NumpyArrayIterator" should have rank 4. You passed an array with shape', (162, 420, 420)))

i tried expand_dims and reshape to add an extra dimension at the end of the array to represent channels
but then it returns

```<code>TypeError: Invalid shape (420, 420, 1) for image data
</code>```

in the plt.imshow stage

im a doctor and not an experienced programmer, so i would really appreciate your help. cheers.

答:
You are correct in adding an extra dimension to represent channels. That part seems fine. The problem is with plotting. For that, you can use:

```<code>plt.matshow(x[..., 0]).
</code>```

where x is the 3D array. The syntax x[..., 0] means take index 0 of the last dimension of array x. The ellipsis (...) is shorthand to fill in the dimensions. For a 3D array, the equivalent call would be x[:, :, 0].

Body:
So i have preprocessed some dicom images to feed a neural network, and in image augmentation step, the image data generator expects a 4d input while my data is 3d (200, 420, 420)

i tried reshaping the array and expanding dimensions, but in both cases i cannot plot the individual images in the array (expects image with shape 420, 420 and instead my new images have shape 420, 420, 1)

and here are my codes;

I have three functions to convert DICOM images into images with good contrast;

This one takes housefield units

def transform_to_hu(medical_image, image):
    intercept = medical_image.RescaleIntercept
    slope = medical_image.RescaleSlope
    hu_image = image * slope + intercept

    return hu_image

This one sets window image values;

def window_image(image, window_center, window_width):
    img_min = window_center - window_width // 2
    img_max = window_center + window_width // 2
    window_image = image.copy()
    window_image[window_image < img_min] = img_min
    window_image[window_image > img_max] = img_max

    return window_image

And this function loads the image:

def load_image(file_path):
    medical_image = dicom.read_file(file_path)
    image = medical_image.pixel_array

    hu_image = transform_to_hu(medical_image, image)
    brain_image = window_image(hu_image, 40, 80)
    return brain_image

Then i load my images:

files = sorted(glob.glob('F:\CT_Data_Classifier\*.dcm'))
images = np.array([load_image(path) for path in files])

images.shape returns (200, 512, 512)
and everything is fine about the data, for example i can plot 100th image by
plt.imshow(images[100]) and it plots an image

i then feed the data into image data generator

train_image_data = ImageDataGenerator(
    rescale=1./255,
    shear_range=0.,
    zoom_range=0.05,
    rotation_range=180,
    width_shift_range=0.05,
    height_shift_range=0.05,
    horizontal_flip=True,
    vertical_flip=True,
    fill_mode='constant',
    cval=0

but then, when i try to plot, with this code:

plt.figure(figsize=(12, 12))
for X_batch, y_batch in train_image_data.flow(trainX, trainY, batch_size=9):
    for i in range(0, 9):
        plt.subplot(330 + 1 + i)
        plt.imshow(X_batch[i])
    plt.show()
    break

it returns

(ValueError: ('Input data in "NumpyArrayIterator" should have rank 4. You passed an array with shape', (162, 420, 420)))

i tried expand_dims and reshape to add an extra dimension at the end of the array to represent channels
but then it returns

TypeError: Invalid shape (420, 420, 1) for image data

in the plt.imshow stage

im a doctor and not an experienced programmer, so i would really appreciate your help. cheers.

Body:
You are correct in adding an extra dimension to represent channels. That part seems fine. The problem is with plotting. For that, you can use:

plt.matshow(x[..., 0]).

where x is the 3D array. The syntax x[..., 0] means take index 0 of the last dimension of array x. The ellipsis (...) is shorthand to fill in the dimensions. For a 3D array, the equivalent call would be x[:, :, 0].


问:
Delete directories with given folder name
I'm trying to write a cron job which would run on a Raspberry Pi and that would once every few days or once every two weeks run and delete some folders, these folders are date specific, and are generated automatically, e.g:

2020-02-08
2020-02-09
2020-02-10
2020-02-11
2020-02-12
2020-02-13
2020-02-14
2020-02-15
2020-02-16
```

<p>I'd like to be able to loop over these, and delete the past X days folders, whilst retaining the past Z days folders, e.g:</p>

<p>delete:</p>

<pre class="lang-sh prettyprint-override"><code>2020-02-08
2020-02-09
2020-02-10
2020-02-11
</code>```

keep:

2020-02-12
2020-02-13
2020-02-14
2020-02-15
2020-02-16
```

and then in 4 - 5 days time it would run again, deleting the ones it kept from the previous week, and so fourth.

I know that I can run rm -rf 2020-* to delete all of the folders/files beginning with that, but I need a script to do the above for me!

Also, in each folder would be thousands of files, this is something to bear in mind with a good perform ant deletion process

答:
Execute this command in the parent directory:

```<code>find  . -mtime +5 -type d -name 2020-\* -exec rm  -rf {} \;
</code>```

The command above will find all directories that are greater than 5 days old and have a name that matches 2020-* ( you may want to consider making this a little more future proof and perhaps go with 2* ).   All directories with that name (and modification time) will be removed.

You may want to hold off on the -exec part of that command.  Try this command first:

```<code>find  . -mtime +5 -type d -name 2\*
</code>```

This will let you know that the found directories are the one's you want to remove before you go ahead and delete them.

Body:
I'm trying to write a cron job which would run on a Raspberry Pi and that would once every few days or once every two weeks run and delete some folders, these folders are date specific, and are generated automatically, e.g:

2020-02-08
2020-02-09
2020-02-10
2020-02-11
2020-02-12
2020-02-13
2020-02-14
2020-02-15
2020-02-16

I'd like to be able to loop over these, and delete the past X days folders, whilst retaining the past Z days folders, e.g:

delete:

2020-02-08
2020-02-09
2020-02-10
2020-02-11

keep:

2020-02-12
2020-02-13
2020-02-14
2020-02-15
2020-02-16

and then in 4 - 5 days time it would run again, deleting the ones it kept from the previous week, and so fourth.

I know that I can run rm -rf 2020-* to delete all of the folders/files beginning with that, but I need a script to do the above for me!

Also, in each folder would be thousands of files, this is something to bear in mind with a good perform ant deletion process

Body:
Execute this command in the parent directory:

find  . -mtime +5 -type d -name 2020-\* -exec rm  -rf {} \;

The command above will find all directories that are greater than 5 days old and have a name that matches 2020-* ( you may want to consider making this a little more future proof and perhaps go with 2* ).   All directories with that name (and modification time) will be removed.

You may want to hold off on the -exec part of that command.  Try this command first:

find  . -mtime +5 -type d -name 2\*

This will let you know that the found directories are the one's you want to remove before you go ahead and delete them.


问:
SQL view, new column based on last row with calculation
Thanks in advance for the attention. I have a table with the structure as shown below. I need a third column, this for the first indice must be (4250 + valores), but from the second indice, must be the back result, plus second indice valores, with the condition: if the sum if greater than 4250, then the third column for this indice must be 4250, in order to sum this import for the next indice.

Below the example in Excel

https://1drv.ms/x/s!AtEkAF7ffIsqg8QxJ_vUuiBgTL98uQ?e=WM7JEg

答:
Seems to be similar to this question

```<code>Result_without_condition -
Max(Greatest(CASE WHEN index > 1
                  THEN Result_without_condition - 4250
                  ELSE 0
             END,0))
Over (ORDER BY index
      ROWS Unbounded Preceding)
</code>```

Edit:

Based on your comment you didn't calculate Result_without_condition, yet, Then you need a nested calculation:

```<code>SELECT dt.*,
   result_without_condition
     - Max(Greatest(CASE WHEN "index" > 1 THEN Result_without_condition - 4250 ELSE 0 END,0))
       Over (ORDER BY "index"
             ROWS Unbounded Preceding)
FROM
 (
   SELECT tab.*,
      Sum("value")
      Over (ORDER BY "index"
            ROWS Unbounded Preceding)
      + 4250 AS Result_without_condition
   FROM tab
 ) AS dt
</code>```

Body:
Seems to be similar to this question

Result_without_condition -
Max(Greatest(CASE WHEN index > 1
                  THEN Result_without_condition - 4250
                  ELSE 0
             END,0))
Over (ORDER BY index
      ROWS Unbounded Preceding)

Edit:

Based on your comment you didn't calculate Result_without_condition, yet, Then you need a nested calculation:

SELECT dt.*,
   result_without_condition
     - Max(Greatest(CASE WHEN "index" > 1 THEN Result_without_condition - 4250 ELSE 0 END,0))
       Over (ORDER BY "index"
             ROWS Unbounded Preceding)
FROM
 (
   SELECT tab.*,
      Sum("value")
      Over (ORDER BY "index"
            ROWS Unbounded Preceding)
      + 4250 AS Result_without_condition
   FROM tab
 ) AS dt


问:
Allowing POSTs to static files in a CouchDB CouchApp
When serving static assets from a CouchApp (e.g. HTML and JS for a Backbone.js app), a 405 Method Not Allowed error is appropriately kicked when those static pages are POSTed to. However, when developing a Facebook app for canvas/iframe, Facebook sends all requests as POSTs. Is there any way to make Couch allow the POST method?</p>

答:
I am pessimistic about this. I'm not sure but it may not be possible.

Is it possible to tell Facebook to add custom headers? Couch supports an X-HTTP-Method-Override header in POST requests. Just set it to the HTTP method you really wanted.


问:
Perl JSON::XS non-OO interface
All of the documentation and examples I have seen for the Perl JSON::XS module use a OO interface, e.g.

```<code>print JSON::XS->new->ascii()->pretty()->canonical()->encode($in);
</code>```

But I don't necessarily want all those options every time, I'd prefer to send them in a hash like you can with the basic JSON module, e.g.

```<code>print to_json($in, { canonical => 1, pretty => 1, ascii => 1 } );
</code>```

sending to that encode_json yields

```<code>Too many arguments for JSON::XS::encode_json
</code>```

Is there any way to do that?

答:
JSON's to_json uses JSON::XS if it's installed, so if you want a version of to_json that uses JSON::XS, simply use the one from JSON.

Or, you could recreate to_json.

```<code>sub to_json
   my $encoder = JSON::XS->new();
   if (@_ > 1) {
      my $opts = $_[1];
      for my $method (keys(%$opts)) {
         $encoder->$_($opts->{$_});
      }
   }

   return $encoder->encode($_[0]);
}
</code>```

But doesn't help stop passing in the options every time. If you're encoding multiple data structures, it's best to create a single object and reuse it.

```<code>my $encoder = JSON::XS->new->ascii->pretty->canonical;

print $encoder->encode($in);
</code>```

Title: Perl JSON::XS non-OO interface

Body:
All of the documentation and examples I have seen for the Perl JSON::XS module use a OO interface, e.g.

print JSON::XS->new->ascii()->pretty()->canonical()->encode($in);

But I don't necessarily want all those options every time, I'd prefer to send them in a hash like you can with the basic JSON module, e.g.

print to_json($in, { canonical => 1, pretty => 1, ascii => 1 } );

sending to that encode_json yields

Too many arguments for JSON::XS::encode_json

Is there any way to do that?

Body:
JSON's to_json uses JSON::XS if it's installed, so if you want a version of to_json that uses JSON::XS, simply use the one from JSON.

Or, you could recreate to_json.

sub to_json
   my $encoder = JSON::XS->new();
   if (@_ > 1) {
      my $opts = $_[1];
      for my $method (keys(%$opts)) {
         $encoder->$_($opts->{$_});
      }
   }

   return $encoder->encode($_[0]);
}

But doesn't help stop passing in the options every time. If you're encoding multiple data structures, it's best to create a single object and reuse it.

my $encoder = JSON::XS->new->ascii->pretty->canonical;

print $encoder->encode($in);


问:
Vertical alignement of span inside a div when the font-size is big
Note: I've already read How to vertically center a  inside a div? but here it's slightly different (see below).

I'm trying to insert some big text inside a circle button, an image inside another one, and a title aligned vertically.

This perfectly works on Chrome (I've used various answers from Circle button css):

But strangely, it doesn't work on Firefox and also iPhone Safari (bad alignment):

How to solve such a vertical alignment problem?

.circlebtn { height: 5.4em; width: 5.4em; border-radius: 50%; background-color: black; color: white; text-align: center; cursor: pointer; border: 0; user-select: none; outline: 0; display: inline-block; margin: 1.9em 0 3em 1em; float: left; }
.circlebtn img { width: 3.75em; }
#a span { font-size: 4em; font-weight: bold; }
#c { margin: 1.3em 0 0 1em; float: left; font-size: 2em; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="a" class="circlebtn"><span>+</span></button>
<button id="b" class="circlebtn"><img src="https://via.placeholder.com/762x416" id="b"></button>
<h1 id="c">HELLO</h1></code>```

Note: I've also tried with vertical-align:middle as suggested in How to vertically center a  inside a div?:

```<code><div class="parent">
  <span class="child">Yes mom, I did my homework lol</span>
</div>
You should then add the CSS rules

.parent { height: 20px; }
.child { line-height: 20px; vertical-align: middle; }
</code>```

but I think the problem here comes from the fact the child span has a different font size.

答:
As mentioned in @TemaniAfif's comments, the font itself can influence the height and alignment, as seen in this jsFiddle.

One solution would be to use JavaScript: How to vertically align all text in CSS?

Another one would be to generate the + sign with CSS only: Make plus symbol in CSS

.plus {
  width:4.5em;
  height:4.5em;

  background:
    linear-gradient(#fff,#fff),
    linear-gradient(#fff,#fff),
    #000;
  background-position:center;
  background-size: 50% 0.5em, 0.5em 50%;
  background-repeat:no-repeat;
}

.radius {
  border-radius:50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="plus radius">
</div></code>```

Body:
Note: I've already read How to vertically center a  inside a div? but here it's slightly different (see below).

I'm trying to insert some big text inside a circle button, an image inside another one, and a title aligned vertically.

This perfectly works on Chrome (I've used various answers from Circle button css):

But strangely, it doesn't work on Firefox and also iPhone Safari (bad alignment):

How to solve such a vertical alignment problem?

.circlebtn { height: 5.4em; width: 5.4em; border-radius: 50%; background-color: black; color: white; text-align: center; cursor: pointer; border: 0; user-select: none; outline: 0; display: inline-block; margin: 1.9em 0 3em 1em; float: left; }
.circlebtn img { width: 3.75em; }
#a span { font-size: 4em; font-weight: bold; }
#c { margin: 1.3em 0 0 1em; float: left; font-size: 2em; }

<button id="a" class="circlebtn">+</button>
<button id="b" class="circlebtn"></button>

HELLO

Note: I've also tried with vertical-align:middle as suggested in How to vertically center a  inside a div?:

  Yes mom, I did my homework lol

You should then add the CSS rules

.parent { height: 20px; }
.child { line-height: 20px; vertical-align: middle; }

but I think the problem here comes from the fact the child span has a different font size.

Body:
As mentioned in @TemaniAfif's comments, the font itself can influence the height and alignment, as seen in this jsFiddle.

One solution would be to use JavaScript: How to vertically align all text in CSS?

Another one would be to generate the + sign with CSS only: Make plus symbol in CSS

.plus {
  width:4.5em;
  height:4.5em;

  background:
    linear-gradient(#fff,#fff),
    linear-gradient(#fff,#fff),
    #000;
  background-position:center;
  background-size: 50% 0.5em, 0.5em 50%;
  background-repeat:no-repeat;
}

.radius {
  border-radius:50%;
}

<div class="plus radius">
</div>


问:
Can we include attachments to iCalendar invitations that are created from an MVC application
How can we send attachment along with an ics file that are created from MVC application.
We are creating the meeting invitations with data fetched from application in ics format and then downloading for the user to click on it and open in outlook.So can we add an attachment also along with the ics file so that users wen open in outlook will see the attachment along with other details.
Please somebody help.</p>

答:
As per https://www.rfc-editor.org/rfc/rfc5545#section-3.8.1.1  or https://icalendar.org/iCalendar-RFC-5545/3-8-1-1-attachment.html, one can ATTACH by referring to the URL of the attachment.

An example given is:

```<code>ATTACH;FMTTYPE=application/postscript:ftp://example.com/pub/
  reports/r-960812.ps
</code>```

Other examples elsewhere in the spec are:

```<code>ATTACH:http://example.com/public/quarterly-report.doc
</code>```

or
"The following example specifies an "ATTACH" property with inline
binary encoded content information:

```<code> ATTACH;FMTTYPE=text/plain;ENCODING=BASE64;VALUE=BINARY:VGhlIH
  F1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4
</code>```

"

or

```<code>ATTACH;FMTTYPE=application/msword:ftp://example.com/pub/docs/
        agenda.doc
</code>```

Body:
As per https://www.rfc-editor.org/rfc/rfc5545#section-3.8.1.1  or https://icalendar.org/iCalendar-RFC-5545/3-8-1-1-attachment.html, one can ATTACH by referring to the URL of the attachment.

An example given is:

ATTACH;FMTTYPE=application/postscript:ftp://example.com/pub/
  reports/r-960812.ps

Other examples elsewhere in the spec are:

ATTACH:http://example.com/public/quarterly-report.doc

or
"The following example specifies an "ATTACH" property with inline
binary encoded content information:

 ATTACH;FMTTYPE=text/plain;ENCODING=BASE64;VALUE=BINARY:VGhlIH
  F1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4

"

or

ATTACH;FMTTYPE=application/msword:ftp://example.com/pub/docs/
        agenda.doc


问:
Hide navbar while ajax loader loading
I'm using ajax loader to hide my page until it loads everything. The problem is, for some reason it doesn't hide my navbar as you can see on the picture below. I want it to hide everything, include the navbar aswell.

```<code> <nav class="navbar navbar-expand-lg navbar-transparent navbar-absolute fixed-top ">
        <div class="container-fluid">
          <div class="navbar-wrapper">

          </div>
          <button class="navbar-toggler" type="button" data-toggle="collapse" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">
            <span class="sr-only">Toggle navigation</span>
            <span class="navbar-toggler-icon icon-bar"></span>
            <span class="navbar-toggler-icon icon-bar"></span>
            <span class="navbar-toggler-icon icon-bar"></span>
          </button>
          <div class="collapse navbar-collapse justify-content-end">
            <form class="navbar-form">
              <div class="input-group no-border">
                <input type="text"  class="form-control" placeholder="Search..." id="myFilter" data-toggle="tooltip" data-placement="left" onkeyup="myFunction()">
                <button type="submit" class="btn btn-white btn-round btn-just-icon">
                  <i class="material-icons">search</i>
                  <div class="ripple-container"></div>
                </button>
              </div>
              <p id="notfound">Not found!</p>
            </form>
            <ul class="navbar-nav">

            </ul>
          </div>
        </div>
      </nav>

<!-- loader -->
   <div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#7cc576"/></svg></div>

$(document).ready(function($) {
    "use strict";
    // loader
    var loader = function() {
        setTimeout(function() {
            if($('#ftco-loader').length > 0) {
                $('#ftco-loader').removeClass('show');
            }
        }, 1);
    };
    loader();

});
</code>```

https://i.gyazo.com/fbf9068d88239986f3ed076860db4ddb.png

答:
I think this is the issue of z-index.
Give your loader a higher z-index w.r.t. to your navbar/header.</p>

Title: Hide navbar while ajax loader loading

Body:
I'm using ajax loader to hide my page until it loads everything. The problem is, for some reason it doesn't hide my navbar as you can see on the picture below. I want it to hide everything, include the navbar aswell.

          <button class="navbar-toggler" type="button" data-toggle="collapse" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">
            Toggle navigation

          </button>

            <form class="navbar-form">

                <input type="text"  class="form-control" placeholder="Search..." id="myFilter" data-toggle="tooltip" data-placement="left" onkeyup="myFunction()">
                <button type="submit" class="btn btn-white btn-round btn-just-icon">
                  search

                </button>

Not found!

            </form>

<svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#7cc576"/></svg>

$(document).ready(function($) {
    "use strict";
    // loader
    var loader = function() {
        setTimeout(function() {
            if($('#ftco-loader').length > 0) {
                $('#ftco-loader').removeClass('show');
            }
        }, 1);
    };
    loader();

});

https://i.gyazo.com/fbf9068d88239986f3ed076860db4ddb.png


问:
Finding the distances from each point to the rest, looping
I am new to python.
I have a csv file containing 400 pairs of x and y in two columns.
I want to loop over the data such that it starts from a pair (x_i,y_i) and finds the distance between that pair and the rest of the 399 points. I want the process to be repeated for all pairs of (x_i,y_i)  and the result is appended to to a list Dist_i

```<code>import pandas as pd
x_y_data = pd.read_csv("x_y_points400_labeled_csv.csv")

x = x_y_data.loc[:,'x']
y = x_y_data.loc[:,'y']

i=0
j=0
while (i<len(x)):
    Dist=np.sqrt((x[i]-x)**2 + (y[j]-y)**2)
    i = 1 + i
    j = 1 + j
print(Dist)

</code>```

output:

```<code>0      676.144955
1      675.503342
2      674.642602
..
396      9.897127
397     21.659654
398     15.508062
399      0.000000
Length: 400, dtype: float64
</code>```

This is how far I went, but it is not what I intend to obtain. My goal is to get something like in the picture attached.

Thanks for your help in advance

enter image description here

Body:
I am new to python.
I have a csv file containing 400 pairs of x and y in two columns.
I want to loop over the data such that it starts from a pair (x_i,y_i) and finds the distance between that pair and the rest of the 399 points. I want the process to be repeated for all pairs of (x_i,y_i)  and the result is appended to to a list Dist_i

import pandas as pd
x_y_data = pd.read_csv("x_y_points400_labeled_csv.csv")

x = x_y_data.loc[:,'x']
y = x_y_data.loc[:,'y']

i=0
j=0
while (i<len(x)):
    Dist=np.sqrt((x[i]-x)**2 + (y[j]-y)**2)
    i = 1 + i
    j = 1 + j
print(Dist)

output:

0      676.144955
1      675.503342
2      674.642602
..
396      9.897127
397     21.659654
398     15.508062
399      0.000000
Length: 400, dtype: float64

This is how far I went, but it is not what I intend to obtain. My goal is to get something like in the picture attached.

Thanks for your help in advance

enter image description here

Body:
You can use broadcasting (arr[:, None]) to do this calculation all at once. This will give you the repetitive calculations you want. Otherwise scipy.spatial.distance.pdist gives you the upper triangle of the calculations.

Sample Data

import pandas as pd
import numpy as np

np.random.seed(123)
N = 6
df = pd.DataFrame(np.random.normal(0, 1, (N, 2)),
                  columns=['X', 'Y'],
                  index=[f'point{i}' for i in range(N)])

x = df['X'].to_numpy()
y = df['Y'].to_numpy()

result = pd.DataFrame(np.sqrt((x[:, None] - x)**2 + (y[:, None] - y)**2),
                      index=df.index,
                      columns=df.index)

          point0    point1    point2    point3    point4    point5
point0  0.000000  2.853297  0.827596  1.957709  3.000780  1.165343
point1  2.853297  0.000000  3.273161  2.915990  1.172704  1.708145
point2  0.827596  3.273161  0.000000  2.782669  3.121463  1.749023
point3  1.957709  2.915990  2.782669  0.000000  3.718481  1.779459
point4  3.000780  1.172704  3.121463  3.718481  0.000000  2.092455
point5  1.165343  1.708145  1.749023  1.779459  2.092455  0.000000

With scipy.

from scipy.spatial.distance import pdist

pdist(df[['X', 'Y']])
array([2.8532972 , 0.82759587, 1.95770875, 3.00078036, 1.16534282,
       3.27316125, 2.91598992, 1.17270443, 1.70814458, 2.78266933,
       3.1214628 , 1.74902298, 3.7184812 , 1.77945856, 2.09245472])

To turn this into the above DataFrame.

L = len(df)

arr = np.zeros((L, L))
arr[np.triu_indices(L, 1)] = pdist(df[['X', 'Y']])
arr = arr + arr.T # Lower triangle b/c symmetric

pd.DataFrame(arr, index=df.index, columns=df.index)

          point0    point1    point2    point3    point4    point5
point0  0.000000  2.853297  0.827596  1.957709  3.000780  1.165343
point1  2.853297  0.000000  3.273161  2.915990  1.172704  1.708145
point2  0.827596  3.273161  0.000000  2.782669  3.121463  1.749023
point3  1.957709  2.915990  2.782669  0.000000  3.718481  1.779459
point4  3.000780  1.172704  3.121463  3.718481  0.000000  2.092455
point5  1.165343  1.708145  1.749023  1.779459  2.092455  0.000000


问:
Using Vue with Quasar and a Router
I'm new to Quasar but I have my MyLayout.vue page and on my page I have q-route-tabs

```<code><q-tabs align="left" shrink>
    <q-route-tab to="/" label="Home" />
    <q-route-tab to="/page1" label="Page One" />
    <q-route-tab to="/page2" label="Page Two" />
    <q-route-tab to="/page3" label="Page three" />
</q-tabs>
</code>```

I need to know what page is loaded and the change the Toolbar Title and set certain components hidden based upon the tab selected.  Before moving over to Quasar but still using Vue I used

created: function() {
    if (this.$router.currentRoute.name === "Page One") {
        this.drawer = false;
        this.ToolbarTitle = "Publications Worksheet";
        this.isDisabled = true;
    }
}
```

this.$router and $router will not compile so I think there must be a different syntax for Quasar

答:
create a method to check the page route

run the method on page mount so that even if the link to the page is
loaded without route change your method will still run

You can add a watch on $route and change the toolbar title based on the
page change.

```<code> methods: {
    checkCurrentRoute() {
      console.log(this.$route);
      if (this.$route.path == "/PageOne") {
        this.drawer = false;
        this.ToolbarTitle = "Publications Worksheet";
        this.isDisabled = true;
      }
    }
  },
 mounted(){
   this.checkCurrentRoute()
 },

  watch: {
    $route() {
      this.checkCurrentRoute();
    }
  },
</code>```

OR

user this.$router.currentRoute.name

```<code> methods: {
    checkCurrentRoute() {
      console.log(this.$router);
      if (this.$router.currentRoute.name == "Page One") {
        this.drawer = false;
        this.ToolbarTitle = "Publications Worksheet";
        this.isDisabled = true;
      }
    }
  },
 mounted(){
   this.checkCurrentRoute()
 },

  watch: {
    $route() {
      this.checkCurrentRoute();
    }
  },
</code>```

Title: Using Vue with Quasar and a Router

Body:
I'm new to Quasar but I have my MyLayout.vue page and on my page I have q-route-tabs

<q-tabs align="left" shrink>
    <q-route-tab to="/" label="Home" />
    <q-route-tab to="/page1" label="Page One" />
    <q-route-tab to="/page2" label="Page Two" />
    <q-route-tab to="/page3" label="Page three" />
</q-tabs>

I need to know what page is loaded and the change the Toolbar Title and set certain components hidden based upon the tab selected.  Before moving over to Quasar but still using Vue I used

created: function() {
    if (this.$router.currentRoute.name === "Page One") {
        this.drawer = false;
        this.ToolbarTitle = "Publications Worksheet";
        this.isDisabled = true;
    }
}

this.$router and $router will not compile so I think there must be a different syntax for Quasar

Body:
create a method to check the page route

run the method on page mount so that even if the link to the page is
loaded without route change your method will still run

You can add a watch on $route and change the toolbar title based on the
page change.

 methods: {
    checkCurrentRoute() {
      console.log(this.$route);
      if (this.$route.path == "/PageOne") {
        this.drawer = false;
        this.ToolbarTitle = "Publications Worksheet";
        this.isDisabled = true;
      }
    }
  },
 mounted(){
   this.checkCurrentRoute()
 },

  watch: {
    $route() {
      this.checkCurrentRoute();
    }
  },

OR

user this.$router.currentRoute.name

 methods: {
    checkCurrentRoute() {
      console.log(this.$router);
      if (this.$router.currentRoute.name == "Page One") {
        this.drawer = false;
        this.ToolbarTitle = "Publications Worksheet";
        this.isDisabled = true;
      }
    }
  },
 mounted(){
   this.checkCurrentRoute()
 },

  watch: {
    $route() {
      this.checkCurrentRoute();
    }
  },


问:
Why does Keras model.predict never execute on this simple machine learning model I've setup?
```<code>import numpy as np
import keras as ks

model = ks.Sequential([ks.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs=np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype = float)
ys=np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype = float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))
</code>```

The model.predict never executes no matter how long I wait. What tests can I do to diagnose the problem? What questions should I be asking myself to find the issue?

Body:
import numpy as np
import keras as ks

model = ks.Sequential([ks.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs=np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype = float)
ys=np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype = float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

The model.predict never executes no matter how long I wait. What tests can I do to diagnose the problem? What questions should I be asking myself to find the issue?

Body:
Code is ok -- ran in less than 1 second for me.

6/6 [==============================] - 0s 101us/step - loss: 4.8739e-05
Epoch 500/500

6/6 [==============================] - 0s 115us/step - loss: 4.7737e-05
[[18.979841]]

Process finished with exit code 0


问:
Changing a numeric month to a name month in pandas or SQL
I have a column 'date' that reads as 2018-01-02 02:06:21 and I want to convert to read as
2018-January-01-02 02:06:21 - Essentially making numeric date to read month name, I have been struggling.  The code I am using:

This is using pandas but can also try and convert into SQL and then bring it over.

df['date'] = df['date'].strftime('%Y-%m') and the error I get when doing this

AttributeError: 'Series' object has no attribute 'strftime'

Any help would be greatly appreciated.

答:
1) The best you can get with the minimal effort pandas is:

```<code>import pandas as pd

dates = ['2018-01-02 02:06:21']

df = pd.DataFrame()
df['date'] = pd.Series(dates)

df['date'] = df['date'].apply(lambda x: pd.to_datetime(x).strftime('%Y-%b-%m-%H:%M:%S'))

print(df)
</code>```

Output: 2018-Jan-01-02:06:21

2) As for SQL. Different SQL products have different means for date formatting. You need to proper tag your question first.

I see that you ask a series of questions about how to accomplish one task. Reading though those questions I get a feeling that you wish to make a minimal effort to complete some task by putting a burden of your work on the others.

Body:
1) The best you can get with the minimal effort pandas is:

import pandas as pd

dates = ['2018-01-02 02:06:21']

df = pd.DataFrame()
df['date'] = pd.Series(dates)

df['date'] = df['date'].apply(lambda x: pd.to_datetime(x).strftime('%Y-%b-%m-%H:%M:%S'))

print(df)

Output: 2018-Jan-01-02:06:21

2) As for SQL. Different SQL products have different means for date formatting. You need to proper tag your question first.

I see that you ask a series of questions about how to accomplish one task. Reading though those questions I get a feeling that you wish to make a minimal effort to complete some task by putting a burden of your work on the others.


问:
Safe to std:move a member?
Have found comparable questions but not exactly with such a case.
Take the following code for example:

```<code>#include <iostream>
#include <string>
#include <vector>

struct Inner
{
    int a, b;
};

struct Outer
{
    Inner inner;
};

std::vector<Inner> vec;

int main()
{
    Outer * an_outer = new Outer;

    vec.push_back(std::move(an_outer->inner));

    delete an_outer;
}
</code>```

Is this safe? Even if those were polymorphic classes or ones with custom destructors?

My concern regards the instance of "Outer" which has a member variable "inner" moved away. From what I learned, moved things should not be touched anymore. However does that include the delete call that is applied to outer and would technically call delete on inner as well (and thus "touch" it)?

答:
std::move is a cast to an rvalue-reference, which primarily changes which constructor/assignment operator overload is chosen. In your example the move-constructor is the default generated move-constructor, which just copies the ints over so nothing happens.

Whether or not this generally safe depends on the way your classes implement move construction/assignment. Assume for example that your class instead held a pointer. You would have to set that to nullptr in the moved-from class to avoid destroying the pointed-to data, if the moved-from class is destroyed.

Because just defining move-semantics is a custom way almost always leads to problems, the rule of five says that if you customize any of:

the copy constructor

the copy assignment operator

the move constructor

the move assignment operator

the destructor

you should usually customize all to ensure that they behave consistently with the expectations a caller would usually have for your class.

Title: Safe to std:move a member?

Body:
Have found comparable questions but not exactly with such a case.
Take the following code for example:

#include <iostream>
#include <string>
#include <vector>

struct Inner
{
    int a, b;
};

struct Outer
{
    Inner inner;
};

std::vector<Inner> vec;

int main()
{
    Outer * an_outer = new Outer;

    vec.push_back(std::move(an_outer->inner));

    delete an_outer;
}

Is this safe? Even if those were polymorphic classes or ones with custom destructors?

My concern regards the instance of "Outer" which has a member variable "inner" moved away. From what I learned, moved things should not be touched anymore. However does that include the delete call that is applied to outer and would technically call delete on inner as well (and thus "touch" it)?


问:
Why is my modulo operator returning a doubled block size for an input of 1 byte?
The idea here is to create a function called calculator that takes an input and compares it to a variable. Compare file size to block size, and if there's a remainder, double the block size to accommodate usage. My problem is, with an input of 1, I still get 8192? Yet the other calculations come out correct. I know that floor division only yields an integer, not a float (which I thought may be a better way to do this because I wanted the real number) yet when I try to float it, I get the same returns. I've also tried floating elsewhere, with either incorrect or the same results as above. When I reversed the order of the modulo, the answer appears correct but I am informed this is wrong and told to do it more like what you see here, with floor division and modulo in this order.

So my question is, why am I getting 8192 with an input of 1, but the rest are right?

```<code>def calculator(somedata):                 # calculator function, 'somedata' is the input
    blocksize = 4096                      # what block size on the partition
                                          # calculate how many blocks are fully occupied
    fullblock = somedata // blocksize     # floor division will give back only the integer yes?
                                          # modulo to check whether there's any remainder
    bytesremain = somedata % blocksize    # which will say 1 or None unless I float yes?
                                          # return the block usage based on byte count?
    if bytesremain > 0:                   # if there's anything left over in the bytesremain
      return(blocksize * 2)               # double the block usage to 2
    return blocksize                      # otherwise return the block usage

print(calculator(1))                      # Should be 4096
print(calculator(4096))                   # Should be 4096
print(calculator(4097))                   # Should be 8192
print(calculator(6000))                   # Should be 8192
</code>```

答:
You probably are looking for:

def calculator(somedata):
    blocksize = 4096
    fullblock = (somedata-1) // blocksize
    return blocksize*(fullblock+1)
```

Body:
The idea here is to create a function called calculator that takes an input and compares it to a variable. Compare file size to block size, and if there's a remainder, double the block size to accommodate usage. My problem is, with an input of 1, I still get 8192? Yet the other calculations come out correct. I know that floor division only yields an integer, not a float (which I thought may be a better way to do this because I wanted the real number) yet when I try to float it, I get the same returns. I've also tried floating elsewhere, with either incorrect or the same results as above. When I reversed the order of the modulo, the answer appears correct but I am informed this is wrong and told to do it more like what you see here, with floor division and modulo in this order.

So my question is, why am I getting 8192 with an input of 1, but the rest are right?

def calculator(somedata):                 # calculator function, 'somedata' is the input
    blocksize = 4096                      # what block size on the partition
                                          # calculate how many blocks are fully occupied
    fullblock = somedata // blocksize     # floor division will give back only the integer yes?
                                          # modulo to check whether there's any remainder
    bytesremain = somedata % blocksize    # which will say 1 or None unless I float yes?
                                          # return the block usage based on byte count?
    if bytesremain > 0:                   # if there's anything left over in the bytesremain
      return(blocksize * 2)               # double the block usage to 2
    return blocksize                      # otherwise return the block usage

print(calculator(1))                      # Should be 4096
print(calculator(4096))                   # Should be 4096
print(calculator(4097))                   # Should be 8192
print(calculator(6000))                   # Should be 8192


问:
Passing a variable in Selenium Xpath
I am trying to pass a variable in Xpath but it is not capturing it .

The Country is captured in query using speech recognisation
My Code ::

**
while True:
query = command().lower()
    Country = ['Germany', 'Netherlands']
    for Country in query:

```<code>     if Country in Country:

        wait = WebDriverWait(driver, 10)

        driver.find_element_by_xpath("(//div[@class='ot-lookup__input-container'])").click()

        wait.until(EC.element_to_be_clickable((By.XPATH, "//button[normalize
                                          space()=\'{}\']"))).format(query).click()
     else:
        speak("Not a valid Country")
     break**
</code>```

If I am giving space()='Germany', then it works fine

答:
.format() is not on correct place. .format() should be apply on xpath string instead outside ))).

```<code>wait.until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='{}']".format('Other')))).click()
</code>```

Title: Passing a variable in Selenium Xpath

Body:
I am trying to pass a variable in Xpath but it is not capturing it .

The Country is captured in query using speech recognisation
My Code ::

**
while True:
query = command().lower()
    Country = ['Germany', 'Netherlands']
    for Country in query:

     if Country in Country:

        wait = WebDriverWait(driver, 10)

        driver.find_element_by_xpath("(//div[@class='ot-lookup__input-container'])").click()

        wait.until(EC.element_to_be_clickable((By.XPATH, "//button[normalize
                                          space()=\'{}\']"))).format(query).click()
     else:
        speak("Not a valid Country")
     break**

If I am giving space()='Germany', then it works fine

Body:
.format() is not on correct place. .format() should be apply on xpath string instead outside ))).

wait.until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='{}']".format('Other')))).click()