问:
keeping a button active while switching between pages
I am making a multi pager for a school project, it has all been going pretty well till now, but there is one thing i can't figure out,
i have a small java script that changes between 2 CSS files when clicked on a switch button, the one CSS`` page is a dark mode of the other CSS page.
so the button works, but every time i switch from the page i am on to another page the button resets, so for example if I'm om the home page and turn dark mode on, and then go to gallery page for example the dark mode resets and goes back to light, i wonder if anyone knows what i have to add to my java script to make this work properly.
thanks in advance.

document.getElementById('myonoffswitch').onclick = function() {
    console.log('123')
    if (document.getElementById('myonoffswitch').checked) {
      document.getElementById('theme').href = "../css/dark.css";
    } else {
      document.getElementById('theme').href = "../css/style.css";
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  margin: 0;
  text-align: center;
}

li {
  float: right;
  display: block;
  height: 45px;
  padding-top: 10px;
  padding-right: 10px;
  text-decoration: none;
}

a {
  text-decoration: none;
  color: rgb(255, 255, 255);
  font-size: 23px;
  text-align: center;
}

.hover {
  display: inline-block;
  position: relative;
}

.hover::before {
  content: '';
  position: absolute;
  width: 100%;
  transform: scaleX(0);
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: rgb(255, 255, 255);
  transform-origin: bottom right;
  transition: transform 0.25s ease-out;
}

.hover:hover::before {
  transform: scaleX(1);
  transform-origin: bottom left;
}

.header {
  position: absolute;
  width: 98%;
  top: 10px;
  left: 0;
  margin-left: 1%;
}

footer {
  background-image: radial-gradient(#000000, #535252);
  border-radius: 10px 10px 10px 10px;
  padding: 10px;
  background-color: rgb(255, 255, 255);
  text-align: center;
  color: rgb(255, 255, 255);
  border-radius: 10px 10px 10px 10px;
  box-shadow: rgb(0, 0, 0) 2px 2px 2px;
  margin-top: auto;
}

center {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

body {
  background-color: rgb(51, 51, 51);
}

.onoffswitch {
  position: relative;
  width: 90px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.onoffswitch-checkbox {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.onoffswitch-label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #FFFFFF;
  border-radius: 20px;
}

.onoffswitch-inner {
  display: block;
  width: 200%;
  margin-left: -100%;
  transition: margin 0.3s ease-in 0s;
}

.onoffswitch-inner:before,
.onoffswitch-inner:after {
  display: block;
  float: left;
  width: 50%;
  height: 30px;
  padding: 0;
  line-height: 30px;
  font-size: 14px;
  color: white;
  font-family: Trebuchet, Arial, sans-serif;
  font-weight: bold;
  box-sizing: border-box;
}

.onoffswitch-inner:before {
  content: "ON";
  padding-left: 10px;
  background-color: #000000;
  color: #FFFFFF;
}

.onoffswitch-inner:after {
  content: "OFF";
  padding-right: 10px;
  background-color: #EEEEEE;
  color: #999999;
  text-align: right;
}

.onoffswitch-switch {
  display: block;
  width: 18px;
  margin: 6px;
  background: #000000;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 56px;
  border: 2px solid #FFFFFF;
  border-radius: 20px;
  transition: all 0.3s ease-in 0s;
}

.onoffswitch-checkbox:checked+.onoffswitch-label .onoffswitch-inner {
  margin-left: 0;
}

.onoffswitch-checkbox:checked+.onoffswitch-label .onoffswitch-switch {
  right: 0px;
}

.box {
  background-color: rgb(0, 0, 0);
  width: 800px;
  border: 5px solid rgb(211, 211, 211);
  padding: 50px;
  margin: 20px;
  color: white;
  font-size: 10px;
  height: 452px;
  word-spacing: 5px;
}

.headline {
  color: white;
  font-size: 30px;
}

.moviecenter {
  position: relative;
  overflow: hidden;
  padding-top: 56.25%;
}

.resp-iframe {
  position: absolute;
  top: 180px;
  left: 1100px;
  width: 912px;
  height: 561px;
  border: 0;
}

#content {
  padding: 10px;
  font-family: abel;
  background-color: rgb(51, 51, 51);
  margin-left: 10px;
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 15px;
  color: #ffffff8a;
  font-size: 20px;
  box-shadow: inset 0px 1px 7px 0px #8585858a;
  text-align: center;
}

#imageTable {
  margin: auto;
  margin-bottom: 10px;
}

.gallery {
  margin: 5px;
  border: 5px solid #000000;
  width: 1000px;
}

#container {
  margin-top: 15px;
  padding: 10px;
}

.desc {
  padding: 25px;
  text-align: center;
}

.gallery:hover {
  border: 5px solid rgb(255, 255, 255);
}

.gallery img {
  width: 100%;
  height: auto;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="description" content="openings pagina van onze portofilio website" />
  <meta name="keywords" content="portofilio, animatie, beeld, geluid, video, internettechnieken, scripten, grafische, vormgeving" />
  <meta name="author" content="Liam De Herdt" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Home</title>
  <link rel="icon" type="image/x-icon" href="../images/heylen.ico">
  <link rel="stylesheet" href="../css/style.css" id="theme">
  <link href="../css/lightbox.css" rel="stylesheet" type="text/css">

S.I.T Secure Inmates Transport

Home

Info

Gallery

Story

Contact

    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" tabindex="0">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a vulputate orci, non posuere metus. Suspendisse potenti. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis scelerisque nibh massa. Sed tempus
      nunc libero, sed dictum tortor facilisis et. Donec dictum, dolor et tristique scelerisque, enim justo vestibulum eros, sed fringilla purus purus non mauris. Nulla vitae neque tortor. Nullam scelerisque faucibus commodo. Donec tincidunt elementum
      nibh ac laoreet. Pellentesque velit odio, eleifend et eros sed, faucibus gravida lorem. Donec vulputate dui ut nibh dictum, ut egestas ante mollis. Suspendisse suscipit tellus urna, id posuere nunc lobortis vel. Pellentesque maximus fringilla augue,
      in tincidunt orci vulputate in. Cras ut dapibus augue, sit amet convallis enim. Donec sollicitudin enim lacinia, bibendum felis vitae, efficitur nisl. Sed scelerisque tellus orci, quis commodo dolor elementum eget. Vestibulum blandit lobortis nisi,
      et hendrerit ipsum tincidunt quis. Ut dapibus mi facilisis est tristique suscipit. Suspendisse suscipit tellus urna, id posuere nunc lobortis vel. Pellentesque maximus fringilla augue, in tincidunt orci vulputate in. Cras ut dapibus augue, sit amet
      convallis enim. Donec sollicitudin enim lacinia, bibendum felis vitae, efficitur nisl. Sed scelerisque tellus orci, quis commodo dolor elementum eget. Vestibulum blandit lobortis nisi, et hendrerit ipsum tincidunt quis. Ut dapibus mi facilisis est
      tristique suscipit.Suspendisse suscipit tellus urna, id posuere nunc lobortis vel. Pellentesque maximus fringilla augue, in tincidunt

Digitale Foto Montage

Technisch Plan

© Liam De Herdt 2020

```

答:
What about javascript's local storage? You could set a value in one page and then retrieve in in the next page. This could be what you see below or the state of your button represented as a string. You could then use this string to set the style of your button to enabled or disable.

Local Storage

// Store enabled value
localStorage.setItem("myButtonState", "enabled");
// Or, Store disabled value
// localStorage.setItem("myButtonState", "disabled");

// Retrieve value
var myButtonState = localStorage.getItem("myButtonState");

// Check value if enabled
if(myButtonState == "enabled") {
  document.getElementById("myButtonState").disabled = false;
}

// Check value if disabled
if(myButtonState == "disabled") {
  document.getElementById("myButtonState").disabled = true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" id="myButton" disabled="">Button1</button></code>```

Body:
I am making a multi pager for a school project, it has all been going pretty well till now, but there is one thing i can't figure out,
i have a small java script that changes between 2 CSS files when clicked on a switch button, the one CSS`` page is a dark mode of the other CSS page.
so the button works, but every time i switch from the page i am on to another page the button resets, so for example if I'm om the home page and turn dark mode on, and then go to gallery page for example the dark mode resets and goes back to light, i wonder if anyone knows what i have to add to my java script to make this work properly.
thanks in advance.

document.getElementById('myonoffswitch').onclick = function() {
    console.log('123')
    if (document.getElementById('myonoffswitch').checked) {
      document.getElementById('theme').href = "../css/dark.css";
    } else {
      document.getElementById('theme').href = "../css/style.css";
    };

ul {
  margin: 0;
  text-align: center;
}

li {
  float: right;
  display: block;
  height: 45px;
  padding-top: 10px;
  padding-right: 10px;
  text-decoration: none;
}

a {
  text-decoration: none;
  color: rgb(255, 255, 255);
  font-size: 23px;
  text-align: center;
}

.hover {
  display: inline-block;
  position: relative;
}

.hover::before {
  content: '';
  position: absolute;
  width: 100%;
  transform: scaleX(0);
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: rgb(255, 255, 255);
  transform-origin: bottom right;
  transition: transform 0.25s ease-out;
}

.hover:hover::before {
  transform: scaleX(1);
  transform-origin: bottom left;
}

.header {
  position: absolute;
  width: 98%;
  top: 10px;
  left: 0;
  margin-left: 1%;
}

footer {
  background-image: radial-gradient(#000000, #535252);
  border-radius: 10px 10px 10px 10px;
  padding: 10px;
  background-color: rgb(255, 255, 255);
  text-align: center;
  color: rgb(255, 255, 255);
  border-radius: 10px 10px 10px 10px;
  box-shadow: rgb(0, 0, 0) 2px 2px 2px;
  margin-top: auto;
}

center {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

body {
  background-color: rgb(51, 51, 51);
}

.onoffswitch {
  position: relative;
  width: 90px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.onoffswitch-checkbox {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.onoffswitch-label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #FFFFFF;
  border-radius: 20px;
}

.onoffswitch-inner {
  display: block;
  width: 200%;
  margin-left: -100%;
  transition: margin 0.3s ease-in 0s;
}

.onoffswitch-inner:before,
.onoffswitch-inner:after {
  display: block;
  float: left;
  width: 50%;
  height: 30px;
  padding: 0;
  line-height: 30px;
  font-size: 14px;
  color: white;
  font-family: Trebuchet, Arial, sans-serif;
  font-weight: bold;
  box-sizing: border-box;
}

.onoffswitch-inner:before {
  content: "ON";
  padding-left: 10px;
  background-color: #000000;
  color: #FFFFFF;
}

.onoffswitch-inner:after {
  content: "OFF";
  padding-right: 10px;
  background-color: #EEEEEE;
  color: #999999;
  text-align: right;
}

.onoffswitch-switch {
  display: block;
  width: 18px;
  margin: 6px;
  background: #000000;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 56px;
  border: 2px solid #FFFFFF;
  border-radius: 20px;
  transition: all 0.3s ease-in 0s;
}

.onoffswitch-checkbox:checked+.onoffswitch-label .onoffswitch-inner {
  margin-left: 0;
}

.onoffswitch-checkbox:checked+.onoffswitch-label .onoffswitch-switch {
  right: 0px;
}

.box {
  background-color: rgb(0, 0, 0);
  width: 800px;
  border: 5px solid rgb(211, 211, 211);
  padding: 50px;
  margin: 20px;
  color: white;
  font-size: 10px;
  height: 452px;
  word-spacing: 5px;
}

.headline {
  color: white;
  font-size: 30px;
}

.moviecenter {
  position: relative;
  overflow: hidden;
  padding-top: 56.25%;
}

.resp-iframe {
  position: absolute;
  top: 180px;
  left: 1100px;
  width: 912px;
  height: 561px;
  border: 0;
}

#content {
  padding: 10px;
  font-family: abel;
  background-color: rgb(51, 51, 51);
  margin-left: 10px;
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 15px;
  color: #ffffff8a;
  font-size: 20px;
  box-shadow: inset 0px 1px 7px 0px #8585858a;
  text-align: center;
}

#imageTable {
  margin: auto;
  margin-bottom: 10px;
}

.gallery {
  margin: 5px;
  border: 5px solid #000000;
  width: 1000px;
}

#container {
  margin-top: 15px;
  padding: 10px;
}

.desc {
  padding: 25px;
  text-align: center;
}

.gallery:hover {
  border: 5px solid rgb(255, 255, 255);
}

.gallery img {
  width: 100%;
  height: auto;
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="description" content="openings pagina van onze portofilio website" />
  <meta name="keywords" content="portofilio, animatie, beeld, geluid, video, internettechnieken, scripten, grafische, vormgeving" />
  <meta name="author" content="Liam De Herdt" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Home</title>
  <link rel="icon" type="image/x-icon" href="../images/heylen.ico">
  <link rel="stylesheet" href="../css/style.css" id="theme">
  <link href="../css/lightbox.css" rel="stylesheet" type="text/css">

S.I.T Secure Inmates Transport

Home

Info

Gallery

Story

Contact

    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" tabindex="0">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a vulputate orci, non posuere metus. Suspendisse potenti. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis scelerisque nibh massa. Sed tempus
      nunc libero, sed dictum tortor facilisis et. Donec dictum, dolor et tristique scelerisque, enim justo vestibulum eros, sed fringilla purus purus non mauris. Nulla vitae neque tortor. Nullam scelerisque faucibus commodo. Donec tincidunt elementum
      nibh ac laoreet. Pellentesque velit odio, eleifend et eros sed, faucibus gravida lorem. Donec vulputate dui ut nibh dictum, ut egestas ante mollis. Suspendisse suscipit tellus urna, id posuere nunc lobortis vel. Pellentesque maximus fringilla augue,
      in tincidunt orci vulputate in. Cras ut dapibus augue, sit amet convallis enim. Donec sollicitudin enim lacinia, bibendum felis vitae, efficitur nisl. Sed scelerisque tellus orci, quis commodo dolor elementum eget. Vestibulum blandit lobortis nisi,
      et hendrerit ipsum tincidunt quis. Ut dapibus mi facilisis est tristique suscipit. Suspendisse suscipit tellus urna, id posuere nunc lobortis vel. Pellentesque maximus fringilla augue, in tincidunt orci vulputate in. Cras ut dapibus augue, sit amet
      convallis enim. Donec sollicitudin enim lacinia, bibendum felis vitae, efficitur nisl. Sed scelerisque tellus orci, quis commodo dolor elementum eget. Vestibulum blandit lobortis nisi, et hendrerit ipsum tincidunt quis. Ut dapibus mi facilisis est
      tristique suscipit.Suspendisse suscipit tellus urna, id posuere nunc lobortis vel. Pellentesque maximus fringilla augue, in tincidunt

Digitale Foto Montage

Technisch Plan

© Liam De Herdt 2020

Body:
What about javascript's local storage? You could set a value in one page and then retrieve in in the next page. This could be what you see below or the state of your button represented as a string. You could then use this string to set the style of your button to enabled or disable.

Local Storage

// Store enabled value
localStorage.setItem("myButtonState", "enabled");
// Or, Store disabled value
// localStorage.setItem("myButtonState", "disabled");

// Retrieve value
var myButtonState = localStorage.getItem("myButtonState");

// Check value if enabled
if(myButtonState == "enabled") {
  document.getElementById("myButtonState").disabled = false;
}

// Check value if disabled
if(myButtonState == "disabled") {
  document.getElementById("myButtonState").disabled = true;
}

<button type="button" id="myButton" disabled="">Button1</button>


来源: stackexchange

问:
Django Custom Authentication - BaseUserManager's create_user not being used
I customizes Django's authentication and now every time I try to create a new user using Django Admin this user's password is saved directly, without being hashed. I found out that create_user method from BaseUserManager class is not being called. When I create a superuser using bash it is done properly. Is there anything wrong with my model?

settings.py

```<code>AUTH_USER_MODEL = 'authentication.BaseAccount'
</code>```

apps/authentication/models.py

```<code>class BaseAccountManager(BaseUserManager):
   def create_user(self, email, password=None, **kwargs):
      if not email:
          raise ValueError('Users must have a valid email address.')

      account = self.model(
        email=self.normalize_email(email)
      )
      account.set_password(password)
      account.save()

   return account

   def create_superuser(self, email, password, **kwargs):
      account = self.create_user(email, password, **kwargs)

      account.is_admin = True
      account.is_staff = True
      account.save()

   return account

class BaseAccount(AbstractBaseUser):
   email = models.EmailField(unique=True)

   first_name = models.CharField(max_length=40, blank=True)
   last_name = models.CharField(max_length=40, blank=True)

   is_admin = models.BooleanField(default=False)
   is_staff = models.BooleanField(default=False)

   created_at = models.DateTimeField(auto_now_add=True)
   updated_at = models.DateTimeField(auto_now=True)

   objects = BaseAccountManager()

   USERNAME_FIELD = 'email'

   def __unicode__(self):
      return self.email

   def get_full_name(self):
      return ' '.join([self.first_name, self.last_name])

   def get_short_name(self):
      return self.first_name

   def has_perm(self, perm, obj=None):
      return self.is_admin

   def has_module_perms(self, app_label):
      return self.is_admin
</code>```

答:
For future readers, because this issue also got me banging my head against the wall...

To access that precious create_user() method from anywhere in your django project :

```<code>from django.contrib.auth import get_user_model

class SomeClass():
    # This could be a form, for example...
    def some_function():
        get_user_model().objects.create_user()
</code>```

If you call it from the save() method of some custom form, please take proper care of the commit parameter, and don't forget to register your custom user model in the settings.py file, as per the Django documentation.

ContentLicense: CC BY-SA 3.0

Body:
I customizes Django's authentication and now every time I try to create a new user using Django Admin this user's password is saved directly, without being hashed. I found out that create_user method from BaseUserManager class is not being called. When I create a superuser using bash it is done properly. Is there anything wrong with my model?

settings.py

AUTH_USER_MODEL = 'authentication.BaseAccount'

apps/authentication/models.py

class BaseAccountManager(BaseUserManager):
   def create_user(self, email, password=None, **kwargs):
      if not email:
          raise ValueError('Users must have a valid email address.')

      account = self.model(
        email=self.normalize_email(email)
      )
      account.set_password(password)
      account.save()

   return account

   def create_superuser(self, email, password, **kwargs):
      account = self.create_user(email, password, **kwargs)

      account.is_admin = True
      account.is_staff = True
      account.save()

   return account

class BaseAccount(AbstractBaseUser):
   email = models.EmailField(unique=True)

   first_name = models.CharField(max_length=40, blank=True)
   last_name = models.CharField(max_length=40, blank=True)

   is_admin = models.BooleanField(default=False)
   is_staff = models.BooleanField(default=False)

   created_at = models.DateTimeField(auto_now_add=True)
   updated_at = models.DateTimeField(auto_now=True)

   objects = BaseAccountManager()

   USERNAME_FIELD = 'email'

   def __unicode__(self):
      return self.email

   def get_full_name(self):
      return ' '.join([self.first_name, self.last_name])

   def get_short_name(self):
      return self.first_name

   def has_perm(self, perm, obj=None):
      return self.is_admin

   def has_module_perms(self, app_label):
      return self.is_admin

Body:
For future readers, because this issue also got me banging my head against the wall...

To access that precious create_user() method from anywhere in your django project :

from django.contrib.auth import get_user_model

class SomeClass():
    # This could be a form, for example...
    def some_function():
        get_user_model().objects.create_user()

If you call it from the save() method of some custom form, please take proper care of the commit parameter, and don't forget to register your custom user model in the settings.py file, as per the Django documentation.

ContentLicense: CC BY-SA 4.0


问:
Displaying index of element after finding it
```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int s;
    std::cin >> s;
    std::vector<int> numbers;

    for(int i{1}; i <= s; i++) {
        int num_input;
        std::cin >> num_input;
        numbers.push_back(num_input);
    }

    int c_s;
    std::cin >> c_s;

    while(c_s--) {
        int n;
        std::cin >> n;

        if(std::find(numbers.begin(),numbers.end(), n) != numbers.end()) {
            std::cout << "Yes" << std::endl;
        } else {
            std::cout << "No" << std::endl;
        }
    }
}
</code>```

There is a coding problem on hacker rank that wants me to display the index of int when I find it, but I can't think of any way to do that. Is there a simpler way to do it?

答:
You can get the index using std::distance on the iterator returned by std::find. You can change your code as follows

```<code>std::vector<int>::iterator it = std::find(numbers.begin(),numbers.end(),n);
if(it != numbers.end()) {
    std::cout << "Yes, found at" << std::distance(numbers.begin(),it) << std::endl;
} else {
    std::cout << "No" << std::endl;
}
</code>```

Body:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int s;
    std::cin >> s;
    std::vector<int> numbers;

    for(int i{1}; i <= s; i++) {
        int num_input;
        std::cin >> num_input;
        numbers.push_back(num_input);
    }

    int c_s;
    std::cin >> c_s;

    while(c_s--) {
        int n;
        std::cin >> n;

        if(std::find(numbers.begin(),numbers.end(), n) != numbers.end()) {
            std::cout << "Yes" << std::endl;
        } else {
            std::cout << "No" << std::endl;
        }
    }
}

There is a coding problem on hacker rank that wants me to display the index of int when I find it, but I can't think of any way to do that. Is there a simpler way to do it?

Body:
You can get the index using std::distance on the iterator returned by std::find. You can change your code as follows

std::vector<int>::iterator it = std::find(numbers.begin(),numbers.end(),n);
if(it != numbers.end()) {
    std::cout << "Yes, found at" << std::distance(numbers.begin(),it) << std::endl;
} else {
    std::cout << "No" << std::endl;
}


问:
Minimum length Unsorted Continous subarray
I am attempting this common interview problem Shortest Unsorted Continous subarray Problem statement looks like this.

Given an unsorted array A of size N. Find the subarray 0 <= s < r < N such that sorting this subarray makes the whole array sorted.

My Approach:

My idea was based on selection sort. We can traverse over the given array A choosing the elements A[i]. For every such element chosen, I tried to determine its correct position in the sorted array. For this, I compared A[i] with every A[j], such that i < j < N. But as you can see this approach took O(N*N) time complexity, but the judge expected a solution of O(N) time complexity and obviously O(1) extra space. Can anyone help me with an acceptable solution?

答:
Steps :

1) Find the first index from left and first index from right where the condition of sorted
   array fails i.e., A[i] > A[i+1]

2) Then find the minimum and maximum element in this range

3) If the minimum element obtained is not greater than all the elements before the
   considered range then, update the starting index

4) If the maximum element obtained is not lesser than all the elements after the
   considered range then, update the ending index

5) Starting and ending index obtained in this way will give us the correct answer

Time Complexity of this approach is O(n) and space complexity is O(1)

If u still have a doubt, you can refer this video.

Link :  https://youtu.be/UfBfr-VRYOU


问:
Python Community : Can we use BDD framework in community version?
I am self learning automation testing using Python. When going through few blogs they mentioned they have used Pycharm Professional version for Behave or Py-test BDD framework.

Can we use Pycharm community version for BDD frameworks?

Any advice is greatly appreciated.

Thanks,

答:
Here is the matrix containing all the differences between Community and Professional versions: https://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html.

According to it BDD frameworks are supported only in Pro.


问:
Binomial distribution series in C Programming
I can write the pascal triangle with the code below.
But my wish is to print the
**

(a+b)^p

** series.
My wish is as follows. Sample output:

```<code>(a+b)^p for unfolding p = 5
1
a^1 + b^1
a^2 + 2*a^1*b^1 + b^2
a^3 + 3*a^2*b^1 + 3*a^1*b^2 + b^3
a^4 + 4*a^3*b^1 + 6*a^2*b^2 + 4*a^1*b^3 + b^4
a^5 + 5*a^4*b^1 + 10*a^3*b^2 + 10*a^2*b^3 + 5*a^1*b^4 + b^5
</code>```

/******** MY Code *********/

```<code> #include <stdio.h>
 long paskal(int,int);
 int main()
 {
   int n=0;
   int m=0;
   int k=0;
   int s=0;
   printf("Enter number of rows:\n");
   scanf("%d", &n);
   for(k = 0; n >= k; k++) {
        for(m = 0; k >= m; m++) {
              long f = paskal(k, m);
                if(k==1)
                    printf("%ld",f);
                else
                    printf("a^%ld %ld b^%ld",k,f,k);
        }
        printf("\n");
    }
    return 0;
 }

 long paskal(int n, int i) {
    if(n == i || i == 0)
      return 1;
    else
      return paskal(n-1, i) + paskal(n-1, i-1);

   }
</code>```

/********OUTPUT**********/

```<code>  Enter number of rows:
  5
  11
  a^2 1 b^2a^2 2 b^2a^2 1 b^2
  a^3 1 b^3a^3 3 b^3a^3 3 b^3a^3 1 b^3
  a^4 1 b^4a^4 4 b^4a^4 6 b^4a^4 4 b^4a^4 1 b^4
  a^5 1 b^5a^5 5 b^5a^5 10 b^5a^5 10 b^5a^5 5 b^5a^5 1 b^5
</code>```

I am sorry for my English. Thank You

答:
In your desired output, I would suggest not printing the power of a when it is 1. So a^1 can just be a.

Then here is how you could do it -- it is simple to remove the if that eliminates the ^1, if you still want it in the output

```<code>// Helper function
void factor(long f, char letter, int power) {
    if (f != 1)
        printf("*");
    if (power != 0) {
        printf("%c", letter);
        if (power != 1)
            printf("^%d", power);
    }
}

int main() {
    int n = 0;
    printf("Enter number of rows:\n");
    scanf("%d", &n);
    if (n > 0)
        printf("1\n");
    for (int k = 1; k < n; k++) {
        for (int m = 0; m <= k; m++) {
            if (m != 0)
                printf(" + ");
            long f = paskal(k, m);
            if (f != 1)
                printf("%ld", f);
            factor(f, 'a', k - m);
            factor(f, 'b', m);
        }
        printf("\n");
    }
    return 0;
}
</code>```

Body:
I can write the pascal triangle with the code below.
But my wish is to print the
**

(a+b)^p

** series.
My wish is as follows. Sample output:

(a+b)^p for unfolding p = 5
1
a^1 + b^1
a^2 + 2*a^1*b^1 + b^2
a^3 + 3*a^2*b^1 + 3*a^1*b^2 + b^3
a^4 + 4*a^3*b^1 + 6*a^2*b^2 + 4*a^1*b^3 + b^4
a^5 + 5*a^4*b^1 + 10*a^3*b^2 + 10*a^2*b^3 + 5*a^1*b^4 + b^5

/******** MY Code *********/

 #include <stdio.h>
 long paskal(int,int);
 int main()
 {
   int n=0;
   int m=0;
   int k=0;
   int s=0;
   printf("Enter number of rows:\n");
   scanf("%d", &n);
   for(k = 0; n >= k; k++) {
        for(m = 0; k >= m; m++) {
              long f = paskal(k, m);
                if(k==1)
                    printf("%ld",f);
                else
                    printf("a^%ld %ld b^%ld",k,f,k);
        }
        printf("\n");
    }
    return 0;
 }

 long paskal(int n, int i) {
    if(n == i || i == 0)
      return 1;
    else
      return paskal(n-1, i) + paskal(n-1, i-1);

   }

/********OUTPUT**********/

  Enter number of rows:
  5
  11
  a^2 1 b^2a^2 2 b^2a^2 1 b^2
  a^3 1 b^3a^3 3 b^3a^3 3 b^3a^3 1 b^3
  a^4 1 b^4a^4 4 b^4a^4 6 b^4a^4 4 b^4a^4 1 b^4
  a^5 1 b^5a^5 5 b^5a^5 10 b^5a^5 10 b^5a^5 5 b^5a^5 1 b^5

I am sorry for my English. Thank You

Body:
In your desired output, I would suggest not printing the power of a when it is 1. So a^1 can just be a.

Then here is how you could do it -- it is simple to remove the if that eliminates the ^1, if you still want it in the output

// Helper function
void factor(long f, char letter, int power) {
    if (f != 1)
        printf("*");
    if (power != 0) {
        printf("%c", letter);
        if (power != 1)
            printf("^%d", power);
    }
}

int main() {
    int n = 0;
    printf("Enter number of rows:\n");
    scanf("%d", &n);
    if (n > 0)
        printf("1\n");
    for (int k = 1; k < n; k++) {
        for (int m = 0; m <= k; m++) {
            if (m != 0)
                printf(" + ");
            long f = paskal(k, m);
            if (f != 1)
                printf("%ld", f);
            factor(f, 'a', k - m);
            factor(f, 'b', m);
        }
        printf("\n");
    }
    return 0;
}


问:
SunCertPathBuilderException on deployment of Spring Boot Okta app
I am deploying a Spring Boot application with Okta OAuth2 Sign On functionality to Wildfly 19. During deployment I am receiving the error below:

```<code>{"WFLYCTL0062: Composite operation failed and was rolled back. Steps
that failed:" => {"Operation step-2" => {"WFLYCTL0080: Failed services" => {"jbo
ss.deployment.subunit.\"OktaSpringBootDemoEAR.ear\".\"OktaSpringBootDemo.war\".u
ndertow-deployment" => "java.lang.RuntimeException: org.springframework.beans.fa
ctory.UnsatisfiedDependencyException: Error creating bean with name 'codeFlowExa
mpleApplication.WebConfig': Unsatisfied dependency expressed through method 'set
ContentNegotationStrategy' parameter 0; nested exception is org.springframework.
beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org
.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWe
bMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigur
ers' parameter 0; nested exception is org.springframework.beans.factory.Unsatisf
iedDependencyException: Error creating bean with name 'org.springframework.secur
ity.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWe
bMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'set
ClientRegistrationRepository' parameter 0; nested exception is org.springframewo
rk.beans.factory.BeanCreationException: Error creating bean with name 'clientReg
istrationRepository' defined in class path resource [org/springframework/boot/au
toconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryCon
figuration.class]: Bean instantiation via factory method failed; nested exceptio
n is org.springframework.beans.BeanInstantiationException: Failed to instantiate
 [org.springframework.security.oauth2.client.registration.InMemoryClientRegistra
tionRepository]: Factory method 'clientRegistrationRepository' threw exception;
nested exception is java.lang.IllegalArgumentException: Unable to resolve Config
uration with the provided Issuer of \"https://dev-494336.okta.com/oauth2/default
\"
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.Uns
atisfiedDependencyException: Error creating bean with name 'codeFlowExampleAppli
cation.WebConfig': Unsatisfied dependency expressed through method 'setContentNe
gotationStrategy' parameter 0; nested exception is org.springframework.beans.fac
tory.UnsatisfiedDependencyException: Error creating bean with name 'org.springfr
amework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfi
guration': Unsatisfied dependency expressed through method 'setConfigurers' para
meter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDepend
encyException: Error creating bean with name 'org.springframework.security.confi
g.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecur
ityConfiguration': Unsatisfied dependency expressed through method 'setClientReg
istrationRepository' parameter 0; nested exception is org.springframework.beans.
factory.BeanCreationException: Error creating bean with name 'clientRegistration
Repository' defined in class path resource [org/springframework/boot/autoconfigu
re/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguratio
n.class]: Bean instantiation via factory method failed; nested exception is org.
springframework.beans.BeanInstantiationException: Failed to instantiate [org.spr
ingframework.security.oauth2.client.registration.InMemoryClientRegistrationRepos
itory]: Factory method 'clientRegistrationRepository' threw exception; nested ex
ception is java.lang.IllegalArgumentException: Unable to resolve Configuration w
ith the provided Issuer of \"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'codeFlowExampleApplication.WebConfig': Unsatisfi
ed dependency expressed through method 'setContentNegotationStrategy' parameter
0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyEx
ception: Error creating bean with name 'org.springframework.boot.autoconfigure.w
eb.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied depen
dency expressed through method 'setConfigurers' parameter 0; nested exception is
 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creatin
g bean with name 'org.springframework.security.config.annotation.web.configurati
on.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfi
ed dependency expressed through method 'setClientRegistrationRepository' paramet
er 0; nested exception is org.springframework.beans.factory.BeanCreationExceptio
n: Error creating bean with name 'clientRegistrationRepository' defined in class
 path resource [org/springframework/boot/autoconfigure/security/oauth2/client/se
rvlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation
 via factory method failed; nested exception is org.springframework.beans.BeanIn
stantiationException: Failed to instantiate [org.springframework.security.oauth2
.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clie
ntRegistrationRepository' threw exception; nested exception is java.lang.Illegal
ArgumentException: Unable to resolve Configuration with the provided Issuer of \
"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'org.springframework.boot.autoconfigure.web.servl
et.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency ex
pressed through method 'setConfigurers' parameter 0; nested exception is org.spr
ingframework.beans.factory.UnsatisfiedDependencyException: Error creating bean w
ith name 'org.springframework.security.config.annotation.web.configuration.OAuth
2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied depen
dency expressed through method 'setClientRegistrationRepository' parameter 0; ne
sted exception is org.springframework.beans.factory.BeanCreationException: Error
 creating bean with name 'clientRegistrationRepository' defined in class path re
source [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OA
uth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via fac
tory method failed; nested exception is org.springframework.beans.BeanInstantiat
ionException: Failed to instantiate [org.springframework.security.oauth2.client.
registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegist
rationRepository' threw exception; nested exception is java.lang.IllegalArgument
Exception: Unable to resolve Configuration with the provided Issuer of \"https:/
/dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'org.springframework.security.config.annotation.w
eb.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfigurati
on': Unsatisfied dependency expressed through method 'setClientRegistrationRepos
itory' parameter 0; nested exception is org.springframework.beans.factory.BeanCr
eationException: Error creating bean with name 'clientRegistrationRepository' de
fined in class path resource [org/springframework/boot/autoconfigure/security/oa
uth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean
 instantiation via factory method failed; nested exception is org.springframewor
k.beans.BeanInstantiationException: Failed to instantiate [org.springframework.s
ecurity.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factor
y method 'clientRegistrationRepository' threw exception; nested exception is jav
a.lang.IllegalArgumentException: Unable to resolve Configuration with the provid
ed Issuer of \"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.BeanCreationException: Error cr
eating bean with name 'clientRegistrationRepository' defined in class path resou
rce [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth
2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factor
y method failed; nested exception is org.springframework.beans.BeanInstantiation
Exception: Failed to instantiate [org.springframework.security.oauth2.client.reg
istration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrat
ionRepository' threw exception; nested exception is java.lang.IllegalArgumentExc
eption: Unable to resolve Configuration with the provided Issuer of \"https://de
v-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to i
nstantiate [org.springframework.security.oauth2.client.registration.InMemoryClie
ntRegistrationRepository]: Factory method 'clientRegistrationRepository' threw e
xception; nested exception is java.lang.IllegalArgumentException: Unable to reso
lve Configuration with the provided Issuer of \"https://dev-494336.okta.com/oaut
h2/default\"
    Caused by: java.lang.IllegalArgumentException: Unable to resolve Configurati
on with the provided Issuer of \"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.web.client.ResourceAccessException: I/O error
 on GET request for \"https://dev-494336.okta.com/oauth2/default/.well-known/ope
nid-configuration\": sun.security.validator.ValidatorException: PKIX path buildi
ng failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to
 find valid certification path to requested target; nested exception is javax.ne
t.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX pat
h building failed: sun.security.provider.certpath.SunCertPathBuilderException: u
nable to find valid certification path to requested target
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.Valid
atorException: PKIX path building failed: sun.security.provider.certpath.SunCert
PathBuilderException: unable to find valid certification path to requested targe
t
    Caused by: sun.security.validator.ValidatorException: PKIX path building fai
led: sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unabl
e to find valid certification path to requested target"}}}}
</code>```

Below is my application.properties file:

```<code>okta.oauth2.issuer=https://dev-494336.okta.com/oauth2/default
okta.oauth2.client-id=<my client id>
okta.oauth2.client-secret=<my client secret>
okta.oauth2.redirect-uri=/authorization-code/callback
okta.oauth2.scopes=profile,email,openid
okta.oauth2.postLogoutRedirectUri=https://<myUrl>/OktaSpringBootDemo
server.use-forward-headers=true
spring.security.oauth2.client.provider.okta.user-name-attribute=email
</code>```

Okta configuration:

```<code>Allowed Grant Types: Authorization Code
Application Type: Web
Login redirect URIs: https://<myUrl>/OktaSpringBootDemo/authorization-code/callback
Logout redirect URIs: https://<myUrl>/OktaSpringBootDemo
Login initiated by: App Only
Initiate login URI: https://<myUrl>/OktaSpringBootDemo
</code>```

My authorization server is the default one provded by Okta

```<code>Name: default
Audience: api://default
Issuer URI: https://dev-494336.okta.com/oauth2/default
Metadata URI: https://dev-494336.okta.com/oauth2/default/.well-known/oauth-authorization-server
</code>```

I have seen posts online about an optional certificate chain field that needs modification, but I do not see that anywhere in my Okta Dev Console. I also tried adding the okta certificate to my keystore and cacerts file, but no resolution there. This application works without any issues on my local Wildfly server and using localhost:8080 as the URLs.

答: I resolved this issue by downloading the public certificate from okta.com and adding it to the cacerts file under jre/lib/security/. Then, I restarted the server and it successfully deployed.

Body:
I am deploying a Spring Boot application with Okta OAuth2 Sign On functionality to Wildfly 19. During deployment I am receiving the error below:

{"WFLYCTL0062: Composite operation failed and was rolled back. Steps
that failed:" => {"Operation step-2" => {"WFLYCTL0080: Failed services" => {"jbo
ss.deployment.subunit.\"OktaSpringBootDemoEAR.ear\".\"OktaSpringBootDemo.war\".u
ndertow-deployment" => "java.lang.RuntimeException: org.springframework.beans.fa
ctory.UnsatisfiedDependencyException: Error creating bean with name 'codeFlowExa
mpleApplication.WebConfig': Unsatisfied dependency expressed through method 'set
ContentNegotationStrategy' parameter 0; nested exception is org.springframework.
beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org
.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWe
bMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigur
ers' parameter 0; nested exception is org.springframework.beans.factory.Unsatisf
iedDependencyException: Error creating bean with name 'org.springframework.secur
ity.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWe
bMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'set
ClientRegistrationRepository' parameter 0; nested exception is org.springframewo
rk.beans.factory.BeanCreationException: Error creating bean with name 'clientReg
istrationRepository' defined in class path resource [org/springframework/boot/au
toconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryCon
figuration.class]: Bean instantiation via factory method failed; nested exceptio
n is org.springframework.beans.BeanInstantiationException: Failed to instantiate
 [org.springframework.security.oauth2.client.registration.InMemoryClientRegistra
tionRepository]: Factory method 'clientRegistrationRepository' threw exception;
nested exception is java.lang.IllegalArgumentException: Unable to resolve Config
uration with the provided Issuer of \"https://dev-494336.okta.com/oauth2/default
\"
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.Uns
atisfiedDependencyException: Error creating bean with name 'codeFlowExampleAppli
cation.WebConfig': Unsatisfied dependency expressed through method 'setContentNe
gotationStrategy' parameter 0; nested exception is org.springframework.beans.fac
tory.UnsatisfiedDependencyException: Error creating bean with name 'org.springfr
amework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfi
guration': Unsatisfied dependency expressed through method 'setConfigurers' para
meter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDepend
encyException: Error creating bean with name 'org.springframework.security.confi
g.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecur
ityConfiguration': Unsatisfied dependency expressed through method 'setClientReg
istrationRepository' parameter 0; nested exception is org.springframework.beans.
factory.BeanCreationException: Error creating bean with name 'clientRegistration
Repository' defined in class path resource [org/springframework/boot/autoconfigu
re/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguratio
n.class]: Bean instantiation via factory method failed; nested exception is org.
springframework.beans.BeanInstantiationException: Failed to instantiate [org.spr
ingframework.security.oauth2.client.registration.InMemoryClientRegistrationRepos
itory]: Factory method 'clientRegistrationRepository' threw exception; nested ex
ception is java.lang.IllegalArgumentException: Unable to resolve Configuration w
ith the provided Issuer of \"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'codeFlowExampleApplication.WebConfig': Unsatisfi
ed dependency expressed through method 'setContentNegotationStrategy' parameter
0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyEx
ception: Error creating bean with name 'org.springframework.boot.autoconfigure.w
eb.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied depen
dency expressed through method 'setConfigurers' parameter 0; nested exception is
 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creatin
g bean with name 'org.springframework.security.config.annotation.web.configurati
on.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfi
ed dependency expressed through method 'setClientRegistrationRepository' paramet
er 0; nested exception is org.springframework.beans.factory.BeanCreationExceptio
n: Error creating bean with name 'clientRegistrationRepository' defined in class
 path resource [org/springframework/boot/autoconfigure/security/oauth2/client/se
rvlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation
 via factory method failed; nested exception is org.springframework.beans.BeanIn
stantiationException: Failed to instantiate [org.springframework.security.oauth2
.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clie
ntRegistrationRepository' threw exception; nested exception is java.lang.Illegal
ArgumentException: Unable to resolve Configuration with the provided Issuer of \
"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'org.springframework.boot.autoconfigure.web.servl
et.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency ex
pressed through method 'setConfigurers' parameter 0; nested exception is org.spr
ingframework.beans.factory.UnsatisfiedDependencyException: Error creating bean w
ith name 'org.springframework.security.config.annotation.web.configuration.OAuth
2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied depen
dency expressed through method 'setClientRegistrationRepository' parameter 0; ne
sted exception is org.springframework.beans.factory.BeanCreationException: Error
 creating bean with name 'clientRegistrationRepository' defined in class path re
source [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OA
uth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via fac
tory method failed; nested exception is org.springframework.beans.BeanInstantiat
ionException: Failed to instantiate [org.springframework.security.oauth2.client.
registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegist
rationRepository' threw exception; nested exception is java.lang.IllegalArgument
Exception: Unable to resolve Configuration with the provided Issuer of \"https:/
/dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'org.springframework.security.config.annotation.w
eb.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfigurati
on': Unsatisfied dependency expressed through method 'setClientRegistrationRepos
itory' parameter 0; nested exception is org.springframework.beans.factory.BeanCr
eationException: Error creating bean with name 'clientRegistrationRepository' de
fined in class path resource [org/springframework/boot/autoconfigure/security/oa
uth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean
 instantiation via factory method failed; nested exception is org.springframewor
k.beans.BeanInstantiationException: Failed to instantiate [org.springframework.s
ecurity.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factor
y method 'clientRegistrationRepository' threw exception; nested exception is jav
a.lang.IllegalArgumentException: Unable to resolve Configuration with the provid
ed Issuer of \"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.factory.BeanCreationException: Error cr
eating bean with name 'clientRegistrationRepository' defined in class path resou
rce [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth
2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factor
y method failed; nested exception is org.springframework.beans.BeanInstantiation
Exception: Failed to instantiate [org.springframework.security.oauth2.client.reg
istration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrat
ionRepository' threw exception; nested exception is java.lang.IllegalArgumentExc
eption: Unable to resolve Configuration with the provided Issuer of \"https://de
v-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to i
nstantiate [org.springframework.security.oauth2.client.registration.InMemoryClie
ntRegistrationRepository]: Factory method 'clientRegistrationRepository' threw e
xception; nested exception is java.lang.IllegalArgumentException: Unable to reso
lve Configuration with the provided Issuer of \"https://dev-494336.okta.com/oaut
h2/default\"
    Caused by: java.lang.IllegalArgumentException: Unable to resolve Configurati
on with the provided Issuer of \"https://dev-494336.okta.com/oauth2/default\"
    Caused by: org.springframework.web.client.ResourceAccessException: I/O error
 on GET request for \"https://dev-494336.okta.com/oauth2/default/.well-known/ope
nid-configuration\": sun.security.validator.ValidatorException: PKIX path buildi
ng failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to
 find valid certification path to requested target; nested exception is javax.ne
t.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX pat
h building failed: sun.security.provider.certpath.SunCertPathBuilderException: u
nable to find valid certification path to requested target
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.Valid
atorException: PKIX path building failed: sun.security.provider.certpath.SunCert
PathBuilderException: unable to find valid certification path to requested targe
t
    Caused by: sun.security.validator.ValidatorException: PKIX path building fai
led: sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unabl
e to find valid certification path to requested target"}}}}

Below is my application.properties file:

okta.oauth2.issuer=https://dev-494336.okta.com/oauth2/default
okta.oauth2.client-id=<my client id>
okta.oauth2.client-secret=<my client secret>
okta.oauth2.redirect-uri=/authorization-code/callback
okta.oauth2.scopes=profile,email,openid
okta.oauth2.postLogoutRedirectUri=https://<myUrl>/OktaSpringBootDemo
server.use-forward-headers=true
spring.security.oauth2.client.provider.okta.user-name-attribute=email

Okta configuration:

Allowed Grant Types: Authorization Code
Application Type: Web
Login redirect URIs: https://<myUrl>/OktaSpringBootDemo/authorization-code/callback
Logout redirect URIs: https://<myUrl>/OktaSpringBootDemo
Login initiated by: App Only
Initiate login URI: https://<myUrl>/OktaSpringBootDemo

My authorization server is the default one provded by Okta

Name: default
Audience: api://default
Issuer URI: https://dev-494336.okta.com/oauth2/default
Metadata URI: https://dev-494336.okta.com/oauth2/default/.well-known/oauth-authorization-server

I have seen posts online about an optional certificate chain field that needs modification, but I do not see that anywhere in my Okta Dev Console. I also tried adding the okta certificate to my keystore and cacerts file, but no resolution there. This application works without any issues on my local Wildfly server and using localhost:8080 as the URLs.


问:
Why does modifier order matter in SwiftUI?
When applying modifiers to a view in SwiftUI, it appears that the order matters.

For example, this code:

HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}
```

<p>..will produce this:</p>

<p><img src="https://i.stack.imgur.com/LjDj3.png" alt="watchOS preview displaying a simple view"></p>

<p>Change the order of the modifiers and things change. This code effectively 'breaks' the modifiers, as padding and corner radius are no longer applied:</p>

<pre class="lang-swift prettyprint-override"><code>HStack {
  Text("Hello world")
    .background(Color(UIColor.darkGray))
    .padding()
    .cornerRadius(20.0)
}
</code>```

Why is this? I'm sure there's a logical explanation but I couldn't find any documentation or rationale for it.

答:
A modifier is function that returns some View by wrapping the content View it modifies. For example .padding returns some View that implements a padding functionality and its content is the View it modifies, plus the padding:

So, conceptually:

```<code>HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}
</code>```

is roughly equivalent to (names and params are made up):

```<code>HStack(content: {
   CornerRadiusView(20.0, content: {
      BackgroundView(Color(UIColor.darkGray), content: {
         PaddingView(content: {
            Text("Hello world")
         })
      })
   })
})
</code>```

Hopefully, it's clear from the example how the order of the modifiers changes the view hierarchy.

Body:
When applying modifiers to a view in SwiftUI, it appears that the order matters.

For example, this code:

HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}

..will produce this:

Change the order of the modifiers and things change. This code effectively 'breaks' the modifiers, as padding and corner radius are no longer applied:

HStack {
  Text("Hello world")
    .background(Color(UIColor.darkGray))
    .padding()
    .cornerRadius(20.0)
}

Why is this? I'm sure there's a logical explanation but I couldn't find any documentation or rationale for it.

Body:
A modifier is function that returns some View by wrapping the content View it modifies. For example .padding returns some View that implements a padding functionality and its content is the View it modifies, plus the padding:

So, conceptually:

HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}

is roughly equivalent to (names and params are made up):

HStack(content: {
   CornerRadiusView(20.0, content: {
      BackgroundView(Color(UIColor.darkGray), content: {
         PaddingView(content: {
            Text("Hello world")
         })
      })
   })
})

Hopefully, it's clear from the example how the order of the modifiers changes the view hierarchy.


问:
R:How to display city level data on map and how to ZOOM it on one specific region of the map
I am using usmap and ggplot to plot population on a map. My data has two columns - population and zipcodes.

Question: How can I display data on city level  using the same libraries or if you know of other libraries that can do the job.

Question: I am plotting California map and I want to zoom on LA county and nearby counties.

Below code gives me a nice California map and population as a color.

```<code>library(usmap)
library(ggplot2)

usmap::plot_usmap("counties",
              include = ("CA") )

plot_usmap(data = data, values = "pop_2015", include = c("CA"), color = "grey") +
theme(legend.position = "right")+scale_fill_gradient(trans = "log10")
</code>```

答:
The tigris package makes downloading zip code tabulation areas fairly simple. You can download as a simple features dataframe so joining your data by zip code using dplyr functions is fairly easy. Here is a quick example:

library(tigris)
library(dplyr)
library(ggplot2)

df <- zctas(cb = TRUE,
            starts_with = c("778"),
            class = "sf")

## generate some sample data that
## can be joined to the downloaded data
sample_data <- tibble(zips = df$ZCTA5CE10,
                      values = rnorm(n = df$ZCTA5CE10))

## left join the sample data to the downloaded data
df <- df %>%
  left_join(sample_data,
            by = c("ZCTA5CE10" = "zips"))

## plot something
ggplot(df) +
  geom_sf(aes(fill = values))
```

Body:
I am using usmap and ggplot to plot population on a map. My data has two columns - population and zipcodes.

Question: How can I display data on city level  using the same libraries or if you know of other libraries that can do the job.

Question: I am plotting California map and I want to zoom on LA county and nearby counties.

Below code gives me a nice California map and population as a color.

library(usmap)
library(ggplot2)

usmap::plot_usmap("counties",
              include = ("CA") )

plot_usmap(data = data, values = "pop_2015", include = c("CA"), color = "grey") +
theme(legend.position = "right")+scale_fill_gradient(trans = "log10")


问:
CMAKE in Visual Studio seems to recognize header files but fail to build anyway
I know this is a common question, but I've already lost two days to this.

I have a VERY basic cmake project in visual studio 2019, that will eventually need to compile for Linux and Windows, but right now I cannot get beyond simple compiler errors.

I have my project directory(as provided by visual studio) as follows

```<code>Solution
|-Project
| |-Includes
| | |-defines.h
| | |-lib.h
| | |-lib.c
| |-main.c
| |-CMakeLists.txt
|-CMakeLists.txt
|-CMakeSettings.json
</code>```

the problem that occurs is, all functions in all files autocomplete appropriately with intellisense, so something is going right. However, when I try to build(for any target) I get undefined reference to {name} for EVERY reference to anything in the lib.h and lib.c files.

The CMakeLists.txt is as below

```<code># CMakeList.txt : CMake project for LabJackStreamPortable, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)

# Add source to this project's executable.
include_directories(Includes)
add_executable (Project "main.c")
# TODO: Add tests and install targets if needed.
</code>```

nothing I've done with changing the include directory, or using  target_include_directories changes anything. I've gotten the project to build for all targets with basic include (stdlib, stdio, etc...) and build referencing basic #define constants from the defines.h. but any function housed in the lib.c file give errors.

答:
From your example, you haven't specified lib.c anywhere, so this file will not be compiled. Therefore, if your main.c file references anything in lib.c, you will certainly receive errors.

If you want CMake to compile lib.c also, you need to list it explicitly as one of the source files:

```<code>add_executable (Project main.c Includes/lib.c)
</code>```

Body:
I know this is a common question, but I've already lost two days to this.

I have a VERY basic cmake project in visual studio 2019, that will eventually need to compile for Linux and Windows, but right now I cannot get beyond simple compiler errors.

I have my project directory(as provided by visual studio) as follows

Solution
|-Project
| |-Includes
| | |-defines.h
| | |-lib.h
| | |-lib.c
| |-main.c
| |-CMakeLists.txt
|-CMakeLists.txt
|-CMakeSettings.json

the problem that occurs is, all functions in all files autocomplete appropriately with intellisense, so something is going right. However, when I try to build(for any target) I get undefined reference to {name} for EVERY reference to anything in the lib.h and lib.c files.

The CMakeLists.txt is as below

# CMakeList.txt : CMake project for LabJackStreamPortable, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)

# Add source to this project's executable.
include_directories(Includes)
add_executable (Project "main.c")
# TODO: Add tests and install targets if needed.

nothing I've done with changing the include directory, or using  target_include_directories changes anything. I've gotten the project to build for all targets with basic include (stdlib, stdio, etc...) and build referencing basic #define constants from the defines.h. but any function housed in the lib.c file give errors.

Body:
From your example, you haven't specified lib.c anywhere, so this file will not be compiled. Therefore, if your main.c file references anything in lib.c, you will certainly receive errors.

If you want CMake to compile lib.c also, you need to list it explicitly as one of the source files:

add_executable (Project main.c Includes/lib.c)


问:
TCPDF - adding annotations for files causes duplicate attachments
We are using TCPDF for PDF generation in our website and we are having some difficulty using it for attaching files. We are putting blank annotations into the PDF which in turn link to the download (which can also be viewed as part of the PDF attachments view)

Our problem is that when we add an attachment it also adds an annotation with a link to the attachment, so in essence we are getting double attachments, whereby some of the links are direct links to download the attachments and some of links to the un-viewable annotations. If we try to remove the annotations then we show just one download link, but then on occasion some of the links will not download the file, this seems to be completely random and nonsensical..

Has anyone had a similar problem with TCPDF, we've found the source code is extremely hard to decipherer as the entire functionality is contained in on 25,000 line file..

Edit to add code sample

```<code>Route::get('/pdf', function() {

    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    $file_path       = storage_path() . '/exports/pdf';

    if (!File::exists($file_path)) {
        File::makeDirectory($file_path, 0775, true);
    }

    $file = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg";

    $pdf->Annotation(0, 0, 0, 0, 'attachment', array('Subtype' => 'FileAttachment',  'FS' => $file));

    $file_no = rand(0, 500);

    $file_name = "test{$file_no}.pdf";
    $file_location =  "{$file_path}/{$file_name}";

    $output_type = "F";

    $pdf->Output($file_location, $output_type);

});
</code>```

Sample output : http://www.filedropper.com/test96
* Please download and open in Acrobat to view attachments

答:
I know this is ancient now, but it was one of the first results I found on Google when I was looking into a similar issue. So I hope this can be of help for someone else encountering a similar issue.

Based on the fact that the attachment annotation was being placed in the top left corner with no size I think what was intended here wasn't adding an annotation at all, but attaching a file and then viewing it in the attachments section of the reader.

We ran into a similar issue assuming (not knowing much about the PDF spec and seeing the same library documentation) that attachments were always added as annotations. But this is not so. And when attachments are added as annotations acrobat reader seems to render a line for the attachment annotation and also a generic attachment line. When you don't actually want an annotation this can be worked around by adding it just as an attachment.

While tcpdf only allows adding attachments as an annotation currently we've added a pull request here to allow adding attachments without annotations: https://github.com/tecnickcom/TCPDF/pull/236

Body:
We are using TCPDF for PDF generation in our website and we are having some difficulty using it for attaching files. We are putting blank annotations into the PDF which in turn link to the download (which can also be viewed as part of the PDF attachments view)

Our problem is that when we add an attachment it also adds an annotation with a link to the attachment, so in essence we are getting double attachments, whereby some of the links are direct links to download the attachments and some of links to the un-viewable annotations. If we try to remove the annotations then we show just one download link, but then on occasion some of the links will not download the file, this seems to be completely random and nonsensical..

Has anyone had a similar problem with TCPDF, we've found the source code is extremely hard to decipherer as the entire functionality is contained in on 25,000 line file..

Edit to add code sample

Route::get('/pdf', function() {

    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    $file_path       = storage_path() . '/exports/pdf';

    if (!File::exists($file_path)) {
        File::makeDirectory($file_path, 0775, true);
    }

    $file = "http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg";

    $pdf->Annotation(0, 0, 0, 0, 'attachment', array('Subtype' => 'FileAttachment',  'FS' => $file));

    $file_no = rand(0, 500);

    $file_name = "test{$file_no}.pdf";
    $file_location =  "{$file_path}/{$file_name}";

    $output_type = "F";

    $pdf->Output($file_location, $output_type);

});

Sample output : http://www.filedropper.com/test96
* Please download and open in Acrobat to view attachments


问:
CSS width of a  tag
I use  tags in my module titles,
e.g.

Categories.

I specify the span's background color/image, width and height in css.

But the span's width depends on its content/text.

So, if I do , with just a background image/color in css, nothing appears.

Of course, I want something to appear.

How can I resolve this?

答:
Use the attribute 'display' as in the example:</p>

```<code><span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>
</code>```

ContentLicense: CC BY-SA 2.5

Title: CSS width of a <span> tag

Body:
Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>

OwnerDisplayName: Antonio


问:
MAPIFolder deprecated so workaround for Outlook programming?
MSDN says this of the MAPIFolder interface (Outlook programming with WPF):

This interface is deprecated; do not
  use this interface. Instead use the
  interface Folder to access all method,
  property, and event members of the COM
  object Folder.

I am trying to get the Drafts folder like so:

Outlook.MAPIFolder oFolder = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts);

How do I do the above without using the MAPIFolder (which is deprecated)?
I guess I don't understand what MSDN is saying (using the Folder interface to access all method etc)

答:
You simply cast it to Outlook.Folder, i.e.

```<code>Outlook.Folder oFolder = (Outlook.Folder) olNS.GetDefaultFolder( Outlook.OlDefaultFolders.olFoderDrafts)
</code>```

Admittedly, the MSDN is rather unclear there. You can think of the Folder interface as a wrapper around the MAPIFolder, with additional support for events.

As I sidenote, I would take the whole 'deprecated' thing with a grain of salt. I'd bet MAPIFolder is here to stay, at least for a couple more versions of Outlook.

Body:
You simply cast it to Outlook.Folder, i.e.

Outlook.Folder oFolder = (Outlook.Folder) olNS.GetDefaultFolder( Outlook.OlDefaultFolders.olFoderDrafts)

Admittedly, the MSDN is rather unclear there. You can think of the Folder interface as a wrapper around the MAPIFolder, with additional support for events.

As I sidenote, I would take the whole 'deprecated' thing with a grain of salt. I'd bet MAPIFolder is here to stay, at least for a couple more versions of Outlook.


问:
How to select and apply styling to custom tags
I'm trying to change a background color of a single table header, the problem is that there is no unique id. There is a unique/costum tag but I can't find a way to select it.

The element looks like this

```

<p>If i select</p>

<pre class="lang-css prettyprint-override"><code>.ag-header-cell.ag-header-cell-sortable {
  background-color: #56CC2B;
}
</code>```

It prints all columns headers. I'd like to select the col-id="name" is that even possible? Here is the page example.

答:
You have two issues here.

Make sure to separate each style accordingly. The style tag should be written this way:

```<code>style="width:180px; left:500px;"
</code>```

And to select the two classes in CSS, simply add a coma (,) and a space between the dots, such as:

```<code>.ag-header-cell,
.ag-header-cell-sortable {
    background-color: #56CC2B;
}
</code>```

Let me know if this is what you where after!

Body:
I'm trying to change a background color of a single table header, the problem is that there is no unique id. There is a unique/costum tag but I can't find a way to select it.

The element looks like this

If i select

.ag-header-cell.ag-header-cell-sortable {
  background-color: #56CC2B;
}

It prints all columns headers. I'd like to select the col-id="name" is that even possible? Here is the page example.

Body:
You have two issues here.

Make sure to separate each style accordingly. The style tag should be written this way:

style="width:180px; left:500px;"

And to select the two classes in CSS, simply add a coma (,) and a space between the dots, such as:

.ag-header-cell,
.ag-header-cell-sortable {
    background-color: #56CC2B;
}

Let me know if this is what you where after!


问:
How to copy Tableau Data Extract logic?
Someone in my org created a Data Extract.  There is an issue in one of the worksheets that uses it, and we suspect it's due to a mistake in how the Union was built.  </p>

<p>But since it's a Data Extract, I can't see the UI for the data merge.  Is there anyway to take a current Data Extract and view the logic that creates it?  </p>

答: Download the extract from the server (I'm assuming you're using server), then open that extract using desktop. You should be able to see the details of it.</p>

Title: How to copy Tableau Data Extract logic?

Body:
Someone in my org created a Data Extract.  There is an issue in one of the worksheets that uses it, and we suspect it's due to a mistake in how the Union was built.

But since it's a Data Extract, I can't see the UI for the data merge.  Is there anyway to take a current Data Extract and view the logic that creates it?


问:
Schedule a daily SQL query and email results as Excel file
I need to schedule a report to run at 2:00 am on weekdays and have those query results emailed to end users as an Excel file. I typically query a data warehouse using Excel's Power Query for other reports. To my knowledge this particular functionality does not exist within the DW tool I use (Jet Data Manager) or Power Query. Is this problem solvable with SSMS? Thanks</p>

答:
Doing so with pure SQL will be challenging, but maybe not impossible.  The most straight-forward way of doing this type of thing would be to use SSRS (SQL Server Reporting Services).  This would allow you to build formatted reports as well as setup scheduling, distribution (to different formats including Excel), etc...  Implementation of SSRS might be overkill for one report, but if you have other, similar requirements, it could make your life a lot easier.

A pure SQL approach would probably involve the following parts:

A SQL Agent job could provide the scheduling, etc...

SQL Server also has a feature called database mail - this is typically configured for sending alerts, but you could also use it to send the results of a query

The tricky part is your excel requirement.  sp_send_dbmail (the proc you would use to send the mail) does allow you to attach query results to the message.  But, you might have to live with something like CSV (that could be opened in Excel).

There could be some other things I'm not thinking of, but hopefully this will help.


问:
LinkedIn & Twitter, Share website image through URL
Following sample URLs helping me to share images to Facebook, GooglePlus and Pinterest:

GooglePlus: https://plus.google.com/share?url=https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png

Facebook: https://www.facebook.com/sharer.php?u=https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png

Pinterest: https://in.pinterest.com/pin/create/button/?url=&media=https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png

Like this, I curious to know, is any Twitter and LinkedIn URL formats that allow image sharing(with just an image URL)...

Thanks!

答:
Twitter...

```<code>https://twitter.com/intent/tweet?url={url}&text={title}&via={user_id}&hashtags={hash_tags}
</code>```

Source: Official Twitter Share URL Documentation.

Linkedin...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Share Documentation

Want to be able to customize the preview of your page, for title, description, image, etc.?  Then check out the necessary og: tags.  Here's LinkedIn documentation for it, but the same documentation applies mostly to all services.

Source: Open Graph Tags Documentation from LinkedIn.

Body:
Twitter...

https://twitter.com/intent/tweet?url={url}&text={title}&via={user_id}&hashtags={hash_tags}

Source: Official Twitter Share URL Documentation.

Linkedin...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Share Documentation

Want to be able to customize the preview of your page, for title, description, image, etc.?  Then check out the necessary og: tags.  Here's LinkedIn documentation for it, but the same documentation applies mostly to all services.

Source: Open Graph Tags Documentation from LinkedIn.


问:
Draw an SVG rectangle with gradientUnits="objectBoundingBox" on Canvas without using the built in transform function or changing the color stops?
Here is an SVG that has a linear gradient that uses objectBoundingBox gradientUnits:

```<code><svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="myGradient" x1="0%" y1="0%" x2="100%" y2="100%" gradientUnits="objectBoundingBox">
      <stop offset="40%" stop-color="yellow" />
      <stop offset="50%" stop-color="black" />
      <stop offset="60%" stop-color="red" />
    </linearGradient>
  </defs>

  <rect x="10" y="10" width="20" height="10" fill="url('#myGradient')" />
</svg>
</code>```

I need to draw this on a Canvas.

I can draw the gradient on a Canvas if I use the transform method:

```<code>const canvas = document.getElementById('canvasBuiltInScale');
const ctx = canvas.getContext('2d');

function draw(x0, y0, x1, y1) {
  ctx.save();

  // create a square 1x1 gradient
  const gradient = ctx.createLinearGradient(0, 0, 1,  1);
  gradient.addColorStop(0.4, 'yellow');
  gradient.addColorStop(0.5, 'black');
  gradient.addColorStop(0.6, 'red');

  // scale it up to the size of the bbox
  const width = x1 - x0;
  const height = y1 - y0;

  ctx.transform(width, 0, 0, height, x0, y0);
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, 1, 1);
  ctx.restore();
}

draw(10, 10, 40, 30);
</code>```

But unfortunately the customer does not want me to use the transform method.

I can draw the same gradient on a Canvas with a home rolled scaling instead.

```<code>const canvas = document.getElementById('canvasHomeRolledScale');
const ctx = canvas.getContext('2d');

function draw(x0, y0, x1, y1) {
  const width = x1-x0;
  const height = y1-y0;

  // The problem is that with userSpace coordinates, the normal to the gradient vector from x0,y0 to x1,y1 will not go between x1,y0 and x0,y1
  // I perform a home baked geometric calculation to find the normal vector to [x1-x0, y1-y0] since its normal vector will pass through [x1-x0, y1-y0]
  const gradient = ctx.createLinearGradient(
    x0 + (width - height) / 2,
    y0 + (height - width) / 2,
    x0 + (width - height) / 2 + height,
    y0 + (height - width) / 2 + width
  );

  gradient.addColorStop(rescale(0.4), 'yellow');
  gradient.addColorStop(rescale(0.5), 'black');
  gradient.addColorStop(rescale(0.6), 'red');
  ctx.fillStyle = gradient;
  ctx.fillRect(x0, y0, width, height);

  // The normal vector calculated above has the right direction, but not the right amplitude.
  // Here I guy guessed that I could use pythagoras theorem to arrive at the correct scale
  function rescale(percent) {
    const max = Math.max(height, width)
    const min = Math.min(height, width)
    const f = (
      Math.sqrt(
        Math.pow(max, 2) + Math.pow(min, 2)
      ) /
      Math.sqrt(
        Math.pow(max, 2) + Math.pow(max, 2)
      )
    );
    const midPoint = 0.5;
    return midPoint - (midPoint-percent) * f
  }
}

draw(10, 10, 40, 30);
</code>```

But I am not allowed to change the percentage of the color stops.

The objection in both cases has been the valid objection that there ought to be a simpler more elegant solution to this problem. Hence, I ask the intelligent people in here if there is a solution that:

Does not use the transform method

Does not change the color stops

答:
You can draw the SVG directly using drawImage:

<canvas id=canvas width=100 height=100></canvas>

```

Body:
Here is an SVG that has a linear gradient that uses objectBoundingBox gradientUnits:

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="myGradient" x1="0%" y1="0%" x2="100%" y2="100%" gradientUnits="objectBoundingBox">
      <stop offset="40%" stop-color="yellow" />
      <stop offset="50%" stop-color="black" />
      <stop offset="60%" stop-color="red" />
    </linearGradient>
  </defs>

  <rect x="10" y="10" width="20" height="10" fill="url('#myGradient')" />
</svg>

I need to draw this on a Canvas.

I can draw the gradient on a Canvas if I use the transform method:

const canvas = document.getElementById('canvasBuiltInScale');
const ctx = canvas.getContext('2d');

function draw(x0, y0, x1, y1) {
  ctx.save();

  // create a square 1x1 gradient
  const gradient = ctx.createLinearGradient(0, 0, 1,  1);
  gradient.addColorStop(0.4, 'yellow');
  gradient.addColorStop(0.5, 'black');
  gradient.addColorStop(0.6, 'red');

  // scale it up to the size of the bbox
  const width = x1 - x0;
  const height = y1 - y0;

  ctx.transform(width, 0, 0, height, x0, y0);
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, 1, 1);
  ctx.restore();
}

draw(10, 10, 40, 30);

But unfortunately the customer does not want me to use the transform method.

I can draw the same gradient on a Canvas with a home rolled scaling instead.

const canvas = document.getElementById('canvasHomeRolledScale');
const ctx = canvas.getContext('2d');

function draw(x0, y0, x1, y1) {
  const width = x1-x0;
  const height = y1-y0;

  // The problem is that with userSpace coordinates, the normal to the gradient vector from x0,y0 to x1,y1 will not go between x1,y0 and x0,y1
  // I perform a home baked geometric calculation to find the normal vector to [x1-x0, y1-y0] since its normal vector will pass through [x1-x0, y1-y0]
  const gradient = ctx.createLinearGradient(
    x0 + (width - height) / 2,
    y0 + (height - width) / 2,
    x0 + (width - height) / 2 + height,
    y0 + (height - width) / 2 + width
  );

  gradient.addColorStop(rescale(0.4), 'yellow');
  gradient.addColorStop(rescale(0.5), 'black');
  gradient.addColorStop(rescale(0.6), 'red');
  ctx.fillStyle = gradient;
  ctx.fillRect(x0, y0, width, height);

  // The normal vector calculated above has the right direction, but not the right amplitude.
  // Here I guy guessed that I could use pythagoras theorem to arrive at the correct scale
  function rescale(percent) {
    const max = Math.max(height, width)
    const min = Math.min(height, width)
    const f = (
      Math.sqrt(
        Math.pow(max, 2) + Math.pow(min, 2)
      ) /
      Math.sqrt(
        Math.pow(max, 2) + Math.pow(max, 2)
      )
    );
    const midPoint = 0.5;
    return midPoint - (midPoint-percent) * f
  }
}

draw(10, 10, 40, 30);

But I am not allowed to change the percentage of the color stops.

The objection in both cases has been the valid objection that there ought to be a simpler more elegant solution to this problem. Hence, I ask the intelligent people in here if there is a solution that:

Does not use the transform method

Does not change the color stops

Body:
You can draw the SVG directly using drawImage:

<canvas id=canvas width=100 height=100></canvas>

<script>
  function svgimage() {
    var image = `
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" version="1.1">
    <defs>
        <linearGradient id="myGradient" x1="0%" y1="0%" x2="100%" y2="100%" gradientUnits="objectBoundingBox">
        <stop offset="40%" stop-color="yellow" />
        <stop offset="50%" stop-color="black" />
        <stop offset="60%" stop-color="red" />
        </linearGradient>
    </defs>

    <rect x="0" y="0" width="100" height="100" fill="url('#myGradient')" />
</svg>`;
    return encodeURIComponent(image);
  }

  function drawImage() {
    ctx.drawImage(img, 0, 0);
  }

  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext('2d');

  var img = new Image();
  img.onload = drawImage
  img.src = 'data:image/svg+xml;charset=utf-8,' + svgimage();
</script>


问:
SCDF Aggregator Emits only the last record
I am currently experimenting for one of the usecase we have to aggregate multiple input meesages into one before it gets written to a file system. Towards this I am trying to use the aggregator module available here
https://repo.spring.io/release/org/springframework/cloud/stream/app/aggregator-processor-kafka/2.1.1.RELEASE/

My Environment is local SCDF/Kafka running on docker Dataflow 2.4.1.Release and Skipper 2.3.1.Release

the stream definition is simple as below

:inputTopic > aggregator > :outputTopic

In the aggregator properties am providing these property values.

```<code>release: size() == 5
group-timeout: 5000
correlation: headers.headerName
aggregation: T(org.springframework.util.StringUtils).collectionToDelimitedString(#this.![new String(payload)],'')
message-store-type: simple
</code>```

There are two issues I have

Though i have given a release size of 5, and if there are say 10
messages, i do not see my output topic to receive two messages

The output topic contains only the last message of an aggregated header and not concatenated values of this list.

Please suggest if there are any additional configurations that would help achieve an aggregated output.

One additional observation is that if i have a stream as

```<code>http | aggregator > :topic
</code>```

The same aggregator config works fine and as desired. But the way we have it, the data is put into a topic via a processor using KStreams and not sure if there is a way in which the headers are generated and read using these default boot apps to a custom processor.

One additional observation during debug of aggregator is that, the correlationKey is obtained or compared via hashCode and not as string, not sure if its a bug or a feature. but this is what is causing the disruption of expected behavior.

答:
For anyone looking for an answer, the things i did to get around is to change the correlation to

```<code>new String[headers.headerName]
</code>```

And explicitly configured the input value serializer to bytearrayserializer

But question i have from Spring team is if I do not have to touch aggregator, is there a property that i can set in my output producer properties in my Kstream app developed in 2.2.4 boot to emit headers as string instead of byte array?

i use following API to set headers

```<code>context.headers().add(key, value.getBytes())
</code>```

I tried

```<code>producer.header-mode: to none/headers.
</code>```

But my aggregator was still not aggregating and giving only last record. Only after changing the aggregator properties it worked. But i want to refrain from changing aggregator property as that stream is not owned by us and is legacy app working fine for other legacy streams.

Body:
I am currently experimenting for one of the usecase we have to aggregate multiple input meesages into one before it gets written to a file system. Towards this I am trying to use the aggregator module available here
https://repo.spring.io/release/org/springframework/cloud/stream/app/aggregator-processor-kafka/2.1.1.RELEASE/

My Environment is local SCDF/Kafka running on docker Dataflow 2.4.1.Release and Skipper 2.3.1.Release

the stream definition is simple as below

:inputTopic > aggregator > :outputTopic

In the aggregator properties am providing these property values.

release: size() == 5
group-timeout: 5000
correlation: headers.headerName
aggregation: T(org.springframework.util.StringUtils).collectionToDelimitedString(#this.![new String(payload)],'')
message-store-type: simple

There are two issues I have

Though i have given a release size of 5, and if there are say 10
messages, i do not see my output topic to receive two messages

The output topic contains only the last message of an aggregated header and not concatenated values of this list.

Please suggest if there are any additional configurations that would help achieve an aggregated output.

One additional observation is that if i have a stream as

http | aggregator > :topic

The same aggregator config works fine and as desired. But the way we have it, the data is put into a topic via a processor using KStreams and not sure if there is a way in which the headers are generated and read using these default boot apps to a custom processor.

One additional observation during debug of aggregator is that, the correlationKey is obtained or compared via hashCode and not as string, not sure if its a bug or a feature. but this is what is causing the disruption of expected behavior.

Body:
For anyone looking for an answer, the things i did to get around is to change the correlation to

new String[headers.headerName]

And explicitly configured the input value serializer to bytearrayserializer

But question i have from Spring team is if I do not have to touch aggregator, is there a property that i can set in my output producer properties in my Kstream app developed in 2.2.4 boot to emit headers as string instead of byte array?

i use following API to set headers

context.headers().add(key, value.getBytes())

I tried

producer.header-mode: to none/headers.

But my aggregator was still not aggregating and giving only last record. Only after changing the aggregator properties it worked. But i want to refrain from changing aggregator property as that stream is not owned by us and is legacy app working fine for other legacy streams.


问:
Why is the output of `typeid(T&).name()` given as `T` instead of `T&`?
As the subject, you could check the related code on https://godbolt.org/z/qtjVP6.

For your convience, the code is posted below:

```<code>#include<typeinfo>
#include<iostream>

class Widget{};

Widget someWidget;

int main()
{
    Widget&& var1 = Widget{};      // here, “&&” means rvalue reference
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

    std::cout << typeid(var2).name() << std::endl;
}
</code>```

Output:6Widget

echo 6Widget | c++filt -t says Widget.

I would be grateful to have some help on this question.

答:
Although, the answer given by iBug is correct in a way, it doesn't really apply to your case.

Let's look at what C++ standard has to say about this. We can see [expr]p5 says:

5 If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

All this is saying is that in:

```<code>     std::cout << typeid(var2).name() << std::endl;
</code>```

the type of var2 is adjusted from Widget& to Widget before the expression is further evaluated.
Now it's easier to see why typeid(var2).name() returns a string corresponding to type Widget.

In case, you want to dig deeper, [expr.typeid]p3 says:

3 When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
  to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer
  (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the
  expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand
  (Clause 5).

Which basically means that var2 in typeid(var2) is a glvalue of a non-polymorphic class type and that for an expression of such a type, the type is its static type. The type therefore is Widget.

See this for more details.

Body:
As the subject, you could check the related code on https://godbolt.org/z/qtjVP6.

For your convience, the code is posted below:

#include<typeinfo>
#include<iostream>

class Widget{};

Widget someWidget;

int main()
{
    Widget&& var1 = Widget{};      // here, “&&” means rvalue reference
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

    std::cout << typeid(var2).name() << std::endl;
}

Output:6Widget

echo 6Widget | c++filt -t says Widget.

I would be grateful to have some help on this question.

Body:
Although, the answer given by iBug is correct in a way, it doesn't really apply to your case.

Let's look at what C++ standard has to say about this. We can see [expr]p5 says:

5 If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

All this is saying is that in:

     std::cout << typeid(var2).name() << std::endl;

the type of var2 is adjusted from Widget& to Widget before the expression is further evaluated.
Now it's easier to see why typeid(var2).name() returns a string corresponding to type Widget.

In case, you want to dig deeper, [expr.typeid]p3 says:

3 When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
  to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer
  (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the
  expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand
  (Clause 5).

Which basically means that var2 in typeid(var2) is a glvalue of a non-polymorphic class type and that for an expression of such a type, the type is its static type. The type therefore is Widget.

See this for more details.


问:
zend two forms same page are submitted together
I built two custom Zend_Form classes: form_1 and form_2.I instanciated both of them in the same controller.

```<code>$form_1=new form_1();
$form_2=new form_2();
</code>```

form_1 and form_2 have respectively submit buttons named 'submit_form_1' the first and 'submit_form_2' the second. (Ex. new Zend_Form_Element_Submit('submit_form_1')..)

So I added to my controller a snippet to check wich form was submitted :

```<code>if(($this->_request->isPost('submit_form_1')))
{
 echo "you clicked for form_1!";
}

if($this->_request->isPost('submit_form_2'))
{
 echo "you clicked for form_2!";
}
</code>```

But it seems that clicking on either submit_form_1 or submit_form_2 both of my forms are posted! so that the above snippet output is:

```<code>you clicked for form_1!you clicked for form_2!
</code>```

what am I missing?

P.s. Both of the form action are left blank so that the form post to same page(I'd prefer to not address these two forms to different actions as you might suggest =))

thanks

Luca

答:
Zend_Controller_Request_Http::isPost() does not take (or use) any arguments.

Both of your conditions are evaluating to true because the request method is POST.

I think you want to use Zend_Controller_Request_Http::getPost() instead, eg

```<code>if ($this->_request->getPost('submit_form_1', false)) {
    echo "you clicked for form_1!";
}

if ($this->_request->getPost('submit_form_2', false)) {
    echo "you clicked for form_2!";
}
</code>```

Body:
I built two custom Zend_Form classes: form_1 and form_2.I instanciated both of them in the same controller.

$form_1=new form_1();
$form_2=new form_2();

form_1 and form_2 have respectively submit buttons named 'submit_form_1' the first and 'submit_form_2' the second. (Ex. new Zend_Form_Element_Submit('submit_form_1')..)

So I added to my controller a snippet to check wich form was submitted :

if(($this->_request->isPost('submit_form_1')))
{
 echo "you clicked for form_1!";
}

if($this->_request->isPost('submit_form_2'))
{
 echo "you clicked for form_2!";
}

But it seems that clicking on either submit_form_1 or submit_form_2 both of my forms are posted! so that the above snippet output is:

you clicked for form_1!you clicked for form_2!

what am I missing?

P.s. Both of the form action are left blank so that the form post to same page(I'd prefer to not address these two forms to different actions as you might suggest =))

thanks

Luca

Body:
Zend_Controller_Request_Http::isPost() does not take (or use) any arguments.

Both of your conditions are evaluating to true because the request method is POST.

I think you want to use Zend_Controller_Request_Http::getPost() instead, eg

if ($this->_request->getPost('submit_form_1', false)) {
    echo "you clicked for form_1!";
}

if ($this->_request->getPost('submit_form_2', false)) {
    echo "you clicked for form_2!";
}