问:
SQL obtain users who have received o send a messages (UPDATE)
```<code>SELECT *
FROM users
WHERE NOT unique_id = {$outgoing_id}
  and unique_id in (select outgoing_msg_id
                    from messages
                    WHERE incoming_msg_id={$outgoing_id})
                    ORDER BY user_id DESC);
</code>```

More info about the DB and tables in: I need to get the list of users who have previously been sent message (MySQL) (This is another question, but about the same)

答:
Here is how I did it with user id 1 as an example:

SELECT
  first_name
FROM
  users
  LEFT JOIN messages received_messages ON received_messages.from_id = 1
  AND received_messages.to_id = users.id
  LEFT JOIN messages sent_messages ON sent_messages.from_id = users.id
  AND sent_messages.to_id = 1
WHERE
  received_messages.id IS NOT NULL
  OR sent_messages.id IS NOT NULL
```

Body:
SELECT *
FROM users
WHERE NOT unique_id = {$outgoing_id}
  and unique_id in (select outgoing_msg_id
                    from messages
                    WHERE incoming_msg_id={$outgoing_id})
                    ORDER BY user_id DESC);

More info about the DB and tables in: I need to get the list of users who have previously been sent message (MySQL) (This is another question, but about the same)


来源: stackexchange

问:
Recreate the Discord Widget using the Discord API
As of now, I am creating my own styled widget using the JSON from https://discordapp.com/api/servers/GUILD-ID/widget.json, which works fine so far. However, this JSON is limited to 99 users, and that's a problem for me.

So I thought, I could just re-create it, using the official Discord API. However, there is some information, I can't find in the API, or maybe I'm just blind.

I am missing the information, which user is currently in which voice channel

I am missing the online status of a user

I am missing the avatar URL

Whether the fields muteand deaf exist within the user object, they are null/empty, while the widget.json displays the correct information

So a user object in the widget.json looks like this:

{
    id: "0",
    username: "xxxx",
    discriminator: "0000",
    avatar: null,
    status: "online",
    deaf: false,
    mute: false,
    self_deaf: true,
    self_mute: true,
    suppress: false,
    channel_id: "555555555555555555",
    avatar_url: "https://cdn.discordapp.com/widget-avatars/XXXXXXXXXXXXXXX"
}
```
<p>while the API returns this:</p>
<pre class="lang-json prettyprint-override"><code>{
    user: {
    id: "999999999999999999",
    username: "xxxx",
    avatar: "257281f9b2aa93be7c12f5c49e122ca3",
    discriminator: "1234",
    public_flags: 576
    },
    roles: [
        "123456789123456789",
        "987654321987654321"
    ],
    nick: "yyyy",
    premium_since: null,
    joined_at: "1970-01-01T00:00:00.000000+00:00",
    is_pending: false,
    mute: false,
    deaf: false
}
</code>```

which is pretty much unusable for my case.

答:
I was just messing around with this earlier today here is what I came up with so far if you never figured that out

css

```<code>        * {
            box-sizing: border-box;
        }

        html,
        body {
            font-family: Whitney, "Helvetica Neue", Helvetica, Arial, sans-serif;
            color: #eeeeef;
            background-color: #36393f;
            display: flex;
            justify-content: flex-start;
            align-items: baseline;
            align-content: flex-start;
            flex-wrap: wrap;
            flex-direction: row;
        }

        p {
            margin: 3;
        }

        .sticky {
            position: -webkit-sticky;
            position: sticky;
            top: 0;
            float: left;
        }

        a {
            background-color: #5865F2;
            box-shadow: inset 0 -0.6em 0 -0.35em rgb(0 0 0 / 17%);
            color: #eeeeef;
            padding: 1em 1.5em;
            position: relative;
            text-decoration: none;
            text-transform: uppercase;
            z-index: 5;
            border-radius: 0.5rem;
            font-weight: bold;
            font-size: 1.5rem;
            float: right;
        }

        a:hover {
            transition: all 1.5s;
            box-shadow: inset 0 0 100px 100px rgb(255 255 255 / 30%);
        }

        a:active {
            box-shadow: none;
            top: 5px;
        }

        header {
            margin: 50px;
        }

        h1 {
            font-size: 4rem;
            z-index: 3;
            text-shadow: 3px 3px 4px #000000a6;
        }

        .member {
            padding: 8px;
            font-size: 1.3rem;
            margin: 5;
            text-shadow: 1.5px 1.5px 16px #00000025;
        }

        img {
            border-radius: 5px;
        }

        .memberText {
            position: absolute;
            margin-top: 5.8px;
            margin-left: 25px;
            font-weight: bold;
        }

        br {
            display: block;
            margin: 10px 0;
            line-height: 22px;
            content: " ";
        }

        #users {
            box-shadow: 20px 3em 20px 1em rgb(0 0 0 / 5%);
        }

        @media only screen and (max-width: 600px) {
            #wrap {
                width: 300px;
                background-image: linear-gradient(to left, transparent, #1d1e2280);
            }
        }
</code>```

meta and script tags

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/6c4ec84abe.js" crossorigin="anonymous"></script>
</code>```

body html

```<code>
<body>

    <header class="sticky"></header>

    <div id="users">
    </div>
</body>
</code>```

JS (I usually load at the bottom of the body tag or load it in with a  tag when messing with DOM elements)

And to get the right JSON for the widget see the picture below

```<code>$.getJSON('https://discord.com/api/guilds/633515516207693864/widget.json', function(data) {

        var members = data.members;

        var title = `<h1>${data.name}</h1>
            <p><a href="${data.instant_invite}"" target="_blank"><i class="fa-brands fa-discord"></i> Join Now</a></p>`;

        for (var member in members) {

            var deaf = (members[member].deaf) ? "<font color='red'><i class='fa-solid fa-headphones'></i></font>" : "";
            var mute = (members[member].mute) ? "<font color='red'><i class='fa-solid fa-microphone-slash'></i></font>" : "";

            var gameCheck = (!members[member].game) ? `<span style="font-weight:100;font-style:italic;"></span>` : `<span style="font-weight:100;font-style:italic;">Playing ${members[member].game.name}</span>`;

            if (members[member].status === "online") {
                status = `<i class='fa-solid fa-circle' style='color:#00ff00ba;font-size:1rem;'></i>`;
            } else if (members[member].status === "idle") {
                status = `<i class="fa-solid fa-moon" style='color:#d9d93be6;font-size:1rem;'></i>`;
            }

            let memberItem = `<img src="${members[member].avatar_url}" style="height:100px; width:auto;margin-right:8px;"><span class="memberText">${status} ${members[member].username}<br><i style='font-size:1rem;font-weight:100 !important;margin-top:5px;'>${gameCheck}<br>${mute} ${deaf}</i></span>`;
            var onlineUsers = (members[member].username == "Hide Bot/User 1" || members[member].username == "Hide Bot/User 2") ? `` : `<div class='member'>${memberItem}</div>`;

            $("#users").append(`${onlineUsers}`);
        }

        $("header").html(title);

    });
</code>```

Also here is a screenshot to get your JSON Api url widget > JSON API" />

ContentLicense: CC BY-SA 4.0

Body:
As of now, I am creating my own styled widget using the JSON from https://discordapp.com/api/servers/GUILD-ID/widget.json, which works fine so far. However, this JSON is limited to 99 users, and that's a problem for me.

So I thought, I could just re-create it, using the official Discord API. However, there is some information, I can't find in the API, or maybe I'm just blind.

I am missing the information, which user is currently in which voice channel

I am missing the online status of a user

I am missing the avatar URL

Whether the fields muteand deaf exist within the user object, they are null/empty, while the widget.json displays the correct information

So a user object in the widget.json looks like this:

{
    id: "0",
    username: "xxxx",
    discriminator: "0000",
    avatar: null,
    status: "online",
    deaf: false,
    mute: false,
    self_deaf: true,
    self_mute: true,
    suppress: false,
    channel_id: "555555555555555555",
    avatar_url: "https://cdn.discordapp.com/widget-avatars/XXXXXXXXXXXXXXX"
}

while the API returns this:

{
    user: {
    id: "999999999999999999",
    username: "xxxx",
    avatar: "257281f9b2aa93be7c12f5c49e122ca3",
    discriminator: "1234",
    public_flags: 576
    },
    roles: [
        "123456789123456789",
        "987654321987654321"
    ],
    nick: "yyyy",
    premium_since: null,
    joined_at: "1970-01-01T00:00:00.000000+00:00",
    is_pending: false,
    mute: false,
    deaf: false
}

which is pretty much unusable for my case.

Body:
I was just messing around with this earlier today here is what I came up with so far if you never figured that out

css

        * {
            box-sizing: border-box;
        }

        html,
        body {
            font-family: Whitney, "Helvetica Neue", Helvetica, Arial, sans-serif;
            color: #eeeeef;
            background-color: #36393f;
            display: flex;
            justify-content: flex-start;
            align-items: baseline;
            align-content: flex-start;
            flex-wrap: wrap;
            flex-direction: row;
        }

        p {
            margin: 3;
        }

        .sticky {
            position: -webkit-sticky;
            position: sticky;
            top: 0;
            float: left;
        }

        a {
            background-color: #5865F2;
            box-shadow: inset 0 -0.6em 0 -0.35em rgb(0 0 0 / 17%);
            color: #eeeeef;
            padding: 1em 1.5em;
            position: relative;
            text-decoration: none;
            text-transform: uppercase;
            z-index: 5;
            border-radius: 0.5rem;
            font-weight: bold;
            font-size: 1.5rem;
            float: right;
        }

        a:hover {
            transition: all 1.5s;
            box-shadow: inset 0 0 100px 100px rgb(255 255 255 / 30%);
        }

        a:active {
            box-shadow: none;
            top: 5px;
        }

        header {
            margin: 50px;
        }

        h1 {
            font-size: 4rem;
            z-index: 3;
            text-shadow: 3px 3px 4px #000000a6;
        }

        .member {
            padding: 8px;
            font-size: 1.3rem;
            margin: 5;
            text-shadow: 1.5px 1.5px 16px #00000025;
        }

        img {
            border-radius: 5px;
        }

        .memberText {
            position: absolute;
            margin-top: 5.8px;
            margin-left: 25px;
            font-weight: bold;
        }

        br {
            display: block;
            margin: 10px 0;
            line-height: 22px;
            content: " ";
        }

        #users {
            box-shadow: 20px 3em 20px 1em rgb(0 0 0 / 5%);
        }

        @media only screen and (max-width: 600px) {
            #wrap {
                width: 300px;
                background-image: linear-gradient(to left, transparent, #1d1e2280);
            }
        }

meta and script tags

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/6c4ec84abe.js" crossorigin="anonymous"></script>

body html

<body>

    <header class="sticky"></header>

    <div id="users">
    </div>
</body>

JS (I usually load at the bottom of the body tag or load it in with a  tag when messing with DOM elements)

And to get the right JSON for the widget see the picture below

$.getJSON('https://discord.com/api/guilds/633515516207693864/widget.json', function(data) {

        var members = data.members;

        var title = `<h1>${data.name}</h1>
            <p><a href="${data.instant_invite}"" target="_blank"><i class="fa-brands fa-discord"></i> Join Now</a></p>`;

        for (var member in members) {

            var deaf = (members[member].deaf) ? "<font color='red'><i class='fa-solid fa-headphones'></i></font>" : "";
            var mute = (members[member].mute) ? "<font color='red'><i class='fa-solid fa-microphone-slash'></i></font>" : "";

            var gameCheck = (!members[member].game) ? `<span style="font-weight:100;font-style:italic;"></span>` : `<span style="font-weight:100;font-style:italic;">Playing ${members[member].game.name}</span>`;

            if (members[member].status === "online") {
                status = `<i class='fa-solid fa-circle' style='color:#00ff00ba;font-size:1rem;'></i>`;
            } else if (members[member].status === "idle") {
                status = `<i class="fa-solid fa-moon" style='color:#d9d93be6;font-size:1rem;'></i>`;
            }

            let memberItem = `<img src="${members[member].avatar_url}" style="height:100px; width:auto;margin-right:8px;"><span class="memberText">${status} ${members[member].username}<br><i style='font-size:1rem;font-weight:100 !important;margin-top:5px;'>${gameCheck}<br>${mute} ${deaf}</i></span>`;
            var onlineUsers = (members[member].username == "Hide Bot/User 1" || members[member].username == "Hide Bot/User 2") ? `` : `<div class='member'>${memberItem}</div>`;

            $("#users").append(`${onlineUsers}`);
        }

        $("header").html(title);

    });

Also here is a screenshot to get your JSON Api url


问:
Auth0, flask: Users need to login twice due to CSRF error
When a user logs into my flask app it does not work first time, but it typically works on the second attempt. The following error occurs on the first login attempt:

```<code>MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response
</code>```

I did not have this problem when running on localhost on a windows PC. I obtained this problem when moving my code to a linode running ubuntu 20.04. I am considering flask in python3 as well as the following packages.

```<code>from flask import Flask
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import session
from flask import url_for
from flask import request
from flask import send_from_directory
from authlib.integrations.flask_client import OAuth
</code>```

My keys are fixed in a .env file. They are not randomly generated.

```<code>oauth = OAuth(app)

auth0 = oauth.register(
    'auth0',
    client_id=AUTH0_CLIENT_ID,
    client_secret=AUTH0_CLIENT_SECRET,
    api_base_url=AUTH0_BASE_URL,
    access_token_url=AUTH0_BASE_URL + '/oauth/token',
    authorize_url=AUTH0_BASE_URL + '/authorize',
    client_kwargs={
        'scope': 'openid profile email',
    },
)
</code>```

The following code in the callback handling gives the CSRF error.

```<code>@app.route('/callback')
def callback_handling():
    auth0.authorize_access_token()
    resp = auth0.get('userinfo')
</code>```

答:
I may have solved this question by updating my ntp on linux with the help of the following link:
https://askubuntu.com/questions/254826/how-to-force-a-clock-update-using-ntp

```<code>apt-get install -y  ntp
sudo service ntp stop
sudo ntpd -gq
sudo service ntp start
</code>```

I also added a try except in my python server

```<code>try:

    auth0.authorize_access_token()
                resp = auth0.get('userinfo')
    userinfo = resp.json()
    session[constants.JWT_PAYLOAD] = userinfo
    session[constants.PROFILE_KEY] = {
        'user_id': userinfo['sub'],
        'name': userinfo['name'],
        'picture': userinfo['picture'],
        'email_verified':userinfo['email_verified']
    }
except:
    return redirect("/mainpage")

#Some code

return redirect('mainpage')
</code>```

Ensure that the 'mainpage' requires authorisation.

Body:
When a user logs into my flask app it does not work first time, but it typically works on the second attempt. The following error occurs on the first login attempt:

MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response

I did not have this problem when running on localhost on a windows PC. I obtained this problem when moving my code to a linode running ubuntu 20.04. I am considering flask in python3 as well as the following packages.

from flask import Flask
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import session
from flask import url_for
from flask import request
from flask import send_from_directory
from authlib.integrations.flask_client import OAuth

My keys are fixed in a .env file. They are not randomly generated.

oauth = OAuth(app)

auth0 = oauth.register(
    'auth0',
    client_id=AUTH0_CLIENT_ID,
    client_secret=AUTH0_CLIENT_SECRET,
    api_base_url=AUTH0_BASE_URL,
    access_token_url=AUTH0_BASE_URL + '/oauth/token',
    authorize_url=AUTH0_BASE_URL + '/authorize',
    client_kwargs={
        'scope': 'openid profile email',
    },
)

The following code in the callback handling gives the CSRF error.

@app.route('/callback')
def callback_handling():
    auth0.authorize_access_token()
    resp = auth0.get('userinfo')

Body:
I may have solved this question by updating my ntp on linux with the help of the following link:
https://askubuntu.com/questions/254826/how-to-force-a-clock-update-using-ntp

apt-get install -y  ntp
sudo service ntp stop
sudo ntpd -gq
sudo service ntp start

I also added a try except in my python server

try:

    auth0.authorize_access_token()
                resp = auth0.get('userinfo')
    userinfo = resp.json()
    session[constants.JWT_PAYLOAD] = userinfo
    session[constants.PROFILE_KEY] = {
        'user_id': userinfo['sub'],
        'name': userinfo['name'],
        'picture': userinfo['picture'],
        'email_verified':userinfo['email_verified']
    }
except:
    return redirect("/mainpage")

#Some code

return redirect('mainpage')

Ensure that the 'mainpage' requires authorisation.


问:
First Unique Character In a String-Leetcode
I have tried out 387.First Unique Character In A string

Given a string s, find the first non-repeating character in it and
return its index. If it does not exist, return -1.

EXAMPLE : 1

```<code> Input: s = "leetcode"

 Output: 0
</code>```

EXAMPLE :2

```<code> Input: s = "loveleetcode"

 Output: 2
</code>```

I have been trying this problem. I thought we will pick one by one all the characters and check if a repeating character exists break from the loop. And if not then return that index.I have thought over a solution which I believe is not the most efficient way but I want to know the how can I solve this problem with the approach given below:

```<code>public int firstUniqChar(String s) {
  for(int i=0;i<s.length();i++){
      for(int j=i+1;j<s.length();j++){
          if(s.charAt(i)==s.charAt(j)){
              break;
          }

      }

  }
    return -1;
}
</code>```

I'm confused how to return the index.I'm unable to find the logic after:

```<code>for(int j=i+1;j<s.length();j++){
              if(s.charAt(i)==s.charAt(j)){
                  break;
              }

          }
</code>```

If anyone can help me find out the logic here.

答:
The lowest complexity I managed to achieve:

```<code>public class UniqueSymbolFinder {
    static int findFirstUniqueChar(String s) {
        Set<Character> set = new HashSet<>(s.length());
        List<CharWithIndex> candidates = new LinkedList<>();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            CharWithIndex charWithIndex = new CharWithIndex(ch, i);

            if (set.add(ch)) {
                candidates.add(charWithIndex);
            } else {
                candidates.remove(charWithIndex);
            }
        }
        return candidates.size() == 0 ? -1 : candidates.get(0).index;
    }

    /**
     * Class for storing the index.
     * Used to avoid of using an indexOf or other iterations.
     */
    private static class CharWithIndex {
        int index;
        char ch;

        private CharWithIndex(char ch, int index) {
            this.ch = ch;
            this.index = index;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            CharWithIndex that = (CharWithIndex) o;
            return ch == that.ch;
        }

        @Override
        public int hashCode() {
            return Objects.hash(ch);
        }
    }
}
</code>```

I believe the memory usage can still be optimized.

Body:
I have tried out 387.First Unique Character In A string

Given a string s, find the first non-repeating character in it and
return its index. If it does not exist, return -1.

EXAMPLE : 1

 Input: s = "leetcode"

 Output: 0

EXAMPLE :2

 Input: s = "loveleetcode"

 Output: 2

I have been trying this problem. I thought we will pick one by one all the characters and check if a repeating character exists break from the loop. And if not then return that index.I have thought over a solution which I believe is not the most efficient way but I want to know the how can I solve this problem with the approach given below:

public int firstUniqChar(String s) {
  for(int i=0;i<s.length();i++){
      for(int j=i+1;j<s.length();j++){
          if(s.charAt(i)==s.charAt(j)){
              break;
          }

      }

  }
    return -1;
}

I'm confused how to return the index.I'm unable to find the logic after:

for(int j=i+1;j<s.length();j++){
              if(s.charAt(i)==s.charAt(j)){
                  break;
              }

          }

If anyone can help me find out the logic here.

Body:
The lowest complexity I managed to achieve:

public class UniqueSymbolFinder {
    static int findFirstUniqueChar(String s) {
        Set<Character> set = new HashSet<>(s.length());
        List<CharWithIndex> candidates = new LinkedList<>();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            CharWithIndex charWithIndex = new CharWithIndex(ch, i);

            if (set.add(ch)) {
                candidates.add(charWithIndex);
            } else {
                candidates.remove(charWithIndex);
            }
        }
        return candidates.size() == 0 ? -1 : candidates.get(0).index;
    }

    /**
     * Class for storing the index.
     * Used to avoid of using an indexOf or other iterations.
     */
    private static class CharWithIndex {
        int index;
        char ch;

        private CharWithIndex(char ch, int index) {
            this.ch = ch;
            this.index = index;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            CharWithIndex that = (CharWithIndex) o;
            return ch == that.ch;
        }

        @Override
        public int hashCode() {
            return Objects.hash(ch);
        }
    }
}

I believe the memory usage can still be optimized.


问:
Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
I have a problem with my webpack project, so I was trying to import one class to another and instantiate it but suddenly an error appear in my console and my program stopped working, it was this:

```<code>Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
</code>```

This is the code of the class were I am trying to import my another class (that is PopUpPlugin):

```<code>import PopupPlugin from './popupPlugin.js';

export const addSearchBtnEvent = (weatherUI) => {
  const searchBtn = document.querySelector('.weather__search');

  searchBtn.addEventListener('click', () => {
    weatherUI.style.opacity = '1';
    weatherUI.style.visibility = 'visible';
  })
}

export const addSearchExitEvent = (weatherUI) => {
  const weatherExit = document.querySelector('.weather__search-exit');

  weatherExit.addEventListener('click', () => {
    weatherUI.style.opacity = '0';
    weatherUI.style.visibility = 'hidden';
  })
}

const popupObj = new PopupPlugin();

class searchDashboard {
  constructor() {

  }

  setInputEvent() {
    const inputSearch = document.querySelector('.weather__city-search');
    const inputSearchBtn = document.querySelector('.weather__search-btn');

    inputSearchBtn.addEventListener('click', () => {
      const inputSearchVal = inputSearch.value;

      this.validateStr(inputSearchVal);
    });
  }

  validateStr() {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      this.popupObj.searchCoincidences(strValue, 'weather__search-ui');
    }
  }
}

export default searchDashboard;
</code>```

I don't actually know why this is happening, I also tried to instantiate it inside the constructor and it worked but it sended me the error of an stack overflow.

PD: If someone needs it here is the code of the PopupPlugin. (Here is what was working to me that was instantiating the class inside the constructor until the stack overflow error appeared)

```<code>import ManageWeatherDashboard from './manageWeatherDashboard.js';
import { getFetch, repeatAppend } from './weatherHelpers.js';

class popupPlugin {
  constructor() {
    this.manageWeatherDashboardObj = new ManageWeatherDashboard();
  }

  validateStr(str) {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      return strValue;
    }
  }

  searchCoincidences(val, parent) {
    getFetch(`https://www.metaweather.com/api/location/search/?query=${val}`)
      .then(res => res.text())
      .then(data => {
        const parentResults = document.querySelector('.'+parent);

        parentResults.innerHTML = '';

        const dataArr = JSON.parse(data)

        if(dataArr.length >= 15) {
          let resVal;

          for(let i = 0; i <= 15; i++) {
            resVal = this.addDOMResultCoincidences(parent, dataArr[i].title,
              dataArr[i].woeid);
          }

          this.whenClickCoincidence(resVal);
        } else {
          let resVal;

          dataArr.forEach(el => {
            resVal = this.addDOMResultCoincidences(parent, el.title, el.woeid);
          })

          this.whenClickCoincidence(resVal);
        }

      })
  }

  addDOMResultCoincidences(parentBlock, name, id) {
    const args = Array.from(arguments);

    if(args[0] === 'popup__results') {
      const popupResults = document.querySelector('.popup__results');

      const divResult = document.createElement('div');
      divResult.className = 'popup__result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      spanResultName.className = 'popup__result-name';

      const cityReturn = document.createTextNode(args[1]);

      spanResultName.appendChild(cityReturn);

      divResult.appendChild(spanResultName);

      popupResults.prepend(divResult);

      return divResult;
    }

    if(args[0] === 'weather__search-ui') {
      const weatherUI = document.querySelector('.weather__search-ui');

      const divResult = document.createElement('div');
      divResult.className = 'weather__search-result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      const spanResultNameText = document.createTextNode(args[1]);
      spanResultName.className = 'weather__city-result';
      spanResultName.appendChild(spanResultNameText);

      const iconResult = document.createElement('i');
      iconResult.className = 'fa fa-arrow-right weather__go-result';

      repeatAppend([spanResultName, iconResult], divResult);

      weatherUI.appendChild(divResult);

      return divResult;
    }
  }

  // When click a coincidence in search field

  whenClickCoincidence(el) {
    const woeId = el.getAttribute('data-woeid');

    el.addEventListener('click', () => {
      let handler = 0;

      if(handler === 0) {
        getFetch(`https://www.metaweather.com/api/location/${woeId}/`)
          .then(res => res.json())
          .then(data => {
            const popup = document.querySelector('.popup');

            const weatherNext6Days = data.consolidated_weather;

            this.manageWeatherDashboardObj.changeWeatherBar(weatherNext6Days[0], data.title);

            weatherNext6Days.slice(1, 6).forEach(el => {
              this.manageWeatherDashboardObj.nextFiveDays(el);
            })

            this.manageWeatherDashboardObj.updateStadistics(weatherNext6Days[0]);

            popup.style.opacity = '0';
            popup.style.visibility = 'hidden';
          })
      }

      handler += 1;
    })
  }
}

export default popupPlugin;
</code>```

答:
Using my IDE auto import I had something like:

```<code>import useStore, { useCart } from "../lib/store"
</code>```

Everything was working fine for awhile! But then I got the same error until I changed my import to be like this:

```<code>import { useStore, useCart } from "../lib/store"
</code>```

Body:
I have a problem with my webpack project, so I was trying to import one class to another and instantiate it but suddenly an error appear in my console and my program stopped working, it was this:

Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

This is the code of the class were I am trying to import my another class (that is PopUpPlugin):

import PopupPlugin from './popupPlugin.js';

export const addSearchBtnEvent = (weatherUI) => {
  const searchBtn = document.querySelector('.weather__search');

  searchBtn.addEventListener('click', () => {
    weatherUI.style.opacity = '1';
    weatherUI.style.visibility = 'visible';
  })
}

export const addSearchExitEvent = (weatherUI) => {
  const weatherExit = document.querySelector('.weather__search-exit');

  weatherExit.addEventListener('click', () => {
    weatherUI.style.opacity = '0';
    weatherUI.style.visibility = 'hidden';
  })
}

const popupObj = new PopupPlugin();

class searchDashboard {
  constructor() {

  }

  setInputEvent() {
    const inputSearch = document.querySelector('.weather__city-search');
    const inputSearchBtn = document.querySelector('.weather__search-btn');

    inputSearchBtn.addEventListener('click', () => {
      const inputSearchVal = inputSearch.value;

      this.validateStr(inputSearchVal);
    });
  }

  validateStr() {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      this.popupObj.searchCoincidences(strValue, 'weather__search-ui');
    }
  }
}

export default searchDashboard;

I don't actually know why this is happening, I also tried to instantiate it inside the constructor and it worked but it sended me the error of an stack overflow.

PD: If someone needs it here is the code of the PopupPlugin. (Here is what was working to me that was instantiating the class inside the constructor until the stack overflow error appeared)

import ManageWeatherDashboard from './manageWeatherDashboard.js';
import { getFetch, repeatAppend } from './weatherHelpers.js';

class popupPlugin {
  constructor() {
    this.manageWeatherDashboardObj = new ManageWeatherDashboard();
  }

  validateStr(str) {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      return strValue;
    }
  }

  searchCoincidences(val, parent) {
    getFetch(`https://www.metaweather.com/api/location/search/?query=${val}`)
      .then(res => res.text())
      .then(data => {
        const parentResults = document.querySelector('.'+parent);

        parentResults.innerHTML = '';

        const dataArr = JSON.parse(data)

        if(dataArr.length >= 15) {
          let resVal;

          for(let i = 0; i <= 15; i++) {
            resVal = this.addDOMResultCoincidences(parent, dataArr[i].title,
              dataArr[i].woeid);
          }

          this.whenClickCoincidence(resVal);
        } else {
          let resVal;

          dataArr.forEach(el => {
            resVal = this.addDOMResultCoincidences(parent, el.title, el.woeid);
          })

          this.whenClickCoincidence(resVal);
        }

      })
  }

  addDOMResultCoincidences(parentBlock, name, id) {
    const args = Array.from(arguments);

    if(args[0] === 'popup__results') {
      const popupResults = document.querySelector('.popup__results');

      const divResult = document.createElement('div');
      divResult.className = 'popup__result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      spanResultName.className = 'popup__result-name';

      const cityReturn = document.createTextNode(args[1]);

      spanResultName.appendChild(cityReturn);

      divResult.appendChild(spanResultName);

      popupResults.prepend(divResult);

      return divResult;
    }

    if(args[0] === 'weather__search-ui') {
      const weatherUI = document.querySelector('.weather__search-ui');

      const divResult = document.createElement('div');
      divResult.className = 'weather__search-result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      const spanResultNameText = document.createTextNode(args[1]);
      spanResultName.className = 'weather__city-result';
      spanResultName.appendChild(spanResultNameText);

      const iconResult = document.createElement('i');
      iconResult.className = 'fa fa-arrow-right weather__go-result';

      repeatAppend([spanResultName, iconResult], divResult);

      weatherUI.appendChild(divResult);

      return divResult;
    }
  }

  // When click a coincidence in search field

  whenClickCoincidence(el) {
    const woeId = el.getAttribute('data-woeid');

    el.addEventListener('click', () => {
      let handler = 0;

      if(handler === 0) {
        getFetch(`https://www.metaweather.com/api/location/${woeId}/`)
          .then(res => res.json())
          .then(data => {
            const popup = document.querySelector('.popup');

            const weatherNext6Days = data.consolidated_weather;

            this.manageWeatherDashboardObj.changeWeatherBar(weatherNext6Days[0], data.title);

            weatherNext6Days.slice(1, 6).forEach(el => {
              this.manageWeatherDashboardObj.nextFiveDays(el);
            })

            this.manageWeatherDashboardObj.updateStadistics(weatherNext6Days[0]);

            popup.style.opacity = '0';
            popup.style.visibility = 'hidden';
          })
      }

      handler += 1;
    })
  }
}

export default popupPlugin;

Body:
Using my IDE auto import I had something like:

import useStore, { useCart } from "../lib/store"

Everything was working fine for awhile! But then I got the same error until I changed my import to be like this:

import { useStore, useCart } from "../lib/store"


问:
Token Authentication Not Working on Django Rest Framework
I have a Django application, which I am using DRF for my API with Session, and Token authentication. I have rest_framework, and rest_framework.authtoken in my installed apps. I have migrated my database and can create tokens for users in the Django Admin. I know all of this is working because I am accessing rest_framework.auth_token's obtain_auth_token view for returning a token when user data is submitted in a POST request, and receive one back. When I try to make a GET request to a view function in my app that has TokenAuthentication on its viewset, it keeps returning.

```<code>{"detail":"Authentication credentials were not provided."}
</code>```

Settings File

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # My Apps
    'rest_framework',
    'rest_auth',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
}
</code>```

URLS

```<code>from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views

from api.views.some_model import MyViewSet

urlpatterns = [
    path('', include(router.urls)),
    path('rest-auth/', include('rest_auth.urls')),
    path('api-token-auth/', views.obtain_auth_token)
]
</code>```

Viewset

```<code>from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated

from some_app.models import SomeModel
from api.serializers.exams import SomeModelSerializer

class ExamViewSet(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication, SessionAuthentication)

    queryset = SomeModel.objects.all()
    serializer_class = SomeModelSerializer
</code>```

Python Script to Get Response

```<code>import requests
import json

data = {
    "username": "myemail@gmail.com",
    "password": "password124"
}
url = "http://localhost:8002/api/v1/api-token-auth/"
response = requests.post(url, data=data)
token = json.loads(response.text).get('token')

if token:
    token = f"Token {token}"
    headers = {"Authentication": token}
    response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)
    print(response.text)
else:
    print('No Key')
</code>```

答:
Authorization:prefix YourToken

If you are using JWT authentication then your request header should look like

Authorization: JWT your-token-here

or

Authorization: Bearer your-token-here

Body:
I have a Django application, which I am using DRF for my API with Session, and Token authentication. I have rest_framework, and rest_framework.authtoken in my installed apps. I have migrated my database and can create tokens for users in the Django Admin. I know all of this is working because I am accessing rest_framework.auth_token's obtain_auth_token view for returning a token when user data is submitted in a POST request, and receive one back. When I try to make a GET request to a view function in my app that has TokenAuthentication on its viewset, it keeps returning.

{"detail":"Authentication credentials were not provided."}

Settings File

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # My Apps
    'rest_framework',
    'rest_auth',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
}

URLS

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views

from api.views.some_model import MyViewSet

urlpatterns = [
    path('', include(router.urls)),
    path('rest-auth/', include('rest_auth.urls')),
    path('api-token-auth/', views.obtain_auth_token)
]

Viewset

from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated

from some_app.models import SomeModel
from api.serializers.exams import SomeModelSerializer

class ExamViewSet(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication, SessionAuthentication)

    queryset = SomeModel.objects.all()
    serializer_class = SomeModelSerializer

Python Script to Get Response

import requests
import json

data = {
    "username": "myemail@gmail.com",
    "password": "password124"
}
url = "http://localhost:8002/api/v1/api-token-auth/"
response = requests.post(url, data=data)
token = json.loads(response.text).get('token')

if token:
    token = f"Token {token}"
    headers = {"Authentication": token}
    response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)
    print(response.text)
else:
    print('No Key')


问:
converting Object -HashMap to XMLObject
I have created a webservice which takes a HashMap as parameter.
I generated the stubs/skeletion using XMLBeans and I am trying to set the values in the parameter and pass it to the webservice.

The issue is:
I have the HashMap or List and API is expecting it to be XMLObject is there any conversion utility which can be useful to convert my value to XMLObject?

答:
not sure about conversion, but I have successfully sent HashMap via webservice by wrapping the HashMap in an object like so:

```<code>class MapObject {
    HashMap<String, String> myMap;

    public MapObject(){}

    public HashMap<String, String> getMap() {
        return myMap;
    }

    public void setMyMap(HashMap<String, String> myMap) {
        this.myMap = myMap;
    }
}
</code>```

Then just make your web service parameter type MapObject.

ContentLicense: CC BY-SA 3.0

Title: converting Object -HashMap to XMLObject

Body:
not sure about conversion, but I have successfully sent HashMap via webservice by wrapping the HashMap in an object like so:

class MapObject {
    HashMap<String, String> myMap;

    public MapObject(){}

    public HashMap<String, String> getMap() {
        return myMap;
    }

    public void setMyMap(HashMap<String, String> myMap) {
        this.myMap = myMap;
    }
}

Then just make your web service parameter type MapObject.


问:
Weird behavior after upgrading to androidx.preference:preference-ktx:1.2.0
I am using Google Map in my Android app, was working properly, now after upgrading

androidx.preference:preference-ktx from 1.1.0 to 1.2.0,

Google Maps stopped displaying map tiles, but everything else is working, tap on map works, ...

答:
Hi did you check the dependencies androidx.preference:preference-ktx:1.2.0 brought? It is possible that some transitive dependency of androidx.preference:preference-ktx:1.2.0 may have caused the update to the same transitive dependency of the Google map library. See Gradle dependency resolution for more info

Also you can print the dependencies tree using the command ./gradlew app:dependencies where app is the name of the application Gradle project. See SO post for the same

To fix  the issue you have to manually resolve the dependency using below Gradle code

```<code>configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        if (details.requested.group == 'culprit dependency group' && details.requested.name == 'culprit dependency version') {
            details.useVersion 'fixing version'
            details.because 'reason why we have fixed the version'
        }
    }
}
</code>```

Details bout dependency resolution at link

Body:
Hi did you check the dependencies androidx.preference:preference-ktx:1.2.0 brought? It is possible that some transitive dependency of androidx.preference:preference-ktx:1.2.0 may have caused the update to the same transitive dependency of the Google map library. See Gradle dependency resolution for more info

Also you can print the dependencies tree using the command ./gradlew app:dependencies where app is the name of the application Gradle project. See SO post for the same

To fix  the issue you have to manually resolve the dependency using below Gradle code

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        if (details.requested.group == 'culprit dependency group' && details.requested.name == 'culprit dependency version') {
            details.useVersion 'fixing version'
            details.because 'reason why we have fixed the version'
        }
    }
}

Details bout dependency resolution at link


问:
how to insert text at specific lines in vim?
I want to put cursor at specific lines that is:

```<code>AAA
BBB
CCC
</code>```

I know how to edit those three lines using CTRL_V and then SHIFT_I, but my question is how do i edit the first and the last line and leave out the second line that is:

```<code>test_AAA
BBB
test_CCC
</code>```

thanks in advance.

答:
Vim doesn't have a built-in "multiple cursors" feature. If you want to do it the vanilla way, you can use :help .:

```<code>" cursor is on first A
> AAA
  BBB
  CCC

" do itest_<Esc>
> test_AAA
  BBB
  CCC

" move the cursor to CCC
  test_AAA
  BBB
> CCC

" press .
  test_AAA
  BBB
> test_CCC
</code>```

or the almighty :help :global, which is the de-facto way to operate on non-contiguous line:

```<code>:g/^AA|^CC/s/^/test_
</code>```

And there are many other ways.

Or you can ask your favourite engine to help you find the couple of plugins that replicate that feature: "vim multiple cursors".

Body:
I want to put cursor at specific lines that is:

AAA
BBB
CCC

I know how to edit those three lines using CTRL_V and then SHIFT_I, but my question is how do i edit the first and the last line and leave out the second line that is:

test_AAA
BBB
test_CCC

thanks in advance.

Body:
Vim doesn't have a built-in "multiple cursors" feature. If you want to do it the vanilla way, you can use :help .:

" cursor is on first A
> AAA
  BBB
  CCC

" do itest_<Esc>
> test_AAA
  BBB
  CCC

" move the cursor to CCC
  test_AAA
  BBB
> CCC

" press .
  test_AAA
  BBB
> test_CCC

or the almighty :help :global, which is the de-facto way to operate on non-contiguous line:

:g/^AA|^CC/s/^/test_

And there are many other ways.

Or you can ask your favourite engine to help you find the couple of plugins that replicate that feature: "vim multiple cursors".


问:
YouTube embed URL validation regex in Laravel 8 in controller
I want to validate my youtube URL like this https://www.youtube.com/embed/xxxxxxxx. How to use the regex in variable link for this?

my code is like this in controller

```<code>$validatedData = $request->validate([
    'title' => 'required',
    'subtitle' => 'required|unique:news',
    'category' => 'required',
    'link' => 'required|regex:??',
    'image1' => 'required|image',
    'image2' => 'image',
    'image3' => 'image',
    'image4' => 'image',
    'content' => 'required'
]);
</code>```

答:
You need to add some custom validation logic for achieving this .Hope this code snippet can help you-

```<code>'link' => [
        'required',
        'url',
        function ($attribute, $requesturl, $failed) {
            if (!preg_match('/(youtube.com|youtu.be)\/(embed)?(\?v=)?(\S+)?/', $requesturl)) {
                $failed(trans("general.not_youtube_url", ["name" => trans("general.url")]));
            }
        },
    ]
</code>```

Or like below-

```<code>public function passes($attribute, $requesturl)
{
    return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$requesturl);
}

'link' => new RuleYoutube,
</code>```

Body:
I want to validate my youtube URL like this https://www.youtube.com/embed/xxxxxxxx. How to use the regex in variable link for this?

my code is like this in controller

$validatedData = $request->validate([
    'title' => 'required',
    'subtitle' => 'required|unique:news',
    'category' => 'required',
    'link' => 'required|regex:??',
    'image1' => 'required|image',
    'image2' => 'image',
    'image3' => 'image',
    'image4' => 'image',
    'content' => 'required'
]);

Body:
You need to add some custom validation logic for achieving this .Hope this code snippet can help you-

'link' => [
        'required',
        'url',
        function ($attribute, $requesturl, $failed) {
            if (!preg_match('/(youtube.com|youtu.be)\/(embed)?(\?v=)?(\S+)?/', $requesturl)) {
                $failed(trans("general.not_youtube_url", ["name" => trans("general.url")]));
            }
        },
    ]

Or like below-

public function passes($attribute, $requesturl)
{
    return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$requesturl);
}

'link' => new RuleYoutube,


问:
Removing URL parameters with Javascript - my solution works, except in some fringe cases and I'm unsure how to fix?
In a nutshell, I have some Javascript I use to remove parameters from the URL. It looks like:

```<code>//Define variable
var objQueryString={};

//Get querystring value
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

//Function used to remove querystring
function removeQString(key) {

    // ignore this bit, I was just playing around with looping multiple times
    for(i=0; i<5; i++) {

    var urlValue=document.location.href;

    //Get query string value
    var searchUrl=location.search;

    if(key!="") {
        oldValue = getParameterByName(key);
        removeVal=key+"="+oldValue;
        if(searchUrl.indexOf('?'+removeVal+'&')!= "-1") {
            urlValue=urlValue.replace('?'+removeVal+'&','?');
        }
        else if(searchUrl.indexOf('&'+removeVal+'&')!= "-1") {
            urlValue=urlValue.replace('&'+removeVal+'&','&');
        }
        else if(searchUrl.indexOf('?'+removeVal)!= "-1") {
            urlValue=urlValue.replace('?'+removeVal,'');
        }
        else if(searchUrl.indexOf('&'+removeVal)!= "-1") {
            urlValue=urlValue.replace('&'+removeVal,'');
        }
    }
    else {
        var searchUrl=location.search;
        urlValue=urlValue.replace(searchUrl,'');
    }
    history.pushState({state:1, rand: Math.random()}, '', urlValue);
}
location.reload();
}
</code>```

I can trigger it using something like:

```<code><a href="#" onClick="removeQString('budget')">
</code>```

This works absolutely fine, except when a URL parameter carries certain encoding. Eg, a date/time variable might look like:

```<code>?expdate=2022-02-13T11%3A25
</code>```

In the above case, the script can't identify and remove and I am unsure how to fix? Can anyone point me in the right direction?

答:
As someone suggested, I have moved away from this rather clunky solution to simply using URLSearchParams. I'd avoided this for IE compatability, but it's too much of a pain to retain.

Using the following now instead:

```<code>function removeParam(key) {
    let url = new URL(window.location.href);
    let params = new URLSearchParams(url.search);

    params.delete(key);
    newURL = location.protocol + '//' + location.host + location.pathname + '?' + params;
    window.location.replace(newURL);
}
</code>```

Body:
In a nutshell, I have some Javascript I use to remove parameters from the URL. It looks like:

//Define variable
var objQueryString={};

//Get querystring value
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

//Function used to remove querystring
function removeQString(key) {

    // ignore this bit, I was just playing around with looping multiple times
    for(i=0; i<5; i++) {

    var urlValue=document.location.href;

    //Get query string value
    var searchUrl=location.search;

    if(key!="") {
        oldValue = getParameterByName(key);
        removeVal=key+"="+oldValue;
        if(searchUrl.indexOf('?'+removeVal+'&')!= "-1") {
            urlValue=urlValue.replace('?'+removeVal+'&','?');
        }
        else if(searchUrl.indexOf('&'+removeVal+'&')!= "-1") {
            urlValue=urlValue.replace('&'+removeVal+'&','&');
        }
        else if(searchUrl.indexOf('?'+removeVal)!= "-1") {
            urlValue=urlValue.replace('?'+removeVal,'');
        }
        else if(searchUrl.indexOf('&'+removeVal)!= "-1") {
            urlValue=urlValue.replace('&'+removeVal,'');
        }
    }
    else {
        var searchUrl=location.search;
        urlValue=urlValue.replace(searchUrl,'');
    }
    history.pushState({state:1, rand: Math.random()}, '', urlValue);
}
location.reload();
}

I can trigger it using something like:

This works absolutely fine, except when a URL parameter carries certain encoding. Eg, a date/time variable might look like:

?expdate=2022-02-13T11%3A25

In the above case, the script can't identify and remove and I am unsure how to fix? Can anyone point me in the right direction?

Body:
As someone suggested, I have moved away from this rather clunky solution to simply using URLSearchParams. I'd avoided this for IE compatability, but it's too much of a pain to retain.

Using the following now instead:

function removeParam(key) {
    let url = new URL(window.location.href);
    let params = new URLSearchParams(url.search);

    params.delete(key);
    newURL = location.protocol + '//' + location.host + location.pathname + '?' + params;
    window.location.replace(newURL);
}


问:
How might I get the script filename from within that script?
I'm pretty sure the answer is no, but thought I'd ask anyway.

If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:

```<code>var scriptName = ???

if (typeof jQuery !== "function") {
    throw new Error(
        "jQuery's script needs to be loaded before " +
        scriptName + ". Check the <script> tag order.");
}
</code>```

Probably more trouble than it's worth for dependency checking, but what the hell.

答:
```<code>var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);
</code>```

Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6

See also: How may I reference the script tag that loaded the currently-executing script?

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I'm pretty sure the answer is no, but thought I'd ask anyway.

If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:

var scriptName = ???

if (typeof jQuery !== "function") {
    throw new Error(
        "jQuery's script needs to be loaded before " +
        scriptName + ". Check the

Body:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);

Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6

See also: How may I reference the script tag that loaded the currently-executing script?


问:
How to check a child value in firebase and hide a button for that user logged in?
I want to hide a Button in my app when the user that is logged in has a specified value in the Realtime Firebase Database.

So I have a child where the value changes between Yes or No it depends on what rights the user is having. So I want to hide a Button when a user has the value No and when the user has the value Yes, it will be available.

My Firebase database structure is like this: (the child "hasusersstorage" is the Yes or No (Ja/Nei)
Firebase structure

Here is the code I've tried but not managed to get it to work.
The currentUser is working, because I use this to setText with a username that is logged in.

```<code>databaseUsers.child(currentUser).child("hasuserstorage").equalTo("Nei").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {

                if (dataSnapshot.hasChild("hasuserstorage")) {

                    bttoaddtool.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

Hope someone can help me out.

答:
I want to hide a Button in my app when the user that is logged in has a specified value in the Firebase database.

If you want to achieve that, then you should create a reference that points exactly to the hasuserstorage field.

When you are using the following code query:

```<code>databaseUsers.child(currentUser).child("hasuserstorage").equalTo("Nei");
</code>```

It doesn't mean that you are checking if the hasuserstorage field of the logged-in user holds the value of Nei. Assuming that Ansatte is a direct child of your root node, to solve this, please use the following lines of code:

```<code>String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference hasUserStorageRef = db.child("Ansatte").child(uid).child("hasuserstorage");
hasUserStorageRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            if(snapshot.exists()) {
                String hasuserstorage = snapshot.getValue(String.class);
                if(hasuserstorage.equals("Ja")) {
                    Log.d("TAG", "hasuserstorage is Ja");
                    bttoaddtool.setVisibility(View.VISIBLE);
                } else if(hasuserstorage.equals("Nei")) {
                    Log.d("TAG", "hasuserstorage is Nei");
                    bttoaddtool.setVisibility(View.GONE);
                }
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});
</code>```

The above code will hide the button if the hasuserstorage will hold the value of Nei, otherwise it will display it.

Body:
I want to hide a Button in my app when the user that is logged in has a specified value in the Realtime Firebase Database.

So I have a child where the value changes between Yes or No it depends on what rights the user is having. So I want to hide a Button when a user has the value No and when the user has the value Yes, it will be available.

My Firebase database structure is like this: (the child "hasusersstorage" is the Yes or No (Ja/Nei)
Firebase structure

Here is the code I've tried but not managed to get it to work.
The currentUser is working, because I use this to setText with a username that is logged in.

databaseUsers.child(currentUser).child("hasuserstorage").equalTo("Nei").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {

                if (dataSnapshot.hasChild("hasuserstorage")) {

                    bttoaddtool.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Hope someone can help me out.

Body:
I want to hide a Button in my app when the user that is logged in has a specified value in the Firebase database.

If you want to achieve that, then you should create a reference that points exactly to the hasuserstorage field.

When you are using the following code query:

databaseUsers.child(currentUser).child("hasuserstorage").equalTo("Nei");

It doesn't mean that you are checking if the hasuserstorage field of the logged-in user holds the value of Nei. Assuming that Ansatte is a direct child of your root node, to solve this, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference hasUserStorageRef = db.child("Ansatte").child(uid).child("hasuserstorage");
hasUserStorageRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            if(snapshot.exists()) {
                String hasuserstorage = snapshot.getValue(String.class);
                if(hasuserstorage.equals("Ja")) {
                    Log.d("TAG", "hasuserstorage is Ja");
                    bttoaddtool.setVisibility(View.VISIBLE);
                } else if(hasuserstorage.equals("Nei")) {
                    Log.d("TAG", "hasuserstorage is Nei");
                    bttoaddtool.setVisibility(View.GONE);
                }
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The above code will hide the button if the hasuserstorage will hold the value of Nei, otherwise it will display it.


问:
Python naming conventions for interfaces and abstract classes?
What is the convention for naming interfaces and abstract classes in Python? PEP 8 doesn't discuss this. For example, in Java, interfaces are often named with an I prefix. In PHP (prior to namespaces), abstract classes are typically named with an _Abstract suffix.

(I realize that Pythonists are not keen on interfaces, and perhaps this is the reason why I can't find much consensus on this topic. But the usage of interfaces and abstract classes is not my question.)

答:
TL;DR

If you don't care about type hints, name them whatever you like. Otherwise, ABCs are your API for other developers. Their names should be clean without any clutter. The concrete implementation should tell you why it is special.

Call your abstract class User and the implementing classes ServerUser and LocalUser

Why would we need such a convention in the first place?

The first one should ask themselves is, why would we care about naming of classes?

In statically typed languages (which python is not), the names of your Interfaces represent an API through which other developers interact with your code. So the caller of a function should quickly understand the meaning of parameters and return types. An example from Java (where prefixing Interfaces has fallen out of fashion some time ago..) would be:

public void signupUsers(Collection<User> users) {
    // TODO: do something with users
}
```
<p>Here we want the name to be as pure as possible. We accept any <code>Collection</code> and any <code>User</code>. It might be an <code>ArrayList</code>, <code>HashSet</code>, <code>LocalUser</code> or a <code>ServerUser</code>, we don't care.</p>
<h2>Why is there no such standard in Python?</h2>
<p>This was not relevant in python, since it is a dynamically typed language. In the following code, you don't care how the classes are called:</p>
```def signup_users(users):
    pass  # TODO: do something with users
```
<p>The name would have only been relevant when creating a class and checking its type, which are not common enough to justify a full blown naming convention</p>
<h2>Why would someone care about naming of classes in Python nowadays?</h2>
<p>But things are changing, because of the introduction of the typing module. You can now explicitly state types. If we want to embrace this new feature, we should consider the naming of our classes.</p>
<h2>So what names should our classes get?</h2>
<p>By the same logic as to why other languages are ditching the prefixes for interfaces, I believe <code>ABC</code>s (if they play a similar role to interfaces) should  have a clean name. A name like <code>User</code> is much nicer to read than <code>IUser</code>. If you have a concrete implementation of your user, the name of that implementation should tell you what is special about it. Is it a user which data is updated with data from a server? Call it <code>ServerUser</code>. Do you store the user data locally? Call it <code>LocalUser</code>.</p>
```def signup_users(users: Iterable[User]) -> None:
    pass  # TODO: do something with users
```
<p>The "ugly" code which cares about the implementation details would look like this:</p>
```lovelace = LocalUser("Aida", "Lovelace", 1815)
babbage = ServerUser("htts://some_service.com/users/charles_babbage")
signup_users([aida, babbage])
```

This puts the burden of dealing with convoluted names on the caller who has to deal with the implementation - as it should

Body:
TL;DR

If you don't care about type hints, name them whatever you like. Otherwise, ABCs are your API for other developers. Their names should be clean without any clutter. The concrete implementation should tell you why it is special.

Call your abstract class User and the implementing classes ServerUser and LocalUser

Why would we need such a convention in the first place?

The first one should ask themselves is, why would we care about naming of classes?

In statically typed languages (which python is not), the names of your Interfaces represent an API through which other developers interact with your code. So the caller of a function should quickly understand the meaning of parameters and return types. An example from Java (where prefixing Interfaces has fallen out of fashion some time ago..) would be:

public void signupUsers(Collection<User> users) {
    // TODO: do something with users
}

Here we want the name to be as pure as possible. We accept any Collection and any User. It might be an ArrayList, HashSet, LocalUser or a ServerUser, we don't care.

Why is there no such standard in Python?

This was not relevant in python, since it is a dynamically typed language. In the following code, you don't care how the classes are called:

def signup_users(users):
    pass  # TODO: do something with users

The name would have only been relevant when creating a class and checking its type, which are not common enough to justify a full blown naming convention

Why would someone care about naming of classes in Python nowadays?

But things are changing, because of the introduction of the typing module. You can now explicitly state types. If we want to embrace this new feature, we should consider the naming of our classes.

So what names should our classes get?

By the same logic as to why other languages are ditching the prefixes for interfaces, I believe ABCs (if they play a similar role to interfaces) should  have a clean name. A name like User is much nicer to read than IUser. If you have a concrete implementation of your user, the name of that implementation should tell you what is special about it. Is it a user which data is updated with data from a server? Call it ServerUser. Do you store the user data locally? Call it LocalUser.

def signup_users(users: Iterable[User]) -> None:
    pass  # TODO: do something with users

The "ugly" code which cares about the implementation details would look like this:

lovelace = LocalUser("Aida", "Lovelace", 1815)
babbage = ServerUser("htts://some_service.com/users/charles_babbage")
signup_users([aida, babbage])

This puts the burden of dealing with convoluted names on the caller who has to deal with the implementation - as it should


答:
Your whole approach seems to be a bit overcomplicated to me. Why not just split the search string by & and then filter out the value that starts with the specific key?

function removeKey(key, querystring) {
  if (querystring.length <= 1) return ""; //or whatever to do if no parameters are present
  querystring = querystring.substring(1); //remove the initial '?'
  var
    queryarray = querystring.split("&"); //split into parameters
  if (key) {
    queryarray = queryarray.filter(function(x) {
      //remove all elements which start with "key="
      return x.indexOf(key+"=") != 0;
    });
  }
  else {
     //do whatever necessary if no key is given
  }

  //join the query back together  (or return an empty string if no parameters left
  return queryarray.length
    ? "?" + queryarray.join("&")
    : "";
}

console.log("1", removeKey("q1", "?q1=abc&q2=xyz&q3=123&q4=blubb%234%xyz"))
console.log("2", removeKey("q1", "?q1=abc"))
console.log("3", removeKey("q1", "?"))
console.log("4", removeKey("q1", ""))```

Title: Removing URL parameters with Javascript - my solution works, except in some fringe cases and I'm unsure how to fix?


问:
chrome.tabs.executeScript not working?
I am trying to learn to use the chrome.tabs.executeScript commend. I've created a simple extension with a browser action. My background.html file currently looks like this:

```

The "content_script.js" file contains document.body.bgColor='red'.

When pushing the browser action's button nothing happens. Obviously I'm missing something very basic.

I've checked with console.log that indeed control reaches the chrome.tabs.executeScript calls when the browser action is pressed. Otherwise I'm not sure how to even check if my content script's code is run (it seems not; console.log I put in the content script has no effect, but maybe it shouldn't have one even if the script is run successfully).

答:
Most of the answers above seems to be working fine for manifest version 2 but when it comes manifest-3 their seems to be some workaround to make the content-script load in the latest manifest 3.We need to use the following steps to execute content script in manifest 3

First adding permission "scripting" in manifest

```<code>"permissions": [
"storage",
"tabs",
"activeTab",
"scripting"
</code>```

]

Once the scripting perimission is provided, we can use the scripting api like below

In background.js,

```<code> chrome.tabs.query({}, (tabList) => {
    if (!tabList.length) return;
    tabList.forEach((tab) => {
      chrome.scripting.executeScript(
        {
          files: ['contentScript.js'],
          target: {
            tabId: tab.id,
            allFrames: true
          }
        }
      );
   });
});
</code>```

In the above code we are executing the contentScript for all the available tabs in tab browser.

Title: chrome.tabs.executeScript not working?

Body:
I am trying to learn to use the chrome.tabs.executeScript commend. I've created a simple extension with a browser action. My background.html file currently looks like this:

The "content_script.js" file contains document.body.bgColor='red'.

When pushing the browser action's button nothing happens. Obviously I'm missing something very basic.

I've checked with console.log that indeed control reaches the chrome.tabs.executeScript calls when the browser action is pressed. Otherwise I'm not sure how to even check if my content script's code is run (it seems not; console.log I put in the content script has no effect, but maybe it shouldn't have one even if the script is run successfully).

Body:
Most of the answers above seems to be working fine for manifest version 2 but when it comes manifest-3 their seems to be some workaround to make the content-script load in the latest manifest 3.We need to use the following steps to execute content script in manifest 3

First adding permission "scripting" in manifest

"permissions": [
"storage",
"tabs",
"activeTab",
"scripting"

]

Once the scripting perimission is provided, we can use the scripting api like below

In background.js,

 chrome.tabs.query({}, (tabList) => {
    if (!tabList.length) return;
    tabList.forEach((tab) => {
      chrome.scripting.executeScript(
        {
          files: ['contentScript.js'],
          target: {
            tabId: tab.id,
            allFrames: true
          }
        }
      );
   });
});

In the above code we are executing the contentScript for all the available tabs in tab browser.


问:
Charts in Oracle Apex
Hi everyone I wanna ask u about how I can bring data last 24 hours into bar charts, is there any   methods to make it please
I have this table without data

datetime
clientchannel
servicename
service_count

13_02_2022 9:35
*****
notification
2

答:
It is a WHERE clause you need, I presume. Something like this:

```<code>select ...
from your_table
where datetime >= sysdate - 1;
</code>```

Why? Because - when you subtract a number from DATE datatype value in Oracle - it subtracts that many days.

```<code>SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select sysdate right_now,
  2         sysdate - 1 yesterday
  3  from dual;

RIGHT_NOW           YESTERDAY
------------------- -------------------
13.02.2022 11:01:34 12.02.2022 11:01:34

SQL>
</code>```

If you store date values as strings (which means that DATETIME column is declared as e.g. VARCHAR2(20), and that's really bad idea), then you first have to convert it to a valid date datatype value - use TO_DATE function with appropriate format mask:

```<code>where to_date(datetime, 'dd_mm_yyyy hh24:mi') >= sysdate - 1
</code>```

[EDIT] If you want to go 60 minutes back, then subtract that many minutes:

```<code>SQL> select sysdate right_now,
  2         sysdate - interval '60' minute an_hour_ago
  3  from dual;

RIGHT_NOW           AN_HOUR_AGO
------------------- -------------------
14.02.2022 07:09:30 14.02.2022 06:09:30

SQL>
</code>```

Title: Charts in Oracle Apex

Body:
It is a WHERE clause you need, I presume. Something like this:

select ...
from your_table
where datetime >= sysdate - 1;

Why? Because - when you subtract a number from DATE datatype value in Oracle - it subtracts that many days.

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select sysdate right_now,
  2         sysdate - 1 yesterday
  3  from dual;

RIGHT_NOW           YESTERDAY
------------------- -------------------
13.02.2022 11:01:34 12.02.2022 11:01:34

SQL>

If you store date values as strings (which means that DATETIME column is declared as e.g. VARCHAR2(20), and that's really bad idea), then you first have to convert it to a valid date datatype value - use TO_DATE function with appropriate format mask:

where to_date(datetime, 'dd_mm_yyyy hh24:mi') >= sysdate - 1

[EDIT] If you want to go 60 minutes back, then subtract that many minutes:

SQL> select sysdate right_now,
  2         sysdate - interval '60' minute an_hour_ago
  3  from dual;

RIGHT_NOW           AN_HOUR_AGO
------------------- -------------------
14.02.2022 07:09:30 14.02.2022 06:09:30

SQL>


问:
Convert CURL to Swift
I need to convert the following curl call of Microsoft Azure Cloud to Swift:

```<code>curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"
</code>```

I need to convert a JSON call of curl to Swift. The problem is I have no experience with JSON calls and don't know how to include headers, a body and parameters.
So I tried the following code:

```<code>
let apiKey = "..."
let location = "..."

class AzureManager {

    static let shared = AzureManager()

    func makeRequest(json: [String: Any], completion: @escaping (String)->()) {

        guard let url = URL(string: "https://api.cognitive.microsofttranslator.com/translate"),
              let payload = try? JSONSerialization.data(withJSONObject: json) else {
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue(apiKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
        request.addValue(location, forHTTPHeaderField: "Ocp-Apim-Subscription-Region")
        request.addValue("application/json", forHTTPHeaderField: "Content-type")
        request.addValue("NaiVVl3DEFG3jdE5DE1NFAA6EABC", forHTTPHeaderField: "X-ClientTraceId")
        request.httpBody = payload

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else { completion("Error::\(String(describing: error?.localizedDescription))"); return }
            guard let data = data else { completion("Error::Empty data"); return }

            let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]

            if let json = json,
               let choices = json["translations"] as? [String: Any],
               let str = choices["text"] as? String {
                completion (str)
            } else {
                completion("Error::nothing returned")
            }

        }.resume()
    }
}
</code>```

And then call it like this:

```<code>let jsonPayload = [
           "api-version": "3.0",
           "from": "en",
           "to": "it",
           "text": "Hello"
           ] as [String : Any]

AzureManager.shared.makeRequest(json: jsonPayload) { [weak self] (str) in
     DispatchQueue.main.async {
           print(str)
     }
}
</code>```

Well, the errors I get are:

```<code>    Optional(["error": {
        code = 400074;
        message = "The body of the request is not valid JSON.";
    }])
</code>```

And:

Error::nothing returned

Here are the Docs of Microsoft Azure Translator:
https://learn.microsoft.com/de-de/azure/cognitive-services/translator/reference/v3-0-translate

答:
Let's analyze your cURL command, let's make it more readable with breaking line. If you want to make it working as such in Terminal.app, just add \ at the end of the line.

```<code>curl \
-X POST \
"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn" \
-H "Ocp-Apim-Subscription-Key: <client-secret>" \
-H "Content-Type: application/json; charset=UTF-8" \
-d "[{'Text':'Hello, what is your name?'}]"
</code>```

-H: Set with addValue(_,forHTTPHeaderField:)
-d: Set it with httpBody =
The long URL, that's request.url

There are two main differences between the cURL command and the URLRequest you mode.

First, you did mix payload & URL settings.

url should be "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn", not "https://api.cognitive.microsofttranslator.com/translate", you put api-version, to, toScript (that one is missing by the way) inside httpBody.
Put them into the URL instead. You can use URLQueryItem to format them correctly. See related question.

Now, once you fix that, there is a second issue:

[{'Text':'Hello, what is your name?'}], I'll by pass the strange fact that it's using single quotes, but, here JSON is an array at top level, not a dictionary. Also, it's Text, not text (it might be case sensitive).

If you want to see what you are sending in httpBody, do not hesitate to do:

```<code>if let jsonStr = String(data: request.httpBody ?? Data(), encoding: .utf8) {
    print("Stringified httpBody: \(jsonStr)")
}
</code>```

So fix your parameters until it matches the on in the working cURL command. As said, it's an array, not a dictionary.

Finally, avoid using try?, please do proper do/try/catch because if it fails, at least you need to know about it.

No need to use .allowFragments if you don't expect a JSON String at top level. Here you are expecting a Dictionary.

And I'd recommand to use Codable now in Swift 4+ instead of JSONSerialization.

Edit: Seeing the doc, as you mixed the parameters/query, keep in mind:
"Query Parameters", that's for URLQueryItems and it's in the URL.
Request Body: That's for the httpBody.

Title: Convert CURL to Swift

Body:
I need to convert the following curl call of Microsoft Azure Cloud to Swift:

curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"

I need to convert a JSON call of curl to Swift. The problem is I have no experience with JSON calls and don't know how to include headers, a body and parameters.
So I tried the following code:

let apiKey = "..."
let location = "..."

class AzureManager {

    static let shared = AzureManager()

    func makeRequest(json: [String: Any], completion: @escaping (String)->()) {

        guard let url = URL(string: "https://api.cognitive.microsofttranslator.com/translate"),
              let payload = try? JSONSerialization.data(withJSONObject: json) else {
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue(apiKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
        request.addValue(location, forHTTPHeaderField: "Ocp-Apim-Subscription-Region")
        request.addValue("application/json", forHTTPHeaderField: "Content-type")
        request.addValue("NaiVVl3DEFG3jdE5DE1NFAA6EABC", forHTTPHeaderField: "X-ClientTraceId")
        request.httpBody = payload

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard error == nil else { completion("Error::\(String(describing: error?.localizedDescription))"); return }
            guard let data = data else { completion("Error::Empty data"); return }

            let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]

            if let json = json,
               let choices = json["translations"] as? [String: Any],
               let str = choices["text"] as? String {
                completion (str)
            } else {
                completion("Error::nothing returned")
            }

        }.resume()
    }
}

And then call it like this:

let jsonPayload = [
           "api-version": "3.0",
           "from": "en",
           "to": "it",
           "text": "Hello"
           ] as [String : Any]

AzureManager.shared.makeRequest(json: jsonPayload) { [weak self] (str) in
     DispatchQueue.main.async {
           print(str)
     }
}

Well, the errors I get are:

    Optional(["error": {
        code = 400074;
        message = "The body of the request is not valid JSON.";
    }])

And:

Error::nothing returned

Here are the Docs of Microsoft Azure Translator:
https://learn.microsoft.com/de-de/azure/cognitive-services/translator/reference/v3-0-translate

Body:
Let's analyze your cURL command, let's make it more readable with breaking line. If you want to make it working as such in Terminal.app, just add \ at the end of the line.

curl \
-X POST \
"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn" \
-H "Ocp-Apim-Subscription-Key: <client-secret>" \
-H "Content-Type: application/json; charset=UTF-8" \
-d "[{'Text':'Hello, what is your name?'}]"

-H: Set with addValue(_,forHTTPHeaderField:)
-d: Set it with httpBody =
The long URL, that's request.url

There are two main differences between the cURL command and the URLRequest you mode.

First, you did mix payload & URL settings.

url should be "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn", not "https://api.cognitive.microsofttranslator.com/translate", you put api-version, to, toScript (that one is missing by the way) inside httpBody.
Put them into the URL instead. You can use URLQueryItem to format them correctly. See related question.

Now, once you fix that, there is a second issue:

[{'Text':'Hello, what is your name?'}], I'll by pass the strange fact that it's using single quotes, but, here JSON is an array at top level, not a dictionary. Also, it's Text, not text (it might be case sensitive).

If you want to see what you are sending in httpBody, do not hesitate to do:

if let jsonStr = String(data: request.httpBody ?? Data(), encoding: .utf8) {
    print("Stringified httpBody: \(jsonStr)")
}

So fix your parameters until it matches the on in the working cURL command. As said, it's an array, not a dictionary.

Finally, avoid using try?, please do proper do/try/catch because if it fails, at least you need to know about it.

No need to use .allowFragments if you don't expect a JSON String at top level. Here you are expecting a Dictionary.

And I'd recommand to use Codable now in Swift 4+ instead of JSONSerialization.

Edit: Seeing the doc, as you mixed the parameters/query, keep in mind:
"Query Parameters", that's for URLQueryItems and it's in the URL.
Request Body: That's for the httpBody.


问:
React Native - updating UI when in a loop using functional component
I am developing a React Native app and I have a process whereby I want to put a progress center or progress bar in the UI as it runs.

I found this code in SO but I'm not sure how to implement in my functional component.

Could please give me an example of how to call ProgressBar from my func component and how to increase progress value.?

Thanks in advance.

```<code>const ProgressBar = (props)=>{

    const [value] = useState(new Animated.Value(props.value))

    useEffect(()=>{
        Animated.timing(value, {
            toValue: props.value,
            duration: 100,
        }).start()
    }, [props.value])

    const width = value.interpolate({
        inputRange: [0, 100],
        outputRange: ['0%', '100%'],
    })

    return (
        <View style={{
            width: '100%',
            height: '100%',
            flexDirection: 'row',
            backgroundColor: 'white',
        }}>
            <Animated.View style={{
                width: width,
                height: '100%',
                backgroundColor: 'green',
            }}></Animated.View>
        </View>
    )
}
</code>```

答:
Use setter to set the value

```<code>const [progress, setProgress] = useState(props.value)

useEffect(()=>{
    Animated.timing(value, {
        toValue: progress,
        duration: 100,
    }).start()
}, [progress])
</code>```

to update progress bar, call setProgress(newValue)

Body:
I am developing a React Native app and I have a process whereby I want to put a progress center or progress bar in the UI as it runs.

I found this code in SO but I'm not sure how to implement in my functional component.

Could please give me an example of how to call ProgressBar from my func component and how to increase progress value.?

Thanks in advance.

const ProgressBar = (props)=>{

    const [value] = useState(new Animated.Value(props.value))

    useEffect(()=>{
        Animated.timing(value, {
            toValue: props.value,
            duration: 100,
        }).start()
    }, [props.value])

    const width = value.interpolate({
        inputRange: [0, 100],
        outputRange: ['0%', '100%'],
    })

    return (
        <View style={{
            width: '100%',
            height: '100%',
            flexDirection: 'row',
            backgroundColor: 'white',
        }}>
            <Animated.View style={{
                width: width,
                height: '100%',
                backgroundColor: 'green',
            }}></Animated.View>
        </View>
    )
}

Body:
Use setter to set the value

const [progress, setProgress] = useState(props.value)

useEffect(()=>{
    Animated.timing(value, {
        toValue: progress,
        duration: 100,
    }).start()
}, [progress])

to update progress bar, call setProgress(newValue)


问:
When to use JFace ComboViewer instead of combo?
In my application I need two combo boxes, the content of second one depends on the current selection of first combo. Should I use JFace ComboViewer for this? or shall I directly use combo?

If I use JFace ComboViewer what flexibility I'll get? or how JFace ComboViewer is better than Combo?

For more clarity, I have to use only strings for my combo.

Thanks in advance!!!

答: Combo is just the widget, ComboViewer wraps that so you use a model other than just strings.  You rarely want to create and interact with plain widgets directly.</p>


答:
You do unnecessary work here. You already capturing some data with regexp, just finish the job with it. It is still naive and will fail on data deliberately encoded to avoid it, but otherwise works with same limitations as your initial key parser - in fact I just copypasted most of code from you.</p>
```<code>function removeQString(query, key) {
    key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("([?&])" + key + "=([^&#]*)")
    return query.replace(regex, '').replace(/^&/, '?')
}

console.log(removeQString('?expdate=2022-02-13T11%3A25&whatever=123', 'expdate'))
// ?whatever=123
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'q'))
// ?oq=url+query+examples&sourceid=chrome&ie=UTF-8
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'oq'))
// ?q=url+query+examples&sourceid=chrome&ie=UTF-8
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'ie'))
// ?q=url+query+examples&oq=url+query+examples&sourceid=chrome
</code>```

Body:
You do unnecessary work here. You already capturing some data with regexp, just finish the job with it. It is still naive and will fail on data deliberately encoded to avoid it, but otherwise works with same limitations as your initial key parser - in fact I just copypasted most of code from you.

function removeQString(query, key) {
    key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("([?&])" + key + "=([^&#]*)")
    return query.replace(regex, '').replace(/^&/, '?')
}

console.log(removeQString('?expdate=2022-02-13T11%3A25&whatever=123', 'expdate'))
// ?whatever=123
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'q'))
// ?oq=url+query+examples&sourceid=chrome&ie=UTF-8
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'oq'))
// ?q=url+query+examples&sourceid=chrome&ie=UTF-8
console.log(removeQString('?q=url+query+examples&oq=url+query+examples&sourceid=chrome&ie=UTF-8', 'ie'))
// ?q=url+query+examples&oq=url+query+examples&sourceid=chrome


问:
How do I pass arguments to Manim Community via command line?
Manim Renders scene(s) to an output file with,

```<code>manim [OPTIONS] FILE [SCENES]
</code>```

I didn't find a way to pass arguments to Manim Community after checking A list of all CLI flags.

How can I pass arguments to Manim Community via the command line? Or further, is there a way to run a manim class without using command line?

答:
I'm not sure I fully understand your first question regarding arguments -- do you mean custom arguments? We don't have support for that yet.

However, you can definitely render scenes from your Python script directly by using a snippet like this:

```<code>with tempconfig({"quality": "medium_quality", "preview": True}):
    scene = YourSceneClass()
    scene.render()
</code>```

This is also useful for debugging Manim scenes.

Body:
Manim Renders scene(s) to an output file with,

manim [OPTIONS] FILE [SCENES]

I didn't find a way to pass arguments to Manim Community after checking A list of all CLI flags.

How can I pass arguments to Manim Community via the command line? Or further, is there a way to run a manim class without using command line?

Body:
I'm not sure I fully understand your first question regarding arguments -- do you mean custom arguments? We don't have support for that yet.

However, you can definitely render scenes from your Python script directly by using a snippet like this:

with tempconfig({"quality": "medium_quality", "preview": True}):
    scene = YourSceneClass()
    scene.render()

This is also useful for debugging Manim scenes.