问:
Not able to login in my phpmyadmin
Could not able to loggin in phpmyadmin after writing a single line of code at the TOP of index.php under phpmyadmin folder.But now i have deleted that single line of code. It is giving me the following error after providing credential-->

```
#0  PMA_sendHeaderLocation(http://linux.mydomain.com/phpmyadmin/index.php?token=8515d1390fbb0db27bebe4abd0668791) called at [/opt/lampp/phpmyadmin/libraries/auth/cookie.auth.lib.php:612]

#1  PMA_auth_set_user() called at [/phpmyadmin/libraries/common.inc.php:828]

#2  require_once(/phpmyadmin/libraries/common.inc.php) called at [/phpmyadmin/index.php:35]
```

Please help me.

答: If you have any spaces in your code at the start of the file, PHP may interpret these to mean put these onto the browser. Doing so causes problems with the header() function as this needs to be the first thing output to the browser for it to work properly. Make sure there are no spaces before or after the

Title: Not able to login in my phpmyadmin

Body:
Could not able to loggin in phpmyadmin after writing a single line of code at the TOP of index.php under phpmyadmin folder.But now i have deleted that single line of code. It is giving me the following error after providing credential-->

#0  PMA_sendHeaderLocation(http://linux.mydomain.com/phpmyadmin/index.php?token=8515d1390fbb0db27bebe4abd0668791) called at [/opt/lampp/phpmyadmin/libraries/auth/cookie.auth.lib.php:612]

#1  PMA_auth_set_user() called at [/phpmyadmin/libraries/common.inc.php:828]

#2  require_once(/phpmyadmin/libraries/common.inc.php) called at [/phpmyadmin/index.php:35]

Please help me.


来源: stackexchange

问:
how to get the request_id from the below json string in C#
Please help, I'm stuck with this

```<code>using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     Console.WriteLine(result);
}
</code>```

output :

```<code>{
    "request_number":"REQ0010201",
    "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca",
    "sys_id":"35c8ba46db3ffa807ea0f4e9bf9619ca"
}
</code>```

But I want output as only request_id to be printed  : b1c8ba46db3ffa807ea0f4e9bf9619ca

答:
if the return data is a json you can two options:

Using substring and indexof in a string for search the data after request_id":"

Serealize the json into a class and use in a class. For this you could use the classes of microsoft or newtonsoft . I prefer this option

see this link

Hope I help you

ContentLicense: CC BY-SA 3.0

Body:
Please help, I'm stuck with this

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     Console.WriteLine(result);
}

output :

{
    "request_number":"REQ0010201",
    "request_id":"b1c8ba46db3ffa807ea0f4e9bf9619ca",
    "sys_id":"35c8ba46db3ffa807ea0f4e9bf9619ca"
}

But I want output as only request_id to be printed  : b1c8ba46db3ffa807ea0f4e9bf9619ca


问:
R error: promise already under evaluation
Can anyone explain how to fix this error? I realize I have not provided all the code. The data is from the well-known weather golf data. The error I am getting is Error in probPCNB(varClass = "play", valueClass = i, inputVar1 = "windy",  :
  promise already under evaluation: recursive default argument reference or earlier problems? I have seen some answers to this kind of problem but I don't exactly understand them and especially in this case. Althougt there are other questions that address this error, it is not clear where the error comes from in this case.

```<code>golf=read.csv(file="weather.nominal.csv")
df=as.data.frame(golf)
df$names<-rownames(df)

conditional_prob_bool <- function(spec11, spec12, spec21, spec22, df){

  consequent_bool <- df[,spec11] == spec12

  consequent_event <- df[consequent_bool,]

  antecedent_bool <- df[,spec21] == spec22
  antecedent_event=df[antecedent_bool,]

  return(prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df))
}

predNBVar2=function(varClass='play',inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df=df){
  ##probPCNB(varClass='play', valueClass='yes', inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df)
  #browser()
  #lev2=levels(df[,varClass])
  lev2=c('yes','no')
  #lev2=levels(df$varClass)
  countt=0
  classprob=0
  predictedclass=lev2[1]
  for(i in lev2){
    p=probPCNB(varClass='play', valueClass=i, inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df=df)
    if(classprob<p){
      classprob=p
      predictedclass=i
    }

  }
  return(paste("best",predictedclass," with measure",classprob ))

}

probPCNB=function(varClass='play', valueClass='true', inputVar1='windy',var1Level=TRUE,inputVar2='humidity',var2Level='high',df){
  #browser()

  A_bool=df[,inputVar1]==var1Level & df[,inputVar2]==var2Level
  A=df[A_bool,]

  class_bool=df[,varClass]==valueClass
  classE=df[class_bool,]

  numerator=prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,valueClass,df)*conditional_prob_bool(inputVar2, var2Level,varClass,valueClass,df)

  lev=levels(df[,varClass])
  denominator=0

  for(i in lev){

    class_bool=df[,varClass]==i

    classE=df[class_bool,]
    class=i
    denominator= denominator+(prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,class,df)*
                                conditional_prob_bool(inputVar2, var2Level,varClass,class,df))

  }
  return(numerator/denominator)

}

predNBVar2()
</code>```

答:
It's because of the argument df=df

Rename df to something else and it should work

Also see: promise already under evaluation: recursive default argument reference or earlier problems?

```<code>golf=read.csv(file="weather.nominal.csv")
df=as.data.frame(golf)
df$names<-rownames(df)

conditional_prob_bool <- function(spec11, spec12, spec21, spec22, df){

  consequent_bool <- df[,spec11] == spec12

  consequent_event <- df[consequent_bool,]

  antecedent_bool <- df[,spec21] == spec22
  antecedent_event=df[antecedent_bool,]

  return(prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df))
}

predNBVar2=function(varClass='play',inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df_predNBVar2=df){
  ##probPCNB(varClass='play', valueClass='yes', inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df_predNBVar2)
  #browser()
  #lev2=levels(df[,varClass])
  lev2=c('yes','no')
  #lev2=levels(df$varClass)
  countt=0
  classprob=0
  predictedclass=lev2[1]
  for(i in lev2){
    p=probPCNB(varClass='play', valueClass=i, inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df=df_predNBVar2)
    if(classprob<p){
      classprob=p
      predictedclass=i
    }

  }
  return(paste("best",predictedclass," with measure",classprob ))

}

probPCNB=function(varClass='play', valueClass='true', inputVar1='windy',var1Level=TRUE,inputVar2='humidity',var2Level='high',df){
  #browser()

  A_bool=df[,inputVar1]==var1Level & df[,inputVar2]==var2Level
  A=df[A_bool,]

  class_bool=df[,varClass]==valueClass
  classE=df[class_bool,]

  numerator=prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,valueClass,df)*conditional_prob_bool(inputVar2, var2Level,varClass,valueClass,df)

  lev=levels(df[,varClass])
  denominator=0

  for(i in lev){

    class_bool=df[,varClass]==i

    classE=df[class_bool,]
    class=i
    denominator= denominator+(prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,class,df)*
                                conditional_prob_bool(inputVar2, var2Level,varClass,class,df))

  }
  return(numerator/denominator)

}

predNBVar2()
</code>```

Body:
Can anyone explain how to fix this error? I realize I have not provided all the code. The data is from the well-known weather golf data. The error I am getting is Error in probPCNB(varClass = "play", valueClass = i, inputVar1 = "windy",  :
  promise already under evaluation: recursive default argument reference or earlier problems? I have seen some answers to this kind of problem but I don't exactly understand them and especially in this case. Althougt there are other questions that address this error, it is not clear where the error comes from in this case.

golf=read.csv(file="weather.nominal.csv")
df=as.data.frame(golf)
df$names<-rownames(df)

conditional_prob_bool <- function(spec11, spec12, spec21, spec22, df){

  consequent_bool <- df[,spec11] == spec12

  consequent_event <- df[consequent_bool,]

  antecedent_bool <- df[,spec21] == spec22
  antecedent_event=df[antecedent_bool,]

  return(prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df))
}

predNBVar2=function(varClass='play',inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df=df){
  ##probPCNB(varClass='play', valueClass='yes', inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df)
  #browser()
  #lev2=levels(df[,varClass])
  lev2=c('yes','no')
  #lev2=levels(df$varClass)
  countt=0
  classprob=0
  predictedclass=lev2[1]
  for(i in lev2){
    p=probPCNB(varClass='play', valueClass=i, inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df=df)
    if(classprob<p){
      classprob=p
      predictedclass=i
    }

  }
  return(paste("best",predictedclass," with measure",classprob ))

}

probPCNB=function(varClass='play', valueClass='true', inputVar1='windy',var1Level=TRUE,inputVar2='humidity',var2Level='high',df){
  #browser()

  A_bool=df[,inputVar1]==var1Level & df[,inputVar2]==var2Level
  A=df[A_bool,]

  class_bool=df[,varClass]==valueClass
  classE=df[class_bool,]

  numerator=prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,valueClass,df)*conditional_prob_bool(inputVar2, var2Level,varClass,valueClass,df)

  lev=levels(df[,varClass])
  denominator=0

  for(i in lev){

    class_bool=df[,varClass]==i

    classE=df[class_bool,]
    class=i
    denominator= denominator+(prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,class,df)*
                                conditional_prob_bool(inputVar2, var2Level,varClass,class,df))

  }
  return(numerator/denominator)

}

predNBVar2()

Body:
It's because of the argument df=df

Rename df to something else and it should work

Also see: promise already under evaluation: recursive default argument reference or earlier problems?

golf=read.csv(file="weather.nominal.csv")
df=as.data.frame(golf)
df$names<-rownames(df)

conditional_prob_bool <- function(spec11, spec12, spec21, spec22, df){

  consequent_bool <- df[,spec11] == spec12

  consequent_event <- df[consequent_bool,]

  antecedent_bool <- df[,spec21] == spec22
  antecedent_event=df[antecedent_bool,]

  return(prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df))
}

predNBVar2=function(varClass='play',inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df_predNBVar2=df){
  ##probPCNB(varClass='play', valueClass='yes', inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df_predNBVar2)
  #browser()
  #lev2=levels(df[,varClass])
  lev2=c('yes','no')
  #lev2=levels(df$varClass)
  countt=0
  classprob=0
  predictedclass=lev2[1]
  for(i in lev2){
    p=probPCNB(varClass='play', valueClass=i, inputVar1='windy',var1Level='TRUE',inputVar2='humidity',var2Level="high",df=df_predNBVar2)
    if(classprob<p){
      classprob=p
      predictedclass=i
    }

  }
  return(paste("best",predictedclass," with measure",classprob ))

}

probPCNB=function(varClass='play', valueClass='true', inputVar1='windy',var1Level=TRUE,inputVar2='humidity',var2Level='high',df){
  #browser()

  A_bool=df[,inputVar1]==var1Level & df[,inputVar2]==var2Level
  A=df[A_bool,]

  class_bool=df[,varClass]==valueClass
  classE=df[class_bool,]

  numerator=prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,valueClass,df)*conditional_prob_bool(inputVar2, var2Level,varClass,valueClass,df)

  lev=levels(df[,varClass])
  denominator=0

  for(i in lev){

    class_bool=df[,varClass]==i

    classE=df[class_bool,]
    class=i
    denominator= denominator+(prob(classE,df)*conditional_prob_bool(inputVar1, var1Level,varClass,class,df)*
                                conditional_prob_bool(inputVar2, var2Level,varClass,class,df))

  }
  return(numerator/denominator)

}

predNBVar2()


问:
Anaconda install on Windows is stuck on executing install.py
Update: Two months after posting this question, I switched to a fresh install of Windows 10 and was able to install the correct version of Anaconda Python. Unfortunately the answers came too late for me to test them.

I want to switch from the 32-bit version of Anaconda Python 3.5 to the 64-bit version. First I uninstalled Anaconda through the 'Programs and Features' window, then I downloaded the Anaconda3-4.2.0-Windows-x86_64.exe installer and attempted to run it. For reference, I am using the 64-bit version of Windows 7. After some initial processing the installer is stuck on Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root

It does not throw any errors, it just hangs. I let it run throughout the night to see if it would progress any further, but unfortunately it was still stuck in the same place in the morning. Afterwards I tried looking for hidden Continuum files from the previous installation and removed those - also removed Anaconda from my PATH variable. I even tried installing miniconda instead of anaconda, but both installers get stuck in the exact same place. Am I missing a hidden file somewhere which is causing the Anaconda installer to hang?

Below is part of the installation log up until the execution command where it gets stuck.

```<code>Installing: dill-0.2.5-py35_0 (into root)
untgz::extract -d 'C:\Users\user.name\AppData\Local\Continuum\Anaconda3' -zbz2 'C:\Users\use.name\AppData\Local\Continuum\Anaconda3\pkgs\dill-0.2.5-py35_0.tar.bz2'
Writing Lib/site-packages/dill-0.2.5-py3.5.egg-info
Writing Lib/site-packages/dill/__diff.py
Writing Lib/site-packages/dill/__init__.py
Writing Lib/site-packages/dill/__pycache__/__diff.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/__init__.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/_objects.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/detect.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/dill.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/info.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/objtypes.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/pointers.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/settings.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/source.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/temp.cpython-35.pyc
Writing Lib/site-packages/dill/_objects.py
Writing Lib/site-packages/dill/detect.py
Writing Lib/site-packages/dill/dill.py
Writing Lib/site-packages/dill/info.py
Writing Lib/site-packages/dill/objtypes.py
Writing Lib/site-packages/dill/pointers.py
Writing Lib/site-packages/dill/settings.py
Writing Lib/site-packages/dill/source.py
Writing Lib/site-packages/dill/temp.py
Writing Scripts/get_objgraph.py
Writing Scripts/unpickle.py
Writing info/LICENSE.txt
Writing info/files
Writing info/has_prefix
Writing info/index.json
Writing info/platform
Writing info/recipe/bld.bat
Writing info/recipe/build.sh
Writing info/recipe/meta.yaml
extraction complete.
Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root
</code>```

答: I have ended pythow process from taskmanager and removed unnecessary/irrelevant from environment path. It resolves my issues.</p>

Body:
Update: Two months after posting this question, I switched to a fresh install of Windows 10 and was able to install the correct version of Anaconda Python. Unfortunately the answers came too late for me to test them.

I want to switch from the 32-bit version of Anaconda Python 3.5 to the 64-bit version. First I uninstalled Anaconda through the 'Programs and Features' window, then I downloaded the Anaconda3-4.2.0-Windows-x86_64.exe installer and attempted to run it. For reference, I am using the 64-bit version of Windows 7. After some initial processing the installer is stuck on Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root

It does not throw any errors, it just hangs. I let it run throughout the night to see if it would progress any further, but unfortunately it was still stuck in the same place in the morning. Afterwards I tried looking for hidden Continuum files from the previous installation and removed those - also removed Anaconda from my PATH variable. I even tried installing miniconda instead of anaconda, but both installers get stuck in the exact same place. Am I missing a hidden file somewhere which is causing the Anaconda installer to hang?

Below is part of the installation log up until the execution command where it gets stuck.

Installing: dill-0.2.5-py35_0 (into root)
untgz::extract -d 'C:\Users\user.name\AppData\Local\Continuum\Anaconda3' -zbz2 'C:\Users\use.name\AppData\Local\Continuum\Anaconda3\pkgs\dill-0.2.5-py35_0.tar.bz2'
Writing Lib/site-packages/dill-0.2.5-py3.5.egg-info
Writing Lib/site-packages/dill/__diff.py
Writing Lib/site-packages/dill/__init__.py
Writing Lib/site-packages/dill/__pycache__/__diff.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/__init__.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/_objects.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/detect.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/dill.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/info.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/objtypes.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/pointers.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/settings.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/source.cpython-35.pyc
Writing Lib/site-packages/dill/__pycache__/temp.cpython-35.pyc
Writing Lib/site-packages/dill/_objects.py
Writing Lib/site-packages/dill/detect.py
Writing Lib/site-packages/dill/dill.py
Writing Lib/site-packages/dill/info.py
Writing Lib/site-packages/dill/objtypes.py
Writing Lib/site-packages/dill/pointers.py
Writing Lib/site-packages/dill/settings.py
Writing Lib/site-packages/dill/source.py
Writing Lib/site-packages/dill/temp.py
Writing Scripts/get_objgraph.py
Writing Scripts/unpickle.py
Writing info/LICENSE.txt
Writing info/files
Writing info/has_prefix
Writing info/index.json
Writing info/platform
Writing info/recipe/bld.bat
Writing info/recipe/build.sh
Writing info/recipe/meta.yaml
extraction complete.
Execute: "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pythonw.exe" -E -s "C:\Users\user.name\AppData\Local\Continuum\Anaconda3\pkgs\.install.py" --root-prefix "C:\Users\user.name\AppData\Local\Continuum\Anaconda3" --post root


问:
How to change the opacity from other elements on focus in an input field
I try to make the body on focus in the input field dark and set the opacity to 6. It works great so far. But I want that the input field does not look like the whole body - and that doesn't work.

I want that the input field on focus is bright and all the rest is dark.

Here's my code:

HTML

```<code><b:navBar position="top" sticky="true" fluid="false" brand="bIg">
    <b:navbarLinks pull="left">
    <h:form styleClass="navbar-form navbar-left">
        <b:inputText placeholder="Suchbegriff" styleClass="inputNavbar"></b:inputText>
        <b:commandButton look="default" value="suchen" styleClass="btnSearch"></b:commandButton>
    </h:form>
    </b:navbarLinks>
    <b:navbarLinks pull="right">
        <b:dropMenu value="" iconAwesome="fa-user">
            <b:navLink value="Profil bearbeiten"></b:navLink>
            <b:navLink></b:navLink>
            <b:navLink value="Abmelden" styleClass="logoutLink"></b:navLink>
        </b:dropMenu>
        <b:dropMenu value="" iconAwesome="fa-wrench">
            <b:navLink value="Einstellungen"></b:navLink>
        </b:dropMenu>
    </b:navbarLinks>
</b:navBar>
</code>```

CSS

```<code>body.dark {
  background-color: #333;
  opacity: 0.6;
}
</code>```

JS

```<code> $(function() {
  $('.inputNavbar').on('focus', function() {
    $('body').not(this).addClass('dark');
  });

 $('.inputNavbar').on('blur', function() {
    $('body').not(this).removeClass('dark');
 });
});
</code>```

答:
$(document).ready(function(){
  $('.inputNavbar').on('focus', function() {

        if(!$('body').hasClass('dark'))
        {
          $('body').removeClass();
           $('body').addClass('dark');
          }

  });

 $('.inputNavbar').on('blur', function() {
       if($('body').hasClass('dark'))
       {
           $('body').removeClass();
           $('body').addClass('Undark');

       }
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body.dark {
  background-color: #333;
  opacity: 1;
}
body.Undark {
  background-color: #fff;
  opacity: 0.6;
}</code>```

        <input type="text" placeholder="Suchbegriff" class="inputNavbar"/>
        <input type="button"  look="default" value="suchen"/>```

Body:
I try to make the body on focus in the input field dark and set the opacity to 6. It works great so far. But I want that the input field does not look like the whole body - and that doesn't work.

I want that the input field on focus is bright and all the rest is dark.

Here's my code:

HTML

    <h:form styleClass="navbar-form navbar-left">

    </h:form>

CSS

body.dark {
  background-color: #333;
  opacity: 0.6;
}

JS

 $(function() {
  $('.inputNavbar').on('focus', function() {
    $('body').not(this).addClass('dark');
  });

 $('.inputNavbar').on('blur', function() {
    $('body').not(this).removeClass('dark');
 });
});

Body:
$(document).ready(function(){
  $('.inputNavbar').on('focus', function() {

        if(!$('body').hasClass('dark'))
        {
          $('body').removeClass();
           $('body').addClass('dark');
          }

  });

 $('.inputNavbar').on('blur', function() {
       if($('body').hasClass('dark'))
       {
           $('body').removeClass();
           $('body').addClass('Undark');

       }
 });
});

body.dark {
  background-color: #333;
  opacity: 1;
}
body.Undark {
  background-color: #fff;
  opacity: 0.6;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

        <input type="text" placeholder="Suchbegriff" class="inputNavbar"/>
        <input type="button"  look="default" value="suchen"/>


问:
pymatgen plotting DOS
I am trying to plot DOS (density of states) with pymatgen but I can't make it work. First time encountering self and class functions in python so I am at a loss.

This link explains the package that has the function I need (I need to use get_site_t2g_eg_resolved_dos(site) part of the class CompleteDos ). This link has the source code for those functions. Looking at the examples found online  I have made this code

```<code>from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.plotter import DosPlotter
from pymatgen.electronic_structure.core import Spin, Orbital

data = CompleteDos.get_site_t2g_eg_resolved_dos
plot = DosPlotter(data)
plot.get_plot(-5,5).show()
</code>```

That code returns an error and I am sure it's because the function get_site_t2g_eg_resolved_dos is not used correctly.

Even if you don't know pymatgen with the links provided I think you could help me in the proper way of using the functions, I'd highly appreciate it. Thanks in advance!

Edit: How the code I am trying looks like now, leave both because I am not sure if I am doing things correctly.

```<code>from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.plotter import DosPlotter
from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.io.vasp.outputs import Vasprun, Procar
from pymatgen.core.ion import Ion

vasprun = Vasprun("./vasprun.xml")

pdos = vasprun.pdos
tdos = vasprun.tdos
efermi = vasprun.efermi
energy = vasprun.eigenvalues
structure = vasprun.structures

a = CompleteDos(structure, tdos, pdos)
data = a.get_site_t2g_eg_resolved_dos(structure)
plot = DosPlotter(data)
plot.get_plot().show()
</code>```

Error in output:

```<code>Traceback (most recent call last):
  File "t2g2g.py", line 21, in <module>
    data= a.get_site_t2g_eg_resolved_dos(structure)
  File "/usr/local/lib/python2.7/dist-packages/pymatgen/electronic_structure/dos.py", line 351, in get_site_t2g_eg_resolved_dos
    for s, atom_dos in self.pdos.items():
AttributeError: 'list' object has no attribute 'items'
</code>```

答:
If you haven't given up here is the solution

```<code>from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.plotter import DosPlotter
from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.io.vasp.outputs import Vasprun, Procar
from pymatgen.core.ion import Ion

vasprun = Vasprun("./vasprun.xml")

pdos = vasprun.pdos
tdos = vasprun.tdos
efermi = vasprun.efermi
energy = vasprun.eigenvalues
structure = vasprun.structures

data = vasprun.complete_dos.get_site_t2g_eg_resolved_dos(vasprun.structures[0][0])
plot = DosPlotter()
plot.add_dos("t2g",data['t2g'])

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

You need to specify the site and mode (t2g/eg) in order to plot.

Title: pymatgen plotting DOS

Body:
I am trying to plot DOS (density of states) with pymatgen but I can't make it work. First time encountering self and class functions in python so I am at a loss.

This link explains the package that has the function I need (I need to use get_site_t2g_eg_resolved_dos(site) part of the class CompleteDos ). This link has the source code for those functions. Looking at the examples found online  I have made this code

from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.plotter import DosPlotter
from pymatgen.electronic_structure.core import Spin, Orbital

data = CompleteDos.get_site_t2g_eg_resolved_dos
plot = DosPlotter(data)
plot.get_plot(-5,5).show()

That code returns an error and I am sure it's because the function get_site_t2g_eg_resolved_dos is not used correctly.

Even if you don't know pymatgen with the links provided I think you could help me in the proper way of using the functions, I'd highly appreciate it. Thanks in advance!

Edit: How the code I am trying looks like now, leave both because I am not sure if I am doing things correctly.

from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.plotter import DosPlotter
from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.io.vasp.outputs import Vasprun, Procar
from pymatgen.core.ion import Ion

vasprun = Vasprun("./vasprun.xml")

pdos = vasprun.pdos
tdos = vasprun.tdos
efermi = vasprun.efermi
energy = vasprun.eigenvalues
structure = vasprun.structures

a = CompleteDos(structure, tdos, pdos)
data = a.get_site_t2g_eg_resolved_dos(structure)
plot = DosPlotter(data)
plot.get_plot().show()

Error in output:

Traceback (most recent call last):
  File "t2g2g.py", line 21, in <module>
    data= a.get_site_t2g_eg_resolved_dos(structure)
  File "/usr/local/lib/python2.7/dist-packages/pymatgen/electronic_structure/dos.py", line 351, in get_site_t2g_eg_resolved_dos
    for s, atom_dos in self.pdos.items():
AttributeError: 'list' object has no attribute 'items'

Body:
If you haven't given up here is the solution

from pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.plotter import DosPlotter
from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.io.vasp.outputs import Vasprun, Procar
from pymatgen.core.ion import Ion

vasprun = Vasprun("./vasprun.xml")

pdos = vasprun.pdos
tdos = vasprun.tdos
efermi = vasprun.efermi
energy = vasprun.eigenvalues
structure = vasprun.structures

data = vasprun.complete_dos.get_site_t2g_eg_resolved_dos(vasprun.structures[0][0])
plot = DosPlotter()
plot.add_dos("t2g",data['t2g'])

plot.show()

You need to specify the site and mode (t2g/eg) in order to plot.


问:
How do I check for token expiration and logout user?
The user can logout himself when he/she clicks on the logout button but if the token is expired he/she cant logout because in my application, the token is used in both server side and front end. When user clicks on the logout button, the token from both server and browser is cleared if token is valid. There is a chance that when user does not log out and his/her token expires but is not being cleared in the browser. For addressing this situation, how do I check for token expiration every time the user visits in my app so if the token is expired, clear the token from the browser?

I tried in saga which watches in the background every time the user refreshes in the page or switch to another page. I don't think this is an efficient way. I reckon middleware comes into play.

```<code>function* loadInitialActions() {
  var dateNow = new Date();
  console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (
    token &&
    jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
  ) {
    yield put(LOGOUT_SUCCESS);
  }
}

function* initialize() {
  const watcher = yield fork(loadInitialActions);
  yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
  yield cancel(watcher);
}

function* rootSaga() {
  console.log("rootSaga");
  yield takeLatest(INITIALIZE, initialize);
}
</code>```

So my question is how do I use the token expiration logic and logout user if token is expired from the middleware?

答:
In my view middleware will be the best option.

You can do something like this

```<code>const checkTokenExpirationMiddleware = store => next => action => {
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (jwtDecode(token).exp < Date.now() / 1000) {
    next(action);
    localStorage.clear();
  }
  next(action);
};
</code>```

You have to then wrap it in applyMiddleware

ContentLicense: CC BY-SA 4.0

Body:
The user can logout himself when he/she clicks on the logout button but if the token is expired he/she cant logout because in my application, the token is used in both server side and front end. When user clicks on the logout button, the token from both server and browser is cleared if token is valid. There is a chance that when user does not log out and his/her token expires but is not being cleared in the browser. For addressing this situation, how do I check for token expiration every time the user visits in my app so if the token is expired, clear the token from the browser?

I tried in saga which watches in the background every time the user refreshes in the page or switch to another page. I don't think this is an efficient way. I reckon middleware comes into play.

function* loadInitialActions() {
  var dateNow = new Date();
  console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (
    token &&
    jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
  ) {
    yield put(LOGOUT_SUCCESS);
  }
}

function* initialize() {
  const watcher = yield fork(loadInitialActions);
  yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
  yield cancel(watcher);
}

function* rootSaga() {
  console.log("rootSaga");
  yield takeLatest(INITIALIZE, initialize);
}

So my question is how do I use the token expiration logic and logout user if token is expired from the middleware?

Body:
In my view middleware will be the best option.

You can do something like this

const checkTokenExpirationMiddleware = store => next => action => {
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (jwtDecode(token).exp < Date.now() / 1000) {
    next(action);
    localStorage.clear();
  }
  next(action);
};

You have to then wrap it in applyMiddleware


问:
Change background-color with different shades of color
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

```<code>background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)
</code>```

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

答:
To instantly change the background color we can do it using jquery.
See this link.

https://jsfiddle.net/9bcgw7x4/6/

```<code>$(document).ready(function(){
  var a = 1;
  var add =2;

  function changeBG(){
    var r = Math.floor((255 * a) / 100);
    var g = Math.floor((255 * (100 - a)) / 100);
    var b = Math.floor((255 * a) / 100);
    if(a<=0){
      add = 2;
    }else if(a>99){
      add=-2;
    }
    a=a+add;
    $('body').css('background-color', 'rgb('+r+','+g+','+b+')');
  }
  setInterval(changeBG, 1000);

});
</code>```

Body:
I am trying to make a webpage with a background that changes color with the shades of the rainbow. I don't want any smooth transitions, I want them to change instantly. With shades, I mean it doesn't just go from red to orange to green e.t.c, I mean it uses the shades of each color.

It's a bit difficult to explain, I got it from this website. If you hit 'inspect element' on the log in page, and then visit console, you'll see a bunch of rainbow text. The code used to achieve this is:

background:linear-gradient(to left, red,orange,yellow,green,blue,indigo,violet)

As you can see there, it's a bunch of different shades from each color in the code. How would I use this, but as a background of my webpage?

Body:
To instantly change the background color we can do it using jquery.
See this link.

https://jsfiddle.net/9bcgw7x4/6/

$(document).ready(function(){
  var a = 1;
  var add =2;

  function changeBG(){
    var r = Math.floor((255 * a) / 100);
    var g = Math.floor((255 * (100 - a)) / 100);
    var b = Math.floor((255 * a) / 100);
    if(a<=0){
      add = 2;
    }else if(a>99){
      add=-2;
    }
    a=a+add;
    $('body').css('background-color', 'rgb('+r+','+g+','+b+')');
  }
  setInterval(changeBG, 1000);

});


问:
How to import LibSVM into my Java code
In Java programming, we should firstly add weka.jar into our classpath, thus we can call all classify or cluster algorithms in WEKA in the form of the following codes,

```<code>import weka.classifiers.trees.RandomForest;
...
RandomForest rf = new RandomForest(); // RandomForest object
</code>```

But unfortunately, we can not use this way to import LibSVM algorithm, because there is not such class in weka.jar.

So, my question is How to import LibSVM into my Java code?  Any help will be grateful :)

答:
Firstly, I'd like to say there are so many methods to solve the problem. The solution I mentioned is quite simple, but other answers from StackOverflow are not detailed descripted, with waste my too much time to verify. So I'm happy to share it with all WEKA beginners :)

a) Download the LibSVM.jar from Maven Repository Center. Note that this LibSVM.jar is different from the libsvm.jar developed by Chih-Chung Chang and Chih-Jen Lin;

b) Add the LibSVM.jar to the classpath of our Java project;

c) Call the classifier LibSVM when you need, see the following Java code.

```<code>import weka.classifiers.functions.LibSVM; // contained in LibSVM.jar

String path = "file/train.arff";
Instances train = DataSource.read(path); // load the dataset
train.setClassIndex(train.numAttribute()-1); // set class index

LibSVM svm = new LibSVM(); // load the svm classifier
svm.buildClassifier(train);

Evaluation eval = new Evaluation(train);
eval.crossValidateModel(svm, train, 10, new Random(1)); // 10-fold cross-validation
</code>```

Title: How to import LibSVM into my Java code

Body:
In Java programming, we should firstly add weka.jar into our classpath, thus we can call all classify or cluster algorithms in WEKA in the form of the following codes,

import weka.classifiers.trees.RandomForest;
...
RandomForest rf = new RandomForest(); // RandomForest object

But unfortunately, we can not use this way to import LibSVM algorithm, because there is not such class in weka.jar.

So, my question is How to import LibSVM into my Java code?  Any help will be grateful :)

Body:
Firstly, I'd like to say there are so many methods to solve the problem. The solution I mentioned is quite simple, but other answers from StackOverflow are not detailed descripted, with waste my too much time to verify. So I'm happy to share it with all WEKA beginners :)

a) Download the LibSVM.jar from Maven Repository Center. Note that this LibSVM.jar is different from the libsvm.jar developed by Chih-Chung Chang and Chih-Jen Lin;

b) Add the LibSVM.jar to the classpath of our Java project;

c) Call the classifier LibSVM when you need, see the following Java code.

import weka.classifiers.functions.LibSVM; // contained in LibSVM.jar

String path = "file/train.arff";
Instances train = DataSource.read(path); // load the dataset
train.setClassIndex(train.numAttribute()-1); // set class index

LibSVM svm = new LibSVM(); // load the svm classifier
svm.buildClassifier(train);

Evaluation eval = new Evaluation(train);
eval.crossValidateModel(svm, train, 10, new Random(1)); // 10-fold cross-validation


问:
Javascript: convert a multidimensional array to object in ajax
I try to send a javascript array to php using ajax he's what I did

```<code>var d = $("#fromDate").val();
var arr = [];
for(var x=0; x<count_select; x++){
       var myArray = new Array();
       myArray['val'] = $("select").eq(x).val();
       myArray['type'] = $("select").eq(x).attr('type');
       myArray['id'] = $("select").eq(x).attr('id');
       arr.push(myArray);
       myArray = new Array();
}
</code>```

The array contains elements as I want in a multidimensional array.

But when I send it to php page like this: (Array is not converted yet here's where I want to convert it to send as json)

```<code>$.ajax({
     type: "POST",
     url: "URL_PATH",
     data: {"arrar":arr,"date":d},
     dataType: "json",
        success: function(data) {
            alert(data);
        }
});
</code>```

In the network tab i find

```<code>date    "2017-07-08"
</code>```

and can't find the array so how can I convert this multidimensional  array to an object so I can handle it using php

答:
```<code>var array = new Array()
array["foo"] = "bar";

console.log(JSON.stringify(array))
// -> []
</code>```

Oops?

The problem here is, that your array is not going to be converted to text properly when its going to be send in the post request. Arrays in JS only expect numbers as indexes, there are no associative arrays in JS. The analogy to associative arrays are objects. where you have a simple key: value store.

What you really want is an object

```<code>var obj = {};
obj["foo"] = "bar";

console.log(JSON.stringify(obj))
// -> { "foo": "bar" }
</code>```

In Javascript everything is an object, so you could do things like:

```<code>var n = 1;
n.name = "number with property";
</code>```

And you would't get an error, even if that makes no sense ;)

Body:
I try to send a javascript array to php using ajax he's what I did

var d = $("#fromDate").val();
var arr = [];
for(var x=0; x<count_select; x++){
       var myArray = new Array();
       myArray['val'] = $("select").eq(x).val();
       myArray['type'] = $("select").eq(x).attr('type');
       myArray['id'] = $("select").eq(x).attr('id');
       arr.push(myArray);
       myArray = new Array();
}

The array contains elements as I want in a multidimensional array.

But when I send it to php page like this: (Array is not converted yet here's where I want to convert it to send as json)

$.ajax({
     type: "POST",
     url: "URL_PATH",
     data: {"arrar":arr,"date":d},
     dataType: "json",
        success: function(data) {
            alert(data);
        }
});

In the network tab i find

date    "2017-07-08"

and can't find the array so how can I convert this multidimensional  array to an object so I can handle it using php

Body:
var array = new Array()
array["foo"] = "bar";

console.log(JSON.stringify(array))
// -> []

Oops?

The problem here is, that your array is not going to be converted to text properly when its going to be send in the post request. Arrays in JS only expect numbers as indexes, there are no associative arrays in JS. The analogy to associative arrays are objects. where you have a simple key: value store.

What you really want is an object

var obj = {};
obj["foo"] = "bar";

console.log(JSON.stringify(obj))
// -> { "foo": "bar" }

In Javascript everything is an object, so you could do things like:

var n = 1;
n.name = "number with property";

And you would't get an error, even if that makes no sense ;)


问:
Fixed width child is shrinking in flexbox
I'm using display:flex for the first time.

You find a codepen here: https://codepen.io/chrispillen/pen/GEYpRg

.node:not(.branch) {
  width: auto;
  height: 100px;
  background: red;
  margin-bottom: 1px;
}

.node.branch,
.node.branch .body {
  width: auto;
  overflow: hidden;
}

.node.branch .leaf {
  width: 100%;
  height: 100px;
  background: blue;
}

.node.branch .body {
  width: 100%;
  display: flex;
  align-items: stretch;
}

.node.branch .body .tribe {
  width: 100px;
  background: blue;
  margin-right: 1px;
}

.node.branch .body .subnodes {
  padding-top: 1px;
  width: 100%;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="node"></div>
<div class="node branch">
  <div class="leaf"></div>
  <div class="body">
    <div class="tribe">TRIBE</div>
    <div class="subnodes">
      <div class="node"></div>
      <div class="node"></div>
    </div>
  </div>
  <div class="leaf"></div>
</div></code>```

The "tribe" element doesn't remain with a width of 100px.

Everything else works as supposed. Can I force it somehow? And by the way: is flex the true reason for this behavior?

答:
Flexbox items have flex-shrink parameter with default of 1. This means that in case your flexbox container don't have enough space its items will shrink.

To disable this behaviour for flexbox item set flex-shrink: 0.

Demo:

.node:not(.branch) {
  width: auto;
  height: 100px;
  background: red;
  margin-bottom: 1px;
}

.node.branch,
.node.branch .body {
  width: auto;
  overflow: hidden;
}

.node.branch .leaf {
  width: 100%;
  height: 100px;
  background: blue;
}

.node.branch .body {
  width: 100%;
  display: flex;
  align-items: stretch;
}

.node.branch .body .tribe {
  width: 100px;
  flex-shrink: 0; /* new */
  background: blue;
  margin-right: 1px;
}

.node.branch .body .subnodes {
  padding-top: 1px;
  width: 100%;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="node"></div>

<div class="node branch">
  <div class="leaf"></div>

  <div class="body">
    <div class="tribe">TRIBE</div>

    <div class="subnodes">
      <div class="node"></div>
      <div class="node"></div>
    </div>
  </div>

  <div class="leaf"></div>
</div></code>```

Body:
I'm using display:flex for the first time.

You find a codepen here: https://codepen.io/chrispillen/pen/GEYpRg

.node:not(.branch) {
  width: auto;
  height: 100px;
  background: red;
  margin-bottom: 1px;
}

.node.branch,
.node.branch .body {
  width: auto;
  overflow: hidden;
}

.node.branch .leaf {
  width: 100%;
  height: 100px;
  background: blue;
}

.node.branch .body {
  width: 100%;
  display: flex;
  align-items: stretch;
}

.node.branch .body .tribe {
  width: 100px;
  background: blue;
  margin-right: 1px;
}

.node.branch .body .subnodes {
  padding-top: 1px;
  width: 100%;
  overflow: hidden;
}

TRIBE

The "tribe" element doesn't remain with a width of 100px.

Everything else works as supposed. Can I force it somehow? And by the way: is flex the true reason for this behavior?

Body:
Flexbox items have flex-shrink parameter with default of 1. This means that in case your flexbox container don't have enough space its items will shrink.

To disable this behaviour for flexbox item set flex-shrink: 0.

Demo:

.node:not(.branch) {
  width: auto;
  height: 100px;
  background: red;
  margin-bottom: 1px;
}

.node.branch,
.node.branch .body {
  width: auto;
  overflow: hidden;
}

.node.branch .leaf {
  width: 100%;
  height: 100px;
  background: blue;
}

.node.branch .body {
  width: 100%;
  display: flex;
  align-items: stretch;
}

.node.branch .body .tribe {
  width: 100px;
  flex-shrink: 0; /* new */
  background: blue;
  margin-right: 1px;
}

.node.branch .body .subnodes {
  padding-top: 1px;
  width: 100%;
  overflow: hidden;
}

<div class="node"></div>

<div class="node branch">
  <div class="leaf"></div>

  <div class="body">
    <div class="tribe">TRIBE</div>

    <div class="subnodes">
      <div class="node"></div>
      <div class="node"></div>
    </div>
  </div>

  <div class="leaf"></div>
</div>


问:
Convert to float and pad left with zero on SQL Server
I need to convert to float and pad left with zero in SQL Server.

I need in this format ####.##.

For example:

```<code>2.23   ->  0002.23
123.3  ->  0123.30
12.65  ->  0012.65
34     ->  0034.00
</code>```

I tried this:

```<code>cast(Weight as decimal(6, 2))
</code>```

and also this:

```<code>REPLACE(STR(Weight, 6), SPACE(1), '0')
</code>```

and this:

```<code>REPLACE(STR(cast(Weight as decimal(6,2)), 6), SPACE(1), '0')
</code>```

But they do not work - I got 5.00 or 000005 and I need 0005.00.

Thanks

答:
If SQL Server 2012+, FORMAT() is an option.

```<code>Select format(123.3,'0000.00')
</code>```

Returns

```<code>0123.30
</code>```

Format() has some nice features, but not known for its performance

Body:
I need to convert to float and pad left with zero in SQL Server.

I need in this format ####.##.

For example:

2.23   ->  0002.23
123.3  ->  0123.30
12.65  ->  0012.65
34     ->  0034.00

I tried this:

cast(Weight as decimal(6, 2))

and also this:

REPLACE(STR(Weight, 6), SPACE(1), '0')

and this:

REPLACE(STR(cast(Weight as decimal(6,2)), 6), SPACE(1), '0')

But they do not work - I got 5.00 or 000005 and I need 0005.00.

Thanks

Body:
If SQL Server 2012+, FORMAT() is an option.

Select format(123.3,'0000.00')

Returns

0123.30

Format() has some nice features, but not known for its performance


问:
Get SynchronizationContext from a given Thread
I can't work out how to get the SynchronizationContext of a given Thread:

```<code>Thread uiThread = UIConfiguration.UIThread;
SynchronizationContext context = uiThread.Huh?;
</code>```

Why would I need that?

Because I need to post to the UIThread from different spots all across the front end application. So I defined a static property in a class called UIConfiguration. I set this property in the Program.Main method:

```<code>UIConfiguration.UIThread = Thread.CurrentThread;
</code>```

In that very moment I can be sure I have the right thread, however I cannot set a static property like

```<code>UIConfiguration.SynchronizationContext = SynchronizationContext.Current
</code>```

because the WinForms implementation of that class has not yet been installed. Since each thread has it's own SynchronizationContext, it must be possible to retrieve it from a given Thread object, or am I completely wrong?

答:
Complete and working extension methods for getting the SynchronizationContext from a Thread or ExecutionContext (or null if none is present), or a DispatcherSynchronizationContext from a Dispatcher. Tested on .NET 4.6.2.

```<code>using Ectx = ExecutionContext;
using Sctx = SynchronizationContext;
using Dctx = DispatcherSynchronizationContext;

public static class _ext
{
    // DispatcherSynchronizationContext from Dispatcher
    public static Dctx GetSyncCtx(this Dispatcher d) => d?.Thread.GetSyncCtx() as Dctx;

    // SynchronizationContext from Thread
    public static Sctx GetSyncCtx(this Thread th) => th?.ExecutionContext?.GetSyncCtx();

    // SynchronizationContext from ExecutionContext
    public static Sctx GetSyncCtx(this Ectx x) => __get(x);

    /* ... continued below ... */
}
</code>```

All of the above functions end up calling the __get code shown below, which warrants some explanation.

Note that __get is a static field, pre-initialized with a discardable lambda block. This allows us to neatly intercept the first caller only, in order to run the one-time initialization, which prepares a tiny and permanent replacement delegate that's much faster and reflection-free.

The final act for the intrepid initialization effort is to swap the replacement into '__get', which simultaneously and tragically means the code discards itself, leaving no trace, and all subsequent callers proceed directly into the DynamicMethod proper without even a hint of bypass logic.

```<code>static Func<Ectx, Sctx> __get = arg =>
{
    // Hijack the first caller to do initialization...

    var fi = typeof(Ectx).GetField(
        "_syncContext",                         // private field in 'ExecutionContext'
        BindingFlags.NonPublic|BindingFlags.Instance);

    var dm = new DynamicMethod(
        "foo",                                  // (any name)
        typeof(Sctx),                           // getter return type
        new[] { typeof(Ectx) },                 // type of getter's single arg
        typeof(Ectx),                           // "owner" type
        true);                                  // allow private field access

    var il = dm.GetILGenerator();
    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldfld, fi);
    il.Emit(OpCodes.Ret);

    // ...now replace ourself...
    __get = (Func<Ectx, Sctx>)dm.CreateDelegate(typeof(Func<Ectx, Sctx>));

    // oh yeah, don't forget to handle the first caller's request
    return __get(arg);                 //  ...never to come back here again. SAD!
};
</code>```

The cute part is the very end where--in order to actually fetch the value for the pre-empted first caller--the function ostensibly calls itself with its own argument, but avoids recursing by replacing itself immediately prior.

There's no particular reason for demonstrating this unusual technique on the particular problem of SynchronizationContext under discussion on this page. Grabbing the _syncContext field out of an ExecutionContext could be easily and trivially addressed with traditional reflection (plus some extension method frosting). But I thought I'd share this approach which I've personally used for quite a while now, because it is also easily adapted and just as widely applicable to such cases.

It's especially appropriate when extreme performance is necessary in accessing the non-public field. I think I originally used this in a QPC-based frequency counter where the field was read in a tight loop that iterated every 20 or 25 nanoseconds, which wouldn't really be possible with conventional reflection.

This concludes the main answer, but below I've included some interesting points, less relevant to the questioner's inquiry, moreso to the technique just demonstrated.

Runtime callers

For clarity, I separated the "installation swap" and "first usage" steps into two separate lines in the code shown above, as opposed to what I have in my own code (the following version also avoids one main-memory fetch versus the previous, potentially implicating thread-safety, see detailed discussion below):

```<code>return (__get = (Func<Ectx, Sctx>)dm.CreateDel...(...))(arg);
</code>```

In other words, all callers, including the first, fetch the value in exactly the same way, and no reflection code is ever used to do so. It only writes the replacement getter. Courtesy of il-visualizer, we can see the body of that DynamicMethod in the debugger at runtime:

Lock-free thread safety

I should note that swapping in the function body is a fully thread-safe operation given the .NET memory model and the lock-free philosophy. The latter favors forward-progress guarantees at the possible expense of doing duplicate or redundant work. Multi-way racing to initialize is correctly permitted on a fully sound theoretical basis:

the race entry point (initialization code) is globally pre-configured and protected (by the .NET loader) so that (multiple) racers (if any) enter the same initializer, which can never be seen as null.

multiple race products (the getter) are always logically identical, so it doesn't matter which one any particular racer (or later non-racing caller) happens to pick up, or even whether any racer ends up using the one they themselves produced;

each installation swap is a single store of size IntPtr, which is guaranteed to be atomic for any respective platform bitness;

finally, and technically absolutely critical to perfect formal correctness, work products of the "losers" are reclaimed by GC and thus do no leak. In this type of race, losers are every racer except the last finisher (since everyone else's efforts get blithely and summarily overwritten with an identical result).

Although I believe these points combine to fully protect the code as written under every possible circumstance, if you're still suspicious or wary of the overall conclusion, you can always add an extra layer of bulletproofing:

```<code>var tmp = (Func<Ectx, Sctx>)dm.CreateDelegate(typeof(Func<Ectx, Sctx>));
Thread.MemoryBarrier();
__get = tmp;
return tmp(arg);
</code>```

It's just a paraniod version. As with the earlier condensed one-liner, the .NET memory model guarantees that there is exactly one store--and zero fetches--to location of '__get'. (The full expanded example at the top does do an extra main memory fetch, but is still sound thanks to the second bullet point) As I mentioned, none of this should be necessary for correctness, but it could, in theory, give a miniscule performance bonus: by conclusively ending the race earlier, the aggressive flush could, in an extremely rare case, prevent a subsequent caller on a dirty cache line from unnecessarily (but again, harmlessly) racing.

Double-thunking

Calls into the final, hyper-fast method are still thunked through the static extension methods shown earlier.
This is because we also need to somehow represent entry point(s) that actually exist at compile time for the compiler to bind against and propagate metadata for. The double-thunk is a small price to pay for the overwhelming convenience of strongly-typed metadata and intellisense in the IDE for customized code that can't actually be resolved until runtime. Yet it runs at least as fast as statically compiled code, way faster that doing a bunch of reflection on every call, so we get the best of both worlds!

Body:
I can't work out how to get the SynchronizationContext of a given Thread:

Thread uiThread = UIConfiguration.UIThread;
SynchronizationContext context = uiThread.Huh?;

Why would I need that?

Because I need to post to the UIThread from different spots all across the front end application. So I defined a static property in a class called UIConfiguration. I set this property in the Program.Main method:

UIConfiguration.UIThread = Thread.CurrentThread;

In that very moment I can be sure I have the right thread, however I cannot set a static property like

UIConfiguration.SynchronizationContext = SynchronizationContext.Current

because the WinForms implementation of that class has not yet been installed. Since each thread has it's own SynchronizationContext, it must be possible to retrieve it from a given Thread object, or am I completely wrong?

Body:
Complete and working extension methods for getting the SynchronizationContext from a Thread or ExecutionContext (or null if none is present), or a DispatcherSynchronizationContext from a Dispatcher. Tested on .NET 4.6.2.

using Ectx = ExecutionContext;
using Sctx = SynchronizationContext;
using Dctx = DispatcherSynchronizationContext;

public static class _ext
{
    // DispatcherSynchronizationContext from Dispatcher
    public static Dctx GetSyncCtx(this Dispatcher d) => d?.Thread.GetSyncCtx() as Dctx;

    // SynchronizationContext from Thread
    public static Sctx GetSyncCtx(this Thread th) => th?.ExecutionContext?.GetSyncCtx();

    // SynchronizationContext from ExecutionContext
    public static Sctx GetSyncCtx(this Ectx x) => __get(x);

    /* ... continued below ... */
}

All of the above functions end up calling the __get code shown below, which warrants some explanation.

Note that __get is a static field, pre-initialized with a discardable lambda block. This allows us to neatly intercept the first caller only, in order to run the one-time initialization, which prepares a tiny and permanent replacement delegate that's much faster and reflection-free.

The final act for the intrepid initialization effort is to swap the replacement into '__get', which simultaneously and tragically means the code discards itself, leaving no trace, and all subsequent callers proceed directly into the DynamicMethod proper without even a hint of bypass logic.

static Func<Ectx, Sctx> __get = arg =>
{
    // Hijack the first caller to do initialization...

    var fi = typeof(Ectx).GetField(
        "_syncContext",                         // private field in 'ExecutionContext'
        BindingFlags.NonPublic|BindingFlags.Instance);

    var dm = new DynamicMethod(
        "foo",                                  // (any name)
        typeof(Sctx),                           // getter return type
        new[] { typeof(Ectx) },                 // type of getter's single arg
        typeof(Ectx),                           // "owner" type
        true);                                  // allow private field access

    var il = dm.GetILGenerator();
    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldfld, fi);
    il.Emit(OpCodes.Ret);

    // ...now replace ourself...
    __get = (Func<Ectx, Sctx>)dm.CreateDelegate(typeof(Func<Ectx, Sctx>));

    // oh yeah, don't forget to handle the first caller's request
    return __get(arg);                 //  ...never to come back here again. SAD!
};

The cute part is the very end where--in order to actually fetch the value for the pre-empted first caller--the function ostensibly calls itself with its own argument, but avoids recursing by replacing itself immediately prior.

There's no particular reason for demonstrating this unusual technique on the particular problem of SynchronizationContext under discussion on this page. Grabbing the _syncContext field out of an ExecutionContext could be easily and trivially addressed with traditional reflection (plus some extension method frosting). But I thought I'd share this approach which I've personally used for quite a while now, because it is also easily adapted and just as widely applicable to such cases.

It's especially appropriate when extreme performance is necessary in accessing the non-public field. I think I originally used this in a QPC-based frequency counter where the field was read in a tight loop that iterated every 20 or 25 nanoseconds, which wouldn't really be possible with conventional reflection.

This concludes the main answer, but below I've included some interesting points, less relevant to the questioner's inquiry, moreso to the technique just demonstrated.

Runtime callers

For clarity, I separated the "installation swap" and "first usage" steps into two separate lines in the code shown above, as opposed to what I have in my own code (the following version also avoids one main-memory fetch versus the previous, potentially implicating thread-safety, see detailed discussion below):

return (__get = (Func<Ectx, Sctx>)dm.CreateDel...(...))(arg);

In other words, all callers, including the first, fetch the value in exactly the same way, and no reflection code is ever used to do so. It only writes the replacement getter. Courtesy of il-visualizer, we can see the body of that DynamicMethod in the debugger at runtime:

Lock-free thread safety

I should note that swapping in the function body is a fully thread-safe operation given the .NET memory model and the lock-free philosophy. The latter favors forward-progress guarantees at the possible expense of doing duplicate or redundant work. Multi-way racing to initialize is correctly permitted on a fully sound theoretical basis:

the race entry point (initialization code) is globally pre-configured and protected (by the .NET loader) so that (multiple) racers (if any) enter the same initializer, which can never be seen as null.

multiple race products (the getter) are always logically identical, so it doesn't matter which one any particular racer (or later non-racing caller) happens to pick up, or even whether any racer ends up using the one they themselves produced;

each installation swap is a single store of size IntPtr, which is guaranteed to be atomic for any respective platform bitness;

finally, and technically absolutely critical to perfect formal correctness, work products of the "losers" are reclaimed by GC and thus do no leak. In this type of race, losers are every racer except the last finisher (since everyone else's efforts get blithely and summarily overwritten with an identical result).

Although I believe these points combine to fully protect the code as written under every possible circumstance, if you're still suspicious or wary of the overall conclusion, you can always add an extra layer of bulletproofing:

var tmp = (Func<Ectx, Sctx>)dm.CreateDelegate(typeof(Func<Ectx, Sctx>));
Thread.MemoryBarrier();
__get = tmp;
return tmp(arg);

It's just a paraniod version. As with the earlier condensed one-liner, the .NET memory model guarantees that there is exactly one store--and zero fetches--to location of '__get'. (The full expanded example at the top does do an extra main memory fetch, but is still sound thanks to the second bullet point) As I mentioned, none of this should be necessary for correctness, but it could, in theory, give a miniscule performance bonus: by conclusively ending the race earlier, the aggressive flush could, in an extremely rare case, prevent a subsequent caller on a dirty cache line from unnecessarily (but again, harmlessly) racing.

Double-thunking

Calls into the final, hyper-fast method are still thunked through the static extension methods shown earlier.
This is because we also need to somehow represent entry point(s) that actually exist at compile time for the compiler to bind against and propagate metadata for. The double-thunk is a small price to pay for the overwhelming convenience of strongly-typed metadata and intellisense in the IDE for customized code that can't actually be resolved until runtime. Yet it runs at least as fast as statically compiled code, way faster that doing a bunch of reflection on every call, so we get the best of both worlds!


问:
Displaying PDF to Browser with PHP not working
Using php's ability to call upon the browser to display a given PDF it doesn't work on my web host. But it works on my local xamp server with apache.

PHP:

```<code>    $title = $_GET['title'];
    $loc = $_GET['loc'];

    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=".$title);
    @readfile($loc);
</code>```

Expected Output: Supposed to be the PDF document being rendered like it does on my local web server.

Actual but unwanted output:
%PDF-1.6 %���� 1638 0 obj <> endobj xref 1638 44 0000000016 00000 n ...

Can be seen here:
http://neilau.me/view.php?title=business-studies-hsc-notes-2006.pdf&loc=pdf/criteria/business-studies/2006/business-studies-hsc-notes-2006.pdf

Is this fixed through changing something on my cpanel? As my code isn't faulty... It works on my local web server.

答:
Use this code</p>

```<code><?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>
</code>```

Body:
Using php's ability to call upon the browser to display a given PDF it doesn't work on my web host. But it works on my local xamp server with apache.

PHP:

    $title = $_GET['title'];
    $loc = $_GET['loc'];

    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=".$title);
    @readfile($loc);

Expected Output: Supposed to be the PDF document being rendered like it does on my local web server.

Actual but unwanted output:
%PDF-1.6 %���� 1638 0 obj <> endobj xref 1638 44 0000000016 00000 n ...

Can be seen here:
http://neilau.me/view.php?title=business-studies-hsc-notes-2006.pdf&loc=pdf/criteria/business-studies/2006/business-studies-hsc-notes-2006.pdf

Is this fixed through changing something on my cpanel? As my code isn't faulty... It works on my local web server.

Body:
Use this code

<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>


问:
Telerik Grid - Export to CSV more columns than displayed on screen
Problem:  How to display more columns in a Telerik grid than are displayed in the rendered grid?

eg I'd like to only display on the screen the Surname, but on dump to csv would like firstname too.

I've tried visible = false, and display = false on the GridBoundColumns, but then they don't come out on the csv.

```<code><telerik:RadGrid ID="grdAuctions" runat="server" AllowAutomaticDeletes="True" AllowAutomaticUpdates="True"
        AllowPaging="False" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="odsAuctionSales"
        GridLines="None" EnableEmbeddedSkins="False" OnItemDataBound="grdAuctionSales_ItemDataBound">
        <ExportSettings HideStructureColumns="true" />
        <MasterTableView Width="100%" CommandItemDisplay="Top">
            <PagerStyle Mode="NextPrevNumericAndAdvanced" />
            <CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToCsvButton="true"
                ExportToCsvImageUrl="~/Images/excel.jpg" ExportToCsvText="Export to csv" />
        </MasterTableView>
        <MasterTableView DataKeyNames="Id" DataSourceID="odsAuctionSales" CssClass="listItems"
            Width="98%">
            <SortExpressions>
                <telerik:GridSortExpression FieldName="Name"></telerik:GridSortExpression>
            </SortExpressions>
            <RowIndicatorColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </RowIndicatorColumn>
            <ExpandCollapseColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridTemplateColumn UniqueName="Edit">
                    <ItemTemplate>
                        <asp:HyperLink ID="edit" runat="server" Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn DataField="NameOnTable" HeaderText="Name On Table" SortExpression="NameOnTable"
                    UniqueName="NameOnTable">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Surname" HeaderText="Surname" SortExpression="Surname"
                    UniqueName="Surname">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Firstname" HeaderText="Firstname" SortExpression="Firstname"
                    UniqueName="Firstname">
                </telerik:GridBoundColumn>
</code>```

Edit Here is how I got it working

```<code>protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.ExportToCsvCommandName)
        {
            grdAuctions.MasterTableView.GetColumn("Edit").Visible = false;
            grdAuctions.MasterTableView.GetColumn("DPSAuthCode").Visible = true;
    grdAuctions.MasterTableView.ExportToCSV();
        }

    }
</code>```

and in the aspx

```<code>OnItemCommand="RadGrid1_ItemCommand"
</code>```

and

```<code> <telerik:GridBoundColumn DataField="DPSAuthCode" HeaderText="DPSAuthCode" Visible="false"
                    SortExpression="DPSAuthCode" UniqueName="DPSAuthCode">
                </telerik:GridBoundColumn>
</code>```

答: Switching the Visible or Display property value prior to the export call should do the trick. Check the relevant section (Hide Columns) here for details.</p>

ContentLicense: CC BY-SA 2.5

Body:
Problem:  How to display more columns in a Telerik grid than are displayed in the rendered grid?

eg I'd like to only display on the screen the Surname, but on dump to csv would like firstname too.

I've tried visible = false, and display = false on the GridBoundColumns, but then they don't come out on the csv.

<telerik:RadGrid ID="grdAuctions" runat="server" AllowAutomaticDeletes="True" AllowAutomaticUpdates="True"
        AllowPaging="False" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="odsAuctionSales"
        GridLines="None" EnableEmbeddedSkins="False" OnItemDataBound="grdAuctionSales_ItemDataBound">
        <ExportSettings HideStructureColumns="true" />
        <MasterTableView Width="100%" CommandItemDisplay="Top">
            <PagerStyle Mode="NextPrevNumericAndAdvanced" />
            <CommandItemSettings ShowAddNewRecordButton="false" ShowRefreshButton="false" ShowExportToCsvButton="true"
                ExportToCsvImageUrl="~/Images/excel.jpg" ExportToCsvText="Export to csv" />
        </MasterTableView>
        <MasterTableView DataKeyNames="Id" DataSourceID="odsAuctionSales" CssClass="listItems"
            Width="98%">
            <SortExpressions>
                <telerik:GridSortExpression FieldName="Name"></telerik:GridSortExpression>
            </SortExpressions>
            <RowIndicatorColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </RowIndicatorColumn>
            <ExpandCollapseColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridTemplateColumn UniqueName="Edit">
                    <ItemTemplate>
                        <asp:HyperLink ID="edit" runat="server" Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn DataField="NameOnTable" HeaderText="Name On Table" SortExpression="NameOnTable"
                    UniqueName="NameOnTable">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Surname" HeaderText="Surname" SortExpression="Surname"
                    UniqueName="Surname">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Firstname" HeaderText="Firstname" SortExpression="Firstname"
                    UniqueName="Firstname">
                </telerik:GridBoundColumn>

Edit Here is how I got it working

protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.ExportToCsvCommandName)
        {
            grdAuctions.MasterTableView.GetColumn("Edit").Visible = false;
            grdAuctions.MasterTableView.GetColumn("DPSAuthCode").Visible = true;
    grdAuctions.MasterTableView.ExportToCSV();
        }

    }

and in the aspx

OnItemCommand="RadGrid1_ItemCommand"

and

 <telerik:GridBoundColumn DataField="DPSAuthCode" HeaderText="DPSAuthCode" Visible="false"
                    SortExpression="DPSAuthCode" UniqueName="DPSAuthCode">
                </telerik:GridBoundColumn>


问:
Issue with "ManyToMany" relationship Spring JPA
I'm new to Spring so sorry if this turns out to be a really dumb question, but I've tried almost everything. I have User and Role entities and there's a many to many relationship between them. If i remove the relationship it works just fine, otherwise I get errors. Could you help me out?

The Role class

```<code>import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Role {

    private Long id;
    private Set<User> users = new HashSet<>();

    public Role(){}
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany(mappedBy = "roles")
    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }
}
</code>```

The User class

```<code>import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class User {

    private Long id;
    private Set<Role> roles = new HashSet<>();

    public User(){}

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id",referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "role_id",referencedColumnName = "id"))
    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}
</code>```

The Errors

```<code>    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at com.restaurant.AppConfig.main(AppConfig.java:14) [main/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table user_roles add constraint FKrhfovtciq1l558cw6udg0h0d3 foreign key (role_id) references role (id)]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: java.sql.SQLException: Cannot add foreign key constraint
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1540) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2595) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1468) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 32 common frames omitted

:bootRun FAILED
</code>```

答:
Consider making this uni-directional.  Under normal circumstances, you only need to know which roles a given user has. So, best fix would be to remove getUsers() from your role class completely.

For reference to get it running, use a join table on both sides of the relationship.  Give this a try;
Role.java;

```<code>@ManyToMany
@JoinTable(name = "user_roles",
    joinColumns = @JoinColumn(name="role_id"),
    inverseJoinColumns = @JoinColumn(name="user_id"))
public Set<User> getUsers ()
</code>```

User.java

```<code>@ManyToMany
@JoinTable(name="user_roles",
    joinColumns=@JoinColumn(name="user_id"),
    inverseJoinColumns=@JoinColumn(name="role_id"))
public Set<Role> getRoles() {
</code>```

[edit] Also try adding this to application.properties but ONLY for testing!

```<code>spring.jpa.hibernate.ddl-auto=create-drop
</code>```

Just in case, from mysql I would also try

```<code>drop database your-database-name;
create database your-database-name;
</code>```

Body:
I'm new to Spring so sorry if this turns out to be a really dumb question, but I've tried almost everything. I have User and Role entities and there's a many to many relationship between them. If i remove the relationship it works just fine, otherwise I get errors. Could you help me out?

The Role class

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Role {

    private Long id;
    private Set<User> users = new HashSet<>();

    public Role(){}
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany(mappedBy = "roles")
    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }
}

The User class

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class User {

    private Long id;
    private Set<Role> roles = new HashSet<>();

    public User(){}

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id",referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "role_id",referencedColumnName = "id"))
    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

The Errors

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at com.restaurant.AppConfig.main(AppConfig.java:14) [main/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table user_roles add constraint FKrhfovtciq1l558cw6udg0h0d3 foreign key (role_id) references role (id)]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: java.sql.SQLException: Cannot add foreign key constraint
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1540) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2595) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1468) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 32 common frames omitted

:bootRun FAILED

Body:
Consider making this uni-directional.  Under normal circumstances, you only need to know which roles a given user has. So, best fix would be to remove getUsers() from your role class completely.

For reference to get it running, use a join table on both sides of the relationship.  Give this a try;
Role.java;

@ManyToMany
@JoinTable(name = "user_roles",
    joinColumns = @JoinColumn(name="role_id"),
    inverseJoinColumns = @JoinColumn(name="user_id"))
public Set<User> getUsers ()

User.java

@ManyToMany
@JoinTable(name="user_roles",
    joinColumns=@JoinColumn(name="user_id"),
    inverseJoinColumns=@JoinColumn(name="role_id"))
public Set<Role> getRoles() {

[edit] Also try adding this to application.properties but ONLY for testing!

spring.jpa.hibernate.ddl-auto=create-drop

Just in case, from mysql I would also try

drop database your-database-name;
create database your-database-name;