问:
Import a module function and required dependencies for it
How do I import and run a Python function and have all the dependencies it uses use the imports from the main Python file?

Main Python file:

```<code>from im import er
import time
er()
</code>```

Python file with function to be imported:

```<code>def er():
    time.sleep(1)
    print('hi')
</code>```

This doesn't work because the time module is not imported in the im.py. How can I make this work without importing the modules it needs each time I run the function?

答:
You have to import the function in the main, and required module for the function in the function file.

Main Python file:

```<code>from im import er

er()
</code>```

Imported module :

```<code>from time import sleep

def er():
    sleep(1)
    print('hi')
</code>```

This behave this way because Python run the imported module when you import it. Then, depending of your import statement, it will do:

import <module>: create a module object named <module> with attributes allowing you to access global scope of this module. If a function is in the global scope of the module, you access it with <module>.<function_name>.

from <module> import *: add to the global scope of the current module the global scope of the imported module (not exactly, but if you need more informations about it, look for wildcard import behaviour). As a good rule of thumb with this import: don't use this.

from <module> import <symbol>: add the symbol of the imported module to the global scope of the current module.

More info about imports:

https://stackoverflow.com/a/10501768/6251742

https://docs.python.org/3/reference/import.html

Body:
How do I import and run a Python function and have all the dependencies it uses use the imports from the main Python file?

Main Python file:

from im import er
import time
er()

Python file with function to be imported:

def er():
    time.sleep(1)
    print('hi')

This doesn't work because the time module is not imported in the im.py. How can I make this work without importing the modules it needs each time I run the function?

Body:
You have to import the function in the main, and required module for the function in the function file.

Main Python file:

from im import er

er()

Imported module :

from time import sleep

def er():
    sleep(1)
    print('hi')

This behave this way because Python run the imported module when you import it. Then, depending of your import statement, it will do:

import <module>: create a module object named <module> with attributes allowing you to access global scope of this module. If a function is in the global scope of the module, you access it with <module>.<function_name>.

from <module> import *: add to the global scope of the current module the global scope of the imported module (not exactly, but if you need more informations about it, look for wildcard import behaviour). As a good rule of thumb with this import: don't use this.

from <module> import <symbol>: add the symbol of the imported module to the global scope of the current module.

More info about imports:

https://stackoverflow.com/a/10501768/6251742

https://docs.python.org/3/reference/import.html


来源: stackexchange

问:
How to find next birthday date from list of date from date now?
I'm struggling with this question? How can I find next birthday Date from my list of date ?
I got

```<code>const myArray = [
          {
            name: 'Joe Blow',
            date: 'Wednesday, November 25, 1992'
          },
          {
            name: 'Sam lol',
            date: 'Thursday, April 16, 1992'
          },
          {
            name: 'Eva lol',
            date: 'Thursday, February 26, 1991'
          }
        ];
        myArray.sort(function compare(a, b) {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateA.getUTCDate() - dateB.getUTCDate();
        });
        // console.log(this.usersBirthdayDate);
        console.log(myArray);
</code>```

but I got Sam first cause he got 1992.. But I would like to display Thursday, February 26, 1991 first

Updated
my solution :

```<code>    sortByDateNoYear(adate, bdate) {
        let results;
        const lhdate = moment(adate.birthdayDate);
        const rhdate = moment(bdate.birthdayDate);
        results =
          lhdate.month() > rhdate.month()
            ? 1
            : lhdate.month() < rhdate.month()
            ? -1
            : 0;
        if (results === 0) {
          results =
            lhdate.date() > rhdate.date()
              ? 1
              : lhdate.date() < rhdate.date()
              ? -1
              : 0;
        }
        return results;
      }
 [array].sort(this.sortByDateNoYear);
</code>```

答:
You can try like this

const myArray = [{
    name: 'Joe Blow',
    date: 'Wednesday, November 25, 1992'
  },
  {
    name: 'Sam lol',
    date: 'Thursday, April 16, 1992'
  },
  {
    name: 'Eva lol',
    date: 'Thursday, February 26, 1991'
  }
];
myArray.sort((a, b) => {
  const ad = new Date(a.date).getTime();
  const bd = new Date(b.date).getTime();
  return ad - bd;
});
// console.log(this.usersBirthdayDate);
console.log(myArray);```

ContentLicense: CC BY-SA 4.0

Body:
I'm struggling with this question? How can I find next birthday Date from my list of date ?
I got

const myArray = [
          {
            name: 'Joe Blow',
            date: 'Wednesday, November 25, 1992'
          },
          {
            name: 'Sam lol',
            date: 'Thursday, April 16, 1992'
          },
          {
            name: 'Eva lol',
            date: 'Thursday, February 26, 1991'
          }
        ];
        myArray.sort(function compare(a, b) {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateA.getUTCDate() - dateB.getUTCDate();
        });
        // console.log(this.usersBirthdayDate);
        console.log(myArray);

but I got Sam first cause he got 1992.. But I would like to display Thursday, February 26, 1991 first

Updated
my solution :

    sortByDateNoYear(adate, bdate) {
        let results;
        const lhdate = moment(adate.birthdayDate);
        const rhdate = moment(bdate.birthdayDate);
        results =
          lhdate.month() > rhdate.month()
            ? 1
            : lhdate.month() < rhdate.month()
            ? -1
            : 0;
        if (results === 0) {
          results =
            lhdate.date() > rhdate.date()
              ? 1
              : lhdate.date() < rhdate.date()
              ? -1
              : 0;
        }
        return results;
      }
 [array].sort(this.sortByDateNoYear);


问:
Is there a better way in C# to reserve long variable name?
```<code>var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName
</code>```

I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#

答:
How about a function:

```<code>Func<typeOfProperty> someName = () => Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName;
</code>```

if you now call

```<code>var test = someName();
</code>```

you would get your desired value without having to type the long chain of properties all the time.

Edit:
Just to be clear, if PropertyNameWhichIsBigName changes, someName() will return the new value.

Body:
var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName

I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#

Body:
How about a function:

Func<typeOfProperty> someName = () => Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName;

if you now call

var test = someName();

you would get your desired value without having to type the long chain of properties all the time.

Edit:
Just to be clear, if PropertyNameWhichIsBigName changes, someName() will return the new value.


问:
SQL retrieve all rows between two dates and a specific number of rows before the date ordered by date
As the title says, I have a table with a date column. I am trying to retrieve all rows between 2 dates as well as X number of rows before the beginning date ordered by date.

Take a select * from table order by date DSC

```<code>20200201
20200101
20191201
20191101
20191001
20190901
20190801
20190701
</code>```

I want between 20200201 and 20191201 and the previous 3 rows(not knowing the date)

```<code>result
20200201
20200101
20191201
20191101
20191001
20190901
</code>```

my current query returns a random set of high dates between the union for some reason:

```<code>(SELECT * FROM Table WHERE Date BETWEEN 20200201 AND 20191201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)
</code>```

Any idea where I am going wrong?

答:
The issue was as jarlh pointed out, the order of the subquery's were not kept(thats why things were jumbled) and a simple ORDER BY of the whole UNION fixed this. I did not try Gordon's response as this solved my issue so:

```<code>(SELECT * FROM Table WHERE Date BETWEEN  20191201 AND 20200201)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)
ORDER BY Date ASC
</code>```

Thank you

Body:
As the title says, I have a table with a date column. I am trying to retrieve all rows between 2 dates as well as X number of rows before the beginning date ordered by date.

Take a select * from table order by date DSC

20200201
20200101
20191201
20191101
20191001
20190901
20190801
20190701

I want between 20200201 and 20191201 and the previous 3 rows(not knowing the date)

result
20200201
20200101
20191201
20191101
20191001
20190901

my current query returns a random set of high dates between the union for some reason:

(SELECT * FROM Table WHERE Date BETWEEN 20200201 AND 20191201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)

Any idea where I am going wrong?

Body:
The issue was as jarlh pointed out, the order of the subquery's were not kept(thats why things were jumbled) and a simple ORDER BY of the whole UNION fixed this. I did not try Gordon's response as this solved my issue so:

(SELECT * FROM Table WHERE Date BETWEEN  20191201 AND 20200201)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)
ORDER BY Date ASC

Thank you


问:
Show and Hide tables with Bootstrap?
I'm currently designing a price table. The table will have three options:

Personal

Professional

Business

each of these options will be on a button. The idea is that when the user clicks on the corresponding button, the table of that plan will be shown.

How should this be done with bootstrap? using jquery?

My logic tells me that it should be something like having all 3 tables in the html and modifying the display attribute according to the button that is clicked. However, I am not entirely clear on this.

答:
you'll probably have to use JQuery indeed. You'll have the choice play with
hide() or show(), but, instead, I prefer to do it like this :

```<code>$("#personal_table_btn").on("click", function() {
    $("#personal_table").toggleClass("hidden");
});
</code>```

Bootstrap got a nice "hidden" class you can toggle, which is very convenient.

Concerning the html, well, you don't really want to load three racks of data when you just need one, so maybe do an ajax call to get only the one you need and display it ?

Title: Show and Hide tables with Bootstrap?

Body:
you'll probably have to use JQuery indeed. You'll have the choice play with
hide() or show(), but, instead, I prefer to do it like this :

$("#personal_table_btn").on("click", function() {
    $("#personal_table").toggleClass("hidden");
});

Bootstrap got a nice "hidden" class you can toggle, which is very convenient.

Concerning the html, well, you don't really want to load three racks of data when you just need one, so maybe do an ajax call to get only the one you need and display it ?


问:
Need Studies, Proof or Research That Show Image Copy Protection Is Not Worth It
I am trying to convince someone that image copy protection such as watermarks, javascript no right clicks, blank image overlays etc is not worth the effort since they are easily bypassed by even non-technical users.

I am also trying to convince them that these measures annoys customers as it impedes the user experience and does nothing to prevent image theft. At the end of the day if its on the internet, its public and people can take it if they want.

So what I'm looking for is a good study, proof, research, anything which has numbers to back up a fall in sales, user experience etc before and after these measures.

Any ideas?

答:
these measures annoys customers as it impedes the user experience

No it doesn't - since when does a properly positioned transparent overlay impede the user experience?

At the end of the day if its on the internet, its public and people can take it if they want.

It's publicly viewable, but it is not theirs to just take. The images are copyright, and subject to copyright laws and international treaties.

not worth the effort since they are easily bypassed by even non-technical users.

Yes this is correct, but those measures will avoid the majority of non-savvy users saving images, it won't stop the people who really want them.

The issue is not with people saving the images, because you have implicitly given them that permission by displaying it on the net (browsers download the image to a cache and then show it). The real issue is people using images illegally, without permission, which is incredibly hard to stop. There is every reason to take reasonable steps to protect your images, if you can stop the not-so-smart users doing it, then you've saved yourself a bit of a headache. For the people who insist on re-using your images, only direct legal action will work with any surety, as threats and complaints to ISPs can be a very hit and miss affair. So if you can mess things up by using discrete but effective watermarks, and obfuscating the source of the image and intefering with the user's ability to right click and save then do it.

But having said that, it's not going to help much when Google indexes your images and displays them when a user does an image search.

ContentLicense: CC BY-SA 3.0


问:
How to click on a drop-down menu item using selenium with python?
I tried to use xpath search but it didn't work for me. The idea is that I pass the mouse over "Nota Fiscal" and then go down with the mouse in the drop-down menu and click on "Emissão". The drop-down menu is inside a frame called "pag_principal" and the rest of the code (which is not here) works within that frame, that is, selenium has switched windows and frames correctly...
Inspect elements
My problem is: selenium.common.exceptions.ElementNotInteractableException: Message: Element  could not be scrolled into view.

How can i fix this?

The code I made to try is this:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys

bot.get('https://www.nfs-e.net/fiscalweb.php')
time.sleep(3)

campo_login = bot.find_element_by_xpath("//input[@name='login_temp']")
campo_login.clear()
campo_login.send_keys(self.usuario)
password = bot.find_element_by_xpath('//*[@id="passw_temp"]')
password.clear()
password.send_keys(self.senha)
password.send_keys(Keys.RETURN)
time.sleep(6)
# handling to new window
bot.switch_to.window(bot.window_handles[1])
bot.maximize_window()

def envio(self):
   bot = self.bot
   time.sleep(5)
   bot.switch_to.frame("pag_principal")
   time.sleep(2)

# this is the part that I want selenium to select the item "Emissão" in the drop-down menu "Nota Fiscal"

   Nota_fiscal = WebDriverWait(bot, 100000).until(EC.element_to_be_clickable((By.XPATH, "/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span"))).click()
   time.sleep(2)
   Emissão = bot.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span').click()
</code>```

[Trying by using select]

```<code>Menu = bot.find_element_by_class_name("menu")
mySelectElement = bot.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/a/span')
dropDownMenu = Select(mySelectElement)
WebDriverWait(bot, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span")))
dropDownMenu.select_by_visible_text('Emissão')
time.sleep(2)
Emissão = bot.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span').click()
</code>```

[I want to click on "Emissão" within the "Nota Fiscal" drop-down menu (I don't know how to edit html)]

Nota Fiscal Eletrônica

 Globais

Cadastros

Diversos

Alterar Senha/E-Mail

CPFCNPJ x Email

Procuração Digital

Pessoas/Endereços

Bairro

Logradouro

Pessoa

Estrangeiros

Consultas

Economico

Atividades

Cadastro Econômico

Pessoas/Endereços

Cidade

Pessoa

Estrangeiros

Autorização

Solicitação de Cancelamento de NFSe

Utilização de NFSe

Configurações

Cabeçalho da NFSe

Consulta

NFS-e Prestadas

NFS-e Tomadas

Nota Fiscal

**Emissão**

Cancelamento

Gerenciamento de Notas

Exportação

         Sair

         <input type="text" id="container_pesquisa" name="container_pesquisa" class="container_busca campo_externo_suggest" placeholder="Pesquisa" onfocus="focusPesquisa(this, 'in')" onblur="focusPesquisa(this, 'out')" suggest="true" autocomplete="off">

```

<p>First I need to hover over these elements for the drop-down menu to appear</p>

<pre class="lang-html prettyprint-override"><code><span>Nota Fiscal</span>
</code>```

And the element I want to click on is this

Emissão
```

答:
Your xpath is completely wrong. Of course nothing is going to happen when you press a span. Try clicking its parent that is an

And try using proper xpaths and not just something you copy pasted from the browser.

```<code>//span[@class='span_menu' and @title='Emissão']::parent/a
</code>```

I repeat. If you provide a minimal HTML example. It will be much easier to help you.

Body:
I tried to use xpath search but it didn't work for me. The idea is that I pass the mouse over "Nota Fiscal" and then go down with the mouse in the drop-down menu and click on "Emissão". The drop-down menu is inside a frame called "pag_principal" and the rest of the code (which is not here) works within that frame, that is, selenium has switched windows and frames correctly...
Inspect elements
My problem is: selenium.common.exceptions.ElementNotInteractableException: Message: Element  could not be scrolled into view.

How can i fix this?

The code I made to try is this:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys

bot.get('https://www.nfs-e.net/fiscalweb.php')
time.sleep(3)

campo_login = bot.find_element_by_xpath("//input[@name='login_temp']")
campo_login.clear()
campo_login.send_keys(self.usuario)
password = bot.find_element_by_xpath('//*[@id="passw_temp"]')
password.clear()
password.send_keys(self.senha)
password.send_keys(Keys.RETURN)
time.sleep(6)
# handling to new window
bot.switch_to.window(bot.window_handles[1])
bot.maximize_window()

def envio(self):
   bot = self.bot
   time.sleep(5)
   bot.switch_to.frame("pag_principal")
   time.sleep(2)

# this is the part that I want selenium to select the item "Emissão" in the drop-down menu "Nota Fiscal"

   Nota_fiscal = WebDriverWait(bot, 100000).until(EC.element_to_be_clickable((By.XPATH, "/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span"))).click()
   time.sleep(2)
   Emissão = bot.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span').click()

[Trying by using select]

Menu = bot.find_element_by_class_name("menu")
mySelectElement = bot.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/a/span')
dropDownMenu = Select(mySelectElement)
WebDriverWait(bot, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span")))
dropDownMenu.select_by_visible_text('Emissão')
time.sleep(2)
Emissão = bot.find_element_by_xpath('/html/body/table/tbody/tr[1]/td/div/div/ul[1]/li[5]/div/ul/li[1]/a/span').click()

[I want to click on "Emissão" within the "Nota Fiscal" drop-down menu (I don't know how to edit html)]

Nota Fiscal Eletrônica

 Globais

Cadastros

Diversos

Alterar Senha/E-Mail

CPFCNPJ x Email

Procuração Digital

Pessoas/Endereços

Bairro

Logradouro

Pessoa

Estrangeiros

Consultas

Economico

Atividades

Cadastro Econômico

Pessoas/Endereços

Cidade

Pessoa

Estrangeiros

Autorização

Solicitação de Cancelamento de NFSe

Utilização de NFSe

Configurações

Cabeçalho da NFSe

Consulta

NFS-e Prestadas

NFS-e Tomadas

Nota Fiscal

**Emissão**

Cancelamento

Gerenciamento de Notas

Exportação

         Sair

         <input type="text" id="container_pesquisa" name="container_pesquisa" class="container_busca campo_externo_suggest" placeholder="Pesquisa" onfocus="focusPesquisa(this, 'in')" onblur="focusPesquisa(this, 'out')" suggest="true" autocomplete="off">

First I need to hover over these elements for the drop-down menu to appear

Nota Fiscal

And the element I want to click on is this

Emissão

Body:
Your xpath is completely wrong. Of course nothing is going to happen when you press a span. Try clicking its parent that is an <a>

And try using proper xpaths and not just something you copy pasted from the browser.

//span[@class='span_menu' and @title='Emissão']::parent/a

I repeat. If you provide a minimal HTML example. It will be much easier to help you.


问:
Flink state restore problems with value state of custom object
For Flink checkpoint restore from savepoint, it runs normally When we use value state of java basic type, but it throws Exception when using value state of java object which may be in-built or custom. What's the key solution for it? Any idea will be appreciated.

code like:

```<code>var playUVState: ValueState[BigInteger] = _
</code>```

```<code>override def open(parameters: Configuration): Unit = {
    playUVState = getRuntimeContext.getState(new ValueStateDescriptor[BigInteger]("playUVState", new BigIntSerializer()))
}
</code>```

Exception when restoring from savepoint path:

```<code>java.lang.Exception: Exception while creating StreamOperatorStateContext.
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:195)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState(AbstractStreamOperator.java:250)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeState(StreamTask.java:738)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:289)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:704)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.flink.util.FlinkException: Could not restore keyed state backend for LegacyKeyedProcessOperator_306d8342cb5b2ad8b53f1be57f65bee8_(28/32) from any of the 1 provided restore options.
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:137)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.keyedStatedBackend(StreamTaskStateInitializerImpl.java:284)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:135)
    ... 5 more
Caused by: java.lang.NullPointerException
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readKeyGroupStateData(HeapKeyedStateBackend.java:479)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readStateHandleStateData(HeapKeyedStateBackend.java:453)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restorePartitionedState(HeapKeyedStateBackend.java:410)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:358)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:104)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.attemptCreateAndRestore(BackendRestorerProcedure.java:151)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:123)
    ... 7 more
</code>```

答:
I tried to reproduce the error you reported, using Flink 1.10 but was not able to. In general, the error you are seeing means that some key group was not found in the snapshot which could mean that either the file is corrupt, the TaskManager got the wrong file, or a serializer screwed things up. Since you are using the BigIntSerializer, this seems correct.

Judging from the stacktrace you provided, it looks like you are using Flink 1.7.2. Can you verify the same behaviour in Flink 1.10? If this still persists, I would be very much interested in getting a reproducible minimal (working) example which experiences this error.

Body:
For Flink checkpoint restore from savepoint, it runs normally When we use value state of java basic type, but it throws Exception when using value state of java object which may be in-built or custom. What's the key solution for it? Any idea will be appreciated.

code like:

var playUVState: ValueState[BigInteger] = _

override def open(parameters: Configuration): Unit = {
    playUVState = getRuntimeContext.getState(new ValueStateDescriptor[BigInteger]("playUVState", new BigIntSerializer()))
}

Exception when restoring from savepoint path:

java.lang.Exception: Exception while creating StreamOperatorStateContext.
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:195)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState(AbstractStreamOperator.java:250)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeState(StreamTask.java:738)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:289)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:704)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.flink.util.FlinkException: Could not restore keyed state backend for LegacyKeyedProcessOperator_306d8342cb5b2ad8b53f1be57f65bee8_(28/32) from any of the 1 provided restore options.
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:137)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.keyedStatedBackend(StreamTaskStateInitializerImpl.java:284)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:135)
    ... 5 more
Caused by: java.lang.NullPointerException
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readKeyGroupStateData(HeapKeyedStateBackend.java:479)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readStateHandleStateData(HeapKeyedStateBackend.java:453)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restorePartitionedState(HeapKeyedStateBackend.java:410)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:358)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:104)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.attemptCreateAndRestore(BackendRestorerProcedure.java:151)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:123)
    ... 7 more


问:
Create wide (desummarized) R data.table
I have a compact data.frame or data.table containing row-wise info on ranges (dt.compact).

```<code>dt.compact = data.table(chr=c('chr1','chr1','chr2','chr2'),start = c(1,5,2,7), stop = c(3,7,3,8))

# Output dt.compact
 chr start stop
1: chr1     1    3
2: chr1     5    7
3: chr2     2    3
4: chr2     7    8
</code>```

Now, I want a simple way to generate a wide data.frame or table with one row per position. Output should look like following:

```<code># Output
do.call(data.table, list(V1 = c(rep('chr1', 6),rep('chr2', 4)), V2 = c(1:3, 5:7, 2:3, 7:8)))

     V1 V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

</code>```

Any suggestions how to achieve this? I thought about mapply (myOwnFunction, ...), but maybe there is already a built-in solution?

Any thoughts are wellcome

答:
Try this:

```<code>dt.compact[, .(chr, seq.int(start, stop)), by = 1:nrow(dt.compact)][, nrow := NULL][]

     chr V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8
</code>```

OR:

```<code>dt.new = dt.compact[, .(chr, seq.int(start, stop)), by = 1:nrow(dt.compact)][, nrow := NULL]
dt.new
    chr V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8
</code>```

The column names can be changed easily.

Title: Create wide (desummarized) R data.table

Body:
I have a compact data.frame or data.table containing row-wise info on ranges (dt.compact).

dt.compact = data.table(chr=c('chr1','chr1','chr2','chr2'),start = c(1,5,2,7), stop = c(3,7,3,8))

# Output dt.compact
 chr start stop
1: chr1     1    3
2: chr1     5    7
3: chr2     2    3
4: chr2     7    8

Now, I want a simple way to generate a wide data.frame or table with one row per position. Output should look like following:

# Output
do.call(data.table, list(V1 = c(rep('chr1', 6),rep('chr2', 4)), V2 = c(1:3, 5:7, 2:3, 7:8)))

     V1 V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

Any suggestions how to achieve this? I thought about mapply (myOwnFunction, ...), but maybe there is already a built-in solution?

Any thoughts are wellcome

Body:
Try this:

dt.compact[, .(chr, seq.int(start, stop)), by = 1:nrow(dt.compact)][, nrow := NULL][]

     chr V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

OR:

dt.new = dt.compact[, .(chr, seq.int(start, stop)), by = 1:nrow(dt.compact)][, nrow := NULL]
dt.new
    chr V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

The column names can be changed easily.


问:
Runing Angular i18 builds in parallel
I have support for 11 languages in my Angular app and I'm using Angular's built-in internationalization(XLF files). It takes forever to do a release(since it builds the app 11 times!). How can I run the build tasks in parallel(I have a 4-core CPU)?</p>

答:
For documentation: my approach of above in a Jenkins pipeline

```<code>def knownLocales = ["en-CH","en-US","en-GB","de-CH","de-DE"]
def ngAotBuildMap = [:]

steps {
    script {
        for (aot_locale in knownLocales) {
            // beware of how Groovy creates closures in loops
            String aotLocaleClosure = "${aot_locale}"

            ngAotBuildMap[aot_locale] = {
                sh """
                    echo "Building locale ${aotLocaleClosure}"
                    cd $WORKSPACE/webclient
                    rm -R -f $WORKSPACE/webclient/dist/${aotLocaleClosure}/
                    ng build --no-progress --configuration=${params.PARAM_SPRING_PROFILE}-${aotLocaleClosure}
                """
            }
        }

        // https://stackoverflow.com/questions/37333796/using-failfast-with-closure-map-breaks-parallel-step/37356318
        ngAotBuildMap.failFast = true
        parallel ngAotBuildMap
    }
}
</code>```

However: with sequential build, 1 AOT build took 3min 30s, total of about 18min for 5 locales. With above script, 1 AOT build takes 15min 30s, total time is pretty much unchanged. I'm guessing in my case the server resources are already maxed out in sequential build, so parallel build doesn't add much.

Title: Runing Angular i18 builds in parallel

Body:
For documentation: my approach of above in a Jenkins pipeline

def knownLocales = ["en-CH","en-US","en-GB","de-CH","de-DE"]
def ngAotBuildMap = [:]

steps {
    script {
        for (aot_locale in knownLocales) {
            // beware of how Groovy creates closures in loops
            String aotLocaleClosure = "${aot_locale}"

            ngAotBuildMap[aot_locale] = {
                sh """
                    echo "Building locale ${aotLocaleClosure}"
                    cd $WORKSPACE/webclient
                    rm -R -f $WORKSPACE/webclient/dist/${aotLocaleClosure}/
                    ng build --no-progress --configuration=${params.PARAM_SPRING_PROFILE}-${aotLocaleClosure}
                """
            }
        }

        // https://stackoverflow.com/questions/37333796/using-failfast-with-closure-map-breaks-parallel-step/37356318
        ngAotBuildMap.failFast = true
        parallel ngAotBuildMap
    }
}

However: with sequential build, 1 AOT build took 3min 30s, total of about 18min for 5 locales. With above script, 1 AOT build takes 15min 30s, total time is pretty much unchanged. I'm guessing in my case the server resources are already maxed out in sequential build, so parallel build doesn't add much.


问:
Semicolon issue in SQL script
I need to update a column value with a stored procedure which contains a semicolon, and this is causing an issue "quoted string not properly ended".

Connected to server using Putty and executing command using SQL Plus

Tried to use /; but it didn't work

```<code>update dummy_table
  set
  col1 = 0, col2 = null, col3 = to_clob(
    'declare
    source_table varchar2(40) := :par1;
    target_table_name varchar2(40) := :par2;
    '||'
    begin  '||'
    select * from temp_table;
    end;
    '||'/'
  ), col4 = null
  where col5 = 'value_1' and col6 = 'value_7';
</code>```

ER: Command should get execute successfully and it should update col3 with given value

AR: Quoted String not properly ended

答:
```<code>set sqlterminator off
update dummy_table
  set
  col1 = 0, col2 = null, col3 = to_clob(
    'declare
    source_table varchar2(40) := :par1;
    target_table_name varchar2(40) := :par2;
    '||'
    begin  '||'
    select * from temp_table;
    end;
    '||'/'
  ), col4 = null
  where col5 = 'value_1' and col6 = 'value_7'
/
set sqlterminator on
</code>```

Title: Semicolon issue in SQL script

Body:
I need to update a column value with a stored procedure which contains a semicolon, and this is causing an issue "quoted string not properly ended".

Connected to server using Putty and executing command using SQL Plus

Tried to use /; but it didn't work

update dummy_table
  set
  col1 = 0, col2 = null, col3 = to_clob(
    'declare
    source_table varchar2(40) := :par1;
    target_table_name varchar2(40) := :par2;
    '||'
    begin  '||'
    select * from temp_table;
    end;
    '||'/'
  ), col4 = null
  where col5 = 'value_1' and col6 = 'value_7';

ER: Command should get execute successfully and it should update col3 with given value

AR: Quoted String not properly ended


问:
Notification in TabActivity in Android
I have TabActivity which has 4 tabs. I wnat to give notification on tab. One is Missed call tab on which I want to show unread count as shown in screenshots of

https://market.android.com/details?id=se.alexanderblom.gmailunreadcount&feature=search_result

Unread count in this image is on application icon but i want it on tab as similar to badge in iphone i want in android.

Can you give reference of any tutorial or tell in how to do this?

答: Use the version of setIndicator() on your TabSpec that takes a custom View that you create (e.g., inflate from a layout file). Then, you can get that View later on by calling getChildTabViewAt() on your TabWidget. You can then update your indicator as you see fit.

Title: Notification in TabActivity in Android


问:
how to specify cell execution in jupyter notebook
I want to run cell 2,3,etc and get the output then execute cell 1.

I am wondering whether it is possible?

答:
You can do this with extensions, you can also reorder them such that the first cell you want to execute becomes the final cell and so this executes in sequential order.

Have a look on init_cell extension. It allows you to mark some cells and run them on load\demand.

Here is the installation instructions.


问:
React - Secure login using a API with windows authentication
I've created and testing my API which responds with authorized  or not-authorized when the credentials have been typed in. I have tested this with postman and works perfectly.

The login I am trying to create is on React and is currently looking like this -

```<code>import React, { Component } from "react";
import { Button, Form, FormGroup, Input } from "reactstrap";
import { withRouter } from "react-router-dom";
import auth from "./auth";

export class Login extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    login = () => {
        auth.login();
    };

    handleSubmit(event) {
        event.preventDefault();
        fetch('http://localhost:5000/api/LoginTest', {
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            body: {
                "username": this.username.value,
                "password": this.username.value
            }
        });
    };

    render() {
        return (
            <div className="Login">
                <form onSubmit={this.handleSubmit}>
                        <h2 id="formTitle" className="text-center">
                        Admin Panel
          </h2>
                        <input
                            id="inputUsername"
                            type="text"
                            placeholder="Username"
                            name="username"
                            ref={(ref) => { this.username = ref }}
                        />

                        <input
                            id="inputPassword"
                            type="password"
                            placeholder="Password"
                            name="password"
                            ref={(ref) => { this.password = ref }}
                        />

                    <button
id="button"
                        type="submit"
                        className="btn btn-block btn-success"
                    >
                        Sign-in
          </button>
                </form>
            </div>
        );
    }
}
export default withRouter(Login);

</code>```

The 2 errors which I'm currently getting are -

415 Unsupported Media Type
OR
When I use mode: no-cors

Acces to fetch at "" from origin has been blocked by the CORS policy

Any help on this would be perfect!

答:
In your fetch options, try setting:
mode: 'cors'

Also make sure that you stringify() your body data

Take a look at this example on the MDN site

Body:
I've created and testing my API which responds with authorized  or not-authorized when the credentials have been typed in. I have tested this with postman and works perfectly.

The login I am trying to create is on React and is currently looking like this -

import React, { Component } from "react";
import { Button, Form, FormGroup, Input } from "reactstrap";
import { withRouter } from "react-router-dom";
import auth from "./auth";

export class Login extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    login = () => {
        auth.login();
    };

    handleSubmit(event) {
        event.preventDefault();
        fetch('http://localhost:5000/api/LoginTest', {
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            body: {
                "username": this.username.value,
                "password": this.username.value
            }
        });
    };

    render() {
        return (

                <form onSubmit={this.handleSubmit}>

                        Admin Panel

                        <input
                            id="inputUsername"
                            type="text"
                            placeholder="Username"
                            name="username"
                            ref={(ref) => { this.username = ref }}
                        />

                        <input
                            id="inputPassword"
                            type="password"
                            placeholder="Password"
                            name="password"
                            ref={(ref) => { this.password = ref }}
                        />

                    <button
id="button"
                        type="submit"
                        className="btn btn-block btn-success"
                    >
                        Sign-in
          </button>
                </form>

        );
    }
}
export default withRouter(Login);

The 2 errors which I'm currently getting are -

415 Unsupported Media Type
OR
When I use mode: no-cors

Acces to fetch at "" from origin has been blocked by the CORS policy

Any help on this would be perfect!


问:
How to combine and filter two dart Streams
I am using flutter_blue for a flutter Application using bluetooth.

flutter_blue presents me with two streams:
   FlutterBlue.instance.connectedDevices
   FlutterBlue.instance.scanResults

I would like to combine those two streams into one and apply a filter.

Googling around I get references to rxdart but still,, I cant get it to work.
Help please :)

答:
I think what you want is StreamGroup from Dart's async package.

The StreamGroup class merges a collection of streams into a single output stream.

It should be pretty easy, you just take your streams and use the StreamGroup.merge(...) method, passing the list of streams you want to merge. Take a look at this example:

import 'dart:async' show Stream;
import 'package:async/async.dart' show StreamGroup;

main() async {
  var s1 = stream(10);
  var s2 = stream(20);
  var s3 = StreamGroup.merge([s1, s2]);
  await for(int val in s3) {
    print(val);
  }
}

Stream<int> stream(int min) async* {
  int i = min;
  while(i < min + 3) {
    yield i++;
  }
}
```

<p>which would print:</p>

<pre class="lang-dart prettyprint-override"><code>10
20
11
21
12
22
</code>```

Once you have merged them, you can use standard Stream methods, such as map(...) to apply your filter in the way you want.

Body:
I think what you want is StreamGroup from Dart's async package.

The StreamGroup class merges a collection of streams into a single output stream.

It should be pretty easy, you just take your streams and use the StreamGroup.merge(...) method, passing the list of streams you want to merge. Take a look at this example:

import 'dart:async' show Stream;
import 'package:async/async.dart' show StreamGroup;

main() async {
  var s1 = stream(10);
  var s2 = stream(20);
  var s3 = StreamGroup.merge([s1, s2]);
  await for(int val in s3) {
    print(val);
  }
}

Stream<int> stream(int min) async* {
  int i = min;
  while(i < min + 3) {
    yield i++;
  }
}

which would print:

10
20
11
21
12
22

Once you have merged them, you can use standard Stream methods, such as map(...) to apply your filter in the way you want.


问:
Windows10 WSL2 Ubuntu / Debian # no network
After upgrading from WSL to WSL2

```<code>sudo apt-get update
</code>```

not works any longer. After:

wsl --set-version Ubuntu-18.04 2

Output is:

```<code>> sudo apt-get update
Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
  Temporary failure resolving 'security.ubuntu.com'
Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Reading package lists... Done
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-updates/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-backports/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/bionic-security/InRelease  Temporary failure resolving 'security.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.
</code>```

After going back to WSL1 the problem disappears again. Same on Debian and analogous in CentOS .. so WSL2 must have a bug.

The Windows10 build Version is 19041 and was installed today.

Any work around for WSL2?
Regards

答:
The generated file /etc/resolv.conf is:

nameserver 172.24.0.1

..had to change it to

nameserver 8.8.8.8

which resolves the problem

Body:
After upgrading from WSL to WSL2

sudo apt-get update

not works any longer. After:

wsl --set-version Ubuntu-18.04 2

Output is:

> sudo apt-get update
Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
  Temporary failure resolving 'security.ubuntu.com'
Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Reading package lists... Done
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-updates/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-backports/InRelease  Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/bionic-security/InRelease  Temporary failure resolving 'security.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.

After going back to WSL1 the problem disappears again. Same on Debian and analogous in CentOS .. so WSL2 must have a bug.

The Windows10 build Version is 19041 and was installed today.

Any work around for WSL2?
Regards


问:
Capture Total Time or duration of a Test Suite using Jasmine Hook
I have been trying to retrieve 'totalTime' from the jasmineDone hook or 'duration' from SuiteResult as documented at [https://jasmine.github.io/api/edge/global.html#] but they don't seem to be available. Would be grateful for any pointers?

I found @DublinDev answer to this Jasmine get current test result which was so helpful. This allows me to get the duration per test using the specDone hook which I could potentially use and add each result, but I am curious to know if I am doing something wrong.

I am using the following code from the link above( 2nd link) and would expect either of the console.logs to output a time but neither are outputting anything

```<code>function dbReporter() {

  this.jasmineStarted = function (options) { };

  this.specStarted = function (result) { };

  this.specDone = async function (result) { };

  this.suiteStarted = function (result) { };

  this.suiteDone = function (result) {
    console.log('duration=', result.duration)
  }
  this.jasmineDone = async function (result) {
    console.log('totalTime=', result.totalTime)
  }
}

module.exports = dbReporter;
</code>```

答:
Given that you have the latest version of Jasmine already I would recommend just making your own timer which starts in jasmineStarted hook and ends in JasmineDone hook.

```<code>onPrepare: () => {

    //Create a global variable to be used for the timer
    global.jasmineTimer = 0;

    jasmine.getEnv().addReporter({
        jasmineStarted: function (options) {
            jasmineTimer = Date.now();
            console.log(`Starting execution ${jasmineTimer}`)
        },
        jasmineDone: async function (result) {

            console.log(`Finished execution in ${(Date.now() - jasmineTimer) / 1000}s`)
        }
    })
}
</code>```

Body:
I have been trying to retrieve 'totalTime' from the jasmineDone hook or 'duration' from SuiteResult as documented at [https://jasmine.github.io/api/edge/global.html#] but they don't seem to be available. Would be grateful for any pointers?

I found @DublinDev answer to this Jasmine get current test result which was so helpful. This allows me to get the duration per test using the specDone hook which I could potentially use and add each result, but I am curious to know if I am doing something wrong.

I am using the following code from the link above( 2nd link) and would expect either of the console.logs to output a time but neither are outputting anything

function dbReporter() {

  this.jasmineStarted = function (options) { };

  this.specStarted = function (result) { };

  this.specDone = async function (result) { };

  this.suiteStarted = function (result) { };

  this.suiteDone = function (result) {
    console.log('duration=', result.duration)
  }
  this.jasmineDone = async function (result) {
    console.log('totalTime=', result.totalTime)
  }
}

module.exports = dbReporter;

Body:
Given that you have the latest version of Jasmine already I would recommend just making your own timer which starts in jasmineStarted hook and ends in JasmineDone hook.

onPrepare: () => {

    //Create a global variable to be used for the timer
    global.jasmineTimer = 0;

    jasmine.getEnv().addReporter({
        jasmineStarted: function (options) {
            jasmineTimer = Date.now();
            console.log(`Starting execution ${jasmineTimer}`)
        },
        jasmineDone: async function (result) {

            console.log(`Finished execution in ${(Date.now() - jasmineTimer) / 1000}s`)
        }
    })
}


问:
Clear form's TextInput when i press connection button
I'm doing a connection interface in react native using php and sql server .

My problem is :
once i connect and access the application, if i press the return button on my phone, i find the form of login still filled with my name and password .

Is there any solution to clear my form's textInput once I press the connection button?

There is my code of react native :

```<code>export default class Home extends React.Component {
  constructor(props){
       super(props)
       this.state={
         username:'',
         usermail:'',
         password:'',
         secureTextEntry:true,
         iconName:"eye"}}

    userRegister = () =>{
   const {username}=this.state;
   const {usermail}=this.state;
   const {password}=this.state;
  this.setState({password:''});

   fetch('http://192.168.1.4:80/recup.php',{
   method:'post',
   header:{
   'Accept':'application/json',
   'Content-type' :'application/json'
   },
   body:JSON.stringify({email:usermail,password:password})})
   .then((responseData)=>responseData.text())
   .then((responseJson)=>{
    }}).catch((error)=>{console.error(error);})
   }
    render() {
        return (
            <View style={styles.container}>
            <TextInput placeholder="Enter mail"  style={styles.input}
            onChangeText= {usermail=>this.setState({usermail })}/>

            <View style={styles.pass}>

        <TextInput placeholder="Enter password" style={{flex:1}} secureTextEntry={this.state.secureTextEntry}
        onChangeText= {password=>this.setState({password})}
        />

            <TouchableOpacity onPress={this.secure} style={{margin:20}}>
            <Icon name="eye" size={20}  /></TouchableOpacity>
            </View>

            <TouchableOpacity style={styles.butt} onPress={this.userRegister}>
                <Text>Connexion</Text>
            </TouchableOpacity>

            </View>
        );

    }

}
</code>```

and this is my login page to better understand my problem :

答:
Change your userRegister function to:

```<code>const userRegister = () =>{
   const username = this.state.username;
   const usermail = this.state.usermail;
   const password = this.state.password;

   this.setState({
      username:'',
      usermail:'',
      password:'',
   });

   fetch('http://192.168.1.4:80/recup.php',{
     method:'post',
     header:{
     'Accept':'application/json',
     'Content-type' :'application/json'
   },
   body:JSON.stringify({email:usermail,password:password})})
     .then((responseData)=>responseData.text())
     .then((responseJson)=>{
        // Success Response
      }})
     .catch((error)=>{console.error(error);})
}
</code>```

Body:
I'm doing a connection interface in react native using php and sql server .

My problem is :
once i connect and access the application, if i press the return button on my phone, i find the form of login still filled with my name and password .

Is there any solution to clear my form's textInput once I press the connection button?

There is my code of react native :

export default class Home extends React.Component {
  constructor(props){
       super(props)
       this.state={
         username:'',
         usermail:'',
         password:'',
         secureTextEntry:true,
         iconName:"eye"}}

    userRegister = () =>{
   const {username}=this.state;
   const {usermail}=this.state;
   const {password}=this.state;
  this.setState({password:''});

   fetch('http://192.168.1.4:80/recup.php',{
   method:'post',
   header:{
   'Accept':'application/json',
   'Content-type' :'application/json'
   },
   body:JSON.stringify({email:usermail,password:password})})
   .then((responseData)=>responseData.text())
   .then((responseJson)=>{
    }}).catch((error)=>{console.error(error);})
   }
    render() {
        return (
            <View style={styles.container}>
            <TextInput placeholder="Enter mail"  style={styles.input}
            onChangeText= {usermail=>this.setState({usermail })}/>

            <View style={styles.pass}>

        <TextInput placeholder="Enter password" style={{flex:1}} secureTextEntry={this.state.secureTextEntry}
        onChangeText= {password=>this.setState({password})}
        />

            <TouchableOpacity onPress={this.secure} style={{margin:20}}>
            <Icon name="eye" size={20}  /></TouchableOpacity>
            </View>

            <TouchableOpacity style={styles.butt} onPress={this.userRegister}>
                <Text>Connexion</Text>
            </TouchableOpacity>

            </View>
        );

    }

}

and this is my login page to better understand my problem :

Body:
Change your userRegister function to:

const userRegister = () =>{
   const username = this.state.username;
   const usermail = this.state.usermail;
   const password = this.state.password;

   this.setState({
      username:'',
      usermail:'',
      password:'',
   });

   fetch('http://192.168.1.4:80/recup.php',{
     method:'post',
     header:{
     'Accept':'application/json',
     'Content-type' :'application/json'
   },
   body:JSON.stringify({email:usermail,password:password})})
     .then((responseData)=>responseData.text())
     .then((responseJson)=>{
        // Success Response
      }})
     .catch((error)=>{console.error(error);})
}


问:
Dropdown menu behind text
I tried to create a drop down menu. That's what I did so far:
http://gegensinn.org/test.html
(I made the drop down menu visible at all time for "debugging")

I think the problem is quite obvious: The menu is behind the text.

First I thought I could fix this with z-index.

Although I'm not quite sure which element has to get the z-index property.

I tried to set the whole menu to z-index:100; and at the same time set the z-index:1; of  .main.

Afterwards I tried to set only the z-index of
 and   but nothing worked.

答:
I think applying z-index like so should work.

CSS

```<code>#menu a
{
  z-index: 100;
}

#menu ul li ul
{
  position: absolute;
}

#main
{
  z-index: 10;
}
</code>```

Some browsers ignore z-index if it is not set on both elements in question.

Title: Dropdown menu behind text

Body:
I think applying z-index like so should work.

CSS

#menu a
{
  z-index: 100;
}

#menu ul li ul
{
  position: absolute;
}

#main
{
  z-index: 10;
}

Some browsers ignore z-index if it is not set on both elements in question.


问:
"Cannot read property 'match' of undefined" during Npm install
I encountered error during  building Jenkins

Jenkins Log

Task :api:processResources
Task :api:classes
Task :web:nodeSetup
Task :web:npmSetup /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npm
-> /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/lib/node_modules/npm/bin/npm-cli.js
/var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npx
-> /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/lib/node_modules/npm/bin/npx-cli.js

npm@6.11.2 added 430 packages from 832 contributors in 6.837s

Task :web:npmInstall FAILED npm ERR! Cannot read property 'match' of undefined

npm ERR! A complete log of this run can be found in: npm ERR!

/var/lib/jenkins/.npm/_logs/2019-10-16T01_11_20_594Z-debug.log

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':web:npmInstall'.

Process 'command '/var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npm''
finished with non-zero exit value 1

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it
incompatible with Gradle 6.0. Use '--warning-mode all' to show the
individual deprecation warnings. See
https://docs.gradle.org/5.0/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 33s

/var/lib/jenkins/.npm/_logs/2019-10-16T01_11_20_594Z-debug.log

```<code>17 silly saveTree   │ ├─┬ clean-css@4.2.1
17 silly saveTree   │ │ └── source-map@0.6.1
17 silly saveTree   │ ├── commander@2.17.1
17 silly saveTree   │ └── he@1.2.0
17 silly saveTree   └─┬ loader-utils@0.2.17
17 silly saveTree     ├── big.js@3.2.0
17 silly saveTree     ├── emojis-list@2.1.0
17 silly saveTree     └── json5@0.5.1
18 verbose stack TypeError: Cannot read property 'match' of undefined
18 verbose stack     at tarballToVersion (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:87:20)
18 verbose stack     at inflatableChild (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:99:22)
18 verbose stack     at BB.each (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:55:12)
18 verbose stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
18 verbose stack     at Object.gotValue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/reduce.js:155:18)
18 verbose stack     at Object.gotAccum (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/reduce.js:144:25)
18 verbose stack     at Object.tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
18 verbose stack     at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
18 verbose stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
18 verbose stack     at Promise._settlePromiseCtx (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:606:10)
18 verbose stack     at _drainQueueStep (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:142:12)
18 verbose stack     at _drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:131:9)
18 verbose stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:147:5)
18 verbose stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
18 verbose stack     at runCallback (timers.js:810:20)
18 verbose stack     at tryOnImmediate (timers.js:768:5)
19 verbose cwd /var/lib/jenkins/workspace/hds_v2_docker/web
20 verbose Linux 4.4.0-59-generic
21 verbose argv "/usr/bin/node" "/usr/local/bin/npm" "install"
22 verbose node v8.16.0
23 verbose npm  v6.9.0
24 error Cannot read property 'match' of undefined
25 verbose exit [ 1, true ]
</code>```

答:
You have to remove both package-lock.json and node_modules/.

If you don't remove both, the problem will come back on the next npm install.

Body:
I encountered error during  building Jenkins

Jenkins Log

Task :api:processResources
Task :api:classes
Task :web:nodeSetup
Task :web:npmSetup /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npm
-> /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/lib/node_modules/npm/bin/npm-cli.js
/var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npx
-> /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/lib/node_modules/npm/bin/npx-cli.js

npm@6.11.2 added 430 packages from 832 contributors in 6.837s

Task :web:npmInstall FAILED npm ERR! Cannot read property 'match' of undefined

npm ERR! A complete log of this run can be found in: npm ERR!

/var/lib/jenkins/.npm/_logs/2019-10-16T01_11_20_594Z-debug.log

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':web:npmInstall'.

Process 'command '/var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npm''
finished with non-zero exit value 1

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it
incompatible with Gradle 6.0. Use '--warning-mode all' to show the
individual deprecation warnings. See
https://docs.gradle.org/5.0/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 33s

/var/lib/jenkins/.npm/_logs/2019-10-16T01_11_20_594Z-debug.log

17 silly saveTree   │ ├─┬ clean-css@4.2.1
17 silly saveTree   │ │ └── source-map@0.6.1
17 silly saveTree   │ ├── commander@2.17.1
17 silly saveTree   │ └── he@1.2.0
17 silly saveTree   └─┬ loader-utils@0.2.17
17 silly saveTree     ├── big.js@3.2.0
17 silly saveTree     ├── emojis-list@2.1.0
17 silly saveTree     └── json5@0.5.1
18 verbose stack TypeError: Cannot read property 'match' of undefined
18 verbose stack     at tarballToVersion (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:87:20)
18 verbose stack     at inflatableChild (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:99:22)
18 verbose stack     at BB.each (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:55:12)
18 verbose stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
18 verbose stack     at Object.gotValue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/reduce.js:155:18)
18 verbose stack     at Object.gotAccum (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/reduce.js:144:25)
18 verbose stack     at Object.tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
18 verbose stack     at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
18 verbose stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
18 verbose stack     at Promise._settlePromiseCtx (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:606:10)
18 verbose stack     at _drainQueueStep (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:142:12)
18 verbose stack     at _drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:131:9)
18 verbose stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:147:5)
18 verbose stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
18 verbose stack     at runCallback (timers.js:810:20)
18 verbose stack     at tryOnImmediate (timers.js:768:5)
19 verbose cwd /var/lib/jenkins/workspace/hds_v2_docker/web
20 verbose Linux 4.4.0-59-generic
21 verbose argv "/usr/bin/node" "/usr/local/bin/npm" "install"
22 verbose node v8.16.0
23 verbose npm  v6.9.0
24 error Cannot read property 'match' of undefined
25 verbose exit [ 1, true ]


问:
Springboot Web Security Configuration not redirecting to login page
I created a small application to learn sprint boot web security. The sample application is mostly inspired from partial instructions provided in "Spring Boot in Action" book.

The problem I am facing is that inspite of configuring access like below, when I open http://localhost:8080/readers/ishwar the application doesn't navigate to login page. It straightaway opens the page represented by http://localhost:8080/readers/ishwar. As far as I have understood the spring security if .access("") is applied then in order to check access by default spring should redirect the user to login page. But it is not.

```<code>package com.example.readingList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.
                authorizeRequests()
                    .antMatchers("/readers").access("hasRole('READER')")
                    .antMatchers("/login").permitAll()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .failureUrl("/login?error=true");

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return readerRepository.getOne(username);
            }
        });
    }
}
</code>```

BUT if I change the code to below then on browsing http://localhost:8080/readers/ishwar I get redirected to login page. What is wrong in first construct? I mean why .access("") is not working

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.
                authorizeRequests()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .failureUrl("/login?error=true");

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return readerRepository.getOne(username);
            }
        });
    }
}
</code>```

Below is how ReaderRepository written

```<code>package com.example.readingList;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ReaderRepository extends JpaRepository<Reader, String> {

}
</code>```

Below is Reader Class. I have deliberately granted "WRITER" role as I want to see that attempt to access page should fail as READER permission is missing. But as such even if I include "READER" permission there is no change in behaviour.

```<code>package com.example.readingList;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Arrays;
import java.util.Collection;

@Entity
public class Reader implements UserDetails {

    private static final long serialVersionUID = 1L;

    @Id
    private String username;
    private String password;
    private String fullname;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("WRITER"));
    }

    //@Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    //@Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getFullname()
    {
        return fullname;
    }

    public void setFullname(String fullname)
    {
        this.fullname = fullname;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
</code>```

Kindly note that I haven't implemented the data source to store/fetch user and password. I was expecting to see at least the redirection to http://localhost:8080/login first but not happening if I use first construct.

Below is my pom.xml file

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

```<code><groupId>com.example</groupId>
<artifactId>readingList</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>readingList</name>
<description>Reading List project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

The ReadingListApplication class

```<code>@Configuration
@SpringBootApplication
public class ReadingListApplication implements WebMvcConfigurer
{

    public static void main(String[] args) {
        SpringApplication.run(ReadingListApplication.class, args);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}
</code>```

ReadingListController class

```<code>package com.example.readingList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class ReadingListController {
    private ReadingListRepository readingListRepository;

    @Autowired
    public ReadingListController(ReadingListRepository readingListRepository)
    {
        this.readingListRepository = readingListRepository;
    }

    @RequestMapping(value="/readers/{reader}", method= RequestMethod.GET)
    public String readersBook(@PathVariable("reader") String reader, Model model)
    {
        List<Book> readingList = readingListRepository.findByReader(reader);
        if (readingList.isEmpty() == false) {
            model.addAttribute("books", readingList);
        }
        return "readingList";
    }

    @RequestMapping(value="/readers/{reader}", method= RequestMethod.POST)
    public String addToReadingList(@PathVariable("reader") String reader, Book book)
    {
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/readers/{reader}";
    }
}

</code>```

答:
It has to do with the AntPathRequestMatcher. In the first example, calling .antMatchers("/readers").access("hasRole('READER')") will not match /readers/ishwar.

Of course authorizeRequests().anyRequest().authenticated() will, which is why you were getting different behavior.

Try the following:

```<code>http.antMatchers("/readers/**")
        .access("hasRole('READER')")
    ...
</code>```

Body:
I created a small application to learn sprint boot web security. The sample application is mostly inspired from partial instructions provided in "Spring Boot in Action" book.

The problem I am facing is that inspite of configuring access like below, when I open http://localhost:8080/readers/ishwar the application doesn't navigate to login page. It straightaway opens the page represented by http://localhost:8080/readers/ishwar. As far as I have understood the spring security if .access("") is applied then in order to check access by default spring should redirect the user to login page. But it is not.

package com.example.readingList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.
                authorizeRequests()
                    .antMatchers("/readers").access("hasRole('READER')")
                    .antMatchers("/login").permitAll()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .failureUrl("/login?error=true");

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return readerRepository.getOne(username);
            }
        });
    }
}

BUT if I change the code to below then on browsing http://localhost:8080/readers/ishwar I get redirected to login page. What is wrong in first construct? I mean why .access("") is not working

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.
                authorizeRequests()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .failureUrl("/login?error=true");

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return readerRepository.getOne(username);
            }
        });
    }
}

Below is how ReaderRepository written

package com.example.readingList;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ReaderRepository extends JpaRepository<Reader, String> {

}

Below is Reader Class. I have deliberately granted "WRITER" role as I want to see that attempt to access page should fail as READER permission is missing. But as such even if I include "READER" permission there is no change in behaviour.

package com.example.readingList;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Arrays;
import java.util.Collection;

@Entity
public class Reader implements UserDetails {

    private static final long serialVersionUID = 1L;

    @Id
    private String username;
    private String password;
    private String fullname;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("WRITER"));
    }

    //@Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    //@Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getFullname()
    {
        return fullname;
    }

    public void setFullname(String fullname)
    {
        this.fullname = fullname;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Kindly note that I haven't implemented the data source to store/fetch user and password. I was expecting to see at least the redirection to http://localhost:8080/login first but not happening if I use first construct.

Below is my pom.xml file

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

<groupId>com.example</groupId>
<artifactId>readingList</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>readingList</name>
<description>Reading List project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

The ReadingListApplication class

@Configuration
@SpringBootApplication
public class ReadingListApplication implements WebMvcConfigurer
{

    public static void main(String[] args) {
        SpringApplication.run(ReadingListApplication.class, args);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}

ReadingListController class

package com.example.readingList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class ReadingListController {
    private ReadingListRepository readingListRepository;

    @Autowired
    public ReadingListController(ReadingListRepository readingListRepository)
    {
        this.readingListRepository = readingListRepository;
    }

    @RequestMapping(value="/readers/{reader}", method= RequestMethod.GET)
    public String readersBook(@PathVariable("reader") String reader, Model model)
    {
        List<Book> readingList = readingListRepository.findByReader(reader);
        if (readingList.isEmpty() == false) {
            model.addAttribute("books", readingList);
        }
        return "readingList";
    }

    @RequestMapping(value="/readers/{reader}", method= RequestMethod.POST)
    public String addToReadingList(@PathVariable("reader") String reader, Book book)
    {
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/readers/{reader}";
    }
}

Body:
It has to do with the AntPathRequestMatcher. In the first example, calling .antMatchers("/readers").access("hasRole('READER')") will not match /readers/ishwar.

Of course authorizeRequests().anyRequest().authenticated() will, which is why you were getting different behavior.

Try the following:

http.antMatchers("/readers/**")
        .access("hasRole('READER')")
    ...


问:
MIPS Counting Number of 1's given a user input (B instruction doesn't jump in MARS)
I wrote a code in MIPS that I thought would take in a users input (decimal number), AND it with 1 and increment this by 1 and shifting the bit position left by 1 until the number reached 0, then display the number of 1s in the decimal number in its binary representation. I am not sure where I went wrong.</p>

```<code># Count number of 1s in a 32 Bit Number
#$t0 = user input
#$t1 = counter
.data
prompt: .asciiz "Enter Number: "
result: .asciiz "Number of 1s counted: "
n:  .word   0
counter:.word   0
    .text

#Prompt User for Number
    li $v0, 4       #load text stored in v0
        la $a0, prompt  #print prompt
        syscall     #call prompt string

#Get user Input
        li $v0, 5   #load number stored in v0
        la $t0, n   #load int into $t0
        syscall     #display integer

#Store user input in $t0 to do function
        move $t0, $v0   #Move value from $v0 to $t0 to modify
        la $t1, counter #load address of counter
        lw $t1, 0($t1)  #load counter to t1

AND:
    andi $t2, $t0, 1 #and user input($t0) with 1 and store in $t2
    beq  $t2, 1, loop #if t2 equals 0 branch
    srl  $t0, $t0, 1 #shift user input($t0) to right 1 position logically
    b AND       #branch this function

loop:
    add $t1, $t1, 1 #add 1 to the counter
    srl $t0, $t0, 1 #shift $to to the right 1 position logically with counter
    beqz $t0, display #If $t0 equals 0 send to display function
    b AND       #send back to AND function if not

display:
       li $v0, 4    #load text stored in v0
       la $a0, result   #print text from address a0
       syscall
       la $a0, ($t1)    #load the address of the counter to a0
       li $v0, 1      #load integer stored in v0
       syscall        #print final integer

</code>```

答:
MARS apparently has an assembler bug on b instructions when the label name is also a valid instruction mnemonic.  It ends up as a branch-to-next instruction.

Changing the label name from AND to AND_TOP made it assemble correctly.  Eraklon found that using a j instruction also worked.  (The : instead of operands disambiguates the token as being a label instead of an instruction, so this is a bug in MARS, not a bug in your code.  clang assembles your source code just fine.  Not that you could run it outside of MARS; it depends on MARS system calls and no-delay-slot branches.)

I tested in Mars 4.5 under Java OpenJDK 1.8.0_232 on Arch GNU/Linux and reproduced @Eraklon's result.  (But the reasoning in that answer is wrong.)

Both b AND instructions assemble to 0x043fFFFF (with listed instruction bgez $0, AND), so the branch target is the instruction right after the branch.  (What would be the delay slot on real MIPS).  How to Calculate Jump Target Address and Branch Target Address? shows that MIPS relative-branch instructions are I-type, and sign-extend the 16 bit immediate (the low 16 of the instruction word) and left-shift by 2.  (Or look at it unshifted as an offset in words).  Relative to the end of the branch-delay slot.  So an offset of -1 gets us to the instruction after the branch.

Also note that 0x043f is not the right opcode and register encoding for bgez.  It should be 0x0401 for bgez $zero.  (http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html shows encodings in binary).  According to llvm-objdump -d (after assembling .word 0x043fffff with clang -target mips), that actually encodes 4 3f ff ff   synci -1($1).  I wonder if the MARS bug was ORing in a -1 value that was wider than it should have been, overwriting some higher bytes?

(bgez $0 is one way to encode an unconditional relative branch in MIPS.  Another way is beq $0,$0, target.  There's no separate opcode, you just have to pick one of the I-type b... machine instructions with inputs that are always true.)

MARS simulates this mis-assembled instruction as a branch-always with the offset it encoded: it effectively falls through the branch.  Or with Settings->Delayed Branching enabled, the instruction after the branch executes twice: once as the delay slot, once as the branch target.

So apparently the simulator doesn't truly decode from machine code, even if you turn on settings->self modifying code.  Or it's just the display that's broken?  IDK, doesn't really matter, this is 100% a bug and instead of poking at the symptoms someone should just look at the MARS source and fix it.

Using a different label name gives correct results: the first b AND_TOP assembles to 0x0401fffb, with MARS listing it as bgez $0, 0xfffffffb.  (Note the numeric offset in the listing, instead of the AND label name.)

And it simulates correctly, with those branches going to the right place.

I didn't check your logic but it seems over-complicated.  Note that la $a0, ($t0) is an insane way to write move $a0, $t0.  Apparently MARS allows that.  There was no reason to load from counter in the first place, though; you can zero a register with addu $t0, $zero, $zero or whatever else you want.  Or write it as move $t0, $zero.

Also this is silly:

```<code>    beqz $t0, display #If $t0 equals 0 send to display function
    b AND_TOP         #send back to AND function if not

display:
</code>```

Just bnez AND_TOP instead of conditionally jumping over an unconditional branch.

Also, neither comment adds anything to the understanding.  If there's something to say about why you jump, or the semantic meaning (e.g. in terms of high-level variables, not register names), then put that in a comment.  e.g. bnez $t0, count_loop   # more bits left to count?

Of course, as @Eraklon points out, your whole branching logic is super over-complicated.  Just isolate the low bit and add it to the count whether it's zero or one.

Or if you care about performance, mask away even and odd bits, right shift by 1, and addu.  Then you have 16x 2-bit accumulators packed into a register.  Repeat with another mask until you have bytes, then either keep going or use a multiply trick to get bytes summed into the high byte.  (See fast popcount Q&As here on stack overflow for bithack answers, or https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel.  Your method is like https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive but more complicated.  There are middle-ground options, e.g. clearing the lowest set bit and counting iterations to make it zero.)

Body:
I wrote a code in MIPS that I thought would take in a users input (decimal number), AND it with 1 and increment this by 1 and shifting the bit position left by 1 until the number reached 0, then display the number of 1s in the decimal number in its binary representation. I am not sure where I went wrong.

# Count number of 1s in a 32 Bit Number
#$t0 = user input
#$t1 = counter
.data
prompt: .asciiz "Enter Number: "
result: .asciiz "Number of 1s counted: "
n:  .word   0
counter:.word   0
    .text

#Prompt User for Number
    li $v0, 4       #load text stored in v0
        la $a0, prompt  #print prompt
        syscall     #call prompt string

#Get user Input
        li $v0, 5   #load number stored in v0
        la $t0, n   #load int into $t0
        syscall     #display integer

#Store user input in $t0 to do function
        move $t0, $v0   #Move value from $v0 to $t0 to modify
        la $t1, counter #load address of counter
        lw $t1, 0($t1)  #load counter to t1

AND:
    andi $t2, $t0, 1 #and user input($t0) with 1 and store in $t2
    beq  $t2, 1, loop #if t2 equals 0 branch
    srl  $t0, $t0, 1 #shift user input($t0) to right 1 position logically
    b AND       #branch this function

loop:
    add $t1, $t1, 1 #add 1 to the counter
    srl $t0, $t0, 1 #shift $to to the right 1 position logically with counter
    beqz $t0, display #If $t0 equals 0 send to display function
    b AND       #send back to AND function if not

display:
       li $v0, 4    #load text stored in v0
       la $a0, result   #print text from address a0
       syscall
       la $a0, ($t1)    #load the address of the counter to a0
       li $v0, 1      #load integer stored in v0
       syscall        #print final integer

Body:
MARS apparently has an assembler bug on b instructions when the label name is also a valid instruction mnemonic.  It ends up as a branch-to-next instruction.

Changing the label name from AND to AND_TOP made it assemble correctly.  Eraklon found that using a j instruction also worked.  (The : instead of operands disambiguates the token as being a label instead of an instruction, so this is a bug in MARS, not a bug in your code.  clang assembles your source code just fine.  Not that you could run it outside of MARS; it depends on MARS system calls and no-delay-slot branches.)

I tested in Mars 4.5 under Java OpenJDK 1.8.0_232 on Arch GNU/Linux and reproduced @Eraklon's result.  (But the reasoning in that answer is wrong.)

Both b AND instructions assemble to 0x043fFFFF (with listed instruction bgez $0, AND), so the branch target is the instruction right after the branch.  (What would be the delay slot on real MIPS).  How to Calculate Jump Target Address and Branch Target Address? shows that MIPS relative-branch instructions are I-type, and sign-extend the 16 bit immediate (the low 16 of the instruction word) and left-shift by 2.  (Or look at it unshifted as an offset in words).  Relative to the end of the branch-delay slot.  So an offset of -1 gets us to the instruction after the branch.

Also note that 0x043f is not the right opcode and register encoding for bgez.  It should be 0x0401 for bgez $zero.  (http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html shows encodings in binary).  According to llvm-objdump -d (after assembling .word 0x043fffff with clang -target mips), that actually encodes 4 3f ff ff   synci -1($1).  I wonder if the MARS bug was ORing in a -1 value that was wider than it should have been, overwriting some higher bytes?

(bgez $0 is one way to encode an unconditional relative branch in MIPS.  Another way is beq $0,$0, target.  There's no separate opcode, you just have to pick one of the I-type b... machine instructions with inputs that are always true.)

MARS simulates this mis-assembled instruction as a branch-always with the offset it encoded: it effectively falls through the branch.  Or with Settings->Delayed Branching enabled, the instruction after the branch executes twice: once as the delay slot, once as the branch target.

So apparently the simulator doesn't truly decode from machine code, even if you turn on settings->self modifying code.  Or it's just the display that's broken?  IDK, doesn't really matter, this is 100% a bug and instead of poking at the symptoms someone should just look at the MARS source and fix it.

Using a different label name gives correct results: the first b AND_TOP assembles to 0x0401fffb, with MARS listing it as bgez $0, 0xfffffffb.  (Note the numeric offset in the listing, instead of the AND label name.)

And it simulates correctly, with those branches going to the right place.

I didn't check your logic but it seems over-complicated.  Note that la $a0, ($t0) is an insane way to write move $a0, $t0.  Apparently MARS allows that.  There was no reason to load from counter in the first place, though; you can zero a register with addu $t0, $zero, $zero or whatever else you want.  Or write it as move $t0, $zero.

Also this is silly:

    beqz $t0, display #If $t0 equals 0 send to display function
    b AND_TOP         #send back to AND function if not

display:

Just bnez AND_TOP instead of conditionally jumping over an unconditional branch.

Also, neither comment adds anything to the understanding.  If there's something to say about why you jump, or the semantic meaning (e.g. in terms of high-level variables, not register names), then put that in a comment.  e.g. bnez $t0, count_loop   # more bits left to count?

Of course, as @Eraklon points out, your whole branching logic is super over-complicated.  Just isolate the low bit and add it to the count whether it's zero or one.

Or if you care about performance, mask away even and odd bits, right shift by 1, and addu.  Then you have 16x 2-bit accumulators packed into a register.  Repeat with another mask until you have bytes, then either keep going or use a multiply trick to get bytes summed into the high byte.  (See fast popcount Q&As here on stack overflow for bithack answers, or https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel.  Your method is like https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive but more complicated.  There are middle-ground options, e.g. clearing the lowest set bit and counting iterations to make it zero.)