问:
I can't run DataTable in VSCode
I'm having some errors using a table using DataTable in Visual Studio Code.

The errors have been commented out in the code for clarity on each line where they result.

I state that I have not installed any extensions in VSCode. Is this possibly necessary to use DataTable and Bootstrap?

On codepen or on JSFiddle the code works correctly.

$(document).ready(function() {
  $("#example").DataTable();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dataTables_length,
.dataTables_wrapper {
    font-size: 1.6rem;

    select,
    input {
        background-color: #f9f9f9; /*semi-colon expected*/
        border: 1px solid #999; /*{ expected*/
        border-radius: 4px; /* { expected*/
        height: 3rem; /*{ expected*/
        line-height: 2; /*{ expected*/
        font-size: 1.8rem;/*{ expected*/
        color: #333;
    }

    .dataTables_length,
    .dataTables_filter {
        margin-top: 30px;
        margin-right: 20px;
        margin-bottom: 10px;
        display: inline-flex;
    }
}</code>```

          Name
          Position
          Office
          Age
          Start date
          Salary

          Name
          Position
          Office
          Age
          Start date
          Salary

          Tiger Nixon
          System Architect
          Edinburgh
          61
          2011/04/25
          $320,800

          Garrett Winters
          Accountant
          Tokyo
          63
          2011/07/25
          $170,750

```

答:
This has nothing to do with DataTables. You are trying to use sass in your CSS page and vscode doesn't recognize sass by default. To solve this

You can either install a sass compiler extension in vscode to compile your sass code to regular CSS or you can convert the sass code to regular CSS. Try this

$(document).ready(function() {
  $("#example").DataTable();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Add this to the head -->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css" />
<script src="//cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>

<div class="container">
  <div class="row">
    <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
      <thead>
        <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Tiger Nixon</td>
          <td>System Architect</td>
          <td>Edinburgh</td>
          <td>61</td>
          <td>2011/04/25</td>
          <td>$320,800</td>
        </tr>
        <tr>
          <td>Garrett Winters</td>
          <td>Accountant</td>
          <td>Tokyo</td>
          <td>63</td>
          <td>2011/07/25</td>
          <td>$170,750</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </tfoot>
    </table>
  </div>
</div></code>```

Title: I can't run DataTable in VSCode

Body:
I'm having some errors using a table using DataTable in Visual Studio Code.

The errors have been commented out in the code for clarity on each line where they result.

I state that I have not installed any extensions in VSCode. Is this possibly necessary to use DataTable and Bootstrap?

On codepen or on JSFiddle the code works correctly.

$(document).ready(function() {
  $("#example").DataTable();
});

.dataTables_length,
.dataTables_wrapper {
    font-size: 1.6rem;

    select,
    input {
        background-color: #f9f9f9; /*semi-colon expected*/
        border: 1px solid #999; /*{ expected*/
        border-radius: 4px; /* { expected*/
        height: 3rem; /*{ expected*/
        line-height: 2; /*{ expected*/
        font-size: 1.8rem;/*{ expected*/
        color: #333;
    }

    .dataTables_length,
    .dataTables_filter {
        margin-top: 30px;
        margin-right: 20px;
        margin-bottom: 10px;
        display: inline-flex;
    }
}

          Name
          Position
          Office
          Age
          Start date
          Salary

          Name
          Position
          Office
          Age
          Start date
          Salary

          Tiger Nixon
          System Architect
          Edinburgh
          61
          2011/04/25
          $320,800

          Garrett Winters
          Accountant
          Tokyo
          63
          2011/07/25
          $170,750

Body:
This has nothing to do with DataTables. You are trying to use sass in your CSS page and vscode doesn't recognize sass by default. To solve this

You can either install a sass compiler extension in vscode to compile your sass code to regular CSS or you can convert the sass code to regular CSS. Try this

$(document).ready(function() {
  $("#example").DataTable();
});

<!-- Add this to the head -->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css" />
<script src="//cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>

<div class="container">
  <div class="row">
    <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
      <thead>
        <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Tiger Nixon</td>
          <td>System Architect</td>
          <td>Edinburgh</td>
          <td>61</td>
          <td>2011/04/25</td>
          <td>$320,800</td>
        </tr>
        <tr>
          <td>Garrett Winters</td>
          <td>Accountant</td>
          <td>Tokyo</td>
          <td>63</td>
          <td>2011/07/25</td>
          <td>$170,750</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </tfoot>
    </table>
  </div>
</div>


来源: stackexchange

问:
Annoying Blue Color for Button in HTML
Screen shot of problem
I am trying to get rid of this annoying blue color in my Bootstrap button supported with Bootstrap. First, there was an underline with blue color, but when add text-decoration: none underline is cleared but still blue color.

      <button type="button" class="btn btn-outline-dark">
            Instagram
          </button>```

But I still have the blue color as in the screenshot. I have tried variations using span but that does not help either. Am I doing something wrong above?

Thank you in advance.

答: You can apply class="btn btn-outline-dark" to the  tag itself, removing the <button> altogether. Bootstrap's documentation includes an example with .

ContentLicense: CC BY-SA 4.0

Title: Annoying Blue Color for Button in HTML

Body:
Screen shot of problem
I am trying to get rid of this annoying blue color in my Bootstrap button supported with Bootstrap. First, there was an underline with blue color, but when add text-decoration: none underline is cleared but still blue color.

      <button type="button" class="btn btn-outline-dark">
            Instagram
          </button>

But I still have the blue color as in the screenshot. I have tried variations using span but that does not help either. Am I doing something wrong above?

Thank you in advance.

Body: You can apply class="btn btn-outline-dark" to the <a> tag itself, removing the <button> altogether. Bootstrap's documentation includes an example with <a>.


问:
Find all permutations code Problem (Java)
I wrote this code to find all possible permutations of some numbers. But i dosen't want to use one digit twice:

123,132,213 are OK, but it produces numbers like 122, 121 etc.

What am i doing wrong?

```<code>import java.util.HashSet;

public class main {

public static void main(String[] args) {

    HashSet<Integer> l = new HashSet<Integer>();
    for(int i=0;i<=3;i++){
        l.add(i);
    }
    perm(l,3,new StringBuffer());

}

 static void perm(HashSet<Integer> in, int depth,StringBuffer out){
    if(depth==0){
        System.out.println(out);
        return;
    }

    int len = in.size();
    HashSet<Integer> tmp = in;

    for(int i=0;i<len;i++){
        out.append(in.toArray()[i]);
        tmp.remove(i);

        perm(tmp,depth-1,out);

        out.deleteCharAt(out.length()-1);
        tmp.add(i);
    }
}
}
</code>```

答: tmp.remove(i) is wrong. You need to remove the ith element from tmp... you are removing the element "i". So, do tmp.remove(in.toArray()[i]). I think that will fix this up. For instance, if the zeroth element is 17, doing tmp.remove(i) will remove all zeroes from the HashSet, not "17".

ContentLicense: CC BY-SA 3.0

Body:
I wrote this code to find all possible permutations of some numbers. But i dosen't want to use one digit twice:

123,132,213 are OK, but it produces numbers like 122, 121 etc.

What am i doing wrong?

import java.util.HashSet;

public class main {

public static void main(String[] args) {

    HashSet<Integer> l = new HashSet<Integer>();
    for(int i=0;i<=3;i++){
        l.add(i);
    }
    perm(l,3,new StringBuffer());

}

 static void perm(HashSet<Integer> in, int depth,StringBuffer out){
    if(depth==0){
        System.out.println(out);
        return;
    }

    int len = in.size();
    HashSet<Integer> tmp = in;

    for(int i=0;i<len;i++){
        out.append(in.toArray()[i]);
        tmp.remove(i);

        perm(tmp,depth-1,out);

        out.deleteCharAt(out.length()-1);
        tmp.add(i);
    }
}
}


问:
getting out a variable from an async function, to another Python script
I'm more a beginner in python. Tried to find answers in the internet. But some things i really don't understand. Maybe here someone can help please.
I want to read out telegram messages and send them to another script. I use telethon. Actually i can print the messages. But i can't get access to variables inside the async function.
Tried different ways... Another function wrapping the async, global variable, return... nothing worked. Maybe i used the wrong syntax... But i can't find an nearly identical example anywhere.
I want to create some kind of automation, by telegram for an art project and want to send different variables from the message to different scripts and then run these scripts. Thanks in advance for your help!</p>
```<code>import configparser
from telethon import TelegramClient, events
import subprocess

config = configparser.ConfigParser()
config.read("config.ini")

# Setting configuration values
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']

api_hash = str(api_hash)

phone = config['Telegram']['phone']
username = config['Telegram']['username']

# Create the client and connect
client = TelegramClient(username, api_id, api_hash)

client.start()

@client.on(events.NewMessage(chats=['https://t.me/test238728']))
async def my_event_handler(msg):
    x = msg.raw_text
    return x

print(x)

client.run_until_disconnected()
</code>```

答:
Got the way to do the return by wrapping into another async function. Now i understand 'return'. Thats not what i need because it exits the function after execution. Also it tells me: Class 'TelegramClient' does not define 'await'. I need 'client.run_until_disconnected()'. I want the function keep running and updates the "global variable" every time a new message arrives.
I think the way to go, are generators and yield function... but i don' find the correct syntax to get it working. Looking forward for any help.</p>
```<code>import configparser
from telethon import TelegramClient, events
import asyncio
import subprocess

config = configparser.ConfigParser()
config.read("config.ini")

# Setting configuration values
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']

api_hash = str(api_hash)

phone = config['Telegram']['phone']
username = config['Telegram']['username']

# Create the client and connect

async def get_msg_async():
    client = TelegramClient(username, api_id, api_hash)

    found = asyncio.get_event_loop().create_future()

    @client.on(events.NewMessage(chats=['https://t.me/test23289347']))
    async def newMessageListener(event):
        newmsg = event.message.message
        found.set_result(newmsg)

    await client.start()

    return await found

def get_msg():
    return asyncio.run(get_msg_async())

print(get_msg())
</code>```

Body:
I'm more a beginner in python. Tried to find answers in the internet. But some things i really don't understand. Maybe here someone can help please.
I want to read out telegram messages and send them to another script. I use telethon. Actually i can print the messages. But i can't get access to variables inside the async function.
Tried different ways... Another function wrapping the async, global variable, return... nothing worked. Maybe i used the wrong syntax... But i can't find an nearly identical example anywhere.
I want to create some kind of automation, by telegram for an art project and want to send different variables from the message to different scripts and then run these scripts. Thanks in advance for your help!

import configparser
from telethon import TelegramClient, events
import subprocess

config = configparser.ConfigParser()
config.read("config.ini")

# Setting configuration values
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']

api_hash = str(api_hash)

phone = config['Telegram']['phone']
username = config['Telegram']['username']

# Create the client and connect
client = TelegramClient(username, api_id, api_hash)

client.start()

@client.on(events.NewMessage(chats=['https://t.me/test238728']))
async def my_event_handler(msg):
    x = msg.raw_text
    return x

print(x)

client.run_until_disconnected()

Body:
Got the way to do the return by wrapping into another async function. Now i understand 'return'. Thats not what i need because it exits the function after execution. Also it tells me: Class 'TelegramClient' does not define 'await'. I need 'client.run_until_disconnected()'. I want the function keep running and updates the "global variable" every time a new message arrives.
I think the way to go, are generators and yield function... but i don' find the correct syntax to get it working. Looking forward for any help.

import configparser
from telethon import TelegramClient, events
import asyncio
import subprocess

config = configparser.ConfigParser()
config.read("config.ini")

# Setting configuration values
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']

api_hash = str(api_hash)

phone = config['Telegram']['phone']
username = config['Telegram']['username']

# Create the client and connect

async def get_msg_async():
    client = TelegramClient(username, api_id, api_hash)

    found = asyncio.get_event_loop().create_future()

    @client.on(events.NewMessage(chats=['https://t.me/test23289347']))
    async def newMessageListener(event):
        newmsg = event.message.message
        found.set_result(newmsg)

    await client.start()

    return await found

def get_msg():
    return asyncio.run(get_msg_async())

print(get_msg())


问:
Sorting a vector of pairs by first element in ascending order, and if equal, sort second element by descending order
I have a vector of pair I want to sort.
I want to sort by first element in ascending order, and if the first element is equal, I want to sort it by descending order of the second element.

Example:

```<code>3 2
1 9
0 4
3 3
</code>```

When sorted, it has to be:

```<code>0 4
1 9
3 3
3 2
</code>```

Is there any way I could achieve this in c++?

答:
Like the guys in comments said, std::sort should work fine with some lambda. Something like this I guess:</p>
```<code>std::vector<std::pair<int, int>> vec{
    {3, 2},
    {1, 9},
    {0, 4},
    {3, 3}
};

std::sort(vec.begin(), vec.end(), [](const auto& l, const auto& r){
    return (l.first == r.first) ? l.second > r.second : l.first < r.first;
});
</code>```

Body:
I have a vector of pair I want to sort.
I want to sort by first element in ascending order, and if the first element is equal, I want to sort it by descending order of the second element.

Example:

3 2
1 9
0 4
3 3

When sorted, it has to be:

0 4
1 9
3 3
3 2

Is there any way I could achieve this in c++?

Body:
Like the guys in comments said, std::sort should work fine with some lambda. Something like this I guess:

std::vector<std::pair<int, int>> vec{
    {3, 2},
    {1, 9},
    {0, 4},
    {3, 3}
};

std::sort(vec.begin(), vec.end(), [](const auto& l, const auto& r){
    return (l.first == r.first) ? l.second > r.second : l.first < r.first;
});


问:
How can I convert human time strings into milliseconds?
Here's what I've tried from this question's's accepted answer

const timeString = '1h 30m 1s'
const milliseconds  = timeString.match(/\d+/g)
       .reduce((acc, cur, idx) => acc + cur * (Math.pow(60, (2 - idx))) * 1000, 0)
console.log(milliseconds)
// result: 5401000
// expected result: 5401000
```
<p>But, here's the problem, if I only put <code>1m</code> for instance, expected output should be 60000 milliseconds</p>
<pre class="lang-js prettyprint-override"><code>const timeString = '1m'
const milliseconds  = timeString.match(/\d+/g)
       .reduce((acc, cur, idx) => acc + cur * (Math.pow(60, (2 - idx))) * 1000, 0)
console.log(milliseconds)
// result: 3600000
// expected result: 60000
</code>```

It thinks that the first argument is an hour, then minute followed by second. No matter what I input. So when I put 1m, it thinks that it is an hour. It's a fixed h, m & s format and I am not able to interchange them.

The solution I want is that I should be able to interchange them parse h as hours, m for minutes, and s for seconds no matter what order and able to choose only h, m or s like

If I only output 1m, should output 1 minute only and so on

const timeString = '1m`
// should output 60000
```
<pre class="lang-js prettyprint-override"><code>const timeString = '2h 1s`
// should output 7201000
</code>```

If I interchange them, it should still output the same result since s is a second and h is an hour

const timeString = '1s 2h`
// should output 7201000
```
<pre class="lang-js prettyprint-override"><code>const timeString = '1s`
// should output 1000
</code>```

or interchange them however I want no matter what format I use, and should still output the desired result in milliseconds

const timeString = '1s 6h 2m`
// should output 21721000
```

答:
If you want something more robust try this:

```<code>const timeString = '1h 30m 1s';
const milliseconds = timeString.match(/\d+\s?\w/g)
    .reduce((acc, cur, i) => {
        var multiplier = 1000;
         switch (cur.slice(-1)) {
            case 'h':
                multiplier *= 60;
            case 'm':
                multiplier *= 60;
            case 's':
                return ((parseInt(cur)?parseInt(cur):0) * multiplier) + acc;
        }
        return acc;
    }, 0);
console.log(milliseconds);
</code>```

This can handle time strings in any order like '12s 5m 1h' and will ignore extraneous elements and even handle strings like 'in 1 hour 24 minutes and 3 seconds'.

Body:
Here's what I've tried from this question's's accepted answer

const timeString = '1h 30m 1s'
const milliseconds  = timeString.match(/\d+/g)
       .reduce((acc, cur, idx) => acc + cur * (Math.pow(60, (2 - idx))) * 1000, 0)
console.log(milliseconds)
// result: 5401000
// expected result: 5401000

But, here's the problem, if I only put 1m for instance, expected output should be 60000 milliseconds

const timeString = '1m'
const milliseconds  = timeString.match(/\d+/g)
       .reduce((acc, cur, idx) => acc + cur * (Math.pow(60, (2 - idx))) * 1000, 0)
console.log(milliseconds)
// result: 3600000
// expected result: 60000

It thinks that the first argument is an hour, then minute followed by second. No matter what I input. So when I put 1m, it thinks that it is an hour. It's a fixed h, m & s format and I am not able to interchange them.

The solution I want is that I should be able to interchange them parse h as hours, m for minutes, and s for seconds no matter what order and able to choose only h, m or s like

If I only output 1m, should output 1 minute only and so on

const timeString = '1m`
// should output 60000

const timeString = '2h 1s`
// should output 7201000

If I interchange them, it should still output the same result since s is a second and h is an hour

const timeString = '1s 2h`
// should output 7201000

const timeString = '1s`
// should output 1000

or interchange them however I want no matter what format I use, and should still output the desired result in milliseconds

const timeString = '1s 6h 2m`
// should output 21721000

Body:
If you want something more robust try this:

const timeString = '1h 30m 1s';
const milliseconds = timeString.match(/\d+\s?\w/g)
    .reduce((acc, cur, i) => {
        var multiplier = 1000;
         switch (cur.slice(-1)) {
            case 'h':
                multiplier *= 60;
            case 'm':
                multiplier *= 60;
            case 's':
                return ((parseInt(cur)?parseInt(cur):0) * multiplier) + acc;
        }
        return acc;
    }, 0);
console.log(milliseconds);

This can handle time strings in any order like '12s 5m 1h' and will ignore extraneous elements and even handle strings like 'in 1 hour 24 minutes and 3 seconds'.


问:
What characters are valid in a URL?
I'm trying to remove the non-URL part of a big string. Most of the regexes I found are like [A-Za-z0-9-_.!~*'()], but there are more things that can a url contain. Like http://127.0.0.1:8080/test?v=123#this for example

So what are the latest characters for a valid URL?

答:
All the gory details can be found in the current RFC on the topic:  RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =.  Everything else must be url-encoded.  Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

Title: What characters are valid in a URL?


问:
Unable to start the server in Django after including polls.urls in mysite/urls.py
I was creating my first view using this in Django I have included all the codes mentioned. I included the below code in ~/testsite/polls/urls.py

```<code>from django.urls import path
from . import views
urlpatterns = [
        path('', views.index, name='index'),
]
</code>```

And I added the line in ~/testsite/testsite/urls.py

```<code>path('polls/', include('polls.urls')),/home/neonreddeye/testsite/polls"""te>
The `urlpatterns` list routes URLs to views. For more information please se>    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
</code>```

When I start the server in linux using

```<code>$ python3 manage.py runserver
</code>```

This is the error I'm getting

```<code>Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 438, in check
    all_issues = checks.run_checks(
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 448, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 634, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 627, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/neonreddeye/testsite/testsite/urls.py", line 1
    /home/neonreddeye/testsite/polls"""testsite URL Configuration
    ^
SyntaxError: invalid syntax
</code>```

What Do I Do to fix this?

答:
Remove the first line in testsite/urls.py

path('polls/', include('polls.urls')),/home/neonreddeye/testsite/polls"""te>

Body:
I was creating my first view using this in Django I have included all the codes mentioned. I included the below code in ~/testsite/polls/urls.py

from django.urls import path
from . import views
urlpatterns = [
        path('', views.index, name='index'),
]

And I added the line in ~/testsite/testsite/urls.py

path('polls/', include('polls.urls')),/home/neonreddeye/testsite/polls"""te>
The `urlpatterns` list routes URLs to views. For more information please se>    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

When I start the server in linux using

$ python3 manage.py runserver

This is the error I'm getting

Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 438, in check
    all_issues = checks.run_checks(
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/usr/local/lib/python3.9/dist-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 448, in check
    for pattern in self.url_patterns:
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 634, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/usr/local/lib/python3.9/dist-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/usr/local/lib/python3.9/dist-packages/django/urls/resolvers.py", line 627, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/neonreddeye/testsite/testsite/urls.py", line 1
    /home/neonreddeye/testsite/polls"""testsite URL Configuration
    ^
SyntaxError: invalid syntax

What Do I Do to fix this?


问:
Is there a way to add an intersection to a set in python?
For example:

```<code>A=set(frozenset[x,x+1]for x in range (10))
B=set()
C=set()
Result=set()
for B in A:
      for C in A:
            if B!=C:
                 Result.add(frozenset(B.intersection(C)))
</code>```

#Error: descriptor 'intersection' for 'frozenset' objects doesn't apply to a 'types.GenericAlias' object

答:
You can just use the .intersection() method:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)
```

Body:
For example:

A=set(frozenset[x,x+1]for x in range (10))
B=set()
C=set()
Result=set()
for B in A:
      for C in A:
            if B!=C:
                 Result.add(frozenset(B.intersection(C)))

#Error: descriptor 'intersection' for 'frozenset' objects doesn't apply to a 'types.GenericAlias' object


问:
Cannot use index access type with T[Key extends keyof T]
I found myself with very often working with arrays like

```<code>[
{key1: val1, key2: value2, key3: val3},
{key1: val1, key2: value2, key3: val3},
{key1: val1, key2: value2, key3: val3}]
</code>```

where I want to transform this into a dictionary/map, e.g.

```<code>[val1FromFirstElement]: {key2: val2, key3, val3},
[val1FromSecondElement]: {key2: val2, key3, val3},
[val1ThirdElement]: {key2: val2, key3, val3}}
</code>```

Often I use a reduce, but it makes the code busy. I want to write a generic helper, where we can ensure the array we are mapping over expects the key we want to index on (in the case above, key1).

```<code>function toDictionary<T, Key extends keyof T> (array: T[], key: Key) {
  return array.reduce((prev, cur: T) => {
      return{...prev, ...{[cur[key]]: cur}};
  }, {})
}
</code>```

The problem is that [cur[key]] won't compile stating A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

I believe an index access type can only be number | string | symbol, but I don't see why I should have to specify anything else as typescript should know that a key type can only be one of these types? Right?

Hoping someone can show me where my misunderstanding is.

答:
This specific error you are getting is because T in toDictionary is unconstrained which makes Key indeterminate.  In other words, as it stands, your function would accept any type for T.

For example, try calling your function as toDictionary([3,4,5], "").  What you'll see is that the first parameter passes fine.  Why? because T[] can be any array since T is unconstrained.  The second parameter generates an error because the only keyof types for the elements in array of numbers like [3,4,5] are the prototype properties for any number, like, toString, toFixed, etc.  And, so, actually, toDictionary([3,4,5], "toString") would pass your typing just fine, even though it's not what you want.

The problem is that what you really want is T to only be types that actually have keys, like in the example you gave of {key1: val1, key2: value2, key3: val3}.  So you need to constrain T somehow.  Constraining it to be extends Record<string,any> would do the trick as now T needs to be some object indexed by strings (as in the examples you gave).  For example, this typing would work for the example you gave:

function toDictionary<T extends Record<string,any>, Key extends keyof T> (array: T[], key: Key) {
  return array.reduce((prev, cur: T) => {
      return{...prev, ...{[cur[key]]: cur}};
  }, {})
}
```

And you'll see that the contrived toDictionary([3,4,5], "toString") example above, now fails properly.

You could also be even more explicit in your constraint, for example T extends {key1:any, key2:any, key3: any} to restrict to just objects with that form.  That really depends on how you want to use it.

(FWIW, it's not clear to me what you expect the behavior to be if the array you pass has multiple items with the same value for key1.  Your current function will just overwrite any previous values with the last one in the iteration; that may not be what you want.)

Body:
I found myself with very often working with arrays like

[
{key1: val1, key2: value2, key3: val3},
{key1: val1, key2: value2, key3: val3},
{key1: val1, key2: value2, key3: val3}]

where I want to transform this into a dictionary/map, e.g.

[val1FromFirstElement]: {key2: val2, key3, val3},
[val1FromSecondElement]: {key2: val2, key3, val3},
[val1ThirdElement]: {key2: val2, key3, val3}}

Often I use a reduce, but it makes the code busy. I want to write a generic helper, where we can ensure the array we are mapping over expects the key we want to index on (in the case above, key1).

function toDictionary<T, Key extends keyof T> (array: T[], key: Key) {
  return array.reduce((prev, cur: T) => {
      return{...prev, ...{[cur[key]]: cur}};
  }, {})
}

The problem is that [cur[key]] won't compile stating A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

I believe an index access type can only be number | string | symbol, but I don't see why I should have to specify anything else as typescript should know that a key type can only be one of these types? Right?

Hoping someone can show me where my misunderstanding is.

Body:
This specific error you are getting is because T in toDictionary is unconstrained which makes Key indeterminate.  In other words, as it stands, your function would accept any type for T.

For example, try calling your function as toDictionary([3,4,5], "").  What you'll see is that the first parameter passes fine.  Why? because T[] can be any array since T is unconstrained.  The second parameter generates an error because the only keyof types for the elements in array of numbers like [3,4,5] are the prototype properties for any number, like, toString, toFixed, etc.  And, so, actually, toDictionary([3,4,5], "toString") would pass your typing just fine, even though it's not what you want.

The problem is that what you really want is T to only be types that actually have keys, like in the example you gave of {key1: val1, key2: value2, key3: val3}.  So you need to constrain T somehow.  Constraining it to be extends Record<string,any> would do the trick as now T needs to be some object indexed by strings (as in the examples you gave).  For example, this typing would work for the example you gave:

function toDictionary<T extends Record<string,any>, Key extends keyof T> (array: T[], key: Key) {
  return array.reduce((prev, cur: T) => {
      return{...prev, ...{[cur[key]]: cur}};
  }, {})
}

And you'll see that the contrived toDictionary([3,4,5], "toString") example above, now fails properly.

You could also be even more explicit in your constraint, for example T extends {key1:any, key2:any, key3: any} to restrict to just objects with that form.  That really depends on how you want to use it.

(FWIW, it's not clear to me what you expect the behavior to be if the array you pass has multiple items with the same value for key1.  Your current function will just overwrite any previous values with the last one in the iteration; that may not be what you want.)


问:
C++ how to make if statements more efficient
So i wrote a program to manipulate a file with questions and answers to a specific order so a program by the name of active presenter can read it and turn it into a quiz. I am pretty new to coding and my code is garbage. I mostly wanna reduce the size of my if statements because i wanna include every word from the alphabet in it. How would i got about doing this?

my code:

```<code>#include<iostream>
#include<fstream>
#include<string.h>
#include<stdio.h>
using namespace std;

main(){
    string mystring, input, output, anwsers, delO, pravi;
    cout<<"Vpisi ime datoteke iz katere bomo vzeli text"<<endl;
    cin>>input;
    if(input.find(".txt")!= std::string::npos){}else{input += ".txt";}
    cout<<"Vpisi ime datoteke v katero bomo dali text"<<endl;
    cin>>output;
    if(output.find(".txt")!= std::string::npos){}else{output += ".txt";}
    cout<<"Vpisi ime datoteke z odgovori"<<endl;
    cin>>anwsers;
    if(anwsers.find(".txt")!= std::string::npos){
    }else{
    anwsers += ".txt";}
    ifstream ifile (input);
    char znakn='~', znakp='=';
    ofstream ofile("delovanje.txt", ios::trunc);
    if(ifile.is_open()){
            while(ifile){
                getline(ifile,mystring);
                if(mystring.find("A-0")!= std::string::npos||
                    mystring.find("K-0")!= std::string::npos||
                    mystring.find("P-0")!= std::string::npos||
                    mystring.find("O-0")!= std::string::npos||
                    mystring.find("N-0")!= std::string::npos||
                    mystring.find("M-0")!= std::string::npos||
                    mystring.find("L-0")!= std::string::npos||
                    mystring.find("R-0")!= std::string::npos||
                    mystring.find("Z-0")!= std::string::npos){
                    string del;
                    del=mystring.substr(0,6);
                    ifstream odgovor(anwsers);
                    if(odgovor.is_open()){
                        while(odgovor){
                            getline(odgovor,delO);
                            if(delO.find(del)!=std::string::npos){
                                int anus=delO.find(del);
                                int daj=anus+9;
                                string pravilno=delO.substr(daj,1);
                                pravi="("+pravilno+")";
                            }
                        }
                    }
                }
                if(mystring.find("(1)")!= std::string::npos||
                   mystring.find("(2)")!= std::string::npos||
                   mystring.find("(3)")!= std::string::npos||
                   mystring.find("(4)")!= std::string::npos||
                   mystring.find("(5)")!= std::string::npos){
                    ofstream ofile("delovanje.txt", ios::app);
                    if(ofile.is_open()){
                        if(mystring.find("(1)")!=std::string::npos){
                            ofile<<" {";
                        }
                        if(mystring.find(pravi)!=std::string::npos){
                            ofile<<znakp<<mystring<<" ";
                        }else{
                            ofile<<znakn<<mystring<<" ";
                        }
                        }
                    }else if(mystring.find("A-0")!= std::string::npos||
                            mystring.find("K-0")!= std::string::npos||
                            mystring.find("P-0")!= std::string::npos||
                            mystring.find("O-0")!= std::string::npos||
                            mystring.find("N-0")!= std::string::npos||
                            mystring.find("M-0")!= std::string::npos||
                            mystring.find("L-0")!= std::string::npos||
                            mystring.find("R-0")!= std::string::npos||
                            mystring.find("Z-0")!= std::string::npos){
                        ofstream ofile("delovanje.txt", ios::app);
                        if(ofile.is_open()){
                            ofile<<"}"<<endl<<endl<<mystring;
                }
            cout<<mystring<<endl;
            }else{
                ofstream ofile("delovanje.txt", ios::app);
                if(ofile.is_open()){
                    ofile<<mystring<<" ";
                    cout<<mystring;
                }else{
                    ofile.open("delovanje.txt", ios::app);
                    if(ofile.is_open()){
                        ofile<<" "<<mystring<<" ";
                        cout<<mystring;
                    }
                }
            }
        }
    }
    ofile.close();
    ofstream koncnica("delovanje.txt", ios::app);
            if(koncnica.is_open()){
                cout<<"}";
            }else{
                koncnica.open("delovanje.txt", ios::app);
                if(koncnica.is_open()){
                cout<<"}";
            }
            }
    koncnica.close();
    ifstream popravljanje("delovanje.txt");
    if(popravljanje.is_open()){
        ofstream popravek(output,ios::trunc);
        while(popravljanje){
            string celota, a, b,fixed;
            int prva,druga,tretja,dolprva,doldruga,potem,ena,dva;
            getline(popravljanje,celota);
            if(celota.find("=(2)")!=std::string::npos){
                prva=celota.find("~(1)");
                druga=celota.find("=(2)");
                tretja=celota.find("~(3)");
                dolprva=druga-prva;
                doldruga=tretja-druga;
                a=celota.substr(prva,dolprva);
                b=celota.substr(druga,doldruga);
                potem=dolprva+doldruga;
                fixed=b+" "+a+" ";
                celota.replace(prva,potem,fixed);
                ena=celota.find("(1)")+1;
                dva=celota.find("(2)")+1;
                string l="2",m="1";
                int bruh=1;
                celota.replace(ena,bruh,l);
                celota.replace(dva,bruh,m);
                if(popravek.is_open()){
                    popravek<<celota<<endl;
                }else{
                    popravek.open(output,ios::app);
                    if(popravek.is_open()){
                        popravek<<celota<<endl;
                    }
                }
            }else{
                if(popravek.is_open()){
                    popravek<<celota<<endl;
                }else{
                    popravek.open(output,ios::app);
                    if(popravek.is_open()){
                        popravek<<celota<<endl;
                    }
            }
        }
    }
    }
    popravljanje.close();
    int odstrani=remove("delovanje.txt");
    if(odstrani==0){
        cout<<endl<<"delovanje.txt deleted"<<endl;
    }else{
        cout<<endl<<"delovanje.txt not deleted"<<endl;
    }
    return 0;
}
</code>```

答:
Note: I just took considered how to reduce the size of the if conditions without considering the possibility of other optimizations.

You could use the regex library to match the strings against patterns. If needed you could also add capturing groups to extract info about the position of substrings.

The following code simply checks prints output to the console depending on the patterns matched:

```<code>class StringHandler
{
public:
    void operator() (std::string const& s)
    {
        if (std::regex_search(s, m_regex1))
        {
            std::cout << "letter and number\n";
        }
        if (std::regex_search(s, m_regex2))
        {
            std::cout << "number in brackets\n";
        }
    }
private:
    std::regex m_regex1{"[AK-PRZ]-0"};
    std::regex m_regex2{"\\(\\d+\\)"};
};

int main()
{
    StringHandler h;

    std::cout << "input1\n";
    h("(200)");
    std::cout << "input2\n";
    h("foo A-0, baz (200) 42");
    std::cout << "input3\n";
    h("( 3 ) X-0");
}
</code>```

Note that matching all uppercase letters is even simpler (regex [A-Z]-0), but I restricted myself to the letters your if statement is matching right now.

Body:
So i wrote a program to manipulate a file with questions and answers to a specific order so a program by the name of active presenter can read it and turn it into a quiz. I am pretty new to coding and my code is garbage. I mostly wanna reduce the size of my if statements because i wanna include every word from the alphabet in it. How would i got about doing this?

my code:

#include<iostream>
#include<fstream>
#include<string.h>
#include<stdio.h>
using namespace std;

main(){
    string mystring, input, output, anwsers, delO, pravi;
    cout<<"Vpisi ime datoteke iz katere bomo vzeli text"<<endl;
    cin>>input;
    if(input.find(".txt")!= std::string::npos){}else{input += ".txt";}
    cout<<"Vpisi ime datoteke v katero bomo dali text"<<endl;
    cin>>output;
    if(output.find(".txt")!= std::string::npos){}else{output += ".txt";}
    cout<<"Vpisi ime datoteke z odgovori"<<endl;
    cin>>anwsers;
    if(anwsers.find(".txt")!= std::string::npos){
    }else{
    anwsers += ".txt";}
    ifstream ifile (input);
    char znakn='~', znakp='=';
    ofstream ofile("delovanje.txt", ios::trunc);
    if(ifile.is_open()){
            while(ifile){
                getline(ifile,mystring);
                if(mystring.find("A-0")!= std::string::npos||
                    mystring.find("K-0")!= std::string::npos||
                    mystring.find("P-0")!= std::string::npos||
                    mystring.find("O-0")!= std::string::npos||
                    mystring.find("N-0")!= std::string::npos||
                    mystring.find("M-0")!= std::string::npos||
                    mystring.find("L-0")!= std::string::npos||
                    mystring.find("R-0")!= std::string::npos||
                    mystring.find("Z-0")!= std::string::npos){
                    string del;
                    del=mystring.substr(0,6);
                    ifstream odgovor(anwsers);
                    if(odgovor.is_open()){
                        while(odgovor){
                            getline(odgovor,delO);
                            if(delO.find(del)!=std::string::npos){
                                int anus=delO.find(del);
                                int daj=anus+9;
                                string pravilno=delO.substr(daj,1);
                                pravi="("+pravilno+")";
                            }
                        }
                    }
                }
                if(mystring.find("(1)")!= std::string::npos||
                   mystring.find("(2)")!= std::string::npos||
                   mystring.find("(3)")!= std::string::npos||
                   mystring.find("(4)")!= std::string::npos||
                   mystring.find("(5)")!= std::string::npos){
                    ofstream ofile("delovanje.txt", ios::app);
                    if(ofile.is_open()){
                        if(mystring.find("(1)")!=std::string::npos){
                            ofile<<" {";
                        }
                        if(mystring.find(pravi)!=std::string::npos){
                            ofile<<znakp<<mystring<<" ";
                        }else{
                            ofile<<znakn<<mystring<<" ";
                        }
                        }
                    }else if(mystring.find("A-0")!= std::string::npos||
                            mystring.find("K-0")!= std::string::npos||
                            mystring.find("P-0")!= std::string::npos||
                            mystring.find("O-0")!= std::string::npos||
                            mystring.find("N-0")!= std::string::npos||
                            mystring.find("M-0")!= std::string::npos||
                            mystring.find("L-0")!= std::string::npos||
                            mystring.find("R-0")!= std::string::npos||
                            mystring.find("Z-0")!= std::string::npos){
                        ofstream ofile("delovanje.txt", ios::app);
                        if(ofile.is_open()){
                            ofile<<"}"<<endl<<endl<<mystring;
                }
            cout<<mystring<<endl;
            }else{
                ofstream ofile("delovanje.txt", ios::app);
                if(ofile.is_open()){
                    ofile<<mystring<<" ";
                    cout<<mystring;
                }else{
                    ofile.open("delovanje.txt", ios::app);
                    if(ofile.is_open()){
                        ofile<<" "<<mystring<<" ";
                        cout<<mystring;
                    }
                }
            }
        }
    }
    ofile.close();
    ofstream koncnica("delovanje.txt", ios::app);
            if(koncnica.is_open()){
                cout<<"}";
            }else{
                koncnica.open("delovanje.txt", ios::app);
                if(koncnica.is_open()){
                cout<<"}";
            }
            }
    koncnica.close();
    ifstream popravljanje("delovanje.txt");
    if(popravljanje.is_open()){
        ofstream popravek(output,ios::trunc);
        while(popravljanje){
            string celota, a, b,fixed;
            int prva,druga,tretja,dolprva,doldruga,potem,ena,dva;
            getline(popravljanje,celota);
            if(celota.find("=(2)")!=std::string::npos){
                prva=celota.find("~(1)");
                druga=celota.find("=(2)");
                tretja=celota.find("~(3)");
                dolprva=druga-prva;
                doldruga=tretja-druga;
                a=celota.substr(prva,dolprva);
                b=celota.substr(druga,doldruga);
                potem=dolprva+doldruga;
                fixed=b+" "+a+" ";
                celota.replace(prva,potem,fixed);
                ena=celota.find("(1)")+1;
                dva=celota.find("(2)")+1;
                string l="2",m="1";
                int bruh=1;
                celota.replace(ena,bruh,l);
                celota.replace(dva,bruh,m);
                if(popravek.is_open()){
                    popravek<<celota<<endl;
                }else{
                    popravek.open(output,ios::app);
                    if(popravek.is_open()){
                        popravek<<celota<<endl;
                    }
                }
            }else{
                if(popravek.is_open()){
                    popravek<<celota<<endl;
                }else{
                    popravek.open(output,ios::app);
                    if(popravek.is_open()){
                        popravek<<celota<<endl;
                    }
            }
        }
    }
    }
    popravljanje.close();
    int odstrani=remove("delovanje.txt");
    if(odstrani==0){
        cout<<endl<<"delovanje.txt deleted"<<endl;
    }else{
        cout<<endl<<"delovanje.txt not deleted"<<endl;
    }
    return 0;
}

Body:
Note: I just took considered how to reduce the size of the if conditions without considering the possibility of other optimizations.

You could use the regex library to match the strings against patterns. If needed you could also add capturing groups to extract info about the position of substrings.

The following code simply checks prints output to the console depending on the patterns matched:

class StringHandler
{
public:
    void operator() (std::string const& s)
    {
        if (std::regex_search(s, m_regex1))
        {
            std::cout << "letter and number\n";
        }
        if (std::regex_search(s, m_regex2))
        {
            std::cout << "number in brackets\n";
        }
    }
private:
    std::regex m_regex1{"[AK-PRZ]-0"};
    std::regex m_regex2{"\\(\\d+\\)"};
};

int main()
{
    StringHandler h;

    std::cout << "input1\n";
    h("(200)");
    std::cout << "input2\n";
    h("foo A-0, baz (200) 42");
    std::cout << "input3\n";
    h("( 3 ) X-0");
}

Note that matching all uppercase letters is even simpler (regex [A-Z]-0), but I restricted myself to the letters your if statement is matching right now.


问:
How to track at which point a variable gets changed?
I have a BOOL instance variable which -for some reason- some time later always reads NO even if I set it to YES (Yes, I am not so stupid to write or read the wrong variable, trust me). I spent an hour searching my whole project for any possibilities where that variable might be set to NO but can't find it.

Is there a way to trace changes of it's value, i.e. to let the debugger halt at exactly the position where the variable is about to be modified?

答:
Refactor code to make your BOOL value @property and use KVO to listen when it will be changed. In listener method you can add next line to log out call stack:</p>

```<code>NSLog(@"Stack: %@", [NSThread callStackSymbols]);
</code>```

Body:
Refactor code to make your BOOL value @property and use KVO to listen when it will be changed. In listener method you can add next line to log out call stack:

NSLog(@"Stack: %@", [NSThread callStackSymbols]);


问:
WooCommerce Rest API gives syntax error
I'm working on a side project and I've been trying to interact with the WooCommerce REST API.

I have everything seemingly correct. I've created the proper keys because they work with cURL. But when I try to utilize the php-wrapper, provided by Automattic, everything stops working.

I have the code set up exactly like they've instructed:
    require DIR . '/../vendor/autoload.php';

use Automattic\WooCommerce\Client;

```<code>$woocommerce = new Client(
    'https://mywebsitenamegoeshere.com',
    '##########',
    '##########',
    [
        'wp_api' => true,
        'version' => 'wc/v2',
        'query_string_auth' => true
    ]
);
</code>```

I'm simply trying to do a request to list the endpoints (which also works with cURL) but as soon as I attempt to interact via the php-wrapper I get this error message:

```<code>Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Syntax error' in /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:346
Stack trace: #0 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(385): Automattic\WooCommerce\HttpClient\HttpClient->processResponse()
#1 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/Client.php(82): Automattic\WooCommerce\HttpClient\HttpClient->request('', 'GET', Array, Array)
#2 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/ticket-data-test-template.php(15): Automattic\WooCommerce\Client->get('')
#3 /nas/content/live/wwitssltest/wp-includes/template-loader.php(74): include('/nas/content/li...')
#4 /nas/content/live/wwitssltest/wp-blog-header.php(19): require_once('/nas/content/li...')
#5 /nas/content in /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 346
</code>```

When I look in the files, specifically HttpClient.php the most specific information I can come across is that the JSON might not be formatted properly?

The documentation seems pretty cut and dry but nothing I do makes any difference.

With the exception of <php print_r( $woocommerce ); ?> which returns the Client object.

答:
You're missing a comma after query_string_auth' => true.
It should be: query_string_auth' => true.

Cheers!

Title: WooCommerce Rest API gives syntax error

Body:
I'm working on a side project and I've been trying to interact with the WooCommerce REST API.

I have everything seemingly correct. I've created the proper keys because they work with cURL. But when I try to utilize the php-wrapper, provided by Automattic, everything stops working.

I have the code set up exactly like they've instructed:
    require DIR . '/../vendor/autoload.php';

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
    'https://mywebsitenamegoeshere.com',
    '##########',
    '##########',
    [
        'wp_api' => true,
        'version' => 'wc/v2',
        'query_string_auth' => true
    ]
);

I'm simply trying to do a request to list the endpoints (which also works with cURL) but as soon as I attempt to interact via the php-wrapper I get this error message:

Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Syntax error' in /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:346
Stack trace: #0 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(385): Automattic\WooCommerce\HttpClient\HttpClient->processResponse()
#1 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/Client.php(82): Automattic\WooCommerce\HttpClient\HttpClient->request('', 'GET', Array, Array)
#2 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/ticket-data-test-template.php(15): Automattic\WooCommerce\Client->get('')
#3 /nas/content/live/wwitssltest/wp-includes/template-loader.php(74): include('/nas/content/li...')
#4 /nas/content/live/wwitssltest/wp-blog-header.php(19): require_once('/nas/content/li...')
#5 /nas/content in /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 346

When I look in the files, specifically HttpClient.php the most specific information I can come across is that the JSON might not be formatted properly?

The documentation seems pretty cut and dry but nothing I do makes any difference.

With the exception of <php print_r( $woocommerce ); ?> which returns the Client object.


问:
ReactJs - Sort method
I have a table in my react app and it gets its data from API.

I want to sort one of its columns. a[obj1][obj2] or b[obj1][obj2] Usually is a string of numbers and sometimes are equal to "-" (Dash)
this is my sort function:

```<code>if (order === "DEF") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) > Number(b[obj1][obj2])
      ? 1
      : Number(b[obj1][obj2]) > Number(a[obj1][obj2]) || a[obj1][obj2] === "-"
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("ASC");
} else if (order === "ASC") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) < Number(b[obj1][obj2]) || a[obj1][obj2] === "-"
      ? 1
      : Number(b[obj1][obj2]) < Number(a[obj1][obj2])
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("DSC");
} else {
  const sorted = defaultCurrency;
  props.setCurrency(sorted);
  setOrder("DEF");
}
</code>```

After the sort is called I want to behave with "-" like a zero,
but the items which are equal to "-"are always placed on the top of the table when the order is equal to ASC or DSC, while the other items of the array are sorted correctly.

答:
If you want to behave with "-" like a zero then in the sort function you can add this as your first condition and return 0.</p>
```<code>.sort((a, b) => {
    if (a[obj1][obj2] === "-") return 0;
    return Number(a[obj1][obj2]) > Number(b[obj1][obj2]) ? 1
     : Number(b[obj1][obj2]) > Number(a[obj1][obj2]) ? -1 : 0
})
</code>```

Title: ReactJs - Sort method

Body:
I have a table in my react app and it gets its data from API.

I want to sort one of its columns. a[obj1][obj2] or b[obj1][obj2] Usually is a string of numbers and sometimes are equal to "-" (Dash)
this is my sort function:

if (order === "DEF") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) > Number(b[obj1][obj2])
      ? 1
      : Number(b[obj1][obj2]) > Number(a[obj1][obj2]) || a[obj1][obj2] === "-"
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("ASC");
} else if (order === "ASC") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) < Number(b[obj1][obj2]) || a[obj1][obj2] === "-"
      ? 1
      : Number(b[obj1][obj2]) < Number(a[obj1][obj2])
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("DSC");
} else {
  const sorted = defaultCurrency;
  props.setCurrency(sorted);
  setOrder("DEF");
}

After the sort is called I want to behave with "-" like a zero,
but the items which are equal to "-"are always placed on the top of the table when the order is equal to ASC or DSC, while the other items of the array are sorted correctly.

Body:
If you want to behave with "-" like a zero then in the sort function you can add this as your first condition and return 0.

.sort((a, b) => {
    if (a[obj1][obj2] === "-") return 0;
    return Number(a[obj1][obj2]) > Number(b[obj1][obj2]) ? 1
     : Number(b[obj1][obj2]) > Number(a[obj1][obj2]) ? -1 : 0
})


问:
Kotlin : How to remove super when overriding method
I have an abstract base class that has open method for optional implementation.

```<code>open fun onBackPressed() = Unit

override fun onResume() {
        super.onResume()
        requireView().onBackPress {
            onBackPressed()
        }
    }
</code>```

When using it in derived class, the method still allows calling of super even though there is nothing to do.

While you can impose a method for calling super using @CallSuper annotation, I need an opposite of it.

答:
EmptySuper is the opposite of CallSuper.

Denotes that any overriding methods should not invoke this method, since it is defined to be empty (or perhaps contain other code not intended to be run when overridden).

Body:
I have an abstract base class that has open method for optional implementation.

open fun onBackPressed() = Unit

override fun onResume() {
        super.onResume()
        requireView().onBackPress {
            onBackPressed()
        }
    }

When using it in derived class, the method still allows calling of super even though there is nothing to do.

While you can impose a method for calling super using @CallSuper annotation, I need an opposite of it.


问:
Problem with setting up Mingw w64 for C++. Possible conflict with existing Anaconda/Jupyter?
While I am setting up MinGW-W64 (from sourceforge) exe file (for Windows 10) for C++, it shows a message that it was not downloaded correctly. My best guess is that I have a Anaconda/Jupyter setup having MinGW-W64, and it is making all the fuss. How to set it up for both C++ (VS Code / Code lite) and Python/Jupyter/Anaconda?</p>

答:
Make sure you don't mix versions in environment variables like PATH.

Maybe your download was bad?

Or you may have an antivirus software preventing the installation...

You could try a standalone MinGW-w64 build from https://winlibs.com/, which doesn't requite installation - just extract the archive and point VSCode to it.


答:
You can simplify this significantly by parsing the compared elements first, and then applying simple logic for the sorting.

Here declaring a single customSort which accepts an array, a function for retreiving the relevant property from each element, and a direction boolean which defaults to ascending: true.

The value of each element is then accessed using the passed function and converted to a number (here with unary +).

Finally the elements are sorted first by whether either isNaN otherwise by subrtracting based on the direction boolean.

const customSort = (arr, prop, asc = true) => {
  return [...arr].sort((a, b) => {
    a = +prop(a);
    b = +prop(b);

    return isNaN(a) - isNaN(b) || (asc ? a - b : b - a);
  })
}

const data = [{ prop1: { prop2: '2' } }, { prop1: { prop2: '5' } }, { prop1: { prop2: '3' } }, { prop1: { prop2: '1' } }, { prop1: { prop2: '-' } }, { prop1: { prop2: '9' } }, { prop1: { prop2: '-' } },];
const obj1 = 'prop1';
const obj2 = 'prop2';

console.log(customSort(data, (o) => o[obj1][obj2], true));
console.log(customSort(data, (o) => o[obj1][obj2], false));```

Title: ReactJs - Sort method


问:
Csv file not found in a .py ending file
so I was trying to open a simple csv file in VS code that I recently downloaded. But the terminal kept saying “gdptable1.csv” not found after running the code. And I clicked “start debugging” as well, but the result is still the same——no such file or directory: ‘gdptable1.csv’

BUT after I created a new file ending with .ipynb, things worked! VS code was able to exhibit the content of the csv file.

I wonder why this is and how I could fix this in the .py ending file. Is there any difference between .py and .ipynb file? Or am I lacking any extensions?

I tried to run the code below in these two files:

```<code>import csv

with open('gdptable1.csv', newline='') as csvfile:
    rows = csv.reader(csvfile, delimiter=',')
    for i in rows:
      print(i)
</code>```

答:
Try this</p>
```<code>import os, csv

os.chdir(os.path.dirname(__file__))

with open('gdptable1.csv', newline='') as csvfile:
    rows = csv.reader(csvfile, delimiter=',')
    for i in rows:
      print(i)
</code>```

Title: Csv file not found in a .py ending file

Body:
so I was trying to open a simple csv file in VS code that I recently downloaded. But the terminal kept saying “gdptable1.csv” not found after running the code. And I clicked “start debugging” as well, but the result is still the same——no such file or directory: ‘gdptable1.csv’

BUT after I created a new file ending with .ipynb, things worked! VS code was able to exhibit the content of the csv file.

I wonder why this is and how I could fix this in the .py ending file. Is there any difference between .py and .ipynb file? Or am I lacking any extensions?

I tried to run the code below in these two files:

import csv

with open('gdptable1.csv', newline='') as csvfile:
    rows = csv.reader(csvfile, delimiter=',')
    for i in rows:
      print(i)

Body:
Try this

import os, csv

os.chdir(os.path.dirname(__file__))

with open('gdptable1.csv', newline='') as csvfile:
    rows = csv.reader(csvfile, delimiter=',')
    for i in rows:
      print(i)


问:
Trigering methods in nested VUE 3 components
I have a simple app. Clicking to [new item] links opens a child component which has a modal window component for user input.

What is the best way to open modal from the App component. I am not also sure this design is the best approach.
I used to manage this with Classes and Methods when I was using native js. But in VUE accessing sub components methods via an interface is a pain.  All  I want to do is to open a new item model anywhere in the app.

Structure:

```<code>|--App.vue
|  |--NewItem.vue
|  |  |--Modal.vue
</code>```

App.vue:

<template>
    + NEW ITEM
   ...
    + NEW ITEM
   ...
   //Create new Item link appears at multiple places in app
   <NewItem />
</template>

```
<p>NewItem.vue:</p>
<pre class="lang-js prettyprint-override"><code><template>
   <Modal v-model:visible="dialogOpen">
        <template v-slot:title>New Item</template>
        <template v-slot:content >
               <input type="text" class="lg" />
               <button @click="create()">ADD ITEM</button>
        </template>
    </Modal>
</template>

<script setup>
import {  ref} from "vue";
import Modal from "./Modal.vue";

const dialogOpen=ref(false);
const create=()=>{
    //logic...
    console.log("create item");
    //close modal...
    dialogOpen.value=false
}
</script>
</code>```

Modal.vue:

<template >
    <template v-if="isVisible" >

                        <slot name="title"></slot>

                        ✖

                    <slot name="content"></slot>

    </template>
</template>

```

答: You can try to add the modal in the App.vue and created a global variable to control its visibility. In case if you have more components, you can just it to parent component of all components (or particular page)</p>

Body:
I have a simple app. Clicking to [new item] links opens a child component which has a modal window component for user input.

What is the best way to open modal from the App component. I am not also sure this design is the best approach.
I used to manage this with Classes and Methods when I was using native js. But in VUE accessing sub components methods via an interface is a pain.  All  I want to do is to open a new item model anywhere in the app.

Structure:

|--App.vue
|  |--NewItem.vue
|  |  |--Modal.vue

App.vue:

<template>
    + NEW ITEM
   ...
    + NEW ITEM
   ...
   //Create new Item link appears at multiple places in app
   <NewItem />
</template>

NewItem.vue:

<template>
   <Modal v-model:visible="dialogOpen">
        <template v-slot:title>New Item</template>
        <template v-slot:content >
               <input type="text" class="lg" />
               <button @click="create()">ADD ITEM</button>
        </template>
    </Modal>
</template>

Modal.vue:

<template >
    <template v-if="isVisible" >

                        <slot name="title"></slot>

                        ✖

                    <slot name="content"></slot>

    </template>
</template>


问:
Multiple audio outputs in .Net
I am looking to build a PC box that can play up to 16 audio files(mp3/wav) out to 16 analog devices(think of it as 16 sets of speakers).  There will be a one to one relationship for audio file to analog output. The solution that is being presented to be hardware wise is to use multiple sound cards, so my question is, is there a library available that will let me play an audio file to a specific sound card / channel?</p>

答: FMOD should do what you're looking for.  It's also an extremely fast, solid and popular library overall.</p>

OwnerDisplayName: Robin Robinson

ContentLicense: CC BY-SA 2.5

Title: Multiple audio outputs in .Net

OwnerDisplayName: DNS


问:
How to set values in Vuex store in Nuxt.js app
I have never used Vuex with Nuxt.js, so I have met the problem. Here is my store/index.js file:

export const state = () => ({
  wrongCredentials: false,
  logged: false,
  uxd: null
})

export const mutations = {
  setWrongCredentials(state, value) {
    state.wrongCredentials = value
  },
  setLogged(state, value) {
    state.logged = value
  },
  setUxd(state, value) {
    state.uxd = value
  },
}
```
<p>As you can see there is state and mutations. In my other file, where I check user's JWT token and, depending on resultM I want set values in store:</p>
<pre class="lang-js prettyprint-override"><code>import jwt from 'jsonwebtoken'
import cert from '../jwt/public'

export default {
  verify (token) {
    jwt.verify(token, cert, async (err, decoded) => {
      if (err) {
        this.$store.state.wrongCredentials = true
        this.$store.state.logged = false
        this.$store.state.uxd = null
      } else {
        this.$store.state.wrongCredentials = false
        this.$store.state.logged = true
        this.$store.state.uxd = decoded.uxd
      }
    })
  }
}
</code>```

The code you see doesn't work correctly, it just doesn't set values, so, I have created mutations and did something like this:

await this.$store.dispatch('setWrongCredentials', true)

Also doesn't work. The problem is, I don't know how to work with Vuex store not in .vue files, so, how can I set values in store?

答:
Unfortunately, I have not found solution of this problem like I wanted in .js file, so, here is another solution.

First of all, you need to set no only state and mutations, but also actions:

export const actions = {
  fetchWrongCredentials(ctx, value) {
    ctx.commit('setWrongCredentials', value)
  },
  fetchLogged(ctx, value) {
    ctx.commit('setLogged', value)
  },
  fetchUxd(ctx, value) {
    ctx.commit('setUxd', value)
  }
}
```
<p>And in your <code>Vue</code> component you need to set values in state using actions, just like that:</p>
<pre class="lang-js prettyprint-override"><code>
  methods: {
    ...mapActions(['fetchWrongCredentials', 'fetchLogged', 'fetchUxd']),
    async login() {
      await login({
        password: this.userPassword,
        login: this.userLogin,
        twoFactor: this.twoFactor
      }).then(result => {
        const jwtRes = jwt.verify(result.token)
        this.fetchLogged(true)
        this.fetchWrongCredentials(false)
        this.fetchUxd(jwtRes.token)
      }).catch(() => {
        this.fetchLogged(false)
        this.fetchWrongCredentials(true)
        this.fetchUxd(null)
        this.error = true
        setTimeout(() => {
          this.error = false
        }, 1000)
      })
    }
  }
</code>```

In my case, I had to modify that .js file:

import jwt from 'jsonwebtoken'
import cert from '../jwt/public'

export default {
  verify (token) {
    return jwt.verify(token, cert, (err, decoded) => {
      if (err) {
        return false
      } else {
        return { token: decoded.uxd }
      }
    })
  }
}

```

Body:
I have never used Vuex with Nuxt.js, so I have met the problem. Here is my store/index.js file:

export const state = () => ({
  wrongCredentials: false,
  logged: false,
  uxd: null
})

export const mutations = {
  setWrongCredentials(state, value) {
    state.wrongCredentials = value
  },
  setLogged(state, value) {
    state.logged = value
  },
  setUxd(state, value) {
    state.uxd = value
  },
}

As you can see there is state and mutations. In my other file, where I check user's JWT token and, depending on resultM I want set values in store:

import jwt from 'jsonwebtoken'
import cert from '../jwt/public'

export default {
  verify (token) {
    jwt.verify(token, cert, async (err, decoded) => {
      if (err) {
        this.$store.state.wrongCredentials = true
        this.$store.state.logged = false
        this.$store.state.uxd = null
      } else {
        this.$store.state.wrongCredentials = false
        this.$store.state.logged = true
        this.$store.state.uxd = decoded.uxd
      }
    })
  }
}

The code you see doesn't work correctly, it just doesn't set values, so, I have created mutations and did something like this:

await this.$store.dispatch('setWrongCredentials', true)

Also doesn't work. The problem is, I don't know how to work with Vuex store not in .vue files, so, how can I set values in store?

Body:
Unfortunately, I have not found solution of this problem like I wanted in .js file, so, here is another solution.

First of all, you need to set no only state and mutations, but also actions:

export const actions = {
  fetchWrongCredentials(ctx, value) {
    ctx.commit('setWrongCredentials', value)
  },
  fetchLogged(ctx, value) {
    ctx.commit('setLogged', value)
  },
  fetchUxd(ctx, value) {
    ctx.commit('setUxd', value)
  }
}

And in your Vue component you need to set values in state using actions, just like that:

  methods: {
    ...mapActions(['fetchWrongCredentials', 'fetchLogged', 'fetchUxd']),
    async login() {
      await login({
        password: this.userPassword,
        login: this.userLogin,
        twoFactor: this.twoFactor
      }).then(result => {
        const jwtRes = jwt.verify(result.token)
        this.fetchLogged(true)
        this.fetchWrongCredentials(false)
        this.fetchUxd(jwtRes.token)
      }).catch(() => {
        this.fetchLogged(false)
        this.fetchWrongCredentials(true)
        this.fetchUxd(null)
        this.error = true
        setTimeout(() => {
          this.error = false
        }, 1000)
      })
    }
  }

In my case, I had to modify that .js file:

import jwt from 'jsonwebtoken'
import cert from '../jwt/public'

export default {
  verify (token) {
    return jwt.verify(token, cert, (err, decoded) => {
      if (err) {
        return false
      } else {
        return { token: decoded.uxd }
      }
    })
  }
}


问:
Refactoring in VS Code
I have single C file open in VS Code:

```<code>struct Sales{
   int total_and_vat;
   int total;
};

struct AllSales {
   struct Sales negative;
   struct Sales positive;
};
</code>```

I have C/C++ and C/C++ Extension Pack  extensions in my VS Code.

Now I would like to rename type Sales to MySales. How to make this in VS Code? I don't need just simple text replace, I need source file analysis. How to make refactoring in VS Code?

答:
Right-click on the 'Sales' method.

You will then be presented with an option to 'Change All Occurrences'

(This can also be achieved by the shortcut F2)

You can now change the name of your method to 'MySales' by simply replacing the highlighted text.

This will change / refractor all occurrences and references to the method to 'MySales'

Title: Refactoring in VS Code

Body:
I have single C file open in VS Code:

struct Sales{
   int total_and_vat;
   int total;
};

struct AllSales {
   struct Sales negative;
   struct Sales positive;
};

I have C/C++ and C/C++ Extension Pack  extensions in my VS Code.

Now I would like to rename type Sales to MySales. How to make this in VS Code? I don't need just simple text replace, I need source file analysis. How to make refactoring in VS Code?


问:
interact with a pc camera using c++
i intend to interact with a pc camera using c plus plus. Are there any libraries you can recommend or ways to go about ? The idea is to take shots with a Samsung wireless cam then get the images transferred unto a pc with cam and on the pc show images as per the face detection using the cam . any ideas where to start ?</p>

答:
Well, there's a wide range of ways to do it. Professional cameras have accompanying SDKs. If you camera is supported by it (I believe most webcams are) you should try OpenCV for a start.

Googling for "opencv face recognition" will yield plenty of hits, so you have a lot of reference material.

Try this reference (Face and Eyes Detection Using OpenCV) for a start.

After you start your project, you can specific questions on StackOverflow or on the OpenCV Yahoo! group.

OwnerDisplayName: joshua

Title: interact with a pc camera using c++

OwnerDisplayName: Vitor Braga


问:
Typescript promise generic type
I've a sample Promise function like below. On success I return a number and on false I return string. The compiler is complaining to specify some kind of generic type to the promise. In this case what type I've to specify? Do I've to specify like Promise<number> or Promise<number | string>?

```<code>function test(arg: string): Promise {
    return new Promise((resolve, reject) => {
        if (arg === "a") {
            resolve(1);
        } else {
            reject("1");
        }
    });
}
</code>```

答:
You could define a custom Promise type that actually also cares about the type of the rejection. You can also just give it a single type and the reject type will be any, like in a normal promise.

type CustomPromise<T, F = any> = {
    catch<TResult = never>(
        onrejected?: ((reason: F) => TResult | PromiseLike<TResult>) | undefined | null
    ): Promise<T | TResult>;
} & Promise<T>;

function test(arg: string): CustomPromise<number, string> {
    return new Promise((resolve, reject) => {
        if (arg === "a") {
            resolve(1);
        } else {
            reject("1");
        }
    });
}

const myPromise = test("a");
myPromise.then((value) => {}); //value is of type `number`
myPromise.catch((reason) => {}); //reason is of type `string`
```

Title: Typescript promise generic type

Body:
I've a sample Promise function like below. On success I return a number and on false I return string. The compiler is complaining to specify some kind of generic type to the promise. In this case what type I've to specify? Do I've to specify like Promise<number> or Promise<number | string>?

function test(arg: string): Promise {
    return new Promise((resolve, reject) => {
        if (arg === "a") {
            resolve(1);
        } else {
            reject("1");
        }
    });
}


问:
Expending Request's interface seems to not work
Hi I'm creating an api with Express and typescript and I'm trying to extend Request to add an user property. So I have search on google and find multiple posts on stackoverflow who explains how to do this but I have a weird error. I have declare my type so I can write req.user on vscode and I don't get any error. VScodre recognise that user is a property of Request but when I try to compile I have an error who indicate that my request object doesn't have a user property. It act like I didn't extend the Request object

here is my interface:

```<code>declare namespace Express{
  export interface Request{
    user: any;
  }
}
</code>```

It is declare in an express.d.ts file directly

I also have edit my tsconfig file to add

```<code>"typeRoots": ["@types", "node_modules/@types", "./src"]
</code>```

and here is the error message :

```<code>error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
</code>```

Do you know what can cause that ?

答:
Probably you already solved the problem, but for future searches, I solved the problem thanks to these steps:

Use the Correct File Path

The custom declaration has to be inside the folder that will be compiled to JS (the 'rootDir' in your tsconfig.json). If, like me, you specified your root dir to be './src', the declaration must be inside the src folder. Otherwise, the compiler won't even look for the file.

Follow this directory structure to create the Express declaration file:

```<code>Directory
|-- src
|   |-- controllers
|   |-- utils
|   |-- @types
|   |   `-- express
|   |       `-- index.d.ts
|   `-- [...]
|-- tsconfig.json
`-- [...]
</code>```

Note that you have to put the name of the module as the folder name, in this case the path will be ./src/@types/express/index.d.ts.

Setup the declaration correctly

Note that you need to specify export interface Request and not just interface Request.

Furthermore, there must not be other imports outside the 'declare', otherwise the declaration will not be accessible globally anymore.

If you need to import something, do it below 'declare' to not break the declaration.

You do not need to do declare global, it will break the code.

```<code>declare namespace Express {
  // Import here any Interface you need
  import User from '../interfaces/user'

  export interface Request {
    user: User // specify your type here
  }
}
</code>```

Set up your tsconfig.json correctly

In your tsconfig.json file, insert these options:

```<code>{
  ...
  "compilerOptions": {
    // This is not necessary (my setup worked without it), but if yours doesn't it's worth a shot
    "typeRoots": ["typings", "node_modules/@types/"],
  },
  // This is important, to make the Compiler find the declaration.
  // Without this, the compiler wouldn't be able to find your custom declaration and apply it
  "ts-node": {
    "files": true
  },
}
</code>```

Body:
Hi I'm creating an api with Express and typescript and I'm trying to extend Request to add an user property. So I have search on google and find multiple posts on stackoverflow who explains how to do this but I have a weird error. I have declare my type so I can write req.user on vscode and I don't get any error. VScodre recognise that user is a property of Request but when I try to compile I have an error who indicate that my request object doesn't have a user property. It act like I didn't extend the Request object

here is my interface:

declare namespace Express{
  export interface Request{
    user: any;
  }
}

It is declare in an express.d.ts file directly

I also have edit my tsconfig file to add

"typeRoots": ["@types", "node_modules/@types", "./src"]

and here is the error message :

error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

Do you know what can cause that ?

Body:
Probably you already solved the problem, but for future searches, I solved the problem thanks to these steps:

Use the Correct File Path

The custom declaration has to be inside the folder that will be compiled to JS (the 'rootDir' in your tsconfig.json). If, like me, you specified your root dir to be './src', the declaration must be inside the src folder. Otherwise, the compiler won't even look for the file.

Follow this directory structure to create the Express declaration file:

Directory
|-- src
|   |-- controllers
|   |-- utils
|   |-- @types
|   |   `-- express
|   |       `-- index.d.ts
|   `-- [...]
|-- tsconfig.json
`-- [...]

Note that you have to put the name of the module as the folder name, in this case the path will be ./src/@types/express/index.d.ts.

Setup the declaration correctly

Note that you need to specify export interface Request and not just interface Request.

Furthermore, there must not be other imports outside the 'declare', otherwise the declaration will not be accessible globally anymore.

If you need to import something, do it below 'declare' to not break the declaration.

You do not need to do declare global, it will break the code.

declare namespace Express {
  // Import here any Interface you need
  import User from '../interfaces/user'

  export interface Request {
    user: User // specify your type here
  }
}

Set up your tsconfig.json correctly

In your tsconfig.json file, insert these options:

{
  ...
  "compilerOptions": {
    // This is not necessary (my setup worked without it), but if yours doesn't it's worth a shot
    "typeRoots": ["typings", "node_modules/@types/"],
  },
  // This is important, to make the Compiler find the declaration.
  // Without this, the compiler wouldn't be able to find your custom declaration and apply it
  "ts-node": {
    "files": true
  },
}


问:
Why is the value of n equal to 5 in the first iteration?
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.</p>
```<code>#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120
</code>```

答:
while (n--)

while checks if n is non zero. (n == 6)

n is being decremented. (n == 5)

Body of the while is executed. (5 is being printed)

To multiple from 6 you need to use do ... while loop

```<code>int main(void)
{
    int ans = 1, n = 6;

    do
    {
        printf("n = %d\n", n);
        ans *= n ? n : 1;
    }while (n--);

    printf("ans = %d", ans);

    return 0;
}
</code>```

or

```<code>    while(n)
    {
        printf("n = %d\n", n);
        ans *= n;  // note you do not need to check if n != 0
        n--;
    }

</code>```

Body:
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.

#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120

Body:
while (n--)

while checks if n is non zero. (n == 6)

n is being decremented. (n == 5)

Body of the while is executed. (5 is being printed)

To multiple from 6 you need to use do ... while loop

int main(void)
{
    int ans = 1, n = 6;

    do
    {
        printf("n = %d\n", n);
        ans *= n ? n : 1;
    }while (n--);

    printf("ans = %d", ans);

    return 0;
}

or

    while(n)
    {
        printf("n = %d\n", n);
        ans *= n;  // note you do not need to check if n != 0
        n--;
    }


问:
Plotting data in order of date
The aim is to plot a historical plot in r. using the following data

```<code>      date new_cases
1   22/01/2020        NA
2   23/01/2020         0
3   24/01/2020         1
4   25/01/2020         0
5   26/01/2020         3
6   27/01/2020         0
7   28/01/2020         0
8   29/01/2020         1
9   30/01/2020         0
10  31/01/2020         2

... etc.
</code>```

I have never plotted like this, the only thing I know is using

```<code>plot(data$new_cases)
</code>```

But surely there is a more a aesthetically pleasing way to do this?
Thanks

答:
For completness, date is a poor and potentially perilous name for variable and my result in a namespace conflict as date corresponds to base and lubridate functions. When using this data, I would suggest that you rename column to case_date or equivalent.

On another matter, if you are using tidyverse you may want to explore lubridate, which is part of tidyverse.

```<code># pasted_data <- read.delim(pipe("pbpaste"))
library("tidyverse")
library("tidyr")
library("lubridate")
pasted_data %>%
  separate(
    col = 1,
    sep = "\\s+",
    into = c("col_ind", "case_date", "cases"),
    convert = TRUE
  ) %>%
  mutate(case_date = dmy(case_date)) %>%
  ggplot(aes(x = case_date, y = cases)) +
  geom_line()
</code>```

For posterity, ff pasted in the available format, data should be separated into distinct columns. While in tidyverse, this can be achieved using tidy::separate.

Title: Plotting data in order of date

Body:
The aim is to plot a historical plot in r. using the following data

      date new_cases
1   22/01/2020        NA
2   23/01/2020         0
3   24/01/2020         1
4   25/01/2020         0
5   26/01/2020         3
6   27/01/2020         0
7   28/01/2020         0
8   29/01/2020         1
9   30/01/2020         0
10  31/01/2020         2

... etc.

I have never plotted like this, the only thing I know is using

plot(data$new_cases)

But surely there is a more a aesthetically pleasing way to do this?
Thanks

Body:
For completness, date is a poor and potentially perilous name for variable and my result in a namespace conflict as date corresponds to base and lubridate functions. When using this data, I would suggest that you rename column to case_date or equivalent.

On another matter, if you are using tidyverse you may want to explore lubridate, which is part of tidyverse.

# pasted_data <- read.delim(pipe("pbpaste"))
library("tidyverse")
library("tidyr")
library("lubridate")
pasted_data %>%
  separate(
    col = 1,
    sep = "\\s+",
    into = c("col_ind", "case_date", "cases"),
    convert = TRUE
  ) %>%
  mutate(case_date = dmy(case_date)) %>%
  ggplot(aes(x = case_date, y = cases)) +
  geom_line()

For posterity, ff pasted in the available format, data should be separated into distinct columns. While in tidyverse, this can be achieved using tidy::separate.


问:
Getting an ArrayList from Firestore and the document name
I'm new on Google Firebase and I'm trying to learn something about it.
I'm doing an Android app where you can create a group of person and set the title of the group..then, in the "group page", you can see all your group in a listview.
The structure of my firestore db is something like this:

users --> email(document) ---> Group(collection) --> GroupName(Document) and the group name document contains the partecipants arrayList (partecipant 0 : Name1, partecipant1: name2 etc).

I would like to retrieve the document id(which is the group title) and the arrayList of partecipants, but I don't know of to use the for each in the code...

This is my code:

```<code>public void load_list_view(){

    String email = getEmail();
    final DocumentReference docRef = db.collection("users").document(email).collection("Group").document();

    docRef.get()
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {

                        titleArray.add(documentSnapshot.getId());
                        titleString = documentSnapshot.getId();

                        partecipantsArray.add(documentSnapshot.getString("partecipant"));
                        num_partecipants =  partecipantsArray.size();
                        numArray.add(num_partecipants);
                        trash = R.drawable.trash_icon;
                        firstChar = Character.toString(titleString.charAt(0));
                        firstCharArray.add(firstChar);
                        customAdapter = new GroupAdapter(GroupActivity.this, firstCharArray, titleArray, numArray, trash);
                        listView.setAdapter(customAdapter);

                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(GroupActivity.this, e.getStackTrace().toString(), Toast.LENGTH_LONG).show();

                }
            });

}
</code>```

with titleArray.add(documentSnapshot.getId()); it retrieve a random ID and I can't understand why.

I haven't found enough documentation on Internet about Arraylist and firestore.

答:
For People doing in kotlin you can do the following things to get an arraylist from FireStore

First get the ArrayList as String

Remove the char at first and last Index

Split the String at each ','

Convert the list to an Array List

Here is the Code

```<code>ArrayList(doc.document.get("id_here").toString().subSequence(1, doc.document.get("id_here").toString().length - 1).split(","))
</code>```
```<code> Also it may have extra spaces so don't forget to use the functions
</code>```

trimStart() && trimEnd()

Body:
I'm new on Google Firebase and I'm trying to learn something about it.
I'm doing an Android app where you can create a group of person and set the title of the group..then, in the "group page", you can see all your group in a listview.
The structure of my firestore db is something like this:

users --> email(document) ---> Group(collection) --> GroupName(Document) and the group name document contains the partecipants arrayList (partecipant 0 : Name1, partecipant1: name2 etc).

I would like to retrieve the document id(which is the group title) and the arrayList of partecipants, but I don't know of to use the for each in the code...

This is my code:

public void load_list_view(){

    String email = getEmail();
    final DocumentReference docRef = db.collection("users").document(email).collection("Group").document();

    docRef.get()
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {

                        titleArray.add(documentSnapshot.getId());
                        titleString = documentSnapshot.getId();

                        partecipantsArray.add(documentSnapshot.getString("partecipant"));
                        num_partecipants =  partecipantsArray.size();
                        numArray.add(num_partecipants);
                        trash = R.drawable.trash_icon;
                        firstChar = Character.toString(titleString.charAt(0));
                        firstCharArray.add(firstChar);
                        customAdapter = new GroupAdapter(GroupActivity.this, firstCharArray, titleArray, numArray, trash);
                        listView.setAdapter(customAdapter);

                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(GroupActivity.this, e.getStackTrace().toString(), Toast.LENGTH_LONG).show();

                }
            });

}

with titleArray.add(documentSnapshot.getId()); it retrieve a random ID and I can't understand why.

I haven't found enough documentation on Internet about Arraylist and firestore.

Body:
For People doing in kotlin you can do the following things to get an arraylist from FireStore

First get the ArrayList as String

Remove the char at first and last Index

Split the String at each ','

Convert the list to an Array List

Here is the Code

ArrayList(doc.document.get("id_here").toString().subSequence(1, doc.document.get("id_here").toString().length - 1).split(","))

 Also it may have extra spaces so don't forget to use the functions

trimStart() && trimEnd()