问:
Angular 13 clean install wouldn't work with web3.js
I cannot make use of the web3 package at all, I'm getting errors in the polyfills.ts file and the given instructions from the Web3Js GitHub aren't working for me

The steps to replicate this:
Started a new project with angular cli:

```<code>ng new test-app
</code>```

Then resumed installing web3 and it's dependencies according to their github instructions

```<code>npm install web3
npm install --save-dev crypto-browserify stream-browserify assert stream-http https-browserify os-browserify
</code>```

After this I have added an additional property (paths) to the tsconfig.json as such:

```<code>"paths" : {
    "crypto": ["./node_modules/crypto-browserify"],
    "stream": ["./node_modules/stream-browserify"],
    "assert": ["./node_modules/assert"],
    "http": ["./node_modules/stream-http"],
    "https": ["./node_modules/https-browserify"],
    "os": ["./node_modules/os-browserify"],
}
</code>```

And finally added this into the polyfills.ts file

```<code>(window as any).global = window;
global.Buffer = Buffer;
global.process = {
    env: { DEBUG: undefined },
    version: '',
    nextTick: require('next-tick')
} as any;
</code>```

Unfortunately those changes aren't working because I'm getting build errors at polyfills.ts, more specifically the following:

Cannot find name 'global'.

Cannot find name 'require'. Do you need to install type definitions for node? Try npm i --save-dev @types/node and then add 'node' to the types field in your tsconfig.

Those additions in the polyfills.ts file are necessary because otherwise I'd get this error:

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
- install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "url": false }

Upon debugging I can see that the global variable is indeed undefined.
I have tried to trick it into declaring it (as found around on some other Stack Overflow threads) at func level (declare global as any, declare require as any) but that would lead me to the upper error.

Npm version - 8.5.0

node.js version - 17.5.0

web3 npm package version - ^1.7.0

After more trial and error I have been able to build and serve properly with all the upper changes but upon any attempt to use web3 in my code, i get the following:

```<code>./node_modules/xhr2-cookies/dist/xml-http-request.js:43:10-24 - Error: Module not found: Error: Can't resolve 'url' in 'D:\Work\Tutorials\CryptoZombies\crypto-zombies-angular\node_modules\xhr2-cookies\dist'
</code>```

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
- install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "url": false }

After installing url and xhr2-cookies I was able to run it (even though I'm getting this warning:

CommonJS or AMD dependencies can cause optimization bailouts.

答: I have installed 2 antique packages (url and xhr2-cookies) and made it work, although it feels wrong and there has to be a more cleaner way since I'm getting a warning about common js dependencies being used and possibly making my bundle bigger.</p>

Body:
I cannot make use of the web3 package at all, I'm getting errors in the polyfills.ts file and the given instructions from the Web3Js GitHub aren't working for me

The steps to replicate this:
Started a new project with angular cli:

ng new test-app

Then resumed installing web3 and it's dependencies according to their github instructions

npm install web3
npm install --save-dev crypto-browserify stream-browserify assert stream-http https-browserify os-browserify

After this I have added an additional property (paths) to the tsconfig.json as such:

"paths" : {
    "crypto": ["./node_modules/crypto-browserify"],
    "stream": ["./node_modules/stream-browserify"],
    "assert": ["./node_modules/assert"],
    "http": ["./node_modules/stream-http"],
    "https": ["./node_modules/https-browserify"],
    "os": ["./node_modules/os-browserify"],
}

And finally added this into the polyfills.ts file

(window as any).global = window;
global.Buffer = Buffer;
global.process = {
    env: { DEBUG: undefined },
    version: '',
    nextTick: require('next-tick')
} as any;

Unfortunately those changes aren't working because I'm getting build errors at polyfills.ts, more specifically the following:

Cannot find name 'global'.

Cannot find name 'require'. Do you need to install type definitions for node? Try npm i --save-dev @types/node and then add 'node' to the types field in your tsconfig.

Those additions in the polyfills.ts file are necessary because otherwise I'd get this error:

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
- install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "url": false }

Upon debugging I can see that the global variable is indeed undefined.
I have tried to trick it into declaring it (as found around on some other Stack Overflow threads) at func level (declare global as any, declare require as any) but that would lead me to the upper error.

Npm version - 8.5.0

node.js version - 17.5.0

web3 npm package version - ^1.7.0

After more trial and error I have been able to build and serve properly with all the upper changes but upon any attempt to use web3 in my code, i get the following:

./node_modules/xhr2-cookies/dist/xml-http-request.js:43:10-24 - Error: Module not found: Error: Can't resolve 'url' in 'D:\Work\Tutorials\CryptoZombies\crypto-zombies-angular\node_modules\xhr2-cookies\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
- install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "url": false }

After installing url and xhr2-cookies I was able to run it (even though I'm getting this warning:

CommonJS or AMD dependencies can cause optimization bailouts.


来源: stackexchange

问:
Give space between <text> components which is a child in a view component
```<code>    import { Text, View, Image, StyleSheet } from 'react-native';
import * as react from 'react';
export default function TabOneScreen(){

  return (
   <View style={styles.container}>

    <Image source = {{uri:'https://notjustdev-dummy.s3.us-east-2.amazonaws.com/avatars/elon.png'}} style={styles.image} />
</code>```

my task is to give space to this text which is supposed to appear in a straight line (Elon Musk

11:11AM) using justifyContent: 'space-between' but its not having any effect instead the text are still together (Elon Musk11:11AM)

```<code>      <View style={styles.row}>
        <Text style={styles.name}>Elon Musk</Text>
        <Text style={styles.text}>11:11 AM</Text>
      </View>
      <Text style={styles.text}>Boi Ice for Janet</Text>
    </View>
   </View>
);
  }

const styles = StyleSheet.create({

container:{
    flexDirection:'row',
    padding:10,
    },

  image:{
    height:60,
    width:60,
    borderRadius:50,
    marginRight:10,
   },
  name:{
    fontSize:20,
  color:'blue',
  },

  row:{
    flexDirection:'row',
    justifyContent: 'space-between',
    },

text:{
  fontSize:20,
  color:'blue'
}
});
</code>```

答:
You would need to use a

row:{
  flex:1
  // other keys
}
```
<p>and/or</p>
<pre class="lang-js prettyprint-override"><code>row:{
  width:'100%'
}
</code>```

so that the view (row) covers the width of the screen.

ContentLicense: CC BY-SA 4.0

Body:
    import { Text, View, Image, StyleSheet } from 'react-native';
import * as react from 'react';
export default function TabOneScreen(){

  return (
   <View style={styles.container}>

    <Image source = {{uri:'https://notjustdev-dummy.s3.us-east-2.amazonaws.com/avatars/elon.png'}} style={styles.image} />

my task is to give space to this text which is supposed to appear in a straight line (Elon Musk

11:11AM) using justifyContent: 'space-between' but its not having any effect instead the text are still together (Elon Musk11:11AM)

      <View style={styles.row}>
        <Text style={styles.name}>Elon Musk</Text>
        <Text style={styles.text}>11:11 AM</Text>
      </View>
      <Text style={styles.text}>Boi Ice for Janet</Text>
    </View>
   </View>
);
  }

const styles = StyleSheet.create({

container:{
    flexDirection:'row',
    padding:10,
    },

  image:{
    height:60,
    width:60,
    borderRadius:50,
    marginRight:10,
   },
  name:{
    fontSize:20,
  color:'blue',
  },

  row:{
    flexDirection:'row',
    justifyContent: 'space-between',
    },

text:{
  fontSize:20,
  color:'blue'
}
});

Body:
You would need to use a

row:{
  flex:1
  // other keys
}

and/or

row:{
  width:'100%'
}

so that the view (row) covers the width of the screen.


问:
upload_max_filesize increase ignored by phpmyadmin
I menaged to decrease upload_max_filesize (to 127M from default 128M), but I am unable to increase it (I tried 129M). What may be wrong?</p>

答: I increased also memory_limit, post_max_size what fixed this problem.</p>

ContentLicense: CC BY-SA 3.0


问:
Plot map using cartopy with hdf5 dataset
I'm curently trying to plot hdf5 files after switching them from hdf4. I got some trouble working out the longitude and latitude variables in the file, both of them have a shape (4224, 3) which I guess correspond to 1 : the number of values and 2 : the starting/middle/ending granule point of the satellite.

My problem is that my data 'extinction_coefficient_532' have a shape (4224, 399) which do not match with my lon/lat variables. Correct me if I'm wrong but I need to have a data file with shape (value, lon, lat) to be plotting it on a map with cartopy.

Is there a way to adapt the shape of the data to match the lon/lat variables ?

```<code>f['Longitude'].shape
Out[296]: (4224, 3)

f['Latitude'].shape
Out[297]: (4224, 3)

f['Extinction_Coefficient_532'].shape
Out[298]: (4224, 399)
</code>```

EDIT :

```<code>f['Extinction_Coefficient_532'].dtype
Out[122]: dtype('>f4')
</code>```

Have a good day,
Thomas

答:
HDF5 is simply a data container. The specific schema/data hierarchy depends on the creator. Ideally they provide documentation, or dataset attributes you can use to interpret the data. Without details it is hard to give specific advice.

That said, I found some documentation that mentions Extinction_Coefficient_532 at  NASA's website for CALIPSO Data. It describes the format of all 3 datasets mentioned above. Brief description provided here:

Latitude / Longitude

Geodetic latitude (/longitude), in degrees, of the laser footprint. For the 5 km profile products, three values are reported:

Footprint latitude (/longitude) for the first pulse included in the 15 shot average

Footprint latitude (/longitude) at the temporal midpoint (i.e., at the 8th of 15 consecutive laser shots)

Footprint latitude (/longitude) for the final pulse.

Extinction Coefficient 532

Particulate extinction coefficients reported for each profile range bin in which the appropriate particulates (i.e., clouds or aerosols) were detected; those range bins in which no particulates were detected contain fill values (-9999)

Based on this, I conclude that you have 4224 longitude and latitude locations and matching extinction coefficients. If this is correct, follow the example on this page to extract the data to create your plot: More advanced mapping with cartopy and matplotlib

It will look something like this:

```<code>import h5py
with h5py.File('yourfilename.h5','r') as h5f:
# first extract the plot data:
# 1) Latitude, 2) Longitude and 3) Extinction Coefficient
    pulse = 0  ## to select a particular pulse, valid range 0-2
    lats = h5f['Latitude'][:,pulse]
    lons = h5f['Longitude'][:,pulse]
    bin_no = 0 ## to plot a particular profile bin, valid range 0-398
    coef = h5f['Extinction_Coefficient_532'][:, bin_no]

# lines below reference plot data extracted above
# May need to be modified to generate the plot type you want.
    ax = plt.axes(projection=ccrs.PlateCarree())
    plt.contourf(lons, lats, coef, 60, transform=ccrs.PlateCarree())
    ax.coastlines()
    plt.show()
</code>```

Body:
I'm curently trying to plot hdf5 files after switching them from hdf4. I got some trouble working out the longitude and latitude variables in the file, both of them have a shape (4224, 3) which I guess correspond to 1 : the number of values and 2 : the starting/middle/ending granule point of the satellite.

My problem is that my data 'extinction_coefficient_532' have a shape (4224, 399) which do not match with my lon/lat variables. Correct me if I'm wrong but I need to have a data file with shape (value, lon, lat) to be plotting it on a map with cartopy.

Is there a way to adapt the shape of the data to match the lon/lat variables ?

f['Longitude'].shape
Out[296]: (4224, 3)

f['Latitude'].shape
Out[297]: (4224, 3)

f['Extinction_Coefficient_532'].shape
Out[298]: (4224, 399)

EDIT :

f['Extinction_Coefficient_532'].dtype
Out[122]: dtype('>f4')

Have a good day,
Thomas

Body:
HDF5 is simply a data container. The specific schema/data hierarchy depends on the creator. Ideally they provide documentation, or dataset attributes you can use to interpret the data. Without details it is hard to give specific advice.

That said, I found some documentation that mentions Extinction_Coefficient_532 at  NASA's website for CALIPSO Data. It describes the format of all 3 datasets mentioned above. Brief description provided here:

Latitude / Longitude

Geodetic latitude (/longitude), in degrees, of the laser footprint. For the 5 km profile products, three values are reported:

Footprint latitude (/longitude) for the first pulse included in the 15 shot average

Footprint latitude (/longitude) at the temporal midpoint (i.e., at the 8th of 15 consecutive laser shots)

Footprint latitude (/longitude) for the final pulse.

Extinction Coefficient 532

Particulate extinction coefficients reported for each profile range bin in which the appropriate particulates (i.e., clouds or aerosols) were detected; those range bins in which no particulates were detected contain fill values (-9999)

Based on this, I conclude that you have 4224 longitude and latitude locations and matching extinction coefficients. If this is correct, follow the example on this page to extract the data to create your plot: More advanced mapping with cartopy and matplotlib

It will look something like this:

import h5py
with h5py.File('yourfilename.h5','r') as h5f:
# first extract the plot data:
# 1) Latitude, 2) Longitude and 3) Extinction Coefficient
    pulse = 0  ## to select a particular pulse, valid range 0-2
    lats = h5f['Latitude'][:,pulse]
    lons = h5f['Longitude'][:,pulse]
    bin_no = 0 ## to plot a particular profile bin, valid range 0-398
    coef = h5f['Extinction_Coefficient_532'][:, bin_no]

# lines below reference plot data extracted above
# May need to be modified to generate the plot type you want.
    ax = plt.axes(projection=ccrs.PlateCarree())
    plt.contourf(lons, lats, coef, 60, transform=ccrs.PlateCarree())
    ax.coastlines()
    plt.show()


问:
How do I add buttons using javascript in a bunch of divs generated by Django through loop?
I am working on a Django project, where I have made a bunch of HTML divs. I want to add a single button on each div.

In the image above, I have created a div of class card-footer with Django for loop. I want to add a blue coloured like button on each of the divs using javascript but you can see in the image that it is being added into only one div.
Here I am sharing my HTML template.

                {% for posts in page_view %}

{{ posts.user }}

{{ posts.timestamp }}

{{ posts.post }}

                        {% include 'network/like.html' %}

                {% empty %}

No post availabel

                {% endfor %}

```
</div>
</div>
</p>
<p>Here is my <code>network/like.html</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card-footer">

    <form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;">
        {% csrf_token %}
        <button id = "like" class="btn btn-link" type="submit">Like</button>
    </form>
    <small id="num_of_likes">{{ posts.likepost.all.count }}</small>

    {% block script %}
        <!-- <script>
            let posts_id = "{{ posts.id }}";
        </script> -->
        <script src="{% static 'network/controller.js' %}"></script>
    {% endblock %}
    <button class="btn btn-link" style="text-decoration: none;">Comment</button>
    View Post
    {% if request.user.id is posts.user.id %}
        Edit

    {% endif %}

</div></code>```

In this div of class card-footer I want to add a button which contains like in innerHTML but it is being added in only the first one, not the others. Here I am sharing my full js code.

document.addEventListener("DOMContentLoaded",function(e){
    // const colon = document.createElement('div');
    // colon.setAttribute('id','colon')
    e.preventDefault()
    const likebtn = document.createElement('button');
    likebtn.setAttribute('class','btn btn-primary');
    likebtn.setAttribute('id','likebtn')
    document.querySelector('.card-footer').appendChild(likebtn);
    document.querySelector('#likebtn').innerHTML = "Like";
    // document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost'));
})

// let is_like = "{{is_like}}";
// let num_like = "{{num_like}}";

function like_function(likepost){
    document.createElement('button').innerHTML = "Love";
    fetch(`/likepost/${posts_id}`)
    // ,{
    //     method:"POST",
    //     body : JSON.stringify({
    //         "is_like" : is_like,
    //         "num_like" : num_like,
    //     })
    // })
    .then(response => response.json())
    .then(result => {
        console.log("Updated.");
        if(result.is_like){
            document.querySelector('#like').innerHTML = "Unike";
        }
        else{
            document.querySelector('#like').innerHTML = "Like";
        }
    })
    location.replace("http://127.0.0.1/")
}

// function like_function(){
//     if (document.querySelector("#like").style.color == "blue"){
//         document.querySelector("#like").style.color = "red";
//     }else{
//         document.querySelector("#like").style.color = "blue";
//     }
// }```

As I'm new to javascript, I can't figure out what is going wrong! Please let me know if I need to share more information or piece of code.

答:
According to the docs the {% include %} tag cannot be used like this (with variables within the template you are going to include.  I'm sure there are ways to accomplish what you want by using JavaScript, or you can just replace the include tag with the entire network/like.html template.

The include tag should be considered as an implementation of “render
this subtemplate and include the HTML”, not as “parse this subtemplate
and include its contents as if it were part of the parent”. This means
that there is no shared state between included templates – each
include is a completely independent rendering process.

I haven't tested this, but another possibility would be to create a custom include template tag, as described here.

Body:
I am working on a Django project, where I have made a bunch of HTML divs. I want to add a single button on each div.

In the image above, I have created a div of class card-footer with Django for loop. I want to add a blue coloured like button on each of the divs using javascript but you can see in the image that it is being added into only one div.
Here I am sharing my HTML template.

                {% for posts in page_view %}

{{ posts.user }}

{{ posts.timestamp }}

{{ posts.post }}

                        {% include 'network/like.html' %}

                {% empty %}

No post availabel

                {% endfor %}

Here is my network/like.html:

    <form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;">
        {% csrf_token %}
        <button id = "like" class="btn btn-link" type="submit">Like</button>
    </form>
    {{ posts.likepost.all.count }}

    {% block script %}

    {% endblock %}
    <button class="btn btn-link" style="text-decoration: none;">Comment</button>
    View Post
    {% if request.user.id is posts.user.id %}
        Edit

    {% endif %}

In this div of class card-footer I want to add a button which contains like in innerHTML but it is being added in only the first one, not the others. Here I am sharing my full js code.

document.addEventListener("DOMContentLoaded",function(e){
    // const colon = document.createElement('div');
    // colon.setAttribute('id','colon')
    e.preventDefault()
    const likebtn = document.createElement('button');
    likebtn.setAttribute('class','btn btn-primary');
    likebtn.setAttribute('id','likebtn')
    document.querySelector('.card-footer').appendChild(likebtn);
    document.querySelector('#likebtn').innerHTML = "Like";
    // document.querySelector('.likepost').addEventListener('click', ()=> like_function('likepost'));
})

// let is_like = "{{is_like}}";
// let num_like = "{{num_like}}";

function like_function(likepost){
    document.createElement('button').innerHTML = "Love";
    fetch(`/likepost/${posts_id}`)
    // ,{
    //     method:"POST",
    //     body : JSON.stringify({
    //         "is_like" : is_like,
    //         "num_like" : num_like,
    //     })
    // })
    .then(response => response.json())
    .then(result => {
        console.log("Updated.");
        if(result.is_like){
            document.querySelector('#like').innerHTML = "Unike";
        }
        else{
            document.querySelector('#like').innerHTML = "Like";
        }
    })
    location.replace("http://127.0.0.1/")
}

// function like_function(){
//     if (document.querySelector("#like").style.color == "blue"){
//         document.querySelector("#like").style.color = "red";
//     }else{
//         document.querySelector("#like").style.color = "blue";
//     }
// }

As I'm new to javascript, I can't figure out what is going wrong! Please let me know if I need to share more information or piece of code.


问:
i am not able to update modal state based on received props value from other component in reactjs
i am not able to update modal state based on received props value from other component in reactjs. i have tried all things but not working. please suggest on it it will be appreciable.

```<code>const ModalExample = ({ elem }) => {

const [modal, setModal] = useState(elem);
useEffect(() => {
    console.log('elem', elem);
})

const toggle = () => {
    setModal(false);
}

return (
    <div>
        <Modal isOpen={modal} toggle={toggle}>
            <ModalHeader toggle={toggle}>Modal title</ModalHeader>
            <ModalBody>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </ModalBody>
            <ModalFooter>
                <Button color="primary" onClick={toggle}>Do Something</Button>{' '}
                <Button color="secondary" onClick={toggle}>Cancel</Button>
            </ModalFooter>
        </Modal>
    </div>
);
</code>```

}

答:
Instead of passing elem prop directly inside useState

do something like this.

```<code>const [modal, setModal] = useState(false)

useEffect(() => {
  setModal(Boolean(elem)) // I suppose it is not boolean so make it boolean
},[elem])
</code>```

Body:
i am not able to update modal state based on received props value from other component in reactjs. i have tried all things but not working. please suggest on it it will be appreciable.

const ModalExample = ({ elem }) => {

const [modal, setModal] = useState(elem);
useEffect(() => {
    console.log('elem', elem);
})

const toggle = () => {
    setModal(false);
}

return (

        <Modal isOpen={modal} toggle={toggle}>
            <ModalHeader toggle={toggle}>Modal title</ModalHeader>
            <ModalBody>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </ModalBody>
            <ModalFooter>
                <Button color="primary" onClick={toggle}>Do Something</Button>{' '}
                <Button color="secondary" onClick={toggle}>Cancel</Button>
            </ModalFooter>
        </Modal>

);

}

Body:
Instead of passing elem prop directly inside useState

do something like this.

const [modal, setModal] = useState(false)

useEffect(() => {
  setModal(Boolean(elem)) // I suppose it is not boolean so make it boolean
},[elem])


问:
graphqlHTTP is not a function
Here is my simple graphql express app

```<code>const express = require('express');
const graphqlHTTP = require('express-graphql');

const app = express();
app.use(
    '/graphql',
    graphqlHTTP({
      graphiql: true,
    })
  );

app.listen(4000, () => {
    console.log("listening for request!");
});
</code>```

I'm getting the following errors when I run it:

```<code> graphqlHTTP({
    ^

TypeError: graphqlHTTP is not a function
    at Object.<anonymous> (D:\PersonalProjects\GraphQL\server\app.js:7:5)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
</code>```

How can I fix it

答:
This code was written with an earlier version of express-graphql.

Prior to v0.10.0, you could use

```<code>var graphqlHTTP = require('express-graphql');
</code>```

After v0.10.0, you need to use

```<code>var { graphqlHTTP } = require('express-graphql');
</code>```

Title: graphqlHTTP is not a function

Body:
Here is my simple graphql express app

const express = require('express');
const graphqlHTTP = require('express-graphql');

const app = express();
app.use(
    '/graphql',
    graphqlHTTP({
      graphiql: true,
    })
  );

app.listen(4000, () => {
    console.log("listening for request!");
});

I'm getting the following errors when I run it:

 graphqlHTTP({
    ^

TypeError: graphqlHTTP is not a function
    at Object.<anonymous> (D:\PersonalProjects\GraphQL\server\app.js:7:5)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

How can I fix it

Body:
This code was written with an earlier version of express-graphql.

Prior to v0.10.0, you could use

var graphqlHTTP = require('express-graphql');

After v0.10.0, you need to use

var { graphqlHTTP } = require('express-graphql');


问:
Can I skip generating the {proxy+} when creating Rest API using Amplify
I am currently playing around with creating rest-api:s with amplify. I am trying to create the following structure:

/helloText

/helloText/{name}

But I get the following error when trying to push the backend:

```<code>Unable to create resource at path '/helloText/{proxy+}': A sibling ({name}) of this resource already has a variable path part -- only one is allowed
</code>```

As I understand, it is because Amplify is creating "greedy paths" by default.

When manually removing these "greedy paths" from the template file RestTest-cloudformation-template.json it works.

Is it somehow possible to create these paths by using only the command line?

答:
There is no configuration switch for that in amplify-cli. You need to create an override. Reference: Amplify override api.
Run:

```<code>amplify override api
</code>```

Then edit generated override.ts like:

```<code>import { AmplifyApiRestResourceStackTemplate } from '@aws-amplify/cli-extensibility-helper';

export function override(resources: AmplifyApiRestResourceStackTemplate) {
  const {paths} = resources.restApi.body;
  Object.keys(paths).forEach((path) => {
    if (path.includes('{proxy+}')) {
      delete paths[path];
    }
  });
}
</code>```

Body:
I am currently playing around with creating rest-api:s with amplify. I am trying to create the following structure:

/helloText

/helloText/{name}

But I get the following error when trying to push the backend:

Unable to create resource at path '/helloText/{proxy+}': A sibling ({name}) of this resource already has a variable path part -- only one is allowed

As I understand, it is because Amplify is creating "greedy paths" by default.

When manually removing these "greedy paths" from the template file RestTest-cloudformation-template.json it works.

Is it somehow possible to create these paths by using only the command line?

Body:
There is no configuration switch for that in amplify-cli. You need to create an override. Reference: Amplify override api.
Run:

amplify override api

Then edit generated override.ts like:

import { AmplifyApiRestResourceStackTemplate } from '@aws-amplify/cli-extensibility-helper';

export function override(resources: AmplifyApiRestResourceStackTemplate) {
  const {paths} = resources.restApi.body;
  Object.keys(paths).forEach((path) => {
    if (path.includes('{proxy+}')) {
      delete paths[path];
    }
  });
}


问:
Neo4j embedded mode use of GDS
I am attempting to use GDS 1.8.2 as part of a system running an embedded Neo4j 4.4.3 server. The embedded server has been an operational component for several years, and several versions of Neo4j, so that component on its own has been time-tested and functions great. This is the first attempt to add support for graph algorithms into that component.

My first test is simply to submit a CQL query:

CALL gds.graph.create("someNamedGraph", ["SomeNodeLabel"], ["SomeRelationshipType"])

In the course of getting this to work, I found I had to register the org.neo4j.gds.catalog.GraphCreateProc class in the GlobalProcedures registry of the graph database. This seems to have been successful because, while I  was initially encountering a CQL exception saying the gds.graph.create procedure is unknown, now it appears to execute without exception. However, I am now seeing that the transaction doesn't produce the named graph (verified by checking the graph database using out-of-the-box Neo4j Community Edition server mode).  It only runs for perhaps 0.1 seconds (vs several seconds when done through the Neo4j Community Edition server mode where it works just fine).

What I now see is that the Query Execution Type (as indicated in the Result object coming back from the execution) is marked as READ_ONLY. There are no exceptions, notifications etc.  I have verified that a subsequent write transaction in the same test code, which creates a simple node (as a test), succeeds in writing a node and the Result object provides all the verifying information for that transaction.

Can anyone suggest why the gds.graph.create procedure would seem to execute with no exceptions yet somehow is getting marked as a READ_ONLY transaction? Is this even the reason why the named graph isn't getting created?

Thank you for suggestions or tips! I'm happy to provide more details if anyone has exploratory questions that might help unearth the root cause for this.

答:
Providing an answer to my own question as this was resolved with assist from Mats Rydberg.  The issue was that the call alone does not execute the operation. The result has to be iterated.

So a more fitting way to do this in embedded mode would be:

```<code>CALL gds.graph.create("someNamedGraph", ["someNodeLabel"], ["someRelationshipType"]) YIELD graphName
</code>```

And, on the server-side:

```<code>try(Transaction tx = graphDb.beginTx())
{
    Result resultSet = tx.execute(cql);
    while(resultSet.hasNext())
        resultSet.next();
}
</code>```

which indeed produces the named graph.

The root problem, to me, is that my original query (with no YIELD clause) works correctly in the built-in browser app for neo4j community edition server-mode, suggesting there are things happening behind the scenes, such that its obfuscated as to how that ends up working.  Regardless, the solution to the problem is now understood and hopefully, in the future, there will be more documentation about making GDS work in embedded mode specifically.

Title: Neo4j embedded mode use of GDS

Body:
Providing an answer to my own question as this was resolved with assist from Mats Rydberg.  The issue was that the call alone does not execute the operation. The result has to be iterated.

So a more fitting way to do this in embedded mode would be:

CALL gds.graph.create("someNamedGraph", ["someNodeLabel"], ["someRelationshipType"]) YIELD graphName

And, on the server-side:

try(Transaction tx = graphDb.beginTx())
{
    Result resultSet = tx.execute(cql);
    while(resultSet.hasNext())
        resultSet.next();
}

which indeed produces the named graph.

The root problem, to me, is that my original query (with no YIELD clause) works correctly in the built-in browser app for neo4j community edition server-mode, suggesting there are things happening behind the scenes, such that its obfuscated as to how that ends up working.  Regardless, the solution to the problem is now understood and hopefully, in the future, there will be more documentation about making GDS work in embedded mode specifically.


问:
How to optimize a rest API response that call external APIs multiple time and responds list of results?
I have written a rest API that takes a request that is a list (size of this list is dynamic).

Now what my API does is, for each item in the list calls an external API and responds with the collection of all the responses.

Please refer the flow diagram below:

Now this process is time consuming and response time is too high.

Note:

This has to be a synchronous process.

We cannot implement pagination here.

Also we don't want to go for multithreading as it can be an overkill if the number of items is too less and if the number of items is too high it may eat up a lot of resources.

So is there something we can do to reduce this response time?

答:
For the solution for your problem I would recommend reactive microservices, that is, how to develop non-blocking synchronous REST APIs and asynchronous event-driven services.

Traditionally, as Java developers, we are used to implementing synchronous
communication using blocking I/O, for example, a RESTful JSON API over HTTP.
Using a blocking I/O means that a thread is allocated from the operating system for the length of the request. If the number of concurrent requests goes up, a server might run out of available threads in the operating system, causing problems ranging from longer response times to crashing servers. Using a microservice architecture typically makes this problem even worse, where typically a chain of cooperating microservices is used to serve a request. The more microservices involved in serving a request, the faster the available threads will be drained.

If a synchronous programming model is preferred, use reactive frameworks
that can execute synchronous requests using non-blocking I/O, without
allocating a thread while waiting for a response. This will make the
microservices easier to scale in order to handle an increased workload.


问:
How do I resolve "cannot find module for path X" importing a local Go module?
In my Go project, I want to break out some generic functionality into a Go module, separate from the main project. I'm doing this outside of GOPATH in keeping with go's future. I don't want to publish the module on GitHub or anywhere else.

All my attempts to import this module into the main project result in:

```<code>cannot find module for path X
</code>```

I've run go mod init X in the module's folder. The contents of its go.mod file is:

```<code>module X
</code>```

Building or installing this module seems to do nothing. I've found no sign of it in $GOPATH/pgk/mod.

I've tried a variety of import statements:

import "X"

import "../x"  (relative path to the module directory)

import "../x/X" (path to the directory + module name)

Help!

答:
Error ?  Go cannot resolve the path to your modules, this is probably from misconfiguration or (not configuring) of the "go.mod" file used for project dependency tracking.

Solution  lets assume your project folder looks like below;

/
|-- folderOne/
|-- folderTwo/
|-- folderThree/
|-- main.go

```<code> And the main.go script imports the modules  folderOne,folderTwo and folderFour's script (folderfour.go) imports the module folderThree.

    folderOne:
    execute in the commandline:
go mod init github.com/../folderOne (i.e path from github.com folder to folderOnes)
    The go mod init command creates a go.mod file to track your code's dependencies

    folderTwo:
    execute in the commandline:
go mod init github.com/../folderTwo (i.e path from github.com folder to folderTwos)
    The go mod init command creates a go.mod file to track your code's dependencies

    folderThree:
    execute in the commandline:
go mod init github.com/../folderThree (i.e path from github.com folder to folderThrees)
    The go mod init command creates a go.mod file to track your code's dependencies

    folderFour:
    execute in the commandline:
go mod init github.com/../folderThree (i.e path from github.com folder to folderFour)
    Go to the folderFours script and import the module folderThree i.e
    import "github.com/../folderThree"

    in folderfours commandline:
$ go mod edit -replace github.com/{pathto}/folderThree=./folderThree**

    then execute: go mod tidy

    in your projects root folder execute the command: go mod init github.com/../ProjectRootDirectory (i.e path from github.com folder to ProjectRootDirectory)

    then to import the modules, i.e folderThree, folderTwo, folderOne
    execute the following at the projects root folder(ie folder with main.go)
$ go mod edit -replace github.com/{pathto}/folderOne=./folderOne
$ go mod edit -replace github.com/{pathto}/folderTwo=./folderTwo
$ go mod edit -replace github.com/{pathto}/folderFour=./folderFour

then execute;
$ go mod tidy
and then
$ go run main.go
</code>```

Body:
In my Go project, I want to break out some generic functionality into a Go module, separate from the main project. I'm doing this outside of GOPATH in keeping with go's future. I don't want to publish the module on GitHub or anywhere else.

All my attempts to import this module into the main project result in:

cannot find module for path X

I've run go mod init X in the module's folder. The contents of its go.mod file is:

module X

Building or installing this module seems to do nothing. I've found no sign of it in $GOPATH/pgk/mod.

I've tried a variety of import statements:

import "X"

import "../x"  (relative path to the module directory)

import "../x/X" (path to the directory + module name)

Help!

Body:
Error ?  Go cannot resolve the path to your modules, this is probably from misconfiguration or (not configuring) of the "go.mod" file used for project dependency tracking.

Solution  lets assume your project folder looks like below;

/
|-- folderOne/
|-- folderTwo/
|-- folderThree/
|-- main.go

 And the main.go script imports the modules  folderOne,folderTwo and folderFour's script (folderfour.go) imports the module folderThree.

    folderOne:
    execute in the commandline:
go mod init github.com/../folderOne (i.e path from github.com folder to folderOnes)
    The go mod init command creates a go.mod file to track your code's dependencies

    folderTwo:
    execute in the commandline:
go mod init github.com/../folderTwo (i.e path from github.com folder to folderTwos)
    The go mod init command creates a go.mod file to track your code's dependencies

    folderThree:
    execute in the commandline:
go mod init github.com/../folderThree (i.e path from github.com folder to folderThrees)
    The go mod init command creates a go.mod file to track your code's dependencies

    folderFour:
    execute in the commandline:
go mod init github.com/../folderThree (i.e path from github.com folder to folderFour)
    Go to the folderFours script and import the module folderThree i.e
    import "github.com/../folderThree"

    in folderfours commandline:
$ go mod edit -replace github.com/{pathto}/folderThree=./folderThree**

    then execute: go mod tidy

    in your projects root folder execute the command: go mod init github.com/../ProjectRootDirectory (i.e path from github.com folder to ProjectRootDirectory)

    then to import the modules, i.e folderThree, folderTwo, folderOne
    execute the following at the projects root folder(ie folder with main.go)
$ go mod edit -replace github.com/{pathto}/folderOne=./folderOne
$ go mod edit -replace github.com/{pathto}/folderTwo=./folderTwo
$ go mod edit -replace github.com/{pathto}/folderFour=./folderFour

then execute;
$ go mod tidy
and then
$ go run main.go


问:
GWT overlay types, converting to JSON
In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?

I currently have

```<code>public final String toJSON() {
    return new JSONObject(this).toString();
}
</code>```

Which seems to work fine. I would like to know if there are any better approaches.

答:
we have a JSNI method like that, but use douglas crockfords JSON library (in case the browser doesn't supply one natively):

https://github.com/douglascrockford/JSON-js

```<code>public native String stringify() /*-{
  return JSON.stringify();
}-*/;
</code>```

whats nice is that stringify can take parameters to pretty-print the output with a specified indentation... among other things

OwnerDisplayName: AlexJReid

ContentLicense: CC BY-SA 2.5

Title: GWT overlay types, converting to JSON

Body:
In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?

I currently have

public final String toJSON() {
    return new JSONObject(this).toString();
}

Which seems to work fine. I would like to know if there are any better approaches.

Body:
we have a JSNI method like that, but use douglas crockfords JSON library (in case the browser doesn't supply one natively):

https://github.com/douglascrockford/JSON-js

public native String stringify() /*-{
  return JSON.stringify();
}-*/;

whats nice is that stringify can take parameters to pretty-print the output with a specified indentation... among other things


问:
Using class instance from main form at button click method
I'm new to C# so sorry for this question...
I have following code:

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Forms;

namespace Test2MailVerteiler
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string MyXmlFile = "C:/Test/Text.xml";
            XmlSerializer xs = new XmlSerializer(typeof(Team));
            using (StreamReader rd = new StreamReader(MyXmlFile))
            {
                Team team = xs.Deserialize(rd) as Team;
                int n = team.TeamMember.Length;
                for (int i = 0; i < n; i++)
                {
                    checkedListBox1.Items.Add(team.TeamMember[i].Name);
                }
            }
        }
        public void btnReset_Click(object sender, EventArgs e)
        {

        }
        private void btnAddFromClipboard_Click(object sender, EventArgs e)
        {
            string sTextClipboard;
            sTextClipboard = Clipboard.GetText();
            //HOW TO USE TEAM HERE
        }

    }

    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Team
    {
        private TeamTeamMember[] teamMemberField;
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("TeamMember")]
        public TeamTeamMember[] TeamMember
        {
            get{ return this.teamMemberField; }
            set{ this.teamMemberField = value; }
        }
    }

    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class TeamTeamMember
    {
        private string nameField;
        private string mailAddressField;
        private string searchNameField;
        private string altSearchNameField;

        public string Name
        {
            get{ return this.nameField; }
            set{ this.nameField = value; }
        }

        public string MailAddress
        {
            get { return this.mailAddressField; }
            set{ this.mailAddressField = value; }
        }

        public string SearchName
        {
            get { return this.searchNameField; }
            set { this.searchNameField = value; }
        }

        /// <remarks/>
        public string AltSearchName
        {
            get { return this.altSearchNameField; }
            set { this.altSearchNameField = value; }
        }
    }
}
</code>```

The class Team is created automatically from an XML file, the instance team is then created when reading the XML and parsing its contents.
This is done in Form1 class. When I now click on btnAddFromClipboard I want to parse the instance team and search for a string in it which I get from clipboard.
But team is not defined in

```<code>private void btnAddFromClipboard_Click(object sender, EventArgs e
</code>```

How can I use the instance team created in Forms1 when the button is clicked?

答:
Define

```<code>Team team =null;
</code>```

inside form class.
Then change the statement in the form constructor
From Team team = xs.Deserialize(rd) as Team; to:

```<code>team = xs.Deserialize(rd) as Team;
</code>```

Body:
I'm new to C# so sorry for this question...
I have following code:

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Forms;

namespace Test2MailVerteiler
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string MyXmlFile = "C:/Test/Text.xml";
            XmlSerializer xs = new XmlSerializer(typeof(Team));
            using (StreamReader rd = new StreamReader(MyXmlFile))
            {
                Team team = xs.Deserialize(rd) as Team;
                int n = team.TeamMember.Length;
                for (int i = 0; i < n; i++)
                {
                    checkedListBox1.Items.Add(team.TeamMember[i].Name);
                }
            }
        }
        public void btnReset_Click(object sender, EventArgs e)
        {

        }
        private void btnAddFromClipboard_Click(object sender, EventArgs e)
        {
            string sTextClipboard;
            sTextClipboard = Clipboard.GetText();
            //HOW TO USE TEAM HERE
        }

    }

    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Team
    {
        private TeamTeamMember[] teamMemberField;
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("TeamMember")]
        public TeamTeamMember[] TeamMember
        {
            get{ return this.teamMemberField; }
            set{ this.teamMemberField = value; }
        }
    }

    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class TeamTeamMember
    {
        private string nameField;
        private string mailAddressField;
        private string searchNameField;
        private string altSearchNameField;

        public string Name
        {
            get{ return this.nameField; }
            set{ this.nameField = value; }
        }

        public string MailAddress
        {
            get { return this.mailAddressField; }
            set{ this.mailAddressField = value; }
        }

        public string SearchName
        {
            get { return this.searchNameField; }
            set { this.searchNameField = value; }
        }

        /// <remarks/>
        public string AltSearchName
        {
            get { return this.altSearchNameField; }
            set { this.altSearchNameField = value; }
        }
    }
}

The class Team is created automatically from an XML file, the instance team is then created when reading the XML and parsing its contents.
This is done in Form1 class. When I now click on btnAddFromClipboard I want to parse the instance team and search for a string in it which I get from clipboard.
But team is not defined in

private void btnAddFromClipboard_Click(object sender, EventArgs e

How can I use the instance team created in Forms1 when the button is clicked?

Body:
Define

Team team =null;

inside form class.
Then change the statement in the form constructor
From Team team = xs.Deserialize(rd) as Team; to:

team = xs.Deserialize(rd) as Team;


问:
Why is the Style not getting applied from code?
I'm trying to create a button from code and make the hover color change, for some reason the setters, etc are not getting applied. I'm pretty sure I'm either missing a step or it's something else but nothing changes, not even the color while not hovering. I'm not trying to make the button in XAML but create it in code and I know how to do it in XAML.</p>
```<code>System.Windows.Controls.Button createPlaylist = new System.Windows.Controls.Button()
     {
        Height = 100,
        Width = 100,
        Margin = new Thickness(0,50,0,0)
    };

    //                                      STYLE END                                   //
    var dt = new DataTemplate();

    Style style = new Style(typeof(System.Windows.Controls.Button), createPlaylist.Style);

    Trigger t = new Trigger();
    t.Property = IsMouseOverProperty;
    t.Value = true;
    Setter setter = new Setter();
    setter.Property = BackgroundProperty;
    setter.Value = Brushes.Blue;
    t.Setters.Add(setter);

    Trigger s = new Trigger();
    s.Property = IsMouseOverProperty;
    s.Value = false;
    Setter set = new Setter();
    set.Property = BackgroundProperty;
    set.Value = Brushes.Red;
    s.Setters.Add(setter);

    style.Triggers.Add(t);

    createPlaylist.Style = style;
</code>```

答:
You have to manage the Background color of the Border within the Template of the Button, instead of just changing the Background property of the Button itself.

i.e. do the equivalent of this XAML:

```<code><Style TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Blue"/>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

Something like this on code behind:

```<code>Style buttonStyle = new Style();

FrameworkElementFactory contentBorder = new FrameworkElementFactory(typeof(Border));
contentBorder.AppendChild(new FrameworkElementFactory(typeof(ContentPresenter)));
contentBorder.SetBinding(Border.BackgroundProperty, new Binding { RelativeSource = RelativeSource.TemplatedParent, Path = new PropertyPath(nameof(Background)) });
ControlTemplate templateButton = new ControlTemplate(typeof(Button)) { VisualTree = contentBorder };
buttonStyle.Setters.Add(new Setter { Property = Button.TemplateProperty, Value = templateButton });

Trigger styleTrigger = new Trigger { Property = Button.IsMouseOverProperty, Value = true };
styleTrigger.Setters.Add(new Setter { Property = Button.BackgroundProperty, Value = Brushes.Blue });
buttonStyle.Triggers.Add(styleTrigger);

createPlaylist.Style = buttonStyle;
</code>```

Body:
I'm trying to create a button from code and make the hover color change, for some reason the setters, etc are not getting applied. I'm pretty sure I'm either missing a step or it's something else but nothing changes, not even the color while not hovering. I'm not trying to make the button in XAML but create it in code and I know how to do it in XAML.

System.Windows.Controls.Button createPlaylist = new System.Windows.Controls.Button()
     {
        Height = 100,
        Width = 100,
        Margin = new Thickness(0,50,0,0)
    };

    //                                      STYLE END                                   //
    var dt = new DataTemplate();

    Style style = new Style(typeof(System.Windows.Controls.Button), createPlaylist.Style);

    Trigger t = new Trigger();
    t.Property = IsMouseOverProperty;
    t.Value = true;
    Setter setter = new Setter();
    setter.Property = BackgroundProperty;
    setter.Value = Brushes.Blue;
    t.Setters.Add(setter);

    Trigger s = new Trigger();
    s.Property = IsMouseOverProperty;
    s.Value = false;
    Setter set = new Setter();
    set.Property = BackgroundProperty;
    set.Value = Brushes.Red;
    s.Setters.Add(setter);

    style.Triggers.Add(t);

    createPlaylist.Style = style;

Body:
You have to manage the Background color of the Border within the Template of the Button, instead of just changing the Background property of the Button itself.

i.e. do the equivalent of this XAML:

<Style TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Blue"/>
        </Trigger>
    </Style.Triggers>
</Style>

Something like this on code behind:

Style buttonStyle = new Style();

FrameworkElementFactory contentBorder = new FrameworkElementFactory(typeof(Border));
contentBorder.AppendChild(new FrameworkElementFactory(typeof(ContentPresenter)));
contentBorder.SetBinding(Border.BackgroundProperty, new Binding { RelativeSource = RelativeSource.TemplatedParent, Path = new PropertyPath(nameof(Background)) });
ControlTemplate templateButton = new ControlTemplate(typeof(Button)) { VisualTree = contentBorder };
buttonStyle.Setters.Add(new Setter { Property = Button.TemplateProperty, Value = templateButton });

Trigger styleTrigger = new Trigger { Property = Button.IsMouseOverProperty, Value = true };
styleTrigger.Setters.Add(new Setter { Property = Button.BackgroundProperty, Value = Brushes.Blue });
buttonStyle.Triggers.Add(styleTrigger);

createPlaylist.Style = buttonStyle;


问:
AWS API Gateway - Call GET Method with C# SDK
I have an API Gateway that uses IAM authorization.  I have a C# application that I'm hoping to call the API with.  I started with a GetMethodRequest but I don't see anyway to set the PathPart parameter.

```<code>var userId = _remoteCredentials.UserId;
var key = _remoteCredentials.Key;

var client = new AmazonAPIGatewayClient(userId, key, Amazon.RegionEndpoint.USEast2);
GetMethodRequest getMethodRequest = new GetMethodRequest();
getMethodRequest.HttpMethod = HttpMethod.Get.ToString();
getMethodRequest.ResourceId = "4abcde";
getMethodRequest.RestApiId = "aasfasdfs";

var task = Task.Run(async () => await client.GetMethodAsync(getMethodRequest).ConfigureAwait(false));
</code>```

I was expecting something like the Test-AGInvokeMethod in the Powershell SDK which allows me to set the query string and the path.

```<code>$response = Test-AGInvokeMethod
                   -RestApiId aasfasdfs
                   -ResourceId 4abcde
                   -HttpMethod GET
                   -PathWithQueryString '/etl/upload_url'
</code>```

Any help is greatly appreciated.

EDIT Below is something of a solution that I ended up using the AWS4RequestSigner is a library that I found on Github

```<code>var signer = new AWS4RequestSigner(userId, key);
var destinationUrl = string.Format("https://ad9vxabc123.execute-api.us-east-2.amazonaws.com/dev/etl/summary/latest?tms_id={0}&model_id={1}", _tmsId, _modelId);
var request = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri(destinationUrl),
};

var signed = Task.Run(async () => await signer.Sign(request, "execute-api", "us-east-2").ConfigureAwait(false));
var signedResult = signed.Result;
</code>```

答:
The AmazonAPIGatewayClient is for managing your API Gateway e.g. adding new stages or deleting API keys.

You're looking to invoke a method on your API Gateway, like Test-AGInvokeMethod does.

To invoke your API gateway, you need to call the deployed API endpoint using a HTTP client.

.NET's in-built HttpClient is a good start.

Body:
I have an API Gateway that uses IAM authorization.  I have a C# application that I'm hoping to call the API with.  I started with a GetMethodRequest but I don't see anyway to set the PathPart parameter.

var userId = _remoteCredentials.UserId;
var key = _remoteCredentials.Key;

var client = new AmazonAPIGatewayClient(userId, key, Amazon.RegionEndpoint.USEast2);
GetMethodRequest getMethodRequest = new GetMethodRequest();
getMethodRequest.HttpMethod = HttpMethod.Get.ToString();
getMethodRequest.ResourceId = "4abcde";
getMethodRequest.RestApiId = "aasfasdfs";

var task = Task.Run(async () => await client.GetMethodAsync(getMethodRequest).ConfigureAwait(false));

I was expecting something like the Test-AGInvokeMethod in the Powershell SDK which allows me to set the query string and the path.

$response = Test-AGInvokeMethod
                   -RestApiId aasfasdfs
                   -ResourceId 4abcde
                   -HttpMethod GET
                   -PathWithQueryString '/etl/upload_url'

Any help is greatly appreciated.

EDIT Below is something of a solution that I ended up using the AWS4RequestSigner is a library that I found on Github

var signer = new AWS4RequestSigner(userId, key);
var destinationUrl = string.Format("https://ad9vxabc123.execute-api.us-east-2.amazonaws.com/dev/etl/summary/latest?tms_id={0}&model_id={1}", _tmsId, _modelId);
var request = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri(destinationUrl),
};

var signed = Task.Run(async () => await signer.Sign(request, "execute-api", "us-east-2").ConfigureAwait(false));
var signedResult = signed.Result;


问:
Salesforce Lead Tracking integration with Contact forms on Wordpress
I have raised this question on the WP Answers as well. But since this uses Salesforce too, wasn't sure if I'd get a response there.

I am using Contact Form 7 on my website and would like to integrate Salesforce lead tracking with it.

I was able to add a hidden field with my oid as suggested on this site

But when I submit the contact form after adding this, it just gets stuck and never actually returns. As soon as I remove the hidden field, it starts working fine.

Has anyone been able to integrate the lead tracking system with Wordpress Contact Form plugins?

I also tried using cform with the instructions provided here. But this gives a warning that fopen failed. I assume thats because fopen does not allow write operations with HTTP wrappers. Not sure how the author managed to get it working!

Would appreciate any help on this! I do not want to use the salesforce Web-to-lead form. Thanks.

答:
From my research into integrating salesforce with cforms the basic principal is that you need the POST info needs to correspond exactly with the cform POST info.

When writing the post you liked to I research the process by using an example form from them - embedded code provided - then found a way to make cforms submit the data, formatted the way they specified to https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8 the url they had in their form.

Feel free to use me if you run into difficulties...


问:
how do i find out how many different states in my data set
I am taking python course and trying to find out how many different states in my data set.

The column is 'ST'

i have attached screenshot

答:
You can use pandas.unique to collect the unique elements of a series

```<code>>>> import pandas as pd

>>> df = pd.DataFrame(data={'ST': ['IL', 'WI',' LA', 'UT', 'IL']})
>>> pd.unique(df['ST'])
array(['IL', 'WI', ' LA', 'UT'], dtype=object)
</code>```

and then use the size of the series

```<code>>>> pd.unique(df['ST']).size
4
</code>```

similarly you can just call the nunique method off the series itself

```<code>>>> df['ST'].nunique()
4
</code>```

Body:
You can use pandas.unique to collect the unique elements of a series

>>> import pandas as pd

>>> df = pd.DataFrame(data={'ST': ['IL', 'WI',' LA', 'UT', 'IL']})
>>> pd.unique(df['ST'])
array(['IL', 'WI', ' LA', 'UT'], dtype=object)

and then use the size of the series

>>> pd.unique(df['ST']).size
4

similarly you can just call the nunique method off the series itself

>>> df['ST'].nunique()
4


问:
How to remote debug a java application running on Azure App Service
When browsing to Settings > Configuration > General Settings Microsoft is pretty clear in that it currently doesn't support remote debugging (Linux App Service Plan, Java 11 SE).

However, I was wondering if there still is way to accomplish this, in a more manual fashion. E.g. I am able to open up a debugging port with the following custom startup command.

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /home/site/wwwroot/app.jar

Notice the log below, that states it is listening on 5005/TCP. As expected, however, this listening port is not getting forwarded by Microsoft's infrastructure.

Also, SSH is only available via browser, so there is no easy way to expose that port by forwarding it like so ssh user@mywebsite.azurewebsites.net -L 5005:localhost:5005.

Any other idea how a remote debugging session might be achieved with Java?

```<code>2021-07-29T14:52:59.769816383Z: [INFO]    _____
2021-07-29T14:52:59.769851884Z: [INFO]    /  _  \ __________ _________   ____
2021-07-29T14:52:59.769857984Z: [INFO]   /  /_\  \___   /  |  \_  __ \_/ __ \
2021-07-29T14:52:59.769873185Z: [INFO]  /    |    \/    /|  |  /|  | \/\  ___/
2021-07-29T14:52:59.769878285Z: [INFO]  \____|__  /_____ \____/ |__|    \___  >
2021-07-29T14:52:59.924543150Z: [INFO]          \/      \/                  \/
2021-07-29T14:52:59.924549150Z: [INFO]  A P P   S E R V I C E   O N   L I N U X
[...]
2021-07-29T14:53:05.404068415Z: [INFO]  STARTUP_FILE=
2021-07-29T14:53:05.419701706Z: [INFO]  STARTUP_COMMAND=java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /home/site/wwwroot/app.jar
2021-07-29T14:53:05.419807209Z: [INFO]  No STARTUP_FILE available.
2021-07-29T14:53:05.419822210Z: [INFO]  Running STARTUP_COMMAND: java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /home/site/wwwroot/app.jar
2021-07-29T14:53:05.468409936Z: [ERROR]  Picked up JAVA_TOOL_OPTIONS: -Xmx1346M -Djava.net.preferIPv4Stack=true
2021-07-29T14:53:05.769742003Z: [INFO]  Listening for transport dt_socket at address: 5005
2021-07-29T14:53:15.032989100Z: [INFO]
2021-07-29T14:53:15.033937730Z: [INFO]    .   ____          _            __ _ _
2021-07-29T14:53:15.034646252Z: [INFO]   /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
2021-07-29T14:53:15.035378475Z: [INFO]  ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2021-07-29T14:53:15.035688785Z: [INFO]   \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
2021-07-29T14:53:15.082402455Z: [INFO]    '  |____| .__|_| |_|_| |_\__, | / / / /
2021-07-29T14:53:15.082444656Z: [INFO]   =========|_|==============|___/=/_/_/_/
2021-07-29T14:53:15.082450956Z: [INFO]   :: Spring Boot ::                (v2.5.3)
2021-07-29T14:53:15.082455556Z: [INFO]
2021-07-29T14:53:15.874610379Z: [INFO]  2021-07-29 14:53:15.853  INFO 122 --- [           main] c.s.r.RemoteDebuggingDemo1Application    : Starting RemoteDebuggingDemo1Application using Java 11.0.7 on 16f2213f1d06 with PID 122 (/home/site/wwwroot/app.jar started by root in /)
2021-07-29T14:53:15.889931561Z: [INFO]  2021-07-29 14:53:15.889  INFO 122 --- [           main] c.s.r.RemoteDebuggingDemo1Application    : No active profile set, falling back to default profiles: default
2021-07-29T14:53:26.797375136Z: [INFO]  2021-07-29 14:53:26.796  INFO 122 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 80 (http)
2021-07-29T14:53:26.919083170Z: [INFO]  2021-07-29 14:53:26.918  INFO 122 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-07-29T14:53:26.921537347Z: [INFO]  2021-07-29 14:53:26.919  INFO 122 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.50]
2021-07-29T14:53:27.704270105Z: [INFO]  2021-07-29 14:53:27.703  INFO 122 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
[...]
</code>```

答:
It is actually possible to remote debug a Java application on Azue Linux AppService, by tunneling through SSH. This was tested on premium App Service Plans. Somehow I never found a documentation suggesting that, so here we go:

You add an application setting JAVA_OPTS to your app

agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:8000

Create a remote-connection with azure cli, that creates a SSH port 1234 on your computer:

az webapp create-remote-connection -g RG -n MY_APP -p 1234

Create a ssh Tunnel from this local SSH port to the remote debugging port in the appservice

ssh -L 1235:127.0.0.1:8000 root@127.0.0.1 -p 1234

You then can attach a debugger of your choice to the port 1235 on your local host: (Maybe eclipse, vscode, intellij)

jdb -attach 1235

The tunnel goes from your computer -> remote-connection via az-cli -> SSH into appservice -> remotedebug port in appservice

Body:
When browsing to Settings > Configuration > General Settings Microsoft is pretty clear in that it currently doesn't support remote debugging (Linux App Service Plan, Java 11 SE).

However, I was wondering if there still is way to accomplish this, in a more manual fashion. E.g. I am able to open up a debugging port with the following custom startup command.

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /home/site/wwwroot/app.jar

Notice the log below, that states it is listening on 5005/TCP. As expected, however, this listening port is not getting forwarded by Microsoft's infrastructure.

Also, SSH is only available via browser, so there is no easy way to expose that port by forwarding it like so ssh user@mywebsite.azurewebsites.net -L 5005:localhost:5005.

Any other idea how a remote debugging session might be achieved with Java?

2021-07-29T14:52:59.769816383Z: [INFO]    _____
2021-07-29T14:52:59.769851884Z: [INFO]    /  _  \ __________ _________   ____
2021-07-29T14:52:59.769857984Z: [INFO]   /  /_\  \___   /  |  \_  __ \_/ __ \
2021-07-29T14:52:59.769873185Z: [INFO]  /    |    \/    /|  |  /|  | \/\  ___/
2021-07-29T14:52:59.769878285Z: [INFO]  \____|__  /_____ \____/ |__|    \___  >
2021-07-29T14:52:59.924543150Z: [INFO]          \/      \/                  \/
2021-07-29T14:52:59.924549150Z: [INFO]  A P P   S E R V I C E   O N   L I N U X
[...]
2021-07-29T14:53:05.404068415Z: [INFO]  STARTUP_FILE=
2021-07-29T14:53:05.419701706Z: [INFO]  STARTUP_COMMAND=java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /home/site/wwwroot/app.jar
2021-07-29T14:53:05.419807209Z: [INFO]  No STARTUP_FILE available.
2021-07-29T14:53:05.419822210Z: [INFO]  Running STARTUP_COMMAND: java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar /home/site/wwwroot/app.jar
2021-07-29T14:53:05.468409936Z: [ERROR]  Picked up JAVA_TOOL_OPTIONS: -Xmx1346M -Djava.net.preferIPv4Stack=true
2021-07-29T14:53:05.769742003Z: [INFO]  Listening for transport dt_socket at address: 5005
2021-07-29T14:53:15.032989100Z: [INFO]
2021-07-29T14:53:15.033937730Z: [INFO]    .   ____          _            __ _ _
2021-07-29T14:53:15.034646252Z: [INFO]   /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
2021-07-29T14:53:15.035378475Z: [INFO]  ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2021-07-29T14:53:15.035688785Z: [INFO]   \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
2021-07-29T14:53:15.082402455Z: [INFO]    '  |____| .__|_| |_|_| |_\__, | / / / /
2021-07-29T14:53:15.082444656Z: [INFO]   =========|_|==============|___/=/_/_/_/
2021-07-29T14:53:15.082450956Z: [INFO]   :: Spring Boot ::                (v2.5.3)
2021-07-29T14:53:15.082455556Z: [INFO]
2021-07-29T14:53:15.874610379Z: [INFO]  2021-07-29 14:53:15.853  INFO 122 --- [           main] c.s.r.RemoteDebuggingDemo1Application    : Starting RemoteDebuggingDemo1Application using Java 11.0.7 on 16f2213f1d06 with PID 122 (/home/site/wwwroot/app.jar started by root in /)
2021-07-29T14:53:15.889931561Z: [INFO]  2021-07-29 14:53:15.889  INFO 122 --- [           main] c.s.r.RemoteDebuggingDemo1Application    : No active profile set, falling back to default profiles: default
2021-07-29T14:53:26.797375136Z: [INFO]  2021-07-29 14:53:26.796  INFO 122 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 80 (http)
2021-07-29T14:53:26.919083170Z: [INFO]  2021-07-29 14:53:26.918  INFO 122 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-07-29T14:53:26.921537347Z: [INFO]  2021-07-29 14:53:26.919  INFO 122 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.50]
2021-07-29T14:53:27.704270105Z: [INFO]  2021-07-29 14:53:27.703  INFO 122 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
[...]


问:
variable for class defined in __main__ with access in different module
I know I'm being dense and I know what the problem is but I can't seem to figure out how to fix it.

testcode.py

```<code>import t2

class t1:
    saved = 0
    @classmethod
    def set_class(cls, number):
        t1.saved = number

not_in_main = t1

if __name__ == "__main__":
    not_in_main.set_class(6)
    used_everywhere = t1

    used_everywhere.set_class(4)
    t2.f1()
</code>```

and then in t2.py

```<code>import testcode

def f1():
    print(f'not_in_main: {testcode.not_in_main.saved}')
    print(f'got here: {testcode.used_everywhere.saved}')
</code>```

Now the output after running python testcode.py will be

```<code>not_in_main: 0
AttributeError: module 'testcode' has no attribute 'used_everywhere'
</code>```

So not_in_main has two different instances one in the main scope and one module scope. Used_everywhere is also in the main scope but another module can't see in instance.

I've looked at many of the scoping issues but I don't see how to fix this. What am I doing wrong?

答:
The fix for this circular issue was to move the class def and creation of the module variable to a file other than where main is. The project now just has main in the a module and most all other code in a separate file.

Breakpoints on the not_in_main show it only being instantiated once as opposed to twice as in the listed code.

When necessary, as in generated code for the UI, that is in a separate module, the import of the module where not_in_main is declared does not cause a circular reference and the fields are properly filled out.

Thanks to @junpa.arrivillaga for the pointers and hints to put me on the right path.

Body:
I know I'm being dense and I know what the problem is but I can't seem to figure out how to fix it.

testcode.py

import t2

class t1:
    saved = 0
    @classmethod
    def set_class(cls, number):
        t1.saved = number

not_in_main = t1

if __name__ == "__main__":
    not_in_main.set_class(6)
    used_everywhere = t1

    used_everywhere.set_class(4)
    t2.f1()

and then in t2.py

import testcode

def f1():
    print(f'not_in_main: {testcode.not_in_main.saved}')
    print(f'got here: {testcode.used_everywhere.saved}')

Now the output after running python testcode.py will be

not_in_main: 0
AttributeError: module 'testcode' has no attribute 'used_everywhere'

So not_in_main has two different instances one in the main scope and one module scope. Used_everywhere is also in the main scope but another module can't see in instance.

I've looked at many of the scoping issues but I don't see how to fix this. What am I doing wrong?


问:
Is there a python module that provides a test for equivalent Unicode characters?
There are multiple Unicode characters that are visually similar, such as:

```<code>":" and "꞉"     U+A789
"?" and "？"    U+FF1F
"*" and "⁎"     U+204E
"'", "`", "‘", "’", and "ʻ"
</code>```

There are also characters with and without diacritical marks, such as:

```<code>"c" and "ç"     U+00E7
"E" and "É"     U+00C9
"I" and "İ"     U+00ED
"i" and "ı"     U+0131
</code>```

I'd like to compare text from various sources, with effectively the same words comparing as equal, such as:

```<code>"naive" and "naïve"
"facade" and "façade"
"Hawai'i" and "Hawaiʻi"
"don't" and "don’t"
"letter 'A'" and "letter ‘A’" and "letter `A'"
"letter "B"" and "letter "“B”"
</code>```

Is there a module that provides tests of equivalence between such characters?

```<code>import unicode
if x != y and not unicode.same_character(x, y):
</code>```

答:
If you transliterate characters, you'll get close to that.

In some cases you mention (e.g. "i" and "ı"), they are not the same character but it might do what you want anyway.

Transliteration is language specific.

Try this module: https://pypi.org/project/transliterate/

Body:
There are multiple Unicode characters that are visually similar, such as:

":" and "꞉"     U+A789
"?" and "？"    U+FF1F
"*" and "⁎"     U+204E
"'", "`", "‘", "’", and "ʻ"

There are also characters with and without diacritical marks, such as:

"c" and "ç"     U+00E7
"E" and "É"     U+00C9
"I" and "İ"     U+00ED
"i" and "ı"     U+0131

I'd like to compare text from various sources, with effectively the same words comparing as equal, such as:

"naive" and "naïve"
"facade" and "façade"
"Hawai'i" and "Hawaiʻi"
"don't" and "don’t"
"letter 'A'" and "letter ‘A’" and "letter `A'"
"letter "B"" and "letter "“B”"

Is there a module that provides tests of equivalence between such characters?

import unicode
if x != y and not unicode.same_character(x, y):


问:
how to change button class when i click on it using Jquery?
so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can't find a way to do it

```<code><html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
      });
    });
  </script>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button id="p" class="btn btn-success">Random button</button>
  </body>
</html>
</code>```

答:
You can put all the classes you want to apply into an array and store the array index of the currently applied class in a variable or using jQuery's .data() method.

Then, whenever the button is clicked, you retrieve and increase the index to get the next class and apply it to the button. Try this

$(document).ready(function () {
    var classes = ['btn-success', 'btn-info', 'btn-primary'];

    $("button").click(function(){
        let idx = $(this).data('class-index') ?? 0; // index of the currently applied class
        let cls = classes[idx+1] ?? classes[0]; // get the next class
        $(this).data('class-index', classes.indexOf(cls)); // store the class index
        $(this).removeClass(classes).addClass(cls); // remove old class and apply new one
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button { outline: none!important; }</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<button id="p" class="btn btn-success">Random button</button>```

Body:
so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can't find a way to do it

    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />

    <button id="p" class="btn btn-success">Random button</button>

Body:
You can put all the classes you want to apply into an array and store the array index of the currently applied class in a variable or using jQuery's .data() method.

Then, whenever the button is clicked, you retrieve and increase the index to get the next class and apply it to the button. Try this

$(document).ready(function () {
    var classes = ['btn-success', 'btn-info', 'btn-primary'];

    $("button").click(function(){
        let idx = $(this).data('class-index') ?? 0; // index of the currently applied class
        let cls = classes[idx+1] ?? classes[0]; // get the next class
        $(this).data('class-index', classes.indexOf(cls)); // store the class index
        $(this).removeClass(classes).addClass(cls); // remove old class and apply new one
    });
});

button { outline: none!important; }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<button id="p" class="btn btn-success">Random button</button>


问:
How can I get my app using Instagram Basic Display API pass app review?
This is now the 4th time I am sending my app for review. I want to use Instagram Basic Display API and therefore require instagram_graph_user_media permission to access media (and incidentally instagram_graph_user_profile). I have 2 test users, my personal IG account with a bunch of pics and a test user that I created with an empty feed. I can login with both users. But when the Instagram app reviewer is logging in, my app can't access their media. I successfully retrieve the access token but when comes the time to call the Graph API here is what happens:

https://graph.instagram.com/me/media?fields=media_type,media_url,permalink,thumbnail_url&access_token=IGQV....

returns

{"error":{"message":"Application does not have permission for this action","type":"IGApiException","code":10,"fbtrace_id":"A99vuaAC41DSvlt0Hxvcly-"}}

答:
This should be obvious but when you are so deep in the hole and try to think why your app is being rejected you stop thinking logically.

Here is what I did:

Create a dummy Instagram account.

Link this account to an email provider that doesn't require a phone/another way of verification (I used ProtonMail).

Use an Instagram Tester account (do the whole process).

In your instructions let the reviewer that they need to log in to ProtonMail to get the Instagram confirmation code; since they will do login from an unknown location (if you could simulate the above in your screencast that would be great, but I didn't do it).

If you apply for both instagram_graph_user_profile and instagram_graph_user_media you need to do this in 2 steps individually.

The second step getting the instagram_graph_user_media permission is much easier.

I lost a couple of days and tried everything and anything before I realized that.

Hopefully, this should help someone that is having the same problem.

The app was approved the first time.


问:
Creating a BroadcastReceiver Dynamically in Android
I am building an Android app that works by providing information via SMS to users.Users send an SMS to a predetermined number hardcoded in the APP and in turn receive a response.

To achieve this, I am using a broadcast Receiver in my Android Manifest

```<code><receiver android:name=".SMSReciever">
        <intent-filter android:priority="2">
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</code>```

If I create a new class SMSReciever, then when a response is received, I would to somehow send the information back to the activity which the user has open on the screen. Is it possible I can do this in my main activity dynamically so that the app can be made more interactive?

I have learnt about the Context.registerReciever method, but how do I mention the priority for the receiver? If the receiver does not have a higher priority, then the messaging app might stop the broadcast from reaching my app. Has anyone come across a solution for something like this?

答:
I would solve this by using a custom intent action like com.example.intent.VERIFICATION_RECEIVED and the broadcasting this from SMSReciever and then having your Activity listen for it with a BroadcastReceiver.

```<code>IntentFilter filter = new IntentFilter(PageFragment.ACTION_LOADING_DONE);
registerReceiver(new MyReceiver(), filter);
</code>```

Using this approach you can keep your SMS handling in SMSReciever and your Activity doesn't need to care about how to handle a SMS.

Body:
I am building an Android app that works by providing information via SMS to users.Users send an SMS to a predetermined number hardcoded in the APP and in turn receive a response.

To achieve this, I am using a broadcast Receiver in my Android Manifest

<receiver android:name=".SMSReciever">
        <intent-filter android:priority="2">
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

If I create a new class SMSReciever, then when a response is received, I would to somehow send the information back to the activity which the user has open on the screen. Is it possible I can do this in my main activity dynamically so that the app can be made more interactive?

I have learnt about the Context.registerReciever method, but how do I mention the priority for the receiver? If the receiver does not have a higher priority, then the messaging app might stop the broadcast from reaching my app. Has anyone come across a solution for something like this?

Body:
I would solve this by using a custom intent action like com.example.intent.VERIFICATION_RECEIVED and the broadcasting this from SMSReciever and then having your Activity listen for it with a BroadcastReceiver.

IntentFilter filter = new IntentFilter(PageFragment.ACTION_LOADING_DONE);
registerReceiver(new MyReceiver(), filter);

Using this approach you can keep your SMS handling in SMSReciever and your Activity doesn't need to care about how to handle a SMS.


问:
How to turn list into dataframe without losing text format in Python?
I webscraped this webpage.

```<code>
from bs4 import BeautifulSoup
import requests
import pandas as pd

url = "https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html"
soup = BeautifulSoup(requests.get(url).content)

data = []

u = soup.select('div.title > a'):
soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{u[0]['href']}").content)
    data.append({ soup.select('main .section p:not([class])')})

print(data)

df = pd.DataFrame(data)

# results (it may not be the same text
[... <p><strong>Duisenberg:</strong> My answer is, well, in the first place when something is before the courts you do not comment. I don't comment and particularly not when it concerns such an esteemed colleague of mine. So, on the hypothetical question whether other people would be eligible for the job, I think it is wise not to go into that either. </p>]

</code>```

The problem is that when I turn data into a dataframe, it remains in a list format which is difficult to handle. I would like it to be saved as a unique object without losing its properties (
,).

If I do this, it loses the division in pararaphs and bolds that will be needed for manipulation.

```<code>data = []

u = soup.select('div.title > a'):
    soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{u[0]['href']}").content)
    data.append({
        'text':' '.join([p.text for p in soup.select('main .section p:not([class])')])
    })

df = pd.DataFrame(data)

# with this however I lose the breakdown in paragraphs, bold characters etc. I'd like to keep them in the text.
</code>```

Can anyone help me with this?

Thanks!

答:
Note sure if I understand it correctly, but if you like to convert the resultset to text you can do it like that:

```<code>''.join([str(e) for e in soup.select('main .section p:not([class])')])
</code>```

Example

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd

url = "https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html"
soup = BeautifulSoup(requests.get(url).content)

data = []

u = soup.select('div.title > a')
soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{u[0]['href']}").content)
data.append({'text':''.join([str(e) for e in soup.select('main .section p:not([class])')])})

pd.DataFrame(data)
</code>```

Output

```<code>text
<p>Good afternoon, the Vice-President and I welcome you to our press conference. </p><p id="_Hlk93669934">The euro area economy is continuing to r...
</code>```

Body:
I webscraped this webpage.

from bs4 import BeautifulSoup
import requests
import pandas as pd

url = "https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html"
soup = BeautifulSoup(requests.get(url).content)

data = []

u = soup.select('div.title > a'):
soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{u[0]['href']}").content)
    data.append({ soup.select('main .section p:not([class])')})

print(data)

df = pd.DataFrame(data)

# results (it may not be the same text
[...
Duisenberg: My answer is, well, in the first place when something is before the courts you do not comment. I don't comment and particularly not when it concerns such an esteemed colleague of mine. So, on the hypothetical question whether other people would be eligible for the job, I think it is wise not to go into that either.
]

The problem is that when I turn data into a dataframe, it remains in a list format which is difficult to handle. I would like it to be saved as a unique object without losing its properties (
,).

If I do this, it loses the division in pararaphs and bolds that will be needed for manipulation.

data = []

u = soup.select('div.title > a'):
    soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{u[0]['href']}").content)
    data.append({
        'text':' '.join([p.text for p in soup.select('main .section p:not([class])')])
    })

df = pd.DataFrame(data)

# with this however I lose the breakdown in paragraphs, bold characters etc. I'd like to keep them in the text.

Can anyone help me with this?

Thanks!

Body:
Note sure if I understand it correctly, but if you like to convert the resultset to text you can do it like that:

''.join([str(e) for e in soup.select('main .section p:not([class])')])

Example

from bs4 import BeautifulSoup
import requests
import pandas as pd

url = "https://www.ecb.europa.eu/press/pressconf/2022/html/index_include.en.html"
soup = BeautifulSoup(requests.get(url).content)

data = []

u = soup.select('div.title > a')
soup = BeautifulSoup(requests.get(f"https://www.ecb.europa.eu{u[0]['href']}").content)
data.append({'text':''.join([str(e) for e in soup.select('main .section p:not([class])')])})

pd.DataFrame(data)

Output

text
<p>Good afternoon, the Vice-President and I welcome you to our press conference. </p><p id="_Hlk93669934">The euro area economy is continuing to r...


问:
Add Space Between Bars in Angularjs Chartjs
I am using Angularjs Chartjs https://jtblin.github.io/angular-chart.js/,

Js Code

```<code>$scope.options = {
    cornerRadius: 20,
    scales: {
        yAxes: [{
                gridLines: {
                    display: false
                }
            }],
        xAxes: [{
                stacked: false,
                barThickness: 11,
                barPercentage: 2.0,
                gridLines: {
                    display: false
                },
                ticks: {
                    minRotation: 20
                }
            }
        ]
    }
};
$scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
$scope.series = ['Series A', 'Series B', 'Series C'];

$scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90],
    [30, 80, 19, 86, 40, 56, 90]
];
</code>```

And In HTML

```<code><div class="row">
            <div class="col-md-12">
                <canvas id="bar" class="chart chart-bar" chart-data="data"
                        chart-labels="labels" chart-series="series" chart-options="options"
                        chart-dataset-override="colors">
                </canvas>
            </div>
        </div>
</code>```

Now I want to Make Space between the bar and make 3 fixed colors and also border-radius from both sides of the bar. I am not able to add images.
Thank You for Your Precious Time.

答:
Try using the .setOptions for global colours of the bars, and xAxes.barThickness for the spacing of bars.

```<code>var app = angular.module('app', ['chart.js', 'ngRoute']);

app.config(function ($routeProvider, ChartJsProvider) {
  $routeProvider.when('/', {
    templateUrl: 'bars.html',
    controller: 'MainCtrl',
  });
  ChartJsProvider.setOptions({
    chartColors: ['#ff0000', '#00ff00', '#0000ff'],
  });
});

app.controller('MainCtrl', function ($scope) {
  $scope.options = {
    cornerRadius: 20,
    scales: {
      yAxes: [
        {
          gridLines: {
            display: false,
          },
        },
      ],
      xAxes: [
        {
          stacked: false,
          barThickness: 20,
          borderWidth:10,
          barPercentage: 2.0,
          gridLines: {
            display: false,
          },
          ticks: {
            minRotation: 20,
          },
        },
      ],
    },
  };
  $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  $scope.series = ['Series A', 'Series B', 'Series C'];

  $scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90],
    [30, 80, 19, 86, 40, 56, 90],
  ];
});
</code>```

Body:
I am using Angularjs Chartjs https://jtblin.github.io/angular-chart.js/,

Js Code

$scope.options = {
    cornerRadius: 20,
    scales: {
        yAxes: [{
                gridLines: {
                    display: false
                }
            }],
        xAxes: [{
                stacked: false,
                barThickness: 11,
                barPercentage: 2.0,
                gridLines: {
                    display: false
                },
                ticks: {
                    minRotation: 20
                }
            }
        ]
    }
};
$scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
$scope.series = ['Series A', 'Series B', 'Series C'];

$scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90],
    [30, 80, 19, 86, 40, 56, 90]
];

And In HTML

                <canvas id="bar" class="chart chart-bar" chart-data="data"
                        chart-labels="labels" chart-series="series" chart-options="options"
                        chart-dataset-override="colors">
                </canvas>

Now I want to Make Space between the bar and make 3 fixed colors and also border-radius from both sides of the bar. I am not able to add images.
Thank You for Your Precious Time.

Body:
Try using the .setOptions for global colours of the bars, and xAxes.barThickness for the spacing of bars.

var app = angular.module('app', ['chart.js', 'ngRoute']);

app.config(function ($routeProvider, ChartJsProvider) {
  $routeProvider.when('/', {
    templateUrl: 'bars.html',
    controller: 'MainCtrl',
  });
  ChartJsProvider.setOptions({
    chartColors: ['#ff0000', '#00ff00', '#0000ff'],
  });
});

app.controller('MainCtrl', function ($scope) {
  $scope.options = {
    cornerRadius: 20,
    scales: {
      yAxes: [
        {
          gridLines: {
            display: false,
          },
        },
      ],
      xAxes: [
        {
          stacked: false,
          barThickness: 20,
          borderWidth:10,
          barPercentage: 2.0,
          gridLines: {
            display: false,
          },
          ticks: {
            minRotation: 20,
          },
        },
      ],
    },
  };
  $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  $scope.series = ['Series A', 'Series B', 'Series C'];

  $scope.data = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90],
    [30, 80, 19, 86, 40, 56, 90],
  ];
});


问:
what does $a = new $b() mean in PHP?
Although I get it that

```<code>$a = new b()
</code>```

would be initializing an object for the class b, but what would

```<code>$a = new $b()
</code>```

mean because I came across some code that happens to work otherwise!

答:
It's a reflexive reference to the class with a name that matches the value of $b.

Example:

```<code>$foo = "Bar";

class Bar
{
   ...code...
}

$baz = new $foo();

//$baz is a new Bar
</code>```

Update just to support: you can call functions this way too:

```<code>function test(){
    echo 123;
}
$a = "test";
$a(); //123 printed
</code>```

Title: what does $a = new $b() mean in PHP?

Body:
Although I get it that

$a = new b()

would be initializing an object for the class b, but what would

$a = new $b()

mean because I came across some code that happens to work otherwise!

Body:
It's a reflexive reference to the class with a name that matches the value of $b.

Example:

$foo = "Bar";

class Bar
{
   ...code...
}

$baz = new $foo();

//$baz is a new Bar

Update just to support: you can call functions this way too:

function test(){
    echo 123;
}
$a = "test";
$a(); //123 printed