问:
Selecting a div in jQuery & appending to the DOM
```<code>        var activeMsg=[];       // Active Users
        var noactiveMsg=[];     // Non-Active Users with a Pending Message
        var noactiveNomsg=[];       // Non-Active Users without a Pending Message

        $('div.chatmember').each(function() {
            currentMember=$(this);

            if($(this).children().children('div').hasClass('chatactivestatus_online')) {
                alert('online');
                activeMsg.push(currentMember);
            }
            if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
                alert('offline');
                noactiveMsg.push(currentMember);
            }
        });

        $.each(noactiveMsg, function(i, e){
             $('#chatCenterMembers').append(e.html());
         })
</code>```

The above code is quering DOM structure that looks like this:

```<code> <div id="chatCenterMembers">
   <div class="chatmember">
      <a class="ststusTitle">
         <div class="chatactivestatus_online"></div>
</code>```

it all works except for currentMember=$(this);
I believe this should hold

when I do the append at the end of the code above it doesn't add
 back into the dom. It adds its children elements only.

答:
Try:</p>

```<code>$('div.chatmember').each(function(domEle){
    currentMember=$(domEle);
</code>```

Body:
        var activeMsg=[];       // Active Users
        var noactiveMsg=[];     // Non-Active Users with a Pending Message
        var noactiveNomsg=[];       // Non-Active Users without a Pending Message

        $('div.chatmember').each(function() {
            currentMember=$(this);

            if($(this).children().children('div').hasClass('chatactivestatus_online')) {
                alert('online');
                activeMsg.push(currentMember);
            }
            if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
                alert('offline');
                noactiveMsg.push(currentMember);
            }
        });

        $.each(noactiveMsg, function(i, e){
             $('#chatCenterMembers').append(e.html());
         })

The above code is quering DOM structure that looks like this:

it all works except for currentMember=$(this);
I believe this should hold

when I do the append at the end of the code above it doesn't add
 back into the dom. It adds its children elements only.

Body:
Try:

$('div.chatmember').each(function(domEle){
    currentMember=$(domEle);


来源: stackexchange

问:
Xcode - can't find Debug View Hierarchy button
I can't find the Debug View Hierarchy button in Xcode.

I've read this:

Xcode 6.1 can't find 'debug view hierarchy' button

and launched my app on the iOS8 simulator but still no luck. Something to do with the Architectures perhaps?

Here's what I'm using:

答:
Thanks @Tibin Thomas and @Khaled Barazi. The Debug View Hierarchy button only appears if you have

checked the Debug executable box and

run your app on the simulator.

By the way, in Xcode 13.1, the button have already become as following icon

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
how to hide html button when disabled
GOOD MORNING, I'm editing on this code... someone can solve this: how to hide the button when it is disabled?

function Selected() {
  return document.querySelectorAll('input[type=radio]:checked').length;
}

function onChange() {
  console.log(Selected());
  document.getElementById('scoreButton').disabled = Selected() < 1;
}

document.querySelectorAll('input[type=radio]').forEach(node => {
  node.addEventListener('change', onChange, false);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="q">
<dl id="1">
    <dd><b>TEXT.</b><br>
      <label><input type="radio" name="q1" value="1a"> 1. </label><br>
      <label><input type="radio" name="q1" value="1b"> 2. </label><br>
      <label><input type="radio" name="q1" value="1c"> 3. </label>
    <hr></dd>
 </dl>

<div><input type="button" value="BUTTON" disabled="" id="scoreButton"></div>
</div></code>```

答:
function Selected() {
  return document.querySelectorAll('input[type=radio]:checked').length;

}

function onChange() {
  console.log(Selected());
  document.getElementById('scoreButton').disabled = Selected() < 1;

}

document.querySelectorAll('input[type=radio]').forEach(node => {
  node.addEventListener('change', onChange, false);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:disabled {
  display:none;
}</code>```

1. text.

      <input type="radio" name="q1" value="1a"> 1.

      <input type="radio" name="q1" value="1b"> 2.

      <input type="radio" name="q1" value="1c"> 3.

<input type="button" value="BUTTON" disabled="" id="scoreButton">

```

Title: how to hide html button when disabled

Body:
GOOD MORNING, I'm editing on this code... someone can solve this: how to hide the button when it is disabled?

function Selected() {
  return document.querySelectorAll('input[type=radio]:checked').length;
}

function onChange() {
  console.log(Selected());
  document.getElementById('scoreButton').disabled = Selected() < 1;
}

document.querySelectorAll('input[type=radio]').forEach(node => {
  node.addEventListener('change', onChange, false);
});

TEXT.

      <input type="radio" name="q1" value="1a"> 1.

      <input type="radio" name="q1" value="1b"> 2.

      <input type="radio" name="q1" value="1c"> 3.

<input type="button" value="BUTTON" disabled="" id="scoreButton">

Body:
function Selected() {
  return document.querySelectorAll('input[type=radio]:checked').length;

}

function onChange() {
  console.log(Selected());
  document.getElementById('scoreButton').disabled = Selected() < 1;

}

document.querySelectorAll('input[type=radio]').forEach(node => {
  node.addEventListener('change', onChange, false);

});

:disabled {
  display:none;
}

<div class="q">
<dl id="1">
    <dd><b>1. text.</b><br>
      <label><input type="radio" name="q1" value="1a"> 1. </label><br>
      <label><input type="radio" name="q1" value="1b"> 2. </label><br>
      <label><input type="radio" name="q1" value="1c"> 3. </label>
    <hr></dd>

<div><input type="button" value="BUTTON" disabled="" id="scoreButton"></div>
</div>


问:
How can I get a data from API promise?
So I created a separate file for API calls, and my API function looks like this:

```<code>const API_BASE = 'https://api.themoviedb.org/3/';
const TMDB_API_KEY = '{api_key}';

export async function fetchPopularMovies() {
      let url: string = `${API_BASE}movie/popular?api_key=${TMDB_API_KEY}`;
      const response = await axios.get(url);
      return response.data;
}
</code>```

As I guessed, the function returns a promise, so I want to get a data from it. I made a useEffect like this:

```<code>const [movies, setMovies] = useState<IMovie[]>();

  useEffect(() =>{
      const response = fetchPopularMovies();
     setMovies(response);
  }, [])
</code>```

It should set movies to a response I get from the function, but the function is a promise so I can't do it. And I'm wondering how can I get the data, I made return response.data inside of a function, but it returns a promise, so I'm trying to guess what I could do wrong.

答:
use then

```<code>const [movies, setMovies] = useState<IMovie[]>();

  useEffect(() =>{
      fetchPopularMovies().then((response) => {
         setMovies(response);
      });
  }, [])
</code>```

Title: How can I get a data from API promise?

Body:
So I created a separate file for API calls, and my API function looks like this:

const API_BASE = 'https://api.themoviedb.org/3/';
const TMDB_API_KEY = '{api_key}';

export async function fetchPopularMovies() {
      let url: string = `${API_BASE}movie/popular?api_key=${TMDB_API_KEY}`;
      const response = await axios.get(url);
      return response.data;
}

As I guessed, the function returns a promise, so I want to get a data from it. I made a useEffect like this:

const [movies, setMovies] = useState<IMovie[]>();

  useEffect(() =>{
      const response = fetchPopularMovies();
     setMovies(response);
  }, [])

It should set movies to a response I get from the function, but the function is a promise so I can't do it. And I'm wondering how can I get the data, I made return response.data inside of a function, but it returns a promise, so I'm trying to guess what I could do wrong.

Body:
use then

const [movies, setMovies] = useState<IMovie[]>();

  useEffect(() =>{
      fetchPopularMovies().then((response) => {
         setMovies(response);
      });
  }, [])


问:
Adding Click Event Listeners During Iteration?
I'm trying to add a click event listener to a bunch of newly created divs in a for loop. The issue I'm having is that only the last div keeps its event listener. I've read up about closures and read several other posts and questions and their answers, and as far as I can tell I have it set up correctly. But it still isn't working for me. Only the final div to be iterated is receiving the event listener.

function edit_entry(k) {
    wrd_input.value = k;
    def_input.value = lexicon[k][1];
    wrd_input.onkeyup();

    delete lexicon[k];
    rewrite_entries();
}

function rewrite_entries(keys = null) {
    if (keys === null) { keys = []; }
    let sorted_keys = sort_lex_keys();
    lex_body.style.color = 'rgb(200, 200, 200)';
    lex_body.innerHTML = '';

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
        lex_body.innerHTML +=
        `<div class='lex-entry' id=${key}><i>${key}</i>\n<p class='pronunciation'>${lexicon[key][0]}</p>${lexicon[key][1]}</div>\n`;
        let entry = document.getElementById(key)
        entry.addEventListener('click', edit_entry.bind(this, key) );
        }
    });
}
```
<p>Current state of the relevant code above. If somebody knows the issue, it'd be very helpful.
If it's relevant, this code is running via Electron (17.0.0).</p>
<p>An attempted solution, using an anonymous arrow function instead of a bind:</p>
<pre class="lang-js prettyprint-override"><code>entry.addEventListener('click', () => edit_entry(key) );
</code>```

yields the same result.

Update:
Changing the .innerHTML attribute of something apparently strips all event listeners. So the solution was simply to create the element completely in js, add it to the container, and then add the listener. This change to the forEach loop solves the problem:

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
            let entry = document.createElement('div');
            entry.className = 'lex-entry';

            let word = document.createElement('p');
            word.appendChild( document.createTextNode(key) );
            word.style.fontStyle = 'italic';

            let pron = document.createElement('p');
            pron.className = 'pronunciation';
            pron.appendChild( document.createTextNode(lexicon[key][0]) );

            let defn = document.createTextNode(lexicon[key][1]);

            entry.append(word, pron, defn);
            entry.addEventListener('click', () => edit_entry(key) );

            lex_body.appendChild(entry);
```

答:
I think that binding the function every time with this is overriding the binding every time, that should be the reason that you are only getting the last one's event.

Inside of the forEach lambda, the this keyword refers to the internal class that is calling the forEach not your rewrite_entries function. Try not binding the call, like so:

entry.addEventListener('click', () => edit_entry(key) );
```

Body:
I'm trying to add a click event listener to a bunch of newly created divs in a for loop. The issue I'm having is that only the last div keeps its event listener. I've read up about closures and read several other posts and questions and their answers, and as far as I can tell I have it set up correctly. But it still isn't working for me. Only the final div to be iterated is receiving the event listener.

function edit_entry(k) {
    wrd_input.value = k;
    def_input.value = lexicon[k][1];
    wrd_input.onkeyup();

    delete lexicon[k];
    rewrite_entries();
}

function rewrite_entries(keys = null) {
    if (keys === null) { keys = []; }
    let sorted_keys = sort_lex_keys();
    lex_body.style.color = 'rgb(200, 200, 200)';
    lex_body.innerHTML = '';

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
        lex_body.innerHTML +=
        `<div class='lex-entry' id=${key}><i>${key}</i>\n<p class='pronunciation'>${lexicon[key][0]}</p>${lexicon[key][1]}</div>\n`;
        let entry = document.getElementById(key)
        entry.addEventListener('click', edit_entry.bind(this, key) );
        }
    });
}

Current state of the relevant code above. If somebody knows the issue, it'd be very helpful.
If it's relevant, this code is running via Electron (17.0.0).

An attempted solution, using an anonymous arrow function instead of a bind:

entry.addEventListener('click', () => edit_entry(key) );

yields the same result.

Update:
Changing the .innerHTML attribute of something apparently strips all event listeners. So the solution was simply to create the element completely in js, add it to the container, and then add the listener. This change to the forEach loop solves the problem:

    sorted_keys.forEach((key) => {
        if (!keys.length || keys.includes(key)) {
            let entry = document.createElement('div');
            entry.className = 'lex-entry';

            let word = document.createElement('p');
            word.appendChild( document.createTextNode(key) );
            word.style.fontStyle = 'italic';

            let pron = document.createElement('p');
            pron.className = 'pronunciation';
            pron.appendChild( document.createTextNode(lexicon[key][0]) );

            let defn = document.createTextNode(lexicon[key][1]);

            entry.append(word, pron, defn);
            entry.addEventListener('click', () => edit_entry(key) );

            lex_body.appendChild(entry);


问:
Python requests WWW-Authenticate missing in headers
I'm trying to access the WWW-Authenticate header after a GET request using Python's requests library. When I do this in Postman it returns it but in Python it doesn't.

Python:

import requests
from requests.auth import HTTPBasicAuth

headers = {
    # "Python-Token": "<calculated when request is sent>",
    # "Host": "<calculated when request is sent>",
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    'x-requested-with': 'XMLHttpRequest',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    "Authorization": "Bearer"
}
site = "https://YourSPOSiteURL/_vti_bin/client.svc/"
auth = HTTPBasicAuth('something@email.com', 'somepasswordhere')
headers = dict( requests.get(f"{site}/_vti_bin/client.svc/", auth=auth).headers )
```
<p><code>headers</code>:</p>
```{'Cache-Control': 'private, max-age=0',
 'Content-Length': '0',
 'Content-Security-Policy': "frame-ancestors 'self' teams.microsoft.com "
                            '*.teams.microsoft.com *.skype.com '
                            '*.teams.microsoft.us local.teams.office.com '
                            '*.powerapps.com *.yammer.com '
                            '*.officeapps.live.com *.office.com '
                            '*.stream.azure-test.net *.microsoftstream.com '
                            '*.dynamics.com;',
 'Date': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'Expires': 'Thu, 20 Jan 2022 14:53:16 GMT',
 'Last-Modified': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'MS-CV': 'xxxxxxxxxxxxx.0',
 'MicrosoftSharePointTeamServices': 'xx.x.x.xxxxx',
 'P3P': 'CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR '
        'SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"',
 'SPRequestGuid': '697da8340-a0d3-30123-9fc9-98c88419387426',
 'Server': 'Microsoft-IIS/10.0',
 'Strict-Transport-Security': 'max-age=31536000',
 'Vary': 'Origin',
 'X-AspNet-Version': '4.0.xxxxx',
 'X-Content-Type-Options': 'nosniff',
 'X-FRAME-OPTIONS': 'SAMEORIGIN',
 'X-MS-InvokeApp': '1; RequireReadOnly',
 'X-Powered-By': 'ASP.NET',
 'X-SharePointHealthScore': '2',
 'request-id': '697da8340-a0d3-30123-9fc9-98c88419387426'}
```

Postman:

I've tried every headers param I can find but can't seem to return the WWW-Authenticate response header which I need...any help would be much appreciated.

Edit:

Within Postman, it looks to be the Host key in the headers get request that's generating the WWW-Authenticate in the response headers. When I remove it (in Postman) I get only a handful of headers in the response headers. But how would I replicate this in Python's requests library?

This is what it says when hovering over the Host header in GET:

答:
When I do this in Postman it returns it but in Python, it doesn't.

You are passing only the basic auth parameter to your request.
You should provide headers whose are set by Postman to get a response like it.

```<code>import requests

headers = {
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    "x-requested-with": "XMLHttpRequest",
    "sec-fetch-site": "same-origin",
    "sec-fetch-mode": "cors",
    "Authorization": "Bearer <token>"
}

response = requests.get(
   url="https://YourSPOSiteURL/_vti_bin/client.svc/",
   auth=("something@email.com", "somepasswordhere"),
   headers=headers
)

print(response.headers.get("WWW-Authenticate"))
</code>```

Body:
I'm trying to access the WWW-Authenticate header after a GET request using Python's requests library. When I do this in Postman it returns it but in Python it doesn't.

Python:

import requests
from requests.auth import HTTPBasicAuth

headers = {
    # "Python-Token": "<calculated when request is sent>",
    # "Host": "<calculated when request is sent>",
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    'x-requested-with': 'XMLHttpRequest',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    "Authorization": "Bearer"
}
site = "https://YourSPOSiteURL/_vti_bin/client.svc/"
auth = HTTPBasicAuth('something@email.com', 'somepasswordhere')
headers = dict( requests.get(f"{site}/_vti_bin/client.svc/", auth=auth).headers )

headers:

{'Cache-Control': 'private, max-age=0',
 'Content-Length': '0',
 'Content-Security-Policy': "frame-ancestors 'self' teams.microsoft.com "
                            '*.teams.microsoft.com *.skype.com '
                            '*.teams.microsoft.us local.teams.office.com '
                            '*.powerapps.com *.yammer.com '
                            '*.officeapps.live.com *.office.com '
                            '*.stream.azure-test.net *.microsoftstream.com '
                            '*.dynamics.com;',
 'Date': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'Expires': 'Thu, 20 Jan 2022 14:53:16 GMT',
 'Last-Modified': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'MS-CV': 'xxxxxxxxxxxxx.0',
 'MicrosoftSharePointTeamServices': 'xx.x.x.xxxxx',
 'P3P': 'CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR '
        'SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"',
 'SPRequestGuid': '697da8340-a0d3-30123-9fc9-98c88419387426',
 'Server': 'Microsoft-IIS/10.0',
 'Strict-Transport-Security': 'max-age=31536000',
 'Vary': 'Origin',
 'X-AspNet-Version': '4.0.xxxxx',
 'X-Content-Type-Options': 'nosniff',
 'X-FRAME-OPTIONS': 'SAMEORIGIN',
 'X-MS-InvokeApp': '1; RequireReadOnly',
 'X-Powered-By': 'ASP.NET',
 'X-SharePointHealthScore': '2',
 'request-id': '697da8340-a0d3-30123-9fc9-98c88419387426'}

Postman:

I've tried every headers param I can find but can't seem to return the WWW-Authenticate response header which I need...any help would be much appreciated.

Edit:

Within Postman, it looks to be the Host key in the headers get request that's generating the WWW-Authenticate in the response headers. When I remove it (in Postman) I get only a handful of headers in the response headers. But how would I replicate this in Python's requests library?

This is what it says when hovering over the Host header in GET:

Body:
When I do this in Postman it returns it but in Python, it doesn't.

You are passing only the basic auth parameter to your request.
You should provide headers whose are set by Postman to get a response like it.

import requests

headers = {
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    "x-requested-with": "XMLHttpRequest",
    "sec-fetch-site": "same-origin",
    "sec-fetch-mode": "cors",
    "Authorization": "Bearer <token>"
}

response = requests.get(
   url="https://YourSPOSiteURL/_vti_bin/client.svc/",
   auth=("something@email.com", "somepasswordhere"),
   headers=headers
)

print(response.headers.get("WWW-Authenticate"))


问:
Installing MongoDB in WSL
I was trying to install MongoDB in WSL running Ubuntu 18.04 after seeing this documentation. But MongoDB says that:

IMPORTANT
The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the official mongodb-org package. If you have already installed the mongodb package on your Ubuntu system, you must first uninstall the mongodb package before proceeding with these instructions.

MongoDB also says that WSL doesn't support mongodb-org

WINDOWS SUBSYSTEM FOR LINUX (WSL) - UNSUPPORTED
MongoDB does not support the Windows Subsystem for Linux (WSL).

So, I installed mongod using sudo apt install mongodb and when I ran mongo it shows the error:

```<code>connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-06-21T13:33:40.606+0530 E  QUERY    [js] Error: couldn't connect to server 127.0.0.1:27017
</code>```

Is there is a way to install the appropriate package and make it running?

答:
I tried all the methods above but none of the methods worked. I came across Microsoft's official documentation and everything works like a charm.

https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-database#install-mongodb

Title: Installing MongoDB in WSL

Body:
I was trying to install MongoDB in WSL running Ubuntu 18.04 after seeing this documentation. But MongoDB says that:

IMPORTANT
The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the official mongodb-org package. If you have already installed the mongodb package on your Ubuntu system, you must first uninstall the mongodb package before proceeding with these instructions.

MongoDB also says that WSL doesn't support mongodb-org

WINDOWS SUBSYSTEM FOR LINUX (WSL) - UNSUPPORTED
MongoDB does not support the Windows Subsystem for Linux (WSL).

So, I installed mongod using sudo apt install mongodb and when I ran mongo it shows the error:

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-06-21T13:33:40.606+0530 E  QUERY    [js] Error: couldn't connect to server 127.0.0.1:27017

Is there is a way to install the appropriate package and make it running?


问:
Got Error: Uncaught TypeError: handleChange is not a function
I want to use the handle function within the input tag. But it's showing an error when I call this function on the main page.

main code:

const Input = ({ placeholder, name, type, value, handleChange }) => (
    <input
        placeholder={placeholder}
        type={type}
        step="0.0001"
        value={value}
        onChange={(e) => handleChange(e, name)}
        className="my-2 w-full rounded-sm p-2 outline-none bg-transparent text-white
        border-none text-sm white-glassmorphism"
    />
);
```
<p>Where the handle Change is declared:</p>
<pre class="lang-js prettyprint-override"><code>const handleChange = (e, name) => {
    setformData((prevState) => ({ ...prevState, [name]: e.target.value }));
};
</code>```

答:
You can use in this way

```<code>const MyTextInput = ({ value, name, type, onChange }) => {
  return (
    <TextInput
      value={value}
      onChangeText={text => onChange({ name, type, text })}
    />
  );
};
</code>```

And then use it whenever you need to use TextInput

```<code>handleChange(event) {
    const {name, type, text} = event;
    .....
}

<MyTextInput name="username" type="text" value={this.state.username} onChange={this.handleChange}}>
<MyTextInput name="password" type="number" value={this.state.password} onChange={this.handleChange}}>
</code>```

Body:
I want to use the handle function within the input tag. But it's showing an error when I call this function on the main page.

main code:

const Input = ({ placeholder, name, type, value, handleChange }) => (
    <input
        placeholder={placeholder}
        type={type}
        step="0.0001"
        value={value}
        onChange={(e) => handleChange(e, name)}
        className="my-2 w-full rounded-sm p-2 outline-none bg-transparent text-white
        border-none text-sm white-glassmorphism"
    />
);

Where the handle Change is declared:

const handleChange = (e, name) => {
    setformData((prevState) => ({ ...prevState, [name]: e.target.value }));
};

Body:
You can use in this way

const MyTextInput = ({ value, name, type, onChange }) => {
  return (
    <TextInput
      value={value}
      onChangeText={text => onChange({ name, type, text })}
    />
  );
};

And then use it whenever you need to use TextInput

handleChange(event) {
    const {name, type, text} = event;
    .....
}

<MyTextInput name="username" type="text" value={this.state.username} onChange={this.handleChange}}>
<MyTextInput name="password" type="number" value={this.state.password} onChange={this.handleChange}}>


问:
How to toggle two icons in v-for list item in Vue
I have a list of items and icons which I want to toggle. How should I do that? Right now my click affects all of the items.</p>
```<code><ion-item
        v-for="course in courses"
        :key="course.id">
  <ion-label class="ion-text-wrap">{{ course.name }}</ion-label>
  <span @click="toggleIcons">
    <ion-icon v-if="isSelected" :icon="ellipseOutline" slot="end"></ion-icon>
    <ion-icon v-else :icon="checkmarkCircleOutline" slot="end"></ion-icon>
  </span>
</ion-item>

///

data() {
    return {
        isSelected: false,
        }
    },
methods: {
    toggleIcons(){
        this.isSelected = !this.isSelected
    }
}
</code>```

答:
Best thing to do is have a data property to keep the index(or the course.id in your case) of the "toggled" button

And then @click set the course.id of the clicked item to the data property, after that you can match the data property to the course.id and show your icon

Check the example below

Data Property

```<code>  data() {
    return {
      selectedCourseId: null,
    }
  },
</code>```

Method to set (or you can set it inline)

```<code>  methods: {
    setSelectedCourseId(id) {
      this.selectedCourseId = id
    },
  }
</code>```

Template

```<code><ion-item v-for="course in courses" :key="course.id">
  <ion-label class="ion-text-wrap">{{ course.name }}</ion-label>
  <span @click="toggleIcons">
    <ion-icon v-if="selectedCourseId === course.id" :icon="ellipseOutline" slot="end"></ion-icon>
    <ion-icon v-else :icon="checkmarkCircleOutline" slot="end"></ion-icon>
  </span>
</ion-item>
</code>```

Body:
I have a list of items and icons which I want to toggle. How should I do that? Right now my click affects all of the items.

<ion-item
        v-for="course in courses"
        :key="course.id">
  <ion-label class="ion-text-wrap">{{ course.name }}</ion-label>

    <ion-icon v-if="isSelected" :icon="ellipseOutline" slot="end"></ion-icon>
    <ion-icon v-else :icon="checkmarkCircleOutline" slot="end"></ion-icon>

</ion-item>

///

data() {
    return {
        isSelected: false,
        }
    },
methods: {
    toggleIcons(){
        this.isSelected = !this.isSelected
    }
}

Body:
Best thing to do is have a data property to keep the index(or the course.id in your case) of the "toggled" button

And then @click set the course.id of the clicked item to the data property, after that you can match the data property to the course.id and show your icon

Check the example below

Data Property

  data() {
    return {
      selectedCourseId: null,
    }
  },

Method to set (or you can set it inline)

  methods: {
    setSelectedCourseId(id) {
      this.selectedCourseId = id
    },
  }

Template

<ion-item v-for="course in courses" :key="course.id">
  <ion-label class="ion-text-wrap">{{ course.name }}</ion-label>
  <span @click="toggleIcons">
    <ion-icon v-if="selectedCourseId === course.id" :icon="ellipseOutline" slot="end"></ion-icon>
    <ion-icon v-else :icon="checkmarkCircleOutline" slot="end"></ion-icon>
  </span>
</ion-item>


问:
Accessing ADLS from Python
I have a simple python script which i wrote years ago which iterates through a local folder and converts the json files to csv.

I now need to convert this to run against a folder in an Azure Data Lake Storage Gen 2 Account. The code is going to be executed in Azure Synapse Analytics using PySpark.
As the ADLS account and the Synapse account are linked, is it just a case of changing the Folder to point to the ADLS account or is there some sort of authentication that i need to add in?

```<code>import glob
import os
file_names = []
Folder = 'C:\\Users\\username\\Documents\\jsonfiles\\'

for filepath in glob.iglob(Folder+'/*.json'):

from pandas import json_normalize
import json

with open(filepath) as data_file:
    d= json.load(data_file)

df = json_normalize(d, 'results')
print (df)

csvname = (os.path.splitext( (os.path.basename(filepath)))[0]+'.parquet')
print(csvname)

df.to_csv(Folder+csvname)
print(filepath)
</code>```

答:
Here is one of the workaround

WAY - 1

You can directly access your files by giving the url of the path. Here is the screenshot where I'm trying to read a json file from my adls storage.

```<code>import pandas as pd

df=pd.read_json("https://<YOUR_STORAGE_ACCOUNT>.blob.core.windows.net/<YOUR_CONTAINER_NAME>/<YOUR_FILE_NAME>")

print(df)
</code>```

WAY - 2

You can load data from Azure Data Lake Store Gen 2 using -

```<code>from pyspark.sql import SparkSession
from pyspark.sql.types import *
account_name = "Your account name"
container_name = "Your container name"
relative_path = "Your path"
adls_path = 'abfss://%s@%s.dfs.core.windows.net/%s' % (container_name, account_name, relative_path)

df1 = spark.read.option('header', 'true') \
                .option('delimiter', ',') \
                .csv(adls_path + '/Testfile.csv')
</code>```

For more information, you can refer How to use Synapse notebooks

Title: Accessing ADLS from Python

Body:
I have a simple python script which i wrote years ago which iterates through a local folder and converts the json files to csv.

I now need to convert this to run against a folder in an Azure Data Lake Storage Gen 2 Account. The code is going to be executed in Azure Synapse Analytics using PySpark.
As the ADLS account and the Synapse account are linked, is it just a case of changing the Folder to point to the ADLS account or is there some sort of authentication that i need to add in?

import glob
import os
file_names = []
Folder = 'C:\\Users\\username\\Documents\\jsonfiles\\'

for filepath in glob.iglob(Folder+'/*.json'):

from pandas import json_normalize
import json

with open(filepath) as data_file:
    d= json.load(data_file)

df = json_normalize(d, 'results')
print (df)

csvname = (os.path.splitext( (os.path.basename(filepath)))[0]+'.parquet')
print(csvname)

df.to_csv(Folder+csvname)
print(filepath)

Body:
Here is one of the workaround

WAY - 1

You can directly access your files by giving the url of the path. Here is the screenshot where I'm trying to read a json file from my adls storage.

import pandas as pd

df=pd.read_json("https://<YOUR_STORAGE_ACCOUNT>.blob.core.windows.net/<YOUR_CONTAINER_NAME>/<YOUR_FILE_NAME>")

print(df)

WAY - 2

You can load data from Azure Data Lake Store Gen 2 using -

from pyspark.sql import SparkSession
from pyspark.sql.types import *
account_name = "Your account name"
container_name = "Your container name"
relative_path = "Your path"
adls_path = 'abfss://%s@%s.dfs.core.windows.net/%s' % (container_name, account_name, relative_path)

df1 = spark.read.option('header', 'true') \
                .option('delimiter', ',') \
                .csv(adls_path + '/Testfile.csv')

For more information, you can refer How to use Synapse notebooks


问:
How to ignore TimeUnit.SECONDS.sleep in unit tests
I have a method which is calling sleep of 30 seconds but I dont want my unit test to have the same. I want my unit test to ignore the sleep and execute the rest on the method or reduce the sleep time to 1 sec.

```<code>public runwithSleep(){
 System.out.println("Before Sleep Time");
 TimeUnit.SECONDS.sleep(30);
 System.out.println("After Sleep Time");
}
</code>```

From the above sample code, How do I ignore the TimeUnit.SECONDS.sleep(30) when executing the unit test for this method. Basically I want to test like if i can reach this method from a condition so I dont want the sleep in the test.

答:
To complement the previous answer from @Michael Gantman, currently above:

Replace the dependencies to the sleep method with a dependency to a Sleeper object that you will inject. In the unit tests, you'll inject a Sleeper that does not wait. Bonus: the tests can interrogate the Sleeper to check if it was called, and with which parameter.

Body:
I have a method which is calling sleep of 30 seconds but I dont want my unit test to have the same. I want my unit test to ignore the sleep and execute the rest on the method or reduce the sleep time to 1 sec.

public runwithSleep(){
 System.out.println("Before Sleep Time");
 TimeUnit.SECONDS.sleep(30);
 System.out.println("After Sleep Time");
}

From the above sample code, How do I ignore the TimeUnit.SECONDS.sleep(30) when executing the unit test for this method. Basically I want to test like if i can reach this method from a condition so I dont want the sleep in the test.


问:
how to store a big image through J2ME
i hav written a code which is following...

```<code>package hello;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import java.io.*;

public class Immutable extends MIDlet implements CommandListener {

private Display display;

private Form form;

private Command exit;

private Image image;

private ImageItem imageItem;

public Immutable() throws IOException

{

display = Display.getDisplay(this);

exit = new Command("Exit", Command.EXIT, 1);

form = new Form("Immutable Image Example");

form.addCommand(exit);

form.setCommandListener(this);

try

{

image = Image.createImage("/hello/minion.png");

imageItem = new ImageItem("This is the IMAGE_ITEM Application",

image,ImageItem.LAYOUT_NEWLINE_BEFORE |ImageItem.LAYOUT_LEFT |

ImageItem.LAYOUT_NEWLINE_AFTER, "My Image");

form.append(imageItem);

}

catch (java.io.IOException error)

{

Alert alert = new Alert("Error", "Cannot load minion.png.",null, null);

alert.setTimeout(Alert.FOREVER);

alert.setType(AlertType.ERROR);

display.setCurrent(alert);

}

}

    public void startApp()
{

        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
    public void commandAction(Command command, Displayable Displayable)
{

if (command == exit)

{

destroyApp(false);

notifyDestroyed();

}
}
}
</code>```

now this image named minion.png is of 32kb and pixel size 803x825. in this case the image is not getting loaded perfectly. i have tried it on emulator and also on nokia 3110. it is giving error saying "out of memory".

same thing is running nicely with another image of size 6kb and pixels 96x96.

please suggest some idea to store an big image. thnx in advance...

答:
more efficient way to resize an image:
http://www.developer.nokia.com/Community/Wiki/Scale_/_Resize_images_in_Java_ME</p>

ContentLicense: CC BY-SA 2.5

Title: how to store a big image through J2ME

Body:
i hav written a code which is following...

package hello;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import java.io.*;

public class Immutable extends MIDlet implements CommandListener {

private Display display;

private Form form;

private Command exit;

private Image image;

private ImageItem imageItem;

public Immutable() throws IOException

{

display = Display.getDisplay(this);

exit = new Command("Exit", Command.EXIT, 1);

form = new Form("Immutable Image Example");

form.addCommand(exit);

form.setCommandListener(this);

try

{

image = Image.createImage("/hello/minion.png");

imageItem = new ImageItem("This is the IMAGE_ITEM Application",

image,ImageItem.LAYOUT_NEWLINE_BEFORE |ImageItem.LAYOUT_LEFT |

ImageItem.LAYOUT_NEWLINE_AFTER, "My Image");

form.append(imageItem);

}

catch (java.io.IOException error)

{

Alert alert = new Alert("Error", "Cannot load minion.png.",null, null);

alert.setTimeout(Alert.FOREVER);

alert.setType(AlertType.ERROR);

display.setCurrent(alert);

}

}

    public void startApp()
{

        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
    public void commandAction(Command command, Displayable Displayable)
{

if (command == exit)

{

destroyApp(false);

notifyDestroyed();

}
}
}

now this image named minion.png is of 32kb and pixel size 803x825. in this case the image is not getting loaded perfectly. i have tried it on emulator and also on nokia 3110. it is giving error saying "out of memory".

same thing is running nicely with another image of size 6kb and pixels 96x96.

please suggest some idea to store an big image. thnx in advance...


问:
Discord JS v13 FFmpeg not found on rootserver
I just installed my DiscordJS Bot on my new rootserver, I copied the files 1:1 to the server and started the Bot. The Bot starts normal but when I try to execute a command where the bot joins a vc and plays audio it says:

```<code>throw new Error('FFmpeg/avconv not found!');
      ^
</code>```

Error: FFmpeg/avconv not found!

Which is weird because I have ffmpeg and ffmpeg-static installed, and the same script works normally on my PC when I run it. Any ideas why?

Edit:
The only difference between the versions on the PC and the rootserver are the Node.js versions; PC: 16.6.0, rootserver: 17.4.0 (the rootserver is running on ubunu 11, and my PC on windows 10)

答:
You didn't install FFmpeg on your host yet

FFmpeg can be installed with npm:

```<code>npm install ffmpeg-static
</code>```

Update: You can also install it directly using apt:

sudo apt install ffmpeg
```

Body:
I just installed my DiscordJS Bot on my new rootserver, I copied the files 1:1 to the server and started the Bot. The Bot starts normal but when I try to execute a command where the bot joins a vc and plays audio it says:

throw new Error('FFmpeg/avconv not found!');
      ^

Error: FFmpeg/avconv not found!

Which is weird because I have ffmpeg and ffmpeg-static installed, and the same script works normally on my PC when I run it. Any ideas why?

Edit:
The only difference between the versions on the PC and the rootserver are the Node.js versions; PC: 16.6.0, rootserver: 17.4.0 (the rootserver is running on ubunu 11, and my PC on windows 10)

Body:
You didn't install FFmpeg on your host yet

FFmpeg can be installed with npm:

npm install ffmpeg-static

Update: You can also install it directly using apt:

sudo apt install ffmpeg


问:
Add PIN contact to BBM Programmatically
Is it possible to add a blackberry PIN to a device's 'black berry messenger' contact list programmatically?

Can anyone verify this for me?

I have looked through the API, but I do not see a clear way.

Thank you.

答:
Before you begin: Make sure that you have completed the task, Register your application with the BlackBerry Messenger platform, and that the class that displays the MyBBMChatScreen screen passes in a reference to the application's associated BBMPlatformContext object into the screen's contructor. (as always :D)

I use this codes to add just one contact. You can modify it to add multiple contact. Just change the size of contacts array.

```<code>String PIN = "123456";
String name = "Someone";
BBMInvitationRequest[] contacts = new BBMInvitationRequest[1];

contacts[0] = new BBMInvitationRequest(PIN, name);
platformContext.getUIService().inviteToBBM(contacts);
</code>```

May this help :)

Title: Add PIN contact to BBM Programmatically

Body:
Before you begin: Make sure that you have completed the task, Register your application with the BlackBerry Messenger platform, and that the class that displays the MyBBMChatScreen screen passes in a reference to the application's associated BBMPlatformContext object into the screen's contructor. (as always :D)

I use this codes to add just one contact. You can modify it to add multiple contact. Just change the size of contacts array.

String PIN = "123456";
String name = "Someone";
BBMInvitationRequest[] contacts = new BBMInvitationRequest[1];

contacts[0] = new BBMInvitationRequest(PIN, name);
platformContext.getUIService().inviteToBBM(contacts);

May this help :)


问:
how to deploy Angular + Springboot project using nginx on azure remote desktop. i am getting this cors errors while accesing the remote site
i am new to deployment. i used Azure remote server for my project deployment. as you aware that angular uses localhost:4200 and springboot uses localhost:8080. when i run the project on remote server itself then it is working fine. but when i running / accesing it remotely through remote server ip then i can only able to access the front end part. and when i check the console they are showing cors errors.

for the cors errors i had already addded code in backend. so there is no issue as such. but when i try to access it remotely then it gives this error.

1 st Error)
main.7dc5cf0db6092584.js:1 ERROR
Mk {headers: Ws, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8080/projects', ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: Ws {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:8080/projects: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:8080/projects"
[[Prototype]]: mb

2 nd Error)
"/#/main/uikit/crudrules:1 Access to XMLHttpRequest at 'http://localhost:8080/escrule' from origin 'http://70.91.52.87' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local."

3rd Error)
polyfills.8078d748ada0b716.js:1 GET http://localhost:8080/projects net::ERR_FAILED

for your information i am giving my nginx config file code.

```<code>#user  nobody;
worker_processes  1;
#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;

    #access_log  logs/access.log  main;

    sendfile        on;
    keepalive_timeout  65;
     upstream springboot
    {
        server localhost:8080  max_conns=10;
    }

    server {
        listen       80;
        server_name  localhost;
    #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   "C:/project related/NewAuditUi/dist/california-ng";
            try_files $uri $uri/ index.html;
        add_header 'Access-Control-Allow-Origin' '*' always;
        }
    location /api {
                 proxy_pass    http://springboot;
          proxy_set_header    Host               $host;
          proxy_set_header    X-Real-IP          $remote_addr;
          proxy_set_header    X-Forwarded-For
$proxy_add_x_forwarded_for;
          proxy_set_header    X-Forwarded-Host   $host;
          proxy_set_header    X-Forwarded-Server $host;
          proxy_set_header    X-Forwarded-Port   $server_port;
          proxy_set_header    X-Forwarded-Proto  $scheme;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
</code>```

i welcome ur all suggestions. if need more information then dont hesitate to ask. Thanks in advance.

答:
In your angular application, try setting the options. To call the  HTTP request, use these options.</p>
```<code>const options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    Authorization: 'Basic ',// your authorization method
    'Access-Control-Allow-Headers':
      'Origin, X-Requested-With, Content-Type, Accept'
  })
};

getPerson(name: string): Observable<any> {
    return this.http
      .get<any>(baseUrl + '/persons/' + name, options)
      .pipe(catchError(this.handleError));
}
</code>```

Body:
i am new to deployment. i used Azure remote server for my project deployment. as you aware that angular uses localhost:4200 and springboot uses localhost:8080. when i run the project on remote server itself then it is working fine. but when i running / accesing it remotely through remote server ip then i can only able to access the front end part. and when i check the console they are showing cors errors.

for the cors errors i had already addded code in backend. so there is no issue as such. but when i try to access it remotely then it gives this error.

1 st Error)
main.7dc5cf0db6092584.js:1 ERROR
Mk {headers: Ws, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8080/projects', ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: Ws {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:8080/projects: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://localhost:8080/projects"
[[Prototype]]: mb

2 nd Error)
"/#/main/uikit/crudrules:1 Access to XMLHttpRequest at 'http://localhost:8080/escrule' from origin 'http://70.91.52.87' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local."

3rd Error)
polyfills.8078d748ada0b716.js:1 GET http://localhost:8080/projects net::ERR_FAILED

for your information i am giving my nginx config file code.

#user  nobody;
worker_processes  1;
#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;

    #access_log  logs/access.log  main;

    sendfile        on;
    keepalive_timeout  65;
     upstream springboot
    {
        server localhost:8080  max_conns=10;
    }

    server {
        listen       80;
        server_name  localhost;
    #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   "C:/project related/NewAuditUi/dist/california-ng";
            try_files $uri $uri/ index.html;
        add_header 'Access-Control-Allow-Origin' '*' always;
        }
    location /api {
                 proxy_pass    http://springboot;
          proxy_set_header    Host               $host;
          proxy_set_header    X-Real-IP          $remote_addr;
          proxy_set_header    X-Forwarded-For
$proxy_add_x_forwarded_for;
          proxy_set_header    X-Forwarded-Host   $host;
          proxy_set_header    X-Forwarded-Server $host;
          proxy_set_header    X-Forwarded-Port   $server_port;
          proxy_set_header    X-Forwarded-Proto  $scheme;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

i welcome ur all suggestions. if need more information then dont hesitate to ask. Thanks in advance.

Body:
In your angular application, try setting the options. To call the  HTTP request, use these options.

const options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    Authorization: 'Basic ',// your authorization method
    'Access-Control-Allow-Headers':
      'Origin, X-Requested-With, Content-Type, Accept'
  })
};

getPerson(name: string): Observable<any> {
    return this.http
      .get<any>(baseUrl + '/persons/' + name, options)
      .pipe(catchError(this.handleError));
}


问:
Is it possible to inherit from something other than the abstract type julia?
I have a function that I can't change and it expects type ExpectedType.

```<code>function some_function(some_parameter::ExpectedType)
   ....
   some implementation
   ....
end
</code>```

I want to pass my object of type OtherType.

I decided to inherit OtherType from ExpectedType.

```<code>struct OtherType <: ExpectedType end
</code>```

But I'm getting an error: ERROR: invalid subtyping in definition of OtherType

Is it possible to inherit from non-abst types?

How can I get the functionality I need?

答:
It is not possible to inherit from non-abstract type.

What I would typically do is writing a constructor for ExpectedType that takes OtherType as argument and then call some_function(ExpectedType(your_object)).

Also then you could define:

```<code>SourceModuleName.some_function(x::OtherType) = some_function(ExpectedType(x))
</code>```

so that you do not have to call the constructor explicitly.

Body:
I have a function that I can't change and it expects type ExpectedType.

function some_function(some_parameter::ExpectedType)
   ....
   some implementation
   ....
end

I want to pass my object of type OtherType.

I decided to inherit OtherType from ExpectedType.

struct OtherType <: ExpectedType end

But I'm getting an error: ERROR: invalid subtyping in definition of OtherType

Is it possible to inherit from non-abst types?

How can I get the functionality I need?

Body:
It is not possible to inherit from non-abstract type.

What I would typically do is writing a constructor for ExpectedType that takes OtherType as argument and then call some_function(ExpectedType(your_object)).

Also then you could define:

SourceModuleName.some_function(x::OtherType) = some_function(ExpectedType(x))

so that you do not have to call the constructor explicitly.


问:
Docker Engine Hyper-V Proxy - Windows 10 Not working
When working behind a corporate proxy (automatically activated in Windows) by Cisco AnyConnect(v4.7.03052) VPN, I'm unable to pull any docker image either from our docker nexus registry or the official registry.

Funny enough, if I set the proxy settings in the config.json and pass the proxy as build-arg my containers are able to build(from previously pulled images) and talk to the exterior.

Only the docker engine is unable to access the internet through the proxy.

I've already tried the following:

Set the HTTP_PROXY/HTTPS_PROXY as environments variables

Set the proxy settings in the Docker Desktop proxy section - Docker doc

Set the resources network IP to the non-secured Cisco AnyConnect routes IPv4

No firewall rules seems to block the outbound request from the docker engine service.

Edit the deamon.json used by the docker service to register the mirror registries.

Stackoverflow answers not working in this case: docker-win10;  docker on windows;  docker image proxy

Platform info:

Win 10 - Build 19401

Docker Desktop 4.4.4(73704)

Docker Engine 20.12.12  (Linux container on Hyper-V)

Cisco AnyConnect v4.7.03052

Error message on docker pull:

```<code>λ  docker pull traefik:2.0
Error response from daemon: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
</code>```

Based on the similar stackoverflow issue briefly executing the command below had it working for a short time:

```<code>cd "C:\Program Files\Docker\Docker"
./DockerCli.exe -SwitchDaemon
</code>```

答:
This was a regression that slipped in the 4.4.4 see github issue.

It seems to have been resolved in the v4.5.0

Body:
When working behind a corporate proxy (automatically activated in Windows) by Cisco AnyConnect(v4.7.03052) VPN, I'm unable to pull any docker image either from our docker nexus registry or the official registry.

Funny enough, if I set the proxy settings in the config.json and pass the proxy as build-arg my containers are able to build(from previously pulled images) and talk to the exterior.

Only the docker engine is unable to access the internet through the proxy.

I've already tried the following:

Set the HTTP_PROXY/HTTPS_PROXY as environments variables

Set the proxy settings in the Docker Desktop proxy section - Docker doc

Set the resources network IP to the non-secured Cisco AnyConnect routes IPv4

No firewall rules seems to block the outbound request from the docker engine service.

Edit the deamon.json used by the docker service to register the mirror registries.

Stackoverflow answers not working in this case: docker-win10;  docker on windows;  docker image proxy

Platform info:

Win 10 - Build 19401

Docker Desktop 4.4.4(73704)

Docker Engine 20.12.12  (Linux container on Hyper-V)

Cisco AnyConnect v4.7.03052

Error message on docker pull:

λ  docker pull traefik:2.0
Error response from daemon: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

Based on the similar stackoverflow issue briefly executing the command below had it working for a short time:

cd "C:\Program Files\Docker\Docker"
./DockerCli.exe -SwitchDaemon


问:
Get a JSONObject of a JSONArray with Value by jQuery
Hi assume that I have a JSON like this:

```<code>var myJson = [{"id":"111","name":"aaa","surname":"bbb"},
     {"id":"222","name":"ccc","surname":"ddd"}]
</code>```

is there any function to get one of jsonobject with a value of jsonobject?
I mean maybe I know that id is 111 how can get the jsonobject with id=111, I don't want to get it with loop I mean is there just function to do it with jQuery?

答:
Change your Json array as below

```<code>var myJson = { "idarray":["111","222"],
"dataarray":{ "111":{"name":"aaa","surname":"bbb"},"222":{"name":"ccc","surname":"ddd"}}
};
</code>```

Now you can access it as below:

myJson.dataarray[myJson.idarray[0]].name   //  ==> "aaa"

or directly by

myJson.dataarray[111].name   //  ==> "aaa"

Body:
Hi assume that I have a JSON like this:

var myJson = [{"id":"111","name":"aaa","surname":"bbb"},
     {"id":"222","name":"ccc","surname":"ddd"}]

is there any function to get one of jsonobject with a value of jsonobject?
I mean maybe I know that id is 111 how can get the jsonobject with id=111, I don't want to get it with loop I mean is there just function to do it with jQuery?

Body:
Change your Json array as below

var myJson = { "idarray":["111","222"],
"dataarray":{ "111":{"name":"aaa","surname":"bbb"},"222":{"name":"ccc","surname":"ddd"}}
};

Now you can access it as below:

myJson.dataarray[myJson.idarray[0]].name   //  ==> "aaa"

or directly by

myJson.dataarray[111].name   //  ==> "aaa"


问:
Send form information to another component
I designed a flash card and I want to change the text of the card when I click on the button, but I do not know how to send the form information to the App component to update the state.
App component

```<code>function App() {
      const [flashCard, setFlashCard] = useState({
        word: "test",
        persianEquivalent: "test",
      });
      const setFlashCardHandler = (e) => {
        setFlashCard({ flashCard: e });
      };
      return (
        <div className="container">
          <Form setFlashCard={setFlashCardHandler} />
          <FlashCard flashCard={flashCard} />
        </div>
      );
    }

export default App;
</code>```

Form component:

```<code>  function Form({ setFlashCard }) {
      const [valueEn, setValueEn] = useState();
      const [valuePer, setValuePer] = useState();
      const setValueHandlerEn = (e) => {
        setValueEn(e.target.value);
      };
      const setValueHandlerPer = (e) => {
        setValuePer(e.target.value);
      };
      const setFlashCardHandler = (e) => {
        e.preventDefault();
        setFlashCard((e)=>{valueEn=e.target[0].value});
      };
      return (
        <form onSubmit={setFlashCardHandler}>
          <input
            id="word-input"
            placeholder="world"
            value={valueEn}
            onChange={setValueHandlerEn}
          />
          <input
            id="persian-equivalent-input"
            placeholder="Equivalent"
            value={valuePer}
            onChange={setValueHandlerPer}
          />
          <button id="submit-btn">send</button>
        </form>
      );
    }

    export default Form;
</code>```

答:
There is an issue with how you set values.

Pass setFlashCard as the prop to Form

```<code><Form setFlashCard={setFlashCard} />
</code>```

In Form change the setFlashCardHandler as below.

```<code>  const setFlashCardHandler = (e) => {
    e.preventDefault();
    setFlashCard({ word: valueEn, persianEquivalent: valuePer });
  };
</code>```

Set empty string ("") as default state to avoid sending undefined.

```<code>  const [valueEn, setValueEn] = useState("");
  const [valuePer, setValuePer] = useState("");
</code>```

Body:
I designed a flash card and I want to change the text of the card when I click on the button, but I do not know how to send the form information to the App component to update the state.
App component

function App() {
      const [flashCard, setFlashCard] = useState({
        word: "test",
        persianEquivalent: "test",
      });
      const setFlashCardHandler = (e) => {
        setFlashCard({ flashCard: e });
      };
      return (

          <Form setFlashCard={setFlashCardHandler} />
          <FlashCard flashCard={flashCard} />

      );
    }

export default App;

Form component:

  function Form({ setFlashCard }) {
      const [valueEn, setValueEn] = useState();
      const [valuePer, setValuePer] = useState();
      const setValueHandlerEn = (e) => {
        setValueEn(e.target.value);
      };
      const setValueHandlerPer = (e) => {
        setValuePer(e.target.value);
      };
      const setFlashCardHandler = (e) => {
        e.preventDefault();
        setFlashCard((e)=>{valueEn=e.target[0].value});
      };
      return (
        <form onSubmit={setFlashCardHandler}>
          <input
            id="word-input"
            placeholder="world"
            value={valueEn}
            onChange={setValueHandlerEn}
          />
          <input
            id="persian-equivalent-input"
            placeholder="Equivalent"
            value={valuePer}
            onChange={setValueHandlerPer}
          />
          <button id="submit-btn">send</button>
        </form>
      );
    }

    export default Form;

Body:
There is an issue with how you set values.

Pass setFlashCard as the prop to Form

<Form setFlashCard={setFlashCard} />

In Form change the setFlashCardHandler as below.

  const setFlashCardHandler = (e) => {
    e.preventDefault();
    setFlashCard({ word: valueEn, persianEquivalent: valuePer });
  };

Set empty string ("") as default state to avoid sending undefined.

  const [valueEn, setValueEn] = useState("");
  const [valuePer, setValuePer] = useState("");


问:
Linq ToList() and Count() performance problem
I have 200k rows in my table and I need to filter the table and then show in datatable. When I try to do that, my sql run fast. But when I want to get row count or run the ToList(), it takes long time. Also when I try to convert it to list it has 15 rows after filter, it has not huge data.</p>
```<code>public static List<Books> GetBooks()
{
    List<Books> bookList = new List<Books>();

    var v = from a in ctx.Books select a);
    int allBooksCount = v.Count(); // I need all books count before filter. but it is so slow is my first problem
    if (isFilter)
        {
           v = v.Where(a => a.startdate <= DateTime.Now && a.enddate>= DateTime.Now);
        }
  .
  .
    bookList = v.ToList(); // also toList is so slow is my second problem
}
</code>```

答:
There's nothing wrong with the code you've shown. So either you have some trouble in the database itself, or you're ruining the query by using IEnumerable instead of IQueryable.

My guess is that either ctx.Books is IEnumerable<Books> (instead of IQueryable<Books>), or that the Count (and Where etc.) method you're calling is the Enumerable version, rather than the Queryable version.
Which version of Count are you actually calling?

Body:
I have 200k rows in my table and I need to filter the table and then show in datatable. When I try to do that, my sql run fast. But when I want to get row count or run the ToList(), it takes long time. Also when I try to convert it to list it has 15 rows after filter, it has not huge data.

public static List<Books> GetBooks()
{
    List<Books> bookList = new List<Books>();

    var v = from a in ctx.Books select a);
    int allBooksCount = v.Count(); // I need all books count before filter. but it is so slow is my first problem
    if (isFilter)
        {
           v = v.Where(a => a.startdate <= DateTime.Now && a.enddate>= DateTime.Now);
        }
  .
  .
    bookList = v.ToList(); // also toList is so slow is my second problem
}


问:
Selected lines with pattern: Vim Visual Mode
I would like to select (in Vim) the lines that start with the same pattern. For example, if I have this:

```<code>if (...) {
    print "Accepted\n"
    o.attr_out = "Accepted";
}
else if (...) {
    print "Partially accepted\n"
    o.attr_out = "Partially Accepted";
}
else if (...) {
    print " NOT Accepted\n"
    o.attr_out = "Not Accepted";
}
</code>```

Skip to this in a quick way in Vim.

```<code>if (...) {
    if (debug == true) print "Accepted\n"
    o.attr_out = "Accepted";
}
else if (...) {
    if (debug == true) print "Partially accepted\n"
    o.attr_out = "Partially Accepted";
}
else if (...) {
    if (debug == true) print " NOT Accepted\n"
    o.attr_out = "Not Accepted";
}
</code>```

答:
You can use the vim command:

:%s/print "/if ( debug == true ) &/g

here's a quick breakdown of the command:

% - include all lines in the search

s - substiture the 1st pattern with the 2nd.

/print "/ - the pattern you're searching for.

if ( debug == true ) &/ - the text you want to replace the pattern with (note & will put back the print " text that it found in the search).

g - replace all occurrences on the same line. (Technically you don't need that here - since there's only one occurrence of print " on each line).

Refer to the :help :s command for more information.

Body:
I would like to select (in Vim) the lines that start with the same pattern. For example, if I have this:

if (...) {
    print "Accepted\n"
    o.attr_out = "Accepted";
}
else if (...) {
    print "Partially accepted\n"
    o.attr_out = "Partially Accepted";
}
else if (...) {
    print " NOT Accepted\n"
    o.attr_out = "Not Accepted";
}

Skip to this in a quick way in Vim.

if (...) {
    if (debug == true) print "Accepted\n"
    o.attr_out = "Accepted";
}
else if (...) {
    if (debug == true) print "Partially accepted\n"
    o.attr_out = "Partially Accepted";
}
else if (...) {
    if (debug == true) print " NOT Accepted\n"
    o.attr_out = "Not Accepted";
}


问:
Map-only job is not running. Stuck at Running job
I have streamed data through Apache Flume and the data has been stored in a temp file in my hdfs folder at: user/*****/tweets/FlumeData.1643626732852.tmp

Now I am trying to run a mapper only job which will be pre-processing the job by way of url removal, # tag removal, @ removal, stop word removal etc.

However, the mapper only job is stopped at Running job.

Mapper job code:

```<code> hadoop jar mr-job-jars/SentimentAnalysisPreprocessingJob.jar com.hadoop.poc.sentimentAnalysis.phase1.SentimentAnalysisPreprocessingDriver /user/*****/tweets/ FlumeData.1643626732852.tmp /output
</code>```

Execution output:

```<code>2022-01-31 06:16:18,151 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
2022-01-31 06:16:18,611 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
2022-01-31 06:16:18,666 INFO mapreduce.JobResourceUploader: Disabling Erasure Coding for path: /tmp/hadoop-yarn/staging/aviparna/.staging/job_1643615018627_0004
2022-01-31 06:16:18,996 INFO input.FileInputFormat: Total input files to process : 1
2022-01-31 06:16:19,108 WARN hdfs.DataStreamer: Caught exception
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1252)
    at java.lang.Thread.join(Thread.java:1326)
    at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:986)
    at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:640)
    at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:810)
2022-01-31 06:16:19,168 INFO mapreduce.JobSubmitter: number of splits:1
2022-01-31 06:16:19,449 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1643615018627_0004
2022-01-31 06:16:19,451 INFO mapreduce.JobSubmitter: Executing with tokens: []
2022-01-31 06:16:19,794 INFO conf.Configuration: resource-types.xml not found
2022-01-31 06:16:19,794 INFO resource.ResourceUtils: Unable to find 'resource-types.xml'.
2022-01-31 06:16:19,935 INFO impl.YarnClientImpl: Submitted application application_1643615018627_0004
2022-01-31 06:16:20,035 INFO mapreduce.Job: The url to track the job: http://ubuntu:8088/proxy/application_1643615018627_0004/
2022-01-31 06:16:20,038 INFO mapreduce.Job: Running job: job_1643615018627_0004
</code>```

What do I need to do to solve this problem? Please help.
Also, for any added information required please inform me. I will try to provide them as soon as possible.

Adding screenshot of the YARN UI:

答:
Solved my problem by changing the mapreduce.framework.name from yarn to local in mapred-site.xml.

The problem seemed to be happening due to resource crunch in the machine.

Also after changing the properties, restart Hadoop services once again.

Body:
I have streamed data through Apache Flume and the data has been stored in a temp file in my hdfs folder at: user/*****/tweets/FlumeData.1643626732852.tmp

Now I am trying to run a mapper only job which will be pre-processing the job by way of url removal, # tag removal, @ removal, stop word removal etc.

However, the mapper only job is stopped at Running job.

Mapper job code:

 hadoop jar mr-job-jars/SentimentAnalysisPreprocessingJob.jar com.hadoop.poc.sentimentAnalysis.phase1.SentimentAnalysisPreprocessingDriver /user/*****/tweets/ FlumeData.1643626732852.tmp /output

Execution output:

2022-01-31 06:16:18,151 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
2022-01-31 06:16:18,611 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
2022-01-31 06:16:18,666 INFO mapreduce.JobResourceUploader: Disabling Erasure Coding for path: /tmp/hadoop-yarn/staging/aviparna/.staging/job_1643615018627_0004
2022-01-31 06:16:18,996 INFO input.FileInputFormat: Total input files to process : 1
2022-01-31 06:16:19,108 WARN hdfs.DataStreamer: Caught exception
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1252)
    at java.lang.Thread.join(Thread.java:1326)
    at org.apache.hadoop.hdfs.DataStreamer.closeResponder(DataStreamer.java:986)
    at org.apache.hadoop.hdfs.DataStreamer.endBlock(DataStreamer.java:640)
    at org.apache.hadoop.hdfs.DataStreamer.run(DataStreamer.java:810)
2022-01-31 06:16:19,168 INFO mapreduce.JobSubmitter: number of splits:1
2022-01-31 06:16:19,449 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1643615018627_0004
2022-01-31 06:16:19,451 INFO mapreduce.JobSubmitter: Executing with tokens: []
2022-01-31 06:16:19,794 INFO conf.Configuration: resource-types.xml not found
2022-01-31 06:16:19,794 INFO resource.ResourceUtils: Unable to find 'resource-types.xml'.
2022-01-31 06:16:19,935 INFO impl.YarnClientImpl: Submitted application application_1643615018627_0004
2022-01-31 06:16:20,035 INFO mapreduce.Job: The url to track the job: http://ubuntu:8088/proxy/application_1643615018627_0004/
2022-01-31 06:16:20,038 INFO mapreduce.Job: Running job: job_1643615018627_0004

What do I need to do to solve this problem? Please help.
Also, for any added information required please inform me. I will try to provide them as soon as possible.

Adding screenshot of the YARN UI:


问:
Is there any event to recognize Scrollbar click
Is there any event that will be raised on scrollbar click.

my requirement is once i click or start dragging the horizontal scrollbar sometask i need to perform.Can anybobody plz let me know which javascript event suits my requirement.

答:
The closest you'll get is

```<code>document.onscroll = function(){alert("you scrolled");}
</code>```

or in jQuery

```<code>$(document).scroll(function(){alert("you scrolled");});
</code>```

Different browsers handle it in different ways, generally they fire everytime the page moves a pixel or more. In Android browsers it only updates when you stop scrolling.

Body:
The closest you'll get is

document.onscroll = function(){alert("you scrolled");}

or in jQuery

$(document).scroll(function(){alert("you scrolled");});

Different browsers handle it in different ways, generally they fire everytime the page moves a pixel or more. In Android browsers it only updates when you stop scrolling.


问:
Send email from .NET Core using Microsoft 365 Family subscription
I have an Office 365 Family subscription (thus using outlook.com) and are trying to send email from a C# application I'm working on. Does anybody know if this is even possible?
From my research there seems to be a lot of people having issue with this approach but I'm trying hard to find out if it's supported</p>

答:
There are different ways of doing the required job:

Use standard .net mechanisms, the same question was posted here:

```<code>            using (SmtpClient client = new SmtpClient()
            {
                Host = "smtp.office365.com",
                Port = 587,
                UseDefaultCredentials = false, // This require to be before setting Credentials property
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("alias@fulldomain.com", "password"), // you must give a full email address for authentication
                TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
                EnableSsl = true // Set to avoid secure connection exception
            })
            {

                MailMessage message = new MailMessage()
                {
                    From = new MailAddress("alias@fulldomain.com"), // sender must be a full email address
                    Subject = subject,
                    IsBodyHtml = true,
                    Body = "<h1>Hello World</h1>",
                    BodyEncoding = System.Text.Encoding.UTF8,
                    SubjectEncoding = System.Text.Encoding.UTF8,

                };
                var toAddresses = recipients.Split(',');
                foreach (var to in toAddresses)
                {
                    message.To.Add(to.Trim());
                }

                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
</code>```

The SmtpClient is usable in .NET Core, but its use isn't recommended. Instead, consider using https://github.com/jstedfast/MailKit .

Use Graph API.

Body:
There are different ways of doing the required job:

Use standard .net mechanisms, the same question was posted here:

            using (SmtpClient client = new SmtpClient()
            {
                Host = "smtp.office365.com",
                Port = 587,
                UseDefaultCredentials = false, // This require to be before setting Credentials property
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("alias@fulldomain.com", "password"), // you must give a full email address for authentication
                TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
                EnableSsl = true // Set to avoid secure connection exception
            })
            {

                MailMessage message = new MailMessage()
                {
                    From = new MailAddress("alias@fulldomain.com"), // sender must be a full email address
                    Subject = subject,
                    IsBodyHtml = true,
                    Body = "<h1>Hello World</h1>",
                    BodyEncoding = System.Text.Encoding.UTF8,
                    SubjectEncoding = System.Text.Encoding.UTF8,

                };
                var toAddresses = recipients.Split(',');
                foreach (var to in toAddresses)
                {
                    message.To.Add(to.Trim());
                }

                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

The SmtpClient is usable in .NET Core, but its use isn't recommended. Instead, consider using https://github.com/jstedfast/MailKit .

Use Graph API.


问:
Is there a way to detect if a given header of the C++ Standard Library is included?
More specifically, is it possible to detect, at compilation time, if a C++ standard header file is included (let say <complex>), and do that in a way that is cross-plateform and cross-compiler ? I'd like it to work with C++11 at least, but for the question's sake, is it possible for any C++ standard ?

I know the implementation of the C++ Standard Library is dependent on the compiler and operating system, but is there a standardized guard name for the header, a macro that I can check the existence of ?

I've run into this : Detect usage of STL in C++ , which is a hack not to use the headers, and this : Is there a way to detect portably that a standard header is included using macros?, which answers with a C++17 feature, and is in fact more about detecting a function.

What I want is to be able to write some preprocessor instruction at a given point in the code that will tell whether the header is included (yet). I checked the source code of (an implementation of) <complex> as an example, and _GLIBCXX_COMPLEX is defined, but probably only for this implementation.

答:
TL;DR : No, there is not, apart from the C++17 feature #if __has_include(<complex>). Not with defined macro anyway.

Long answer : there are two parts to the answer. What I read from some headers, and the tests I ran on differents OS with differents compilers.

Warning : I will write also about C, as some compilers uses the same macros. I also use the shortcut 'for C' and 'for C++' instead of 'when the header complex.h is included' and 'when the header <complex> is included'.

Ok, here's my best answer as for now.

About C and complex.h :

In C, the existence of the macro
_Complex_I is the only macro that I think should be defined in any complex.h header, as it is specified by the ISO C99 (cf. ISO/IEC 9899:1999/TC3 text). The tests I ran shows that this is a realistic hypothesis. There are some additionnal macro used, such as _COMPLEX_H that seems to be defined when compiling with GCC,
and _C_COMPLEX_T when compiling with MSVC. There might be others, I didn't find them, please don't hesitate to add them.

But it is C, not C++, and one should not mix both.

About C++ and <complex> :

The C++ standard (ISO/CEI 14882:2011) does not specify such macro. In fact, it does not specify the inclusion of any macro (at first glance).
It does specify the existence of the complex class however, but this does not answer the question.
For what I read, _COMPLEX_ and  _C_COMPLEX_T seems to be defined in the <complex> header for
LLVM-clang and MSVC, but also in the complex.h for the apple implementation of the C math library (libm).

However, my tests with the LLVM-clang compiler on macOS failed showing those macro, and I can't find the file where I read that information.
I also found that g++ is defining _GLIBCXX_COMPLEX.

If one wanted to do that with a C++ older than C++17, a solution would be to test with the given compilers and architectures the code will run onto.
That is quite bad, but it's the closest answer I get.

The tests :

I give here the code that I run on the different OS, the compiler options, their version, and the results they prompt. _Complex_I was indeed defined for all C headers.

I wasn't able to run the test on macOS with GCC and G++, but I bet that _Complex_I will be defined with  GCC and _GLIBCXX_COMPLEX with G++.

Tests for C++

G++ -std=c++11 v9.3.0 on Ubuntu 20.04 :
_GLIBCXX_COMPLEX

G++ -std=c++11 v11.2.0 on windows 10 (via Cygwin) :
_GLIBCXX_COMPLEX

MSVC default c++11 option v14.29.xxxxx.x on windows 10 :
_C_COMPLEX_T
_COMPLEX_

Apple LLVM-clang -std=c++11 v10.0.1 : None (doesn't mean there is none, just that I don't know which one)

Code for C++:

#include <iostream>
#include <complex>

int main(){

#ifdef _COMPLEX_
    std::cout << "_COMPLEX_" << std::endl;
#endif

#ifdef _C_COMPLEX_T
    std::cout << "_C_COMPLEX_T" << std::endl;
#endif

#ifdef _COMPLEX_H
    std::cout << "_COMPLEX_H" << std::endl;
#endif

#ifdef _Complex_I
    std::cout << "_Complex_I" << std::endl;
#endif

#ifdef _GLIBCXX_COMPLEX
    std::cout << "_GLIBCXX_COMPLEX" << std::endl;
#endif

    return 0;
}
```
<h3>Tests for C :</h3>
<p>GCC -std=c99 v9.3.0 on Ubuntu 20.04 :
<code>_Complex_I</code> <code>_COMPLEX_H</code></p>
<p>GCC -std=c99 v11.2.0 on windows 10 (via Cygwin) :
<code>_Complex_I</code> <code>_COMPLEX_H</code></p>
<p>MSVC -std=c99 v14.29.xxxxx.x on windows 10 :
<code>_Complex_I</code> <code>_C_COMPLEX_T</code></p>
<p>Apple LLVM-clang -std=c99 v10.0.1 : <code>_Complex_I</code></p>
<h3>Code for C:</h3>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
#include <complex.h>

int main(){

#ifdef _COMPLEX_
    printf("_COMPLEX_\n");
#endif

#ifdef _C_COMPLEX_T
    printf("_C_COMPLEX_T\n");
#endif

#ifdef _COMPLEX_H
    printf("_COMPLEX_H\n");
#endif

#ifdef _Complex_I
    printf("_Complex_I\n");
#endif

#ifdef _GLIBCXX_COMPLEX
    printf("_GLIBCXX_COMPLEX\n");
#endif

    return 0;
}
</code>```

To sum up :

MSVC is defining _C_COMPLEX_T whatever C or C++ used, and also _COMPLEX_ for C++. _Complex_I is always defined for C, and G++ seems to define _GLIBCXX_COMPLEX whatever the plateform (test to be done on macOS) for C++.

Body:
TL;DR : No, there is not, apart from the C++17 feature #if __has_include(<complex>). Not with defined macro anyway.

Long answer : there are two parts to the answer. What I read from some headers, and the tests I ran on differents OS with differents compilers.

Warning : I will write also about C, as some compilers uses the same macros. I also use the shortcut 'for C' and 'for C++' instead of 'when the header complex.h is included' and 'when the header <complex> is included'.

Ok, here's my best answer as for now.

About C and complex.h :

In C, the existence of the macro
_Complex_I is the only macro that I think should be defined in any complex.h header, as it is specified by the ISO C99 (cf. ISO/IEC 9899:1999/TC3 text). The tests I ran shows that this is a realistic hypothesis. There are some additionnal macro used, such as _COMPLEX_H that seems to be defined when compiling with GCC,
and _C_COMPLEX_T when compiling with MSVC. There might be others, I didn't find them, please don't hesitate to add them.

But it is C, not C++, and one should not mix both.

About C++ and <complex> :

The C++ standard (ISO/CEI 14882:2011) does not specify such macro. In fact, it does not specify the inclusion of any macro (at first glance).
It does specify the existence of the complex class however, but this does not answer the question.
For what I read, _COMPLEX_ and  _C_COMPLEX_T seems to be defined in the <complex> header for
LLVM-clang and MSVC, but also in the complex.h for the apple implementation of the C math library (libm).

However, my tests with the LLVM-clang compiler on macOS failed showing those macro, and I can't find the file where I read that information.
I also found that g++ is defining _GLIBCXX_COMPLEX.

If one wanted to do that with a C++ older than C++17, a solution would be to test with the given compilers and architectures the code will run onto.
That is quite bad, but it's the closest answer I get.

The tests :

I give here the code that I run on the different OS, the compiler options, their version, and the results they prompt. _Complex_I was indeed defined for all C headers.

I wasn't able to run the test on macOS with GCC and G++, but I bet that _Complex_I will be defined with  GCC and _GLIBCXX_COMPLEX with G++.

Tests for C++

G++ -std=c++11 v9.3.0 on Ubuntu 20.04 :
_GLIBCXX_COMPLEX

G++ -std=c++11 v11.2.0 on windows 10 (via Cygwin) :
_GLIBCXX_COMPLEX

MSVC default c++11 option v14.29.xxxxx.x on windows 10 :
_C_COMPLEX_T
_COMPLEX_

Apple LLVM-clang -std=c++11 v10.0.1 : None (doesn't mean there is none, just that I don't know which one)

Code for C++:

#include <iostream>
#include <complex>

int main(){

#ifdef _COMPLEX_
    std::cout << "_COMPLEX_" << std::endl;
#endif

#ifdef _C_COMPLEX_T
    std::cout << "_C_COMPLEX_T" << std::endl;
#endif

#ifdef _COMPLEX_H
    std::cout << "_COMPLEX_H" << std::endl;
#endif

#ifdef _Complex_I
    std::cout << "_Complex_I" << std::endl;
#endif

#ifdef _GLIBCXX_COMPLEX
    std::cout << "_GLIBCXX_COMPLEX" << std::endl;
#endif

    return 0;
}

Tests for C :

GCC -std=c99 v9.3.0 on Ubuntu 20.04 :
_Complex_I _COMPLEX_H

GCC -std=c99 v11.2.0 on windows 10 (via Cygwin) :
_Complex_I _COMPLEX_H

MSVC -std=c99 v14.29.xxxxx.x on windows 10 :
_Complex_I _C_COMPLEX_T

Apple LLVM-clang -std=c99 v10.0.1 : _Complex_I

Code for C:

#include <stdlib.h>
#include <stdio.h>
#include <complex.h>

int main(){

#ifdef _COMPLEX_
    printf("_COMPLEX_\n");
#endif

#ifdef _C_COMPLEX_T
    printf("_C_COMPLEX_T\n");
#endif

#ifdef _COMPLEX_H
    printf("_COMPLEX_H\n");
#endif

#ifdef _Complex_I
    printf("_Complex_I\n");
#endif

#ifdef _GLIBCXX_COMPLEX
    printf("_GLIBCXX_COMPLEX\n");
#endif

    return 0;
}

To sum up :

MSVC is defining _C_COMPLEX_T whatever C or C++ used, and also _COMPLEX_ for C++. _Complex_I is always defined for C, and G++ seems to define _GLIBCXX_COMPLEX whatever the plateform (test to be done on macOS) for C++.


问:
C# (429) Too Many Requests
I've been using the WebClient in C# to get specific data from a webpage. That works well until I do it more than 2 times. If I do it more than more than 2 times it gives me the "(429) Too Many Requests." error. I have looked at other questions regarding this issue, by the way.</p>

答:
This post is old, but I had the same issue downloading images from my webserver.
I found the solution on this post

```<code>// THIS LINE IS THE IMPORTANT ONE
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
                "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
                ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
                "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";
</code>```

I haven't had any issues since.

Title: C# (429) Too Many Requests

Body:
This post is old, but I had the same issue downloading images from my webserver.
I found the solution on this post

// THIS LINE IS THE IMPORTANT ONE
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
                "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
                ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
                "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";

I haven't had any issues since.


问:
select all "groups/partitions" where parameter is found
Without going into too much detail - I need to create groups (grouped on a specific field) of data and then display all GROUPS of records that contain a parameter.  I need all records in a GROUP even if some do not match the parameter.  Any GROUPS where no records contain the parameter would be suppressed.

I'm working with db2 and I just need help with the basic syntax.  I'm thinking a PARTITION_BY used within a subquery might be the correct approach.  Any ideas?  Thanks in advance.

答:
Does it answer the question ?

```<code>with table1 (group_column, expression, other_column) as (
  values
  ('group1', 'false', 'First in G1'),
  ('group1', 'false', 'Second in G1'),
  ('group2', 'false', 'First in G2'),
  ('group2', 'true', 'Second in G2'),
  ('group3', 'true', 'Full G3')
)
select
  table1.group_column, expression, other_column
from table1
  inner join
  (
    select
      distinct group_column
    from table1
    where expression = 'true'
  ) as groups on table1.group_column = groups.group_column
</code>```

GROUP_COLUMN
EXPRESSION
OTHER_COLUMN

group2
false
First in G2

group2
true
Second in G2

group3
true
Full G3

Body:
Does it answer the question ?

with table1 (group_column, expression, other_column) as (
  values
  ('group1', 'false', 'First in G1'),
  ('group1', 'false', 'Second in G1'),
  ('group2', 'false', 'First in G2'),
  ('group2', 'true', 'Second in G2'),
  ('group3', 'true', 'Full G3')
)
select
  table1.group_column, expression, other_column
from table1
  inner join
  (
    select
      distinct group_column
    from table1
    where expression = 'true'
  ) as groups on table1.group_column = groups.group_column

GROUP_COLUMN
EXPRESSION
OTHER_COLUMN

group2
false
First in G2

group2
true
Second in G2

group3
true
Full G3


问:
How is -13 % 64 = -13 in PHP?
Derived from this question : (Java) How does java do modulus calculations with negative numbers?

Anywhere to force PHP to return positive 51?

update

Looking for a configuration setting to fix, instead hard-guessing

Or other math function like bcmath?

updated

Not entire convinced by that java answer, as it does not take account of negative modulus
-13+(-64) =?

答:
I hate using if in this case when you can calculate it right away.

```<code>$r = ($x % $n + $n) % $n;
</code>```

when $n is positive.

Title: How is -13 % 64 = -13 in PHP?

Body:
I hate using if in this case when you can calculate it right away.

$r = ($x % $n + $n) % $n;

when $n is positive.


问:
Bash command option clarification bash -ex
could you please explain to me what exactly this shell command do?
It is quite difficoult to retrive the description of this -ex option.

sh #!/bin/bash -ex

Thanks in advance

答:
It means you're invoking new bash shell with -e and -x shell options

See shell options here: https://tldp.org/LDP/abs/html/options.html

-e   errexit Abort script at first error, when a command exits with non-zero status (except in until or while loops, if-tests, list constructs)

-x   xtrace  Similar to -v, but expands commands

since -x is similar to -v:

-v   verbose Print each command to stdout before executing it

So it's actually dropping to next level shell:

```<code>$ echo $SHLVL
1
$ sh #!/bin/bash -ex
$ echo $SHLVL
2
</code>```

in which in this level 2 shell, option -e and -x is activated

Body:
It means you're invoking new bash shell with -e and -x shell options

See shell options here: https://tldp.org/LDP/abs/html/options.html

-e   errexit Abort script at first error, when a command exits with non-zero status (except in until or while loops, if-tests, list constructs)

-x   xtrace  Similar to -v, but expands commands

since -x is similar to -v:

-v   verbose Print each command to stdout before executing it

So it's actually dropping to next level shell:

$ echo $SHLVL
1
$ sh #!/bin/bash -ex
$ echo $SHLVL
2

in which in this level 2 shell, option -e and -x is activated


问:
How can I read MS Office files in a server without installing MS Office and without using the Interop Library?
The interop library is slow and needs MS Office installed.
Many times you don't want to install MS Office on servers.

I'd like to use Apache POI, but I'm on .NET.

I need only to extract the text portion of the files, not creating nor "storing information" in Office files.

I need to tell you that I've got a very large document library, and I can't convert it to newer XML files.

I don't want to write a parser for the binaries files.
A library like Apache POI does this for us. Unfortunately, it is only for the Java platform. Maybe I should consider writing this application in Java.

I am still not finding an open source alternative to POI in .NET, I think I'll write my own application in Java.

答: In Java world, there is also JExcelApi. It is very clearly written, from what I was able to see, much cleaner then POI. So maybe even a port of that code to .NET is not out of the question, depending of course you have enough of time on your hands.</p>

OwnerDisplayName: volothamp

LastEditorDisplayName: warren

OwnerDisplayName: javashlook


问:
Once something is HTML or URL encoded should it ever be decoded? Is encoding enough?
First time AntiXSS 4 user here. In order to make my application more secure, I've used Microsoft.Security.Application.Encoder.UrlEncode on QueryString parameters and
Microsoft.Security.Application.Encoder.HtmlEncode on a parameter entered into a form field.

I have a multiple and I would appreciate it if you could try to answer all of them (doesn't have to be at once or by the same person - any abswers at all would be very helpful).

My first question is am I using these methods appropriately (that is am I using an appropriate AntiXSS method for an appropriate situation)?

My second question is once I've encoded something, should it ever be decoded. I am confused because I know that HttpUtility class provides ways to both encode and decode so why isn't the same done in AntiXSS? If this helps, the parameters that I've encoded are never going to be treated as anything other then text inside the application.

My third question is related to the third one but I wanted to emphasize it because it's important (and is probably the source of my overall confusion). I've heard that the .NET framework automatically decodes things like QueryStrings, hence no no need for explicit decode method. If that is so, then what is the point of HTML encoding something in the first place if it is going to be undone. It just... doesn't seem safe? What am I missing, especially since, as mentioned the HttpUtility class provides for decoding.

And the last question, does AntiXSS help against SQL injection at all or does it only protext against XSS attacks?

答:
It's hard to say if you're using it correctly. If you use UrlEncode when building a query string which is then output as a link in a page then yes that's correct. If you're Html Encoding when you write something out as a value then yes, that's correct (well kind of, if it's set via an HTML attribute you ought to use HtmlAttributeEncode, but they're pretty much the same.)

The .NET decoders work with AntiXSS's encoded values, so there was no point in me rewriting them grin

The point of encoding is that you do it when you output. So, for example, if a user has, on a form, input window.alert('Numpty!) and you just put that input raw in your output the javascript would run. If you encoded it first you would see < become < and so on.

No, SQL injection is an entirely different problem.

Body:
It's hard to say if you're using it correctly. If you use UrlEncode when building a query string which is then output as a link in a page then yes that's correct. If you're Html Encoding when you write something out as a value then yes, that's correct (well kind of, if it's set via an HTML attribute you ought to use HtmlAttributeEncode, but they're pretty much the same.)

The .NET decoders work with AntiXSS's encoded values, so there was no point in me rewriting them grin

The point of encoding is that you do it when you output. So, for example, if a user has, on a form, input window.alert('Numpty!) and you just put that input raw in your output the javascript would run. If you encoded it first you would see < become &lt; and so on.

No, SQL injection is an entirely different problem.