问:
the filetype you are attempting to upload is not allowed codeigniter webp
I am trying to upload a webp image from website which developed by using CodeIgniter. But I am getting "the filetype you are attempting to upload is not allowed" error.

application/config/mimes.php

```<code>'webp' => array(
    'image/webp'
),
</code>```

in upload function

```<code>$config['allowed_types'] = 'gif|jpg|png|jpeg|webp|JPEG|JPG|PNG|GIF|WEBP';
$this->upload->initialize($config);
echo "Upload about to start";
if ($this->upload->do_upload("images")) {
 $uploadData = $this->upload->data();
}
</code>```

答:
You can add the line:
to the CodeIgniter config file 'mimes.php'

```<code>'webp'  =>  array('image/webp'),
</code>```

This will certainly allow the upload of the 'webp' type;

But be warned that any image processing may fail if you have other functions that then handle the 'webp' - like typical image resizing - i.e. :

"Re-sizing -
Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct."

Also - do not CAPITALIZE your 'allowed_types'!
""

Body:
I am trying to upload a webp image from website which developed by using CodeIgniter. But I am getting "the filetype you are attempting to upload is not allowed" error.

application/config/mimes.php

'webp' => array(
    'image/webp'
),

in upload function

$config['allowed_types'] = 'gif|jpg|png|jpeg|webp|JPEG|JPG|PNG|GIF|WEBP';
$this->upload->initialize($config);
echo "Upload about to start";
if ($this->upload->do_upload("images")) {
 $uploadData = $this->upload->data();
}

Body:
You can add the line:
to the CodeIgniter config file 'mimes.php'

'webp'  =>  array('image/webp'),

This will certainly allow the upload of the 'webp' type;

But be warned that any image processing may fail if you have other functions that then handle the 'webp' - like typical image resizing - i.e. :

"Re-sizing -
Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct."

Also - do not CAPITALIZE your 'allowed_types'!
""


来源: stackexchange

问:
How to send SMS from asp.net application

Possible Duplicate:

  sms from our site

I want to send SMS from my asp.net application. Suppose there will be 2 text boxes in my UI, one for mobile or cell phone number and another one is for message writing. When I will click the submit button then this SMS will be send to that cell number.
I want to use my cell phone number as transmission number.
Please inform me the possible ways.
I am using asp.net C#

答:
You'll need to find yourself an SMS gateway and use their API.

Check out http://www.twilio.com/ they give you some free credit for when you sign up.

ContentLicense: CC BY-SA 3.0


问:
Using ngx-intl-tel-input break Mat Dialog
If I use ngx-tel-input it renders an empty dialog.</p>
```<code> <ngx-intl-tel-input name="phone" formControlName="PhoneNumber"
                        [cssClass]="{'form-control h-auto form-control-solid py-4 d-block': 1 }"
                        [preferredCountries]="preferredCountries" [enableAutoCountrySelect]="true"
                        [enablePlaceholder]="true" [searchCountryFlag]="true"
                        [searchCountryField]="[SearchCountryField.Iso2, SearchCountryField.Name]"
                        [selectFirstCountry]="true" [selectedCountryISO]="CountryISO.UnitedStates" [maxLength]="15"
                        [phoneValidation]="true" [separateDialCode]="separateDialCode"
                        [numberFormat]="PhoneNumberFormat.National">
 </ngx-intl-tel-input>
</code>```

答:
Might be rest of the html code around the ngx-intl-tel-input, check for differences what might be missing. I don't see anything explicitly wrong with the code you have provided.

  <form #f="ngForm" [formGroup]="phoneForm">
    <ngx-intl-tel-input
    [cssClass]="'custom'"
    [preferredCountries]="['sg']"
    [onlyCountries]="['my', 'us']"
    [enablePlaceholder]="true"
    [enableAutoCountrySelect]="true"
    name="phone"
    formControlName="phone"></ngx-intl-tel-input>
  </form>
```
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

    phoneForm = new FormGroup({
        phone: new FormControl('', [Validators.required])
    });

}
</code>```

Here is a working example: https://stackblitz.com/edit/angular-ngx-intl-tel-input-cxfoib?file=src%2Fapp%2Fapp.component.html

ContentLicense: CC BY-SA 4.0

Body:
If I use ngx-tel-input it renders an empty dialog.

 <ngx-intl-tel-input name="phone" formControlName="PhoneNumber"
                        [cssClass]="{'form-control h-auto form-control-solid py-4 d-block': 1 }"
                        [preferredCountries]="preferredCountries" [enableAutoCountrySelect]="true"
                        [enablePlaceholder]="true" [searchCountryFlag]="true"
                        [searchCountryField]="[SearchCountryField.Iso2, SearchCountryField.Name]"
                        [selectFirstCountry]="true" [selectedCountryISO]="CountryISO.UnitedStates" [maxLength]="15"
                        [phoneValidation]="true" [separateDialCode]="separateDialCode"
                        [numberFormat]="PhoneNumberFormat.National">
 </ngx-intl-tel-input>

Body:
Might be rest of the html code around the ngx-intl-tel-input, check for differences what might be missing. I don't see anything explicitly wrong with the code you have provided.

  <form #f="ngForm" [formGroup]="phoneForm">
    <ngx-intl-tel-input
    [cssClass]="'custom'"
    [preferredCountries]="['sg']"
    [onlyCountries]="['my', 'us']"
    [enablePlaceholder]="true"
    [enableAutoCountrySelect]="true"
    name="phone"
    formControlName="phone"></ngx-intl-tel-input>
  </form>

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

    phoneForm = new FormGroup({
        phone: new FormControl('', [Validators.required])
    });

}

Here is a working example: https://stackblitz.com/edit/angular-ngx-intl-tel-input-cxfoib?file=src%2Fapp%2Fapp.component.html


问:
How do I declare the objects related to one class in other?
The error shows: no matching functions for call to birthday::birthday(). How else should I declare the objects of one class in another class?

```<code>#include <iostream>

using namespace std;

class birthday
{

public:

    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    int date;
    int month;
    int year;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}
</code>```

答:
The problem is that your class birthday has a user-defined constructor and therefore the compiler will not synthesize the default constructor birthday::birthday() for your class.

So when you wrote,

```<code>class person
{
    //other members here
    private:
         birthday day; //this need the default constructor of birthday. But since class birthday has no default constructor this statement gives error
};
</code>```

In the above snippet, the statetment, birthday day; needs the default constructor of class birthday but since there isn't one, so this statement results in the mentioned error.

Solution

To solve this you can add a default constructor for your class birthday as shown below:

```<code>class birthday
{

public:
    //add default constructor
    birthday() = default;
    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    //using in class initializers give some default values to the data members according to your needs
    int date = 0;
    int month =0;
    int year = 0;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on ";

        day.printdate();//moved this out of the cout because printdat() does not return anything
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}
</code>```

Some of the changes that i made include:

Added default constructor for class birthday.

Used in-class initializers for data member date, year and month inside class birthday.

There was another problem with your code. Originally you had a statement cout<<day.printdate() in your program. But since printdate() has return type void, so the statement cout<<day.printdate() will give you error. To solve this, i removed the cout from this statement.

The output of the modified program can be seen here.

Body:
The error shows: no matching functions for call to birthday::birthday(). How else should I declare the objects of one class in another class?

#include <iostream>

using namespace std;

class birthday
{

public:

    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    int date;
    int month;
    int year;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}

Body:
The problem is that your class birthday has a user-defined constructor and therefore the compiler will not synthesize the default constructor birthday::birthday() for your class.

So when you wrote,

class person
{
    //other members here
    private:
         birthday day; //this need the default constructor of birthday. But since class birthday has no default constructor this statement gives error
};

In the above snippet, the statetment, birthday day; needs the default constructor of class birthday but since there isn't one, so this statement results in the mentioned error.

Solution

To solve this you can add a default constructor for your class birthday as shown below:

class birthday
{

public:
    //add default constructor
    birthday() = default;
    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    //using in class initializers give some default values to the data members according to your needs
    int date = 0;
    int month =0;
    int year = 0;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on ";

        day.printdate();//moved this out of the cout because printdat() does not return anything
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}

Some of the changes that i made include:

Added default constructor for class birthday.

Used in-class initializers for data member date, year and month inside class birthday.

There was another problem with your code. Originally you had a statement cout<<day.printdate() in your program. But since printdate() has return type void, so the statement cout<<day.printdate() will give you error. To solve this, i removed the cout from this statement.

The output of the modified program can be seen here.


问:
Incremental sum in Oracle SQL using analytic functions
How can I sum values per record from a table?
If I have

row
key
value
expected

row 1
A
1
1

row 2
A
5
6

row 3
B
10
10

row 4
B
1
11

row 5
B
1
12

can you point me some directions?

thanks

答:
You can use Windowing Functions

Something like

```<code>select t.*,
sum(value) over (partition by key order by "row" rows unbounded preceding) expected
from tab t;
</code>```

Note that ROW is a reserved word. You can create a table with a column row, but you better use another name.

Body:
You can use Windowing Functions

Something like

select t.*,
sum(value) over (partition by key order by "row" rows unbounded preceding) expected
from tab t;

Note that ROW is a reserved word. You can create a table with a column row, but you better use another name.


问:
Hide SVG width till the animation-delay
I am trying to animate the width of a svg rect with the following code.

window.onload = function() {
    var viewBoxWidth = document.querySelector('svg').viewBox.baseVal.width;
    var rect1 = document.getElementById('r1');
    var rect1Width = rect1.getBBox().width;
    var pct = (rect1Width / viewBoxWidth) * 100;
    rect1.style.setProperty('--w1', pct + '%');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.r1 {
    animation-name: moveWidth;
    animation-delay: 2s;
    animation-duration: 2s;
    animation-iteration-count: 1;
    animation-timing-function: linear;
    animation-direction: normal;
    animation-fill-mode: forwards;
}

@keyframes moveWidth {
    0% {
        width: 0%;
    }
    100% {
        width: var(--w1);
    }
}</code>```

<!DOCTYPE html>

    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
    <rect class="r1" id="r1" x="10" y="10" width="200" height="20" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="10" y="30" width="200" height="20" stroke="none" fill="green"></rect>
  </svg>

```

The animation is taking place but how can I hide the width of r1 till the animation kicks in at the 2s, (till the delay).

答:
window.onload = function() {
  var viewBoxWidth = document.querySelector('svg').viewBox.baseVal.width;
  var rect1 = document.getElementById('r1');
  var rect1Width = rect1.getBBox().width;
  var pct = (rect1Width / viewBoxWidth) * 100;
  rect1.style.setProperty('--w1', pct + '%');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.r1 {
visibility:hidden;/*hide default*/
  animation-name: moveWidth;
  animation-delay: 2s;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-timing-function: linear;
  animation-direction: normal;
  animation-fill-mode: forwards;

}

@keyframes moveWidth {
  0% {
    visibility:visible;/*show again*/
    width: 0%;
  }
  100% {
  visibility:visible;/*Edit-2 maintains visibility after animation overs*/
    width: var(--w1);
  }
}</code>```

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
    <rect class="r1" id="r1" x="10" y="10" width="200" height="20" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="10" y="30" width="200" height="20" stroke="none" fill="green"></rect>
  </svg>```

use css visibility

Edit-2: maintains visibility after animation overs)

Title: Hide SVG width till the animation-delay

Body:
I am trying to animate the width of a svg rect with the following code.

window.onload = function() {
    var viewBoxWidth = document.querySelector('svg').viewBox.baseVal.width;
    var rect1 = document.getElementById('r1');
    var rect1Width = rect1.getBBox().width;
    var pct = (rect1Width / viewBoxWidth) * 100;
    rect1.style.setProperty('--w1', pct + '%');
}

.r1 {
    animation-name: moveWidth;
    animation-delay: 2s;
    animation-duration: 2s;
    animation-iteration-count: 1;
    animation-timing-function: linear;
    animation-direction: normal;
    animation-fill-mode: forwards;
}

@keyframes moveWidth {
    0% {
        width: 0%;
    }
    100% {
        width: var(--w1);
    }
}

<!DOCTYPE html>

    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
    <rect class="r1" id="r1" x="10" y="10" width="200" height="20" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="10" y="30" width="200" height="20" stroke="none" fill="green"></rect>
  </svg>

The animation is taking place but how can I hide the width of r1 till the animation kicks in at the 2s, (till the delay).

Body:
window.onload = function() {
  var viewBoxWidth = document.querySelector('svg').viewBox.baseVal.width;
  var rect1 = document.getElementById('r1');
  var rect1Width = rect1.getBBox().width;
  var pct = (rect1Width / viewBoxWidth) * 100;
  rect1.style.setProperty('--w1', pct + '%');
}

.r1 {
visibility:hidden;/*hide default*/
  animation-name: moveWidth;
  animation-delay: 2s;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-timing-function: linear;
  animation-direction: normal;
  animation-fill-mode: forwards;

}

@keyframes moveWidth {
  0% {
    visibility:visible;/*show again*/
    width: 0%;
  }
  100% {
  visibility:visible;/*Edit-2 maintains visibility after animation overs*/
    width: var(--w1);
  }
}

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
    <rect class="r1" id="r1" x="10" y="10" width="200" height="20" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="10" y="30" width="200" height="20" stroke="none" fill="green"></rect>
  </svg>

use css visibility

Edit-2: maintains visibility after animation overs)


问:
Assertion testing a void function
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

```<code>void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}
</code>```

答: The function has side-effects. You're supposed to test that the side-effects are what they are supposed to be. This applies to all functions that have side-effects; not only those that return void. The function modifies elements of arr.

Title: Assertion testing a void function

Body:
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}


问:
PHP Regular expressions problem
I'm using regex to pull info from a html table.

But I'm messing up some how, and have no idea why.

PHP CODE:

```<code>$printable = file_get_contents('./testplaylist.php', true);

if(preg_match_all('/<TR[^>]*>(.*?)<\/TR>/si', $printable, $matches, PREG_SET_ORDER)); {
foreach($matches as $match) {
$data = "$match[1]";

echo("$data <br />");

}
}
</code>```

HTML DATA:

```<code><TR class=" light ">
Stuff in here
</TR>
</code>```

Any help would be appreciated,

Thanks!

答:
Use PHP's document object model to be safe when parsing HTML. Except for very simple regexes, HTML parsing rapidly gets out of control when you DIY. There's a bit of overhead to set it up, but once you get going it's straightforward.

See DOM for instructions on how to use it.

If you stick to the regex technique, at the least, you may need to escape all '<' and '>'s eg.

```<code>/\<TR[^>]*\>(.*?)\<\/TR\>/si
</code>```

Title: PHP Regular expressions problem

Body:
I'm using regex to pull info from a html table.

But I'm messing up some how, and have no idea why.

PHP CODE:

$printable = file_get_contents('./testplaylist.php', true);

if(preg_match_all('/
]*>(.*?)<\/TR>/si', $printable, $matches, PREG_SET_ORDER)); {
foreach($matches as $match) {
$data = "$match[1]";

echo("$data
");

}
}

HTML DATA:

Stuff in here

Any help would be appreciated,

Thanks!

Body:
Use PHP's document object model to be safe when parsing HTML. Except for very simple regexes, HTML parsing rapidly gets out of control when you DIY. There's a bit of overhead to set it up, but once you get going it's straightforward.

See DOM for instructions on how to use it.

If you stick to the regex technique, at the least, you may need to escape all '<' and '>'s eg.

/\<TR[^>]*\>(.*?)\<\/TR\>/si


问:
Why do I have to import traceback if it already exists?
If I write something in Python and things go awry, I automatically get a traceback.

For example:

```<code>#!/usr/bin/env python

print("this will raise a division by zero exception")
print(2/0)
</code>```

It automatically throws a traceback with the exception

```<code>>>> %Run test.py
this will raise a division by zero exception
Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 4, in <module>
    print(2/0)
ZeroDivisionError: division by zero
>>>
</code>```

Now, let's assume that I don't want the program to crash-and-burn, but I want to handle the exception gracefully - say I need to close files or whatever.

Viz.:

```<code>#!/usr/bin/env python
import sys

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    sys.exit(0)
</code>```

Which gets me the expected:

```<code>>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>
</code>```

However, if I try to handle the exception manually, I am told that in order to get the system provided traceback, (the call stack and location of the error), I have to import traceback.

When I do that, I can get all the information I want.

```<code>#!/usr/bin/env python
import sys
import traceback

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    traceback.print_exc()
    sys.exit(0)
</code>```

And the expected result:

```<code>────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 9, in <module>
    print(2/0)
ZeroDivisionError: division by zero

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>
</code>```

"Traceback" appears to already exist as the traceback is automatic on unhandled exceptions

Why do I have to import traceback if I use a try/except block, but don't if I don't?

答: The traceback reflects the state of the Python Interpreter at a given point during the execution of some code. The Python Interpreter obviously has access to its own state, and shares it with the user, by printing that error message, when an exception is thrown and not handled. It also gives the code access to it – via the traceback module, which is why you need to import it.</p>

Body:
If I write something in Python and things go awry, I automatically get a traceback.

For example:

#!/usr/bin/env python

print("this will raise a division by zero exception")
print(2/0)

It automatically throws a traceback with the exception

>>> %Run test.py
this will raise a division by zero exception
Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 4, in <module>
    print(2/0)
ZeroDivisionError: division by zero
>>>

Now, let's assume that I don't want the program to crash-and-burn, but I want to handle the exception gracefully - say I need to close files or whatever.

Viz.:

#!/usr/bin/env python
import sys

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    sys.exit(0)

Which gets me the expected:

>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>

However, if I try to handle the exception manually, I am told that in order to get the system provided traceback, (the call stack and location of the error), I have to import traceback.

When I do that, I can get all the information I want.

#!/usr/bin/env python
import sys
import traceback

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    traceback.print_exc()
    sys.exit(0)

And the expected result:

────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 9, in <module>
    print(2/0)
ZeroDivisionError: division by zero

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>

"Traceback" appears to already exist as the traceback is automatic on unhandled exceptions

Why do I have to import traceback if I use a try/except block, but don't if I don't?


问:
Firestore Security Rules for specific user that was added in the Firebase console directly
I have this user where I added it directly from the firebase console, hence, it is not in any user collection.

Is it possible that only this specific userID can access collections of orders and products?

答:
If it's only one user then you can restrict read access of those collections to that specific UID using the following rule:</p>
```<code>match /orders/{orderId} {
  allow read: if request.auth.uid == "firebase_user_id";
}
</code>```

Body:
If it's only one user then you can restrict read access of those collections to that specific UID using the following rule:

match /orders/{orderId} {
  allow read: if request.auth.uid == "firebase_user_id";
}


问:
Push an associative item into an array in JavaScript
How can I correct the following code?

var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);```

JSFiddle

答:
If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.

// Order of entry altered
let obj = {}; //  will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);

// Order of entry maintained for future iteration
obj = []; //  will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);```

Body:
How can I correct the following code?

var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);

JSFiddle


问:
CS1950 The best overloaded add method Dictionary<string,Func<string>) for the collection initializer has some invalid arguments
I am running into this error.. not sure what I am missing. This is reproducible code.

Sorry for the edit on the question- What if I wish to pass 2 strings to the function?

```<code>  class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        string myString = "test";
        string testString = "test";

        IDictionary<string, Func<string>> identityInformation = new Dictionary<string, Func<string>>
    {
        { "text1", () => {return test(myString, testString); } },
        { "text2", () => { return test(myString, testString); } }
    };

}
    public static string test(string myString, string testString)
    {
        return myString;
    }

}
</code>```

答:
EDIT
based on comments you can go with option A and call method when adding item into dictionary

```<code>string myString = "test";
string testString = "test";
var identityInformation = new Dictionary<string, string>
{
    { "text1", test(myString, testString) },
    { "text2", test(myString, testString) }
};

public static string test(string myString, string testString)
{
    return myString;
}
</code>```

Not sure which is defined interface you need to follow. There are multiple ways to fix it. Because Func  it has no parameters and returns string, which test method is not. Therefore:

A- Change dictionary to store results

```<code> Dictionary<string, string>
</code>```

B- change signature of dictionary to Func<string,string> and store delegates. Then myString as parameter will be used later.

```<code>IDictionary<string, Func<string,string>> identityInformation = new Dictionary<string, Func<string,string>>
{
    { "text1", test },
    { "text2", test }
};
</code>```

C- add lambda

```<code>IDictionary<string, Func<string>> identityInformation = new Dictionary<string, Func<string>>
{
    { "text1", () => test(myString) },
    { "text2", () => test(myString) }
};
</code>```

Body:
I am running into this error.. not sure what I am missing. This is reproducible code.

Sorry for the edit on the question- What if I wish to pass 2 strings to the function?

  class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        string myString = "test";
        string testString = "test";

        IDictionary<string, Func<string>> identityInformation = new Dictionary<string, Func<string>>
    {
        { "text1", () => {return test(myString, testString); } },
        { "text2", () => { return test(myString, testString); } }
    };

}
    public static string test(string myString, string testString)
    {
        return myString;
    }

}

Body:
EDIT
based on comments you can go with option A and call method when adding item into dictionary

string myString = "test";
string testString = "test";
var identityInformation = new Dictionary<string, string>
{
    { "text1", test(myString, testString) },
    { "text2", test(myString, testString) }
};

public static string test(string myString, string testString)
{
    return myString;
}

Not sure which is defined interface you need to follow. There are multiple ways to fix it. Because Func  it has no parameters and returns string, which test method is not. Therefore:

A- Change dictionary to store results

 Dictionary<string, string>

B- change signature of dictionary to Func<string,string> and store delegates. Then myString as parameter will be used later.

IDictionary<string, Func<string,string>> identityInformation = new Dictionary<string, Func<string,string>>
{
    { "text1", test },
    { "text2", test }
};

C- add lambda

IDictionary<string, Func<string>> identityInformation = new Dictionary<string, Func<string>>
{
    { "text1", () => test(myString) },
    { "text2", () => test(myString) }
};


问:
iOS: Twilio Verify for React Native: Exception while calling the API
I'm using Twilio Verify for React Native and I'm getting an error (log below) when using their snippet to create a Factor:

export async function createTwilioVerifyFactor(identity) {
  const pushToken = await messaging().getToken()

  const accessTokenResponse = await getTwilioVerifyAccessToken(identity)
  const hashedIdentity = accessTokenResponse.identity
  const accessToken = accessTokenResponse.token

  try {
    const factor = await TwilioVerify.createFactor(
      new PushFactorPayload(
        // factor name
        Device.deviceName ?? 'Unknown Device',
        Constants.manifest.extra.twilioVerifyServiceSid,
        hashedIdentity,
        pushToken,
        accessToken
      )
    )
    if (!factor.sid) throw new Error('Failed to create factor')
    return factor
  } catch (e) { console.log(JSON.stringify(e, null, 2) }
}
```
<p>I made sure none of the required values are <code>null</code>/<code>undefined</code>, but I'm still getting an error.</p>
<p><strong>Android devices give no trouble</strong>, but iOS devices do. The <code>try / catch</code> block results in the following log:</p>
```{
  "nativeStackAndroid": [
    {
      "lineNumber": 95,
      "file": "FactorAPIClient.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.api.FactorAPIClient$create$2"
    },
    {
      "lineNumber": 61,
      "file": "FactorAPIClient.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.api.FactorAPIClient$create$2"
    },
    {
      "lineNumber": 68,
      "file": "NetworkAdapter.kt",
      "methodName": "execute",
      "class": "com.twilio.verify.networking.NetworkAdapter"
    },
    {
      "lineNumber": 89,
      "file": "FactorAPIClient.kt",
      "methodName": "create",
      "class": "com.twilio.verify.api.FactorAPIClient"
    },
    {
      "lineNumber": 49,
      "file": "FactorRepository.kt",
      "methodName": "create",
      "class": "com.twilio.verify.domain.factor.FactorRepository"
    },
    {
      "lineNumber": 87,
      "file": "PushFactory.kt",
      "methodName": "create",
      "class": "com.twilio.verify.domain.factor.PushFactory"
    },
    {
      "lineNumber": 55,
      "file": "FactorFacade.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.domain.factor.FactorFacade$createFactor$1"
    },
    {
      "lineNumber": 43,
      "file": "FactorFacade.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.domain.factor.FactorFacade$createFactor$1"
    },
    {
      "lineNumber": 68,
      "file": "Executor.kt",
      "methodName": "run",
      "class": "com.twilio.verify.threading.Task"
    },
    {
      "lineNumber": 1167,
      "file": "ThreadPoolExecutor.java",
      "methodName": "runWorker",
      "class": "java.util.concurrent.ThreadPoolExecutor"
    },
    {
      "lineNumber": 641,
      "file": "ThreadPoolExecutor.java",
      "methodName": "run",
      "class": "java.util.concurrent.ThreadPoolExecutor$Worker"
    },
    {
      "lineNumber": 929,
      "file": "Thread.java",
      "methodName": "run",
      "class": "java.lang.Thread"
    }
  ],
  "userInfo": null,
  "message": "{60401} Exception while calling the API",
  "code": "EUNSPECIFIED",
  "line": 5737,
  "column": 45,
  "sourceURL": "http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=my.app&modulesOnly=false&runModule=true"
}
```

Am I potentially doing something wrong?

答:
Twilio developer evangelist here.

I see a couple of potential issues here. First, the error says:

{60401} Exception while calling the API

Error 60401 implies there was a network error. You say that this was not an issue in an emulator, but happened on real devices. Did you check those real devices' network connections?

Secondly, you're using const to declare the factor variable inside the try/catch block, however you then try to use the factor variable after the catch block. At that stage the factor is now out of scope as consts are block scoped. You'll likely get an error like "Cannot read properties of undefined". It's probably best to do the rest of your logic within the try bock.

  try {
    const factor = await TwilioVerify.createFactor(
      new PushFactorPayload(
        // factor name
        Device.deviceName ?? 'Unknown Device',
        Constants.manifest.extra.twilioVerifyServiceSid,
        hashedIdentity,
        pushToken,
        accessToken
      )
    )
    if (!factor.sid) throw new Error('Failed to create factor')

    return factor
  } catch (e) { console.log(JSON.stringify(e, null, 2) }
}

```

Body:
I'm using Twilio Verify for React Native and I'm getting an error (log below) when using their snippet to create a Factor:

export async function createTwilioVerifyFactor(identity) {
  const pushToken = await messaging().getToken()

  const accessTokenResponse = await getTwilioVerifyAccessToken(identity)
  const hashedIdentity = accessTokenResponse.identity
  const accessToken = accessTokenResponse.token

  try {
    const factor = await TwilioVerify.createFactor(
      new PushFactorPayload(
        // factor name
        Device.deviceName ?? 'Unknown Device',
        Constants.manifest.extra.twilioVerifyServiceSid,
        hashedIdentity,
        pushToken,
        accessToken
      )
    )
    if (!factor.sid) throw new Error('Failed to create factor')
    return factor
  } catch (e) { console.log(JSON.stringify(e, null, 2) }
}

I made sure none of the required values are null/undefined, but I'm still getting an error.

Android devices give no trouble, but iOS devices do. The try / catch block results in the following log:

{
  "nativeStackAndroid": [
    {
      "lineNumber": 95,
      "file": "FactorAPIClient.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.api.FactorAPIClient$create$2"
    },
    {
      "lineNumber": 61,
      "file": "FactorAPIClient.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.api.FactorAPIClient$create$2"
    },
    {
      "lineNumber": 68,
      "file": "NetworkAdapter.kt",
      "methodName": "execute",
      "class": "com.twilio.verify.networking.NetworkAdapter"
    },
    {
      "lineNumber": 89,
      "file": "FactorAPIClient.kt",
      "methodName": "create",
      "class": "com.twilio.verify.api.FactorAPIClient"
    },
    {
      "lineNumber": 49,
      "file": "FactorRepository.kt",
      "methodName": "create",
      "class": "com.twilio.verify.domain.factor.FactorRepository"
    },
    {
      "lineNumber": 87,
      "file": "PushFactory.kt",
      "methodName": "create",
      "class": "com.twilio.verify.domain.factor.PushFactory"
    },
    {
      "lineNumber": 55,
      "file": "FactorFacade.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.domain.factor.FactorFacade$createFactor$1"
    },
    {
      "lineNumber": 43,
      "file": "FactorFacade.kt",
      "methodName": "invoke",
      "class": "com.twilio.verify.domain.factor.FactorFacade$createFactor$1"
    },
    {
      "lineNumber": 68,
      "file": "Executor.kt",
      "methodName": "run",
      "class": "com.twilio.verify.threading.Task"
    },
    {
      "lineNumber": 1167,
      "file": "ThreadPoolExecutor.java",
      "methodName": "runWorker",
      "class": "java.util.concurrent.ThreadPoolExecutor"
    },
    {
      "lineNumber": 641,
      "file": "ThreadPoolExecutor.java",
      "methodName": "run",
      "class": "java.util.concurrent.ThreadPoolExecutor$Worker"
    },
    {
      "lineNumber": 929,
      "file": "Thread.java",
      "methodName": "run",
      "class": "java.lang.Thread"
    }
  ],
  "userInfo": null,
  "message": "{60401} Exception while calling the API",
  "code": "EUNSPECIFIED",
  "line": 5737,
  "column": 45,
  "sourceURL": "http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=my.app&modulesOnly=false&runModule=true"
}

Am I potentially doing something wrong?


问:
How to store value of an input box in a variable?
I am trying to make a chat application with scaledrone.
I was following this tutorial: https://www.scaledrone.com/blog/javascript-chat-room-tutorial/
but after setting up the basic chat, I wanted to let users define their own name. So I made an input box and then tried using js to take the input box value and assign it to a variable. And then for the name part of the chat application, instead of using the random name function I was using earlier. However, I got the error "can not read properties of null(reading addEventListener) in my console and the submit button did not show up at all.
What did I do wrong?
The code I used is in pastebin links below.
The scaledrone documentation is here: https://www.scaledrone.com/docs/api-clients/javascript
Thanks in advance.
also, I added the raw text of my javascript file below because stack overflow won't let me post without adding some code(first time posting to stack overflow lol).

https://pastebin.com/9DvF3WnX
https://pastebin.com/UrZ1xsMB

```<code>const CLIENT_ID = 'keECa1lpVtgABa1F';
const splash=document.querySelector('.splash');
const stuffjs=document.querySelector('.stuff');
var yourname;

/*function createMenuItem(name) {
  let inputname = document.createElement('input');
  inputname.placeholder = name;
  inputname.className='inputnamefield';
  return inputname;
}*/
/*function createButton(btnname){
  let btn = document.createElement('input');
  btn.type = 'submit';
  btn.className='submitbtn';
  return btn;
}*/
const inputnameagain=document.querySelector('.inputnamefield');
const buttoon=document.querySelector('.submitbtn');
buttoon.addEventListener('click',(e) => {
  setTimeout(()=>{
  yourname=inputboxstuff.value()
  },1);
});

/*document.addEventListener('DOMContentLoaded',(e)=>{
  setTimeout(()=>{
    splash.classList.add('display-none');

  },2000);
})
splash.addEventListener('mousedown',
(e)=>{
  setTimeout(()=>{
    splash.parentElement.removeChild(splash);

  },1);
})*/

const drone = new ScaleDrone(CLIENT_ID, {
  data: { // Will be sent out as clientData via events
    name: yourname,
    color: getRandomColor(),
  },
});

let members = [];

drone.on('open', error => {
  if (error) {
    return console.error(error);
  }
  console.log('Successfully connected to Scaledrone');

  const room = drone.subscribe('observable-room');
  room.on('open', error => {
    if (error) {
      return console.error(error);
    }
    console.log('Successfully joined room');
  });

  room.on('members', m => {
    members = m;
    updateMembersDOM();
  });

  room.on('member_join', member => {
    members.push(member);
    updateMembersDOM();
  });

  room.on('member_leave', ({id}) => {
    const index = members.findIndex(member => member.id === id);
    members.splice(index, 1);
    updateMembersDOM();
  });

  room.on('data', (text, member) => {
    if (member) {
      addMessageToListDOM(text, member);
    } else {
      // Message is from server
    }
  });
});

drone.on('close', event => {
  console.log('Connection was closed', event);
});

drone.on('error', error => {
  console.error(error);
});

function getRandomName() {
  const adjs = ["autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark", "summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter", "patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green", "long", "late", "lingering", "bold", "little", "morning", "muddy", "old", "red", "rough", "still", "small", "sparkling", "throbbing", "shy", "wandering", "withered", "wild", "black", "young", "holy", "solitary", "fragrant", "aged", "snowy", "proud", "floral", "restless", "divine", "polished", "ancient", "purple", "lively", "nameless"];
  const nouns = ["waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning", "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter", "forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook", "butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly", "feather", "grass", "haze", "mountain", "night", "pond", "darkness", "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder", "violet", "water", "wildflower", "wave", "water", "resonance", "sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper", "frog", "smoke", "star"];
  return (
    adjs[Math.floor(Math.random() * adjs.length)] +
    "_" +
    nouns[Math.floor(Math.random() * nouns.length)]
  );
}

function getRandomColor() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16);
}

//------------- DOM STUFF

const DOM = {
  membersCount: document.querySelector('.members-count'),
  membersList: document.querySelector('.members-list'),
  messages: document.querySelector('.messages'),
  input: document.querySelector('.message-form__input'),
  form: document.querySelector('.message-form'),
};

DOM.form.addEventListener('submit', sendMessage);

function sendMessage() {
  const value = DOM.input.value;
  if (value === '') {
    return;
  }
  DOM.input.value = '';
  drone.publish({
    room: 'observable-room',
    message: value,
  });
}

function createMemberElement(member) {
  const { name, color } = member.clientData;
  const el = document.createElement('div');
  el.appendChild(document.createTextNode(name));
  el.className = 'member';
  el.style.color = color;
  return el;
}

function updateMembersDOM() {
  DOM.membersCount.innerText = `${members.length} users in room:`;
  DOM.membersList.innerHTML = '';
  members.forEach(member =>
    DOM.membersList.appendChild(createMemberElement(member))
  );
}

function createMessageElement(text, member) {
  const el = document.createElement('div');
  el.appendChild(createMemberElement(member));
  el.appendChild(document.createTextNode(text));
  el.className = 'message';
  return el;
}

function addMessageToListDOM(text, member) {
  const el = DOM.messages;
  const wasTop = el.scrollTop === el.scrollHeight - el.clientHeight;
  el.appendChild(createMessageElement(text, member));
  if (wasTop) {
    el.scrollTop = el.scrollHeight - el.clientHeight;
  }
}
</code>```

答:
How to store a input box value in a variable

const inputnamefield = document.querySelector('.inputnamefield');
const button = document.querySelector('.submitbtn');

button.addEventListener('click', (e) => {
   setTimeout(() => {
       const yourname = inputnamefield.value
   }, 1);
})
```

Body:
I am trying to make a chat application with scaledrone.
I was following this tutorial: https://www.scaledrone.com/blog/javascript-chat-room-tutorial/
but after setting up the basic chat, I wanted to let users define their own name. So I made an input box and then tried using js to take the input box value and assign it to a variable. And then for the name part of the chat application, instead of using the random name function I was using earlier. However, I got the error "can not read properties of null(reading addEventListener) in my console and the submit button did not show up at all.
What did I do wrong?
The code I used is in pastebin links below.
The scaledrone documentation is here: https://www.scaledrone.com/docs/api-clients/javascript
Thanks in advance.
also, I added the raw text of my javascript file below because stack overflow won't let me post without adding some code(first time posting to stack overflow lol).

https://pastebin.com/9DvF3WnX
https://pastebin.com/UrZ1xsMB

const CLIENT_ID = 'keECa1lpVtgABa1F';
const splash=document.querySelector('.splash');
const stuffjs=document.querySelector('.stuff');
var yourname;

/*function createMenuItem(name) {
  let inputname = document.createElement('input');
  inputname.placeholder = name;
  inputname.className='inputnamefield';
  return inputname;
}*/
/*function createButton(btnname){
  let btn = document.createElement('input');
  btn.type = 'submit';
  btn.className='submitbtn';
  return btn;
}*/
const inputnameagain=document.querySelector('.inputnamefield');
const buttoon=document.querySelector('.submitbtn');
buttoon.addEventListener('click',(e) => {
  setTimeout(()=>{
  yourname=inputboxstuff.value()
  },1);
});

/*document.addEventListener('DOMContentLoaded',(e)=>{
  setTimeout(()=>{
    splash.classList.add('display-none');

  },2000);
})
splash.addEventListener('mousedown',
(e)=>{
  setTimeout(()=>{
    splash.parentElement.removeChild(splash);

  },1);
})*/

const drone = new ScaleDrone(CLIENT_ID, {
  data: { // Will be sent out as clientData via events
    name: yourname,
    color: getRandomColor(),
  },
});

let members = [];

drone.on('open', error => {
  if (error) {
    return console.error(error);
  }
  console.log('Successfully connected to Scaledrone');

  const room = drone.subscribe('observable-room');
  room.on('open', error => {
    if (error) {
      return console.error(error);
    }
    console.log('Successfully joined room');
  });

  room.on('members', m => {
    members = m;
    updateMembersDOM();
  });

  room.on('member_join', member => {
    members.push(member);
    updateMembersDOM();
  });

  room.on('member_leave', ({id}) => {
    const index = members.findIndex(member => member.id === id);
    members.splice(index, 1);
    updateMembersDOM();
  });

  room.on('data', (text, member) => {
    if (member) {
      addMessageToListDOM(text, member);
    } else {
      // Message is from server
    }
  });
});

drone.on('close', event => {
  console.log('Connection was closed', event);
});

drone.on('error', error => {
  console.error(error);
});

function getRandomName() {
  const adjs = ["autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark", "summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter", "patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green", "long", "late", "lingering", "bold", "little", "morning", "muddy", "old", "red", "rough", "still", "small", "sparkling", "throbbing", "shy", "wandering", "withered", "wild", "black", "young", "holy", "solitary", "fragrant", "aged", "snowy", "proud", "floral", "restless", "divine", "polished", "ancient", "purple", "lively", "nameless"];
  const nouns = ["waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning", "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter", "forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook", "butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly", "feather", "grass", "haze", "mountain", "night", "pond", "darkness", "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder", "violet", "water", "wildflower", "wave", "water", "resonance", "sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper", "frog", "smoke", "star"];
  return (
    adjs[Math.floor(Math.random() * adjs.length)] +
    "_" +
    nouns[Math.floor(Math.random() * nouns.length)]
  );
}

function getRandomColor() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16);
}

//------------- DOM STUFF

const DOM = {
  membersCount: document.querySelector('.members-count'),
  membersList: document.querySelector('.members-list'),
  messages: document.querySelector('.messages'),
  input: document.querySelector('.message-form__input'),
  form: document.querySelector('.message-form'),
};

DOM.form.addEventListener('submit', sendMessage);

function sendMessage() {
  const value = DOM.input.value;
  if (value === '') {
    return;
  }
  DOM.input.value = '';
  drone.publish({
    room: 'observable-room',
    message: value,
  });
}

function createMemberElement(member) {
  const { name, color } = member.clientData;
  const el = document.createElement('div');
  el.appendChild(document.createTextNode(name));
  el.className = 'member';
  el.style.color = color;
  return el;
}

function updateMembersDOM() {
  DOM.membersCount.innerText = `${members.length} users in room:`;
  DOM.membersList.innerHTML = '';
  members.forEach(member =>
    DOM.membersList.appendChild(createMemberElement(member))
  );
}

function createMessageElement(text, member) {
  const el = document.createElement('div');
  el.appendChild(createMemberElement(member));
  el.appendChild(document.createTextNode(text));
  el.className = 'message';
  return el;
}

function addMessageToListDOM(text, member) {
  const el = DOM.messages;
  const wasTop = el.scrollTop === el.scrollHeight - el.clientHeight;
  el.appendChild(createMessageElement(text, member));
  if (wasTop) {
    el.scrollTop = el.scrollHeight - el.clientHeight;
  }
}


问:
Microsoft.AspNetCore.Mvc.NewtonsoftJson 6.0.2 is not compatible with net5.0
I am using Visual Studio 2019 on a Mac, trying to start a REST API project.

Immediately got stuck when trying to install NewtonsoftJson 6.0.2

I was just following a tutorial, and version of NewtonsoftJson that was being using was 3.1.9.

Firstly - Is there a way to install 6.0.2?

Secondly - If 6.0.2 cannot be installed, is there a way to install the older version so I can proceed with this tutorial?

Edit

I added Newtonsoft.Json 13.0.1 per suggestions in the comments, but I am still getting the red line beneath the text below that reads AddNewtonsoftJson():

```<code>services.AddControllersWithViews().AddNewtonsoftJson();
</code>```

答:
It seems you've misstated in your question what you're installing. The package you're actually installing is not Newtonsoft.Json, but rather Microsoft.AspNetCore.Mvc.NewtonsoftJson. The AddNewtonsoftJson extension method comes from that library.

Newtonsoft.Json is a library for serializing/deserializing JSON. It's one of the most heavily used .NET libraries out there. In fact, it's the most downloaded package on Nuget.org.

Microsoft.AspNetCore.Mvc.NewtonsoftJson is a library that integrates Newtonsoft.Json with ASP.NET Core MVC so that it uses Newtonsoft.Json for its JSON serialization/deserialization needs. It depends on Newtonsoft.Json, which you can see by examining the dependencies of the package on nuget.org.

So, you say your app is .NET 5, and you're following a tutorial that uses Microsoft.AspNetCore.Mvc.NewtonsoftJson v6.0.2. If you look at the dependencies page on nuget.org (or better yet, on Fuget where it's a bit clearer), you'll see that v6.0.2 only runs on .NET 6. Therefore the tutorial you're following is for .NET 6.

So, you've got a couple possible options from here:

You can install the latest version of Microsoft.AspNetCore.Mvc.NewtonsoftJson that supports running on .NET 5. That's  v5.0.14, and it depends on Newtonsoft.Json v12.0.2. That's not the most recent (it came out in 2019), but it's not extremely old. Keep in mind there may be other differences in your .NET 5 app compared to the .NET 6 tutorial you're trying to run.

You can start using .NET 6 to match your tutorial. That gets you on the newest version, which has a lot of nice improvements, and it's a Long Term Support version, so it will be supported much longer than .NET 5. This may require a newer version of Visual Studio, or you could use Visual Studio Code.

You can find a different tutorial altogether that is specific to .NET 5.

Body:
I am using Visual Studio 2019 on a Mac, trying to start a REST API project.

Immediately got stuck when trying to install NewtonsoftJson 6.0.2

I was just following a tutorial, and version of NewtonsoftJson that was being using was 3.1.9.

Firstly - Is there a way to install 6.0.2?

Secondly - If 6.0.2 cannot be installed, is there a way to install the older version so I can proceed with this tutorial?

Edit

I added Newtonsoft.Json 13.0.1 per suggestions in the comments, but I am still getting the red line beneath the text below that reads AddNewtonsoftJson():

services.AddControllersWithViews().AddNewtonsoftJson();


问:
DJI Assistant 2 simulator will not run missions. DJI ERROR 5021 "TOTAL MISSION DISTANCE TOO LARGE"
So I have been writing an application to run custom missions, the missions run fine and everything works as intended, however when attempting to run on the simulator I receive this error.

The missions should not be considered too large as I calculate distance at 1081m and attempting to physically run this mission succeeds. Trying to do the same in the simulator is resulting in error code 5021.

If it is helpful I also get error code 1003 "This process has timed out"

Any help with this would be appreciated as I have spent much time trying to solve this issue.

I can provide further info if needed however nothing seems relevant at this time except that which I have said.

答:
Are you using the waypoint function to let the drone move with pre-defined latitude and longitude? If the answer is yes! then possibly that because the constant latitude and longitude in the GUI of the simulator are far from your GPS points.
And this is not allowed from the SDK for safety reasons.

So, basically, it is not allowed to set waypoints far from the Home location (the location where the drone would take off from)


问:
laravel morphToMany with additional field in pivot table
I create the following database structure to manage different service contents for different batch and just because this structure must be replicated for sub services too I decided to use a "Many To Many Polymorphic Relations" with Laravel.

.

To create a new record in table "service_and_relatives_contents" and another association record in table "service____relative_content_batch_a" (my pivot table) I used :

```<code>$service -> relatives() -> create($arrRelatives)
</code>```

the problem is with that code is that I can't populate "batches_id" fields in my pivot table.
For this reason I used the following code :

```<code>$relativeId = $service->relatives()->create($arrRelatives)->id;
$service->relatives()->updateExistingPivot($relativeId,['batches_id'=>$keyRelatives]);
</code>```

It works well but it is the right way to create and associate a record in the same time?

Please consider this as an example, I will use laravel conventions for table name and foreign-key for the live version.

答:
I tink make a create query build morpth and polymorph Many to Many

```<code>               |-----------------------------------------|
User::join(table_a, user.id, forein.id)->join(table_b, table_a.id, forein.id)
  |----------------------|

> $res = User::join('model_has_roles','users.id','model_id')->join('role_has_permissions','model_has_roles.role_id','model_id')->get()
</code>```

thank

Body:
I create the following database structure to manage different service contents for different batch and just because this structure must be replicated for sub services too I decided to use a "Many To Many Polymorphic Relations" with Laravel.

.

To create a new record in table "service_and_relatives_contents" and another association record in table "service____relative_content_batch_a" (my pivot table) I used :

$service -> relatives() -> create($arrRelatives)

the problem is with that code is that I can't populate "batches_id" fields in my pivot table.
For this reason I used the following code :

$relativeId = $service->relatives()->create($arrRelatives)->id;
$service->relatives()->updateExistingPivot($relativeId,['batches_id'=>$keyRelatives]);

It works well but it is the right way to create and associate a record in the same time?

Please consider this as an example, I will use laravel conventions for table name and foreign-key for the live version.

Body:
I tink make a create query build morpth and polymorph Many to Many

               |-----------------------------------------|
User::join(table_a, user.id, forein.id)->join(table_b, table_a.id, forein.id)
  |----------------------|

> $res = User::join('model_has_roles','users.id','model_id')->join('role_has_permissions','model_has_roles.role_id','model_id')->get()

thank


答:
Simple and easy solution change animation-fill-mode: forwards; to animation-fill-mode: both; and width into px or %

.r1 {
    animation-name: moveWidth;
    animation-delay: 2s;
    animation-duration: 2s;
    animation-iteration-count: 1;
    animation-timing-function: linear;
    animation-direction: normal;
    animation-fill-mode: both;
}

@keyframes moveWidth {
    0% {
        width: 0%;
    }
    100% {
        width: 200px;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<body>

    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
    <rect class="r1" id="r1" x="10" y="10" width="200" height="20" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="10" y="30" width="200" height="20" stroke="none" fill="green"></rect>
  </svg>
</body>

</html></code>```

Title: Hide SVG width till the animation-delay

Body:
Simple and easy solution change animation-fill-mode: forwards; to animation-fill-mode: both; and width into px or %

.r1 {
    animation-name: moveWidth;
    animation-delay: 2s;
    animation-duration: 2s;
    animation-iteration-count: 1;
    animation-timing-function: linear;
    animation-direction: normal;
    animation-fill-mode: both;
}

@keyframes moveWidth {
    0% {
        width: 0%;
    }
    100% {
        width: 200px;
    }
}

<!DOCTYPE html>
<html>

<body>

    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
    <rect class="r1" id="r1" x="10" y="10" width="200" height="20" stroke="none" fill="orange"></rect>
    <rect class="r2" id="r2" x="10" y="30" width="200" height="20" stroke="none" fill="green"></rect>
  </svg>
</body>

</html>


答: You need to find a gateway or such kind of service first. The service provider will probably offer you the method or API to integrate your web site to their service. This topic has also been discussed in these forums for several times before. You can search for those threads and see if they are suitable for you.</p>

Title: How to send SMS from asp.net application

Body:
Possible Duplicate:

  sms from our site

I want to send SMS from my asp.net application. Suppose there will be 2 text boxes in my UI, one for mobile or cell phone number and another one is for message writing. When I will click the submit button then this SMS will be send to that cell number.
I want to use my cell phone number as transmission number.
Please inform me the possible ways.
I am using asp.net C#


问:
How to map a subarray
I am using a sample I found online to map a subarray and can't seem to get it to work.

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-map-subarray',
  templateUrl: './map-subarray.component.html',
  styleUrls: ['./map-subarray.component.css']
})
export class MapSubarrayComponent implements OnInit {

  books: any[] = [
    {
      title: 'Books by Nigerian authors',
      // An array of books in shelves
      shelves: [
        {
          id: 1,
          category: 'Fiction',
          title: 'Things fall Apart',
          author: 'Chinua Achebe'
        },
        {
          id: 2,
          category: 'drama',
          title: 'Under the Udala trees',
          author: 'Chinelo Okparanta'
        }
      ]
    }
  ];
  categories: any[] = [];

  constructor() { }

  ngOnInit(): void {
    // Gets the selves from the books array
    this.categories = this.books.map((book) => this.books.shelves);

    // Gets the list of categories on the shelves
    this.categories = this.books.map((book) => book.shelves.map((shelf) => shelf.category);
  }

}
</code>```

But I get an error in the first map on shelves:

And an error on shelf for the second mapping line. Perhaps fixing the 1st map will lead to fixing the second.

jitendra's answer works fine.

But I am curious why using the map for shelves gives me back an array which I cannot apparently use - ie. shelves.title. And it doesn't work in the template with the *ngFor.

But the index one does work.

Does that have something to do with flattening?

答:
To get shelves you didn't require use map function.

You can use the below code to get shelves. as you can see in the first index of the array you have shelves. so you need to 0th index to get shelves.

```<code>this.categories = [...this.books[0].shelves];
</code>```

Or  using if you want to use map then you can use this code:

```<code>this.categories = this.books.map((book) => this.books[0].shelves);

// Gets the list of categories on the shelves
</code>```

I think you missed one round bracket. You can try this code:

```<code>this.categories = this.books.map((book) => book.shelves.map((shelf) => shelf.category));
 // this.categories It will console ["Fiction","drama"]
 console.log(this.categories);
</code>```

Title: How to map a subarray

Body:
I am using a sample I found online to map a subarray and can't seem to get it to work.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-map-subarray',
  templateUrl: './map-subarray.component.html',
  styleUrls: ['./map-subarray.component.css']
})
export class MapSubarrayComponent implements OnInit {

  books: any[] = [
    {
      title: 'Books by Nigerian authors',
      // An array of books in shelves
      shelves: [
        {
          id: 1,
          category: 'Fiction',
          title: 'Things fall Apart',
          author: 'Chinua Achebe'
        },
        {
          id: 2,
          category: 'drama',
          title: 'Under the Udala trees',
          author: 'Chinelo Okparanta'
        }
      ]
    }
  ];
  categories: any[] = [];

  constructor() { }

  ngOnInit(): void {
    // Gets the selves from the books array
    this.categories = this.books.map((book) => this.books.shelves);

    // Gets the list of categories on the shelves
    this.categories = this.books.map((book) => book.shelves.map((shelf) => shelf.category);
  }

}

But I get an error in the first map on shelves:

And an error on shelf for the second mapping line. Perhaps fixing the 1st map will lead to fixing the second.

jitendra's answer works fine.

But I am curious why using the map for shelves gives me back an array which I cannot apparently use - ie. shelves.title. And it doesn't work in the template with the *ngFor.

But the index one does work.

Does that have something to do with flattening?

Body:
To get shelves you didn't require use map function.

You can use the below code to get shelves. as you can see in the first index of the array you have shelves. so you need to 0th index to get shelves.

this.categories = [...this.books[0].shelves];

Or  using if you want to use map then you can use this code:

this.categories = this.books.map((book) => this.books[0].shelves);

// Gets the list of categories on the shelves

I think you missed one round bracket. You can try this code:

this.categories = this.books.map((book) => book.shelves.map((shelf) => shelf.category));
 // this.categories It will console ["Fiction","drama"]
 console.log(this.categories);


问:
Join three tables that do not all share foreign keys
I have three tables: event, location and itinerary. Event and itinerary have a foreign key constraint. Location and itinerary have a foreign key constraint. Itinerary has a foreign key constraint on both location and event.

I would like to select an event and join the itinerary and location to the query. However, I am trying to figure out the best way to do this. I could just select from the itinerary table, however, an event can have multiple itinerary entries and i only need to grab the earliest itinerary. This is the code I have so far, it is failing with:

INVALID SYNTAX on line 11

```<code>SELECT e.id,
    (SELECT i.start_time FROM "itinerary" i WHERE e.id = i.event_id ORDER BY start_time LIMIT 1),
    (SELECT i.end_time FROM "itinerary" i WHERE e.id = i.event_id ORDER BY end_time LIMIT 1),
    e.event_name, e.description, e.is_plan, e.timestamp, e.organizer_id, e.event_type_id, et.value,
    e.curated, l.city, l.state_province, l.country, l.geolocation
    AS event_type_value, ep.privacy
    AS event_privacy
    FROM "event" e
    INNER JOIN event_type et ON e.event_type_id = et.id
    INNER JOIN event_privacy ep ON e.event_privacy_id = ep.id
    INNER JOIN location l WHERE i.location_id = l.id
    WHERE  e.premium=True AND l.city = 'Madrid';
</code>```

I am pretty sure it is because I am trying to create a relationship between two unrelated tables. So my question is what should I do? Should I use a CROSS JOIN, SUB QUERY or select from Itinerary and join the other related tables? If I went with the last option how could i select the itinerary that has the earliest start date since one event can have multiple itineraries?

答:
try change your line 11 to

```<code>INNER JOIN location l ON i.location_id = l.id
</code>```

instead of

```<code>INNER JOIN location l WHERE i.location_id = l.id
</code>```

Body:
I have three tables: event, location and itinerary. Event and itinerary have a foreign key constraint. Location and itinerary have a foreign key constraint. Itinerary has a foreign key constraint on both location and event.

I would like to select an event and join the itinerary and location to the query. However, I am trying to figure out the best way to do this. I could just select from the itinerary table, however, an event can have multiple itinerary entries and i only need to grab the earliest itinerary. This is the code I have so far, it is failing with:

INVALID SYNTAX on line 11

SELECT e.id,
    (SELECT i.start_time FROM "itinerary" i WHERE e.id = i.event_id ORDER BY start_time LIMIT 1),
    (SELECT i.end_time FROM "itinerary" i WHERE e.id = i.event_id ORDER BY end_time LIMIT 1),
    e.event_name, e.description, e.is_plan, e.timestamp, e.organizer_id, e.event_type_id, et.value,
    e.curated, l.city, l.state_province, l.country, l.geolocation
    AS event_type_value, ep.privacy
    AS event_privacy
    FROM "event" e
    INNER JOIN event_type et ON e.event_type_id = et.id
    INNER JOIN event_privacy ep ON e.event_privacy_id = ep.id
    INNER JOIN location l WHERE i.location_id = l.id
    WHERE  e.premium=True AND l.city = 'Madrid';

I am pretty sure it is because I am trying to create a relationship between two unrelated tables. So my question is what should I do? Should I use a CROSS JOIN, SUB QUERY or select from Itinerary and join the other related tables? If I went with the last option how could i select the itinerary that has the earliest start date since one event can have multiple itineraries?

Body:
try change your line 11 to

INNER JOIN location l ON i.location_id = l.id

instead of

INNER JOIN location l WHERE i.location_id = l.id


问:
Jetpack compose and viewModels - Ignore last state value on first composition
How do i ignore the viewModel's last state on the first composition of a composable?
The usecase is the following:

User enters MyDumbComposable

Clicks to add a song to a playlist

When the action is successful, popBack

This is my viewModel

```<code>@HiltViewModel
class AddToPlaylistViewModel @Inject constructor(
    private val addToPlaylistUseCase: AddToPlaylistUseCase,
) : ViewModel() {

    private val _state = mutableStateOf<AddToPlaylistState>(AddToPlaylistState.Initial)

    val state: State<AddToPlaylistState> = _state

    operator fun invoke(
        params: AddToPlaylistParams
    ) {
        addToPlaylistUseCase(params)
            .flowOn(Dispatchers.IO)
            .onEach { _state.value = it }
            .launchIn(viewModelScope)
    }
}
</code>```

This is MyDumbComposable

```<code>fun MyDumbComposable(
    addToPlaylistViewModel: AddToPlaylistViewModel = hiltViewModel(),
    song: Song,
    popBack: () -> Unit
) {
    if (addToPlaylistViewModel.state.value is AddToPlaylistState.Loaded) {
        LaunchedEffect(Unit) {
            popBack()
        }
    }

    fun onClick(playlist: PlaylistWithSongs) {
        addToPlaylistViewModel(
            AddToPlaylistParams(
                selected = Selected(listOf(song)),
                playlist = playlist.playlist
            )
        )
    }
 ///...
</code>```

It works the first time and pops correctly.
However, whenever the user returns to that
composable, the AddToPlaylistViewModel is cached
so the last value is still AddToPlaylistState.Loaded,
meaning it'll pop the screen right away.

答:
I ended up resetting my state using a DisposableEffect:</p>
```<code>DisposableEffect(Unit) {
        onDispose {
            addToPlaylistViewModel.resetState()
        }
    }
</code>```

Body:
How do i ignore the viewModel's last state on the first composition of a composable?
The usecase is the following:

User enters MyDumbComposable

Clicks to add a song to a playlist

When the action is successful, popBack

This is my viewModel

@HiltViewModel
class AddToPlaylistViewModel @Inject constructor(
    private val addToPlaylistUseCase: AddToPlaylistUseCase,
) : ViewModel() {

    private val _state = mutableStateOf<AddToPlaylistState>(AddToPlaylistState.Initial)

    val state: State<AddToPlaylistState> = _state

    operator fun invoke(
        params: AddToPlaylistParams
    ) {
        addToPlaylistUseCase(params)
            .flowOn(Dispatchers.IO)
            .onEach { _state.value = it }
            .launchIn(viewModelScope)
    }
}

This is MyDumbComposable

fun MyDumbComposable(
    addToPlaylistViewModel: AddToPlaylistViewModel = hiltViewModel(),
    song: Song,
    popBack: () -> Unit
) {
    if (addToPlaylistViewModel.state.value is AddToPlaylistState.Loaded) {
        LaunchedEffect(Unit) {
            popBack()
        }
    }

    fun onClick(playlist: PlaylistWithSongs) {
        addToPlaylistViewModel(
            AddToPlaylistParams(
                selected = Selected(listOf(song)),
                playlist = playlist.playlist
            )
        )
    }
 ///...

It works the first time and pops correctly.
However, whenever the user returns to that
composable, the AddToPlaylistViewModel is cached
so the last value is still AddToPlaylistState.Loaded,
meaning it'll pop the screen right away.

Body:
I ended up resetting my state using a DisposableEffect:

DisposableEffect(Unit) {
        onDispose {
            addToPlaylistViewModel.resetState()
        }
    }


问:
How to make navbar responsive?
I just learned about responsive design and adapting a page to smaller screens for accessibility, however, I'm having trouble thinking about a way to make my navbar responsive (showing the three bars instead of the whole navbar.

This is my custom navbar:

:root{ --main_color: #004771; --main_color_shade: #072060; --footer_color: #383838;}

.navbar_maincontainer{width:100%; height:50px; background-color:var(--main_color); display:flex; align-items:center; padding:0px 100px; font-size:17px;}

.navbar_link_wrapper{width:auto; height:100%; position:relative; }

.navbar_link{color:white; font-size:17px; width:100%; height:100%; display:flex; justify-content:center; align-items:center; padding:0px 30px;}

.navbar_link_wrapper:hover{background-color:var(--main_color_shade);}

.navbar_sublinks_container{position:absolute; box-shadow:4px 4px 4px rgba(0,0,0,0.2); width:300px; height:auto; left:0px; top:-700px; transition:all 600ms ease; background-color:#383838; z-index:9999999999; display:none; flex-direction:column;}

.navbar_sublink{padding:0px 15px; height:50px; display:flex; align-items:center; transition:all 600ms ease; color:rgba(255,255,255,0.8); font-size:14px; font-weight:400;}

.navbar_sublinks_line{width:100%; border-bottom:1px solid rgba(255,255,255,0.1); height:1px; margin:0 auto;}

.navbar_sublinks_title{padding:10px 0px; width:100%; color:white; font-size:13px;}

.active{background-color:var(--main_color_shade);}

.active_sub{background-color:rgba(0,0,0,0.3);}

.navbar_sublink:hover{background-color:rgba(0,0,0,0.3);}

.navbar_link_wrapper:hover .navbar_sublinks_container{display:flex;  top:100%;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar_maincontainer" style="">
    <div class="navbar_link_wrapper">
        Inicio
    </div>
    <div class="navbar_link_wrapper" style="margin-left:auto;">
        Servicios
        <div class="navbar_sublinks_container" style=" ">
            Clases a domicilio
            Clases en grupo
            Clases para cachorros
    </div>
    <div class="navbar_link_wrapper" style="">
        Quienes somos
    </div>
    <div class="navbar_link_wrapper">
        Formate con nosotros
        <div class="navbar_sublinks_container">
            Formación básica
            Formación avanzada
        </div>
    </div>
    <div class="navbar_link_wrapper">
        Contactar

    </div>
    <div class="navbar_link_wrapper">
        Testimonios
    </div>
    <div class="navbar_link_wrapper">
        Preguntas
    </div>
</div></code>```

答:
 const selectElement =(element)=>document.querySelector(element);
   selectElement('.mobile-menu').addeEventListner('click',()=>{
     selectElement('header').classList.toggle('active');
   })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,
*::after,
*::before {
  padding: 0;
  margin: 0;
}
html {
  font-size: 10px;
  font-family: "SF Pro Display", sans-serif;
}
a {
  display: block;
  text-decoration: none !important;
}
.container {
  max-width: 98rem;
  margin: 0 auto;
  padding: 0 2.2rem;
}

.header {
  position: fixed;
  top: 0;
  z-index: 1400;
  width: 100%;
  height: 4.4rem;
  background-color: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(2rem);
}

.nav-list {
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 -1rem;
}

.nav-list-mobile {
  display: none;
}

.nav-link {
  font-size: 1.4rem;
  color: #fff;
  padding: 0 1rem;
  transition: opacity 0.5s;
}

.nav-link:hover {
  opacity: 0.7;
}

.nav-link-apple {
  width: 1.6rem;
  height: 4.4rem;
  background: url("/assets/apple.svg") center no-repeat;
}

.nav-link-search {
  width: 1.6rem;
  height: 4.4rem;
  background: url("/assets/search.svg") center no-repeat;
}
.nav-link-bag {
  width: 1.4rem;
  height: 4.4rem;
  background: url("/assets/bag.svg") center no-repeat;
}

.iphone-11-pro {
  background: url("/assets/iphone_11_pro_large.jpg");
  margin-top: 4.4rem;
}

.hero {
  height: 69.2rem;
  background-size: auto 73.6rem;
  background-position: center;
  background-repeat: no-repeat;
  border-top: 0.6rem solid #fff;
  border-bottom: 0.6rem solid #fff;
}

.title {
  color: #fff;
  text-align: center;
  padding-top: 5.5rem;
}

.title-heading {
  font-size: 5.6rem;
  line-height: 1.07143;
  letter-spacing: -0.005rem;
}

.title-sub-heading {
  font-size: 2.65rem;
  margin-top: 0.6rem;
  letter-spacing: 0.008rem;
  font-weight: 400;
}

.title-price {
  font-size: 1.7rem;
  color: #888;
  margin-top: 0.68rem;
}

.cta {
  text-align: center;
  margin-top: 1.8rem;
}
.cta-link {
  color: #66bbff;
  font-size: 2.1rem;
  display: inline-block;
}

.cta-link:nth-child(2) {
  margin-top: 2.6rem;
}

.cta-link:hover {
  border-bottom: 2px solid #66bbff;
}

@media screen and (max-width: 1068px) {
  .iphone-11-pro {
    background: url("/assets/iphone_11_pro_medium.jpg");
  }
  .hero {
    height: 65rem;
    background-size: auto 69.8rem;
    background-position: bottom center;
    background-repeat: no-repeat;
    // border-top: .6rem solid #fff;
    // border-bottom: .6rem solid #fff ;
  }
}

@media screen and (max-width: 767px) {
  .header {
    height: 4.8rem;
    transition: background 0.36s cubic-bezier(0.32, 0.68, 0.24, 1),
      height 0.56s cubic-bezier(0.32, 0.68, 0.24, 1);
  }

  .header .container {
    padding: 0;
  }

  .nav-list {
    margin-top: 0;
  }

  .nav-item {
    width: 4.8rem;
    height: 4.8rem;
    display: flex;
    justify-content: center;
  }
  .nav-item-hidden {
    display: none;
  }
  .mobile-menu {
    position: relative;
    z-index: 1500;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .line {
    position: absolute;
    width: 1.7rem;
    height: 1px;
    background-color: #fff;
    transition: margin-top 0.3192s cubic-bezier(0.04, 0.04, 0.12, 0.96);
  }

  .line-top {
    margin-top: 3px;
  }
  .line-bottom {
    margin-top: -0.4rem;
  }
  .active .line-top {
    margin-top: 0;
    transform: rotate(45deg);
    transition: transform 0.3192s 0.1s cubic-bezier(0.04, 0.04, 0.12, 0.96);
  }
  .active .line-bottom {
    margin-top: 0;
    transform: rotate(-45deg);
    transition: transform 0.3192s 0.1s cubic-bezier(0.04, 0.04, 0.12, 0.96);
  }

  .header.active {
    height: 100%;
    background-color: #000;
  }
  .nav-link-apple {
    width: 1.8rem;
    height: 4.8rem;
    position: relative;
    z-index: 1500;

    //
  }
  .nav-link-bag {
    width: 1.8rem;
    height: 4.8rem;
    transition: opacity 3s;
  }

  .nav {
    position: relative;
  }
  .nav-link {
    font-size: 1.7rem;
    padding: 0;
    margin: auto 0;
  }

  .nav-list-larger {
    position: fixed;
    top: 0;
    left: 0;
    width: 0;
    height: 0;
    display: block;
    padding: 10.5rem;
    z-index: 1000;
    opacity: 0;
    box-sizing: border-box;
    transition: opacity 0.3s;
  }

  .nav-list-mobile {
    display: flex;
  }

  .active .nav-list-larger {
    width: 100%;
    height: 100vh;
    opacity: 1;
    visibility: visible;
  }
  .active .nav-list-bag {
    opacity: 0;
    transition: opacity;
  }
  .nav-list-larger .nav-item {
    width: 100%;
    justify-content: flex-start;
    border-bottom: 2px solid rgba(255, 255, 255, 0.1);
  }
  .nav-list-larger .nav-item:nth-child(9) {
    border-bottom: none;
  }

  .active .nav-list-larger .nav-item {
    animation: fadeIn 1s ease-in;
  }
  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
}</code>```

                    Mac

                    iPad

                    iPhone

                    Watch

                    TV

                    Music

                    Support

```

Title: How to make navbar responsive?

Body:
I just learned about responsive design and adapting a page to smaller screens for accessibility, however, I'm having trouble thinking about a way to make my navbar responsive (showing the three bars instead of the whole navbar.

This is my custom navbar:

:root{ --main_color: #004771; --main_color_shade: #072060; --footer_color: #383838;}

.navbar_maincontainer{width:100%; height:50px; background-color:var(--main_color); display:flex; align-items:center; padding:0px 100px; font-size:17px;}

.navbar_link_wrapper{width:auto; height:100%; position:relative; }

.navbar_link{color:white; font-size:17px; width:100%; height:100%; display:flex; justify-content:center; align-items:center; padding:0px 30px;}

.navbar_link_wrapper:hover{background-color:var(--main_color_shade);}

.navbar_sublinks_container{position:absolute; box-shadow:4px 4px 4px rgba(0,0,0,0.2); width:300px; height:auto; left:0px; top:-700px; transition:all 600ms ease; background-color:#383838; z-index:9999999999; display:none; flex-direction:column;}

.navbar_sublink{padding:0px 15px; height:50px; display:flex; align-items:center; transition:all 600ms ease; color:rgba(255,255,255,0.8); font-size:14px; font-weight:400;}

.navbar_sublinks_line{width:100%; border-bottom:1px solid rgba(255,255,255,0.1); height:1px; margin:0 auto;}

.navbar_sublinks_title{padding:10px 0px; width:100%; color:white; font-size:13px;}

.active{background-color:var(--main_color_shade);}

.active_sub{background-color:rgba(0,0,0,0.3);}

.navbar_sublink:hover{background-color:rgba(0,0,0,0.3);}

.navbar_link_wrapper:hover .navbar_sublinks_container{display:flex;  top:100%;}

        Inicio

        Servicios

            Clases a domicilio
            Clases en grupo
            Clases para cachorros

        Quienes somos

        Formate con nosotros

            Formación básica
            Formación avanzada

        Contactar

        Testimonios

        Preguntas

Body:
 const selectElement =(element)=>document.querySelector(element);
   selectElement('.mobile-menu').addeEventListner('click',()=>{
     selectElement('header').classList.toggle('active');
   })

*,
*::after,
*::before {
  padding: 0;
  margin: 0;
}
html {
  font-size: 10px;
  font-family: "SF Pro Display", sans-serif;
}
a {
  display: block;
  text-decoration: none !important;
}
.container {
  max-width: 98rem;
  margin: 0 auto;
  padding: 0 2.2rem;
}

.header {
  position: fixed;
  top: 0;
  z-index: 1400;
  width: 100%;
  height: 4.4rem;
  background-color: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(2rem);
}

.nav-list {
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 -1rem;
}

.nav-list-mobile {
  display: none;
}

.nav-link {
  font-size: 1.4rem;
  color: #fff;
  padding: 0 1rem;
  transition: opacity 0.5s;
}

.nav-link:hover {
  opacity: 0.7;
}

.nav-link-apple {
  width: 1.6rem;
  height: 4.4rem;
  background: url("/assets/apple.svg") center no-repeat;
}

.nav-link-search {
  width: 1.6rem;
  height: 4.4rem;
  background: url("/assets/search.svg") center no-repeat;
}
.nav-link-bag {
  width: 1.4rem;
  height: 4.4rem;
  background: url("/assets/bag.svg") center no-repeat;
}

.iphone-11-pro {
  background: url("/assets/iphone_11_pro_large.jpg");
  margin-top: 4.4rem;
}

.hero {
  height: 69.2rem;
  background-size: auto 73.6rem;
  background-position: center;
  background-repeat: no-repeat;
  border-top: 0.6rem solid #fff;
  border-bottom: 0.6rem solid #fff;
}

.title {
  color: #fff;
  text-align: center;
  padding-top: 5.5rem;
}

.title-heading {
  font-size: 5.6rem;
  line-height: 1.07143;
  letter-spacing: -0.005rem;
}

.title-sub-heading {
  font-size: 2.65rem;
  margin-top: 0.6rem;
  letter-spacing: 0.008rem;
  font-weight: 400;
}

.title-price {
  font-size: 1.7rem;
  color: #888;
  margin-top: 0.68rem;
}

.cta {
  text-align: center;
  margin-top: 1.8rem;
}
.cta-link {
  color: #66bbff;
  font-size: 2.1rem;
  display: inline-block;
}

.cta-link:nth-child(2) {
  margin-top: 2.6rem;
}

.cta-link:hover {
  border-bottom: 2px solid #66bbff;
}

@media screen and (max-width: 1068px) {
  .iphone-11-pro {
    background: url("/assets/iphone_11_pro_medium.jpg");
  }
  .hero {
    height: 65rem;
    background-size: auto 69.8rem;
    background-position: bottom center;
    background-repeat: no-repeat;
    // border-top: .6rem solid #fff;
    // border-bottom: .6rem solid #fff ;
  }
}

@media screen and (max-width: 767px) {
  .header {
    height: 4.8rem;
    transition: background 0.36s cubic-bezier(0.32, 0.68, 0.24, 1),
      height 0.56s cubic-bezier(0.32, 0.68, 0.24, 1);
  }

  .header .container {
    padding: 0;
  }

  .nav-list {
    margin-top: 0;
  }

  .nav-item {
    width: 4.8rem;
    height: 4.8rem;
    display: flex;
    justify-content: center;
  }
  .nav-item-hidden {
    display: none;
  }
  .mobile-menu {
    position: relative;
    z-index: 1500;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .line {
    position: absolute;
    width: 1.7rem;
    height: 1px;
    background-color: #fff;
    transition: margin-top 0.3192s cubic-bezier(0.04, 0.04, 0.12, 0.96);
  }

  .line-top {
    margin-top: 3px;
  }
  .line-bottom {
    margin-top: -0.4rem;
  }
  .active .line-top {
    margin-top: 0;
    transform: rotate(45deg);
    transition: transform 0.3192s 0.1s cubic-bezier(0.04, 0.04, 0.12, 0.96);
  }
  .active .line-bottom {
    margin-top: 0;
    transform: rotate(-45deg);
    transition: transform 0.3192s 0.1s cubic-bezier(0.04, 0.04, 0.12, 0.96);
  }

  .header.active {
    height: 100%;
    background-color: #000;
  }
  .nav-link-apple {
    width: 1.8rem;
    height: 4.8rem;
    position: relative;
    z-index: 1500;

    //
  }
  .nav-link-bag {
    width: 1.8rem;
    height: 4.8rem;
    transition: opacity 3s;
  }

  .nav {
    position: relative;
  }
  .nav-link {
    font-size: 1.7rem;
    padding: 0;
    margin: auto 0;
  }

  .nav-list-larger {
    position: fixed;
    top: 0;
    left: 0;
    width: 0;
    height: 0;
    display: block;
    padding: 10.5rem;
    z-index: 1000;
    opacity: 0;
    box-sizing: border-box;
    transition: opacity 0.3s;
  }

  .nav-list-mobile {
    display: flex;
  }

  .active .nav-list-larger {
    width: 100%;
    height: 100vh;
    opacity: 1;
    visibility: visible;
  }
  .active .nav-list-bag {
    opacity: 0;
    transition: opacity;
  }
  .nav-list-larger .nav-item {
    width: 100%;
    justify-content: flex-start;
    border-bottom: 2px solid rgba(255, 255, 255, 0.1);
  }
  .nav-list-larger .nav-item:nth-child(9) {
    border-bottom: none;
  }

  .active .nav-list-larger .nav-item {
    animation: fadeIn 1s ease-in;
  }
  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
}

<div class="header">
    <div class="container">
        <nav class="nav">
            <ul class="nav-list nav-list-mobile">
                <li class="nav-item">
                    <div class="mobile-menu">
                        <span class="line line-top"></span>
                        <span class="line line-bottom"></span>
                    </div>
                </li>
                <li class="nav-item">
                    <a href="index.html" class="nav-link nav-link-apple"></a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link nav-link-bag"></a>
                </li>
            </ul>
            <ul class="nav-list nav-list-larger">

                <li class="nav-item nav-item-hidden">
                    <a href="index.html" class="nav-link nav-link-apple">
                       <!-- <i class="fa fa-apple"></i> -->
                    </a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">Mac</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">iPad</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">iPhone</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">Watch</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">TV</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">Music</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link">Support</a>
                </li>
                <li class="nav-item">
                    <a href="#" class="nav-link nav-link-search"></a>
                </li>
                <li class="nav-item nav-item-hidden">
                    <a href="#" class="nav-link nav-link-bag"></a>
                </li>
            </ul>
        </nav>
    </div>
</div>


问:
Use 'import module' or 'from module import'?
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?

答:
Both ways are supported for a reason: there are times when one is more appropriate than the other.

import module: nice when you are using many bits from the module. drawback is that you'll need to qualify each reference with the module name.

from module import ...: nice that imported items are usable directly without module name prefix. The drawback is that you must list each thing you use, and that it's not clear in code where something came from.

Which to use depends on which makes the code clear and readable, and has more than a little to do with personal preference. I lean toward import module generally because in the code it's very clear where an object or function came from. I use from module import ... when I'm using some object/function a lot in the code.

OwnerDisplayName: kRON

OwnerDisplayName: dwc


问:
Argument abbreviations with non-consecutive lettering (partial matching++)?
This is a long shot, but is there a way to specify abbreviations for argument names that aren't consecutive in letter order?  Partial matching doesn't work well for some very long descriptive names.

Examples: (format is "long name - typical partial match - what I'd like")

,stringsAsFactors - ,strings - ,saf or ,asfact

,market_initial - ,mark - ,mkt

,rebalanceFunction - ,rebalance - ,rebfn

This is not a huge deal, and I can see how it would cause more problems than it's worth, but there are some cases where I have a convention for abbreviations across a package and it's weird to break them just because a particular argument is more descriptive (because it's using it in a particular way).  So the long form could tell the user exactly how it's being used in this particular function, but in the short form people would understand what its use is and I could keep the convention.

答:
I'll just add the answer I've given to you in the chat. If you look at how the R core developers do that for different arguments, you just use the function declaration for that. From read.table , which contains an argument as.is and an argument stringsAsFactors that do exactly the same (or actually the opposite) :

```<code>function (file, -some pars-, as.is = !stringsAsFactors, -some more pars -
    stringsAsFactors = default.stringsAsFactors(), -more pars - )
{
    #function code using as.is
}
</code>```

Thing is, this only works if you specify a default value for either of them. Pretty often, NULL is a good candidate :

```<code>myfunc <- function(x, market_initial=NULL, mkt = market_initial, ...){

    if(is.null(mkt)) {
        print("give me market_initial!") # instead of missing(mkt)
    } else {
        print(mkt)
    }

}
</code>```

Body:
I'll just add the answer I've given to you in the chat. If you look at how the R core developers do that for different arguments, you just use the function declaration for that. From read.table , which contains an argument as.is and an argument stringsAsFactors that do exactly the same (or actually the opposite) :

function (file, -some pars-, as.is = !stringsAsFactors, -some more pars -
    stringsAsFactors = default.stringsAsFactors(), -more pars - )
{
    #function code using as.is
}

Thing is, this only works if you specify a default value for either of them. Pretty often, NULL is a good candidate :

myfunc <- function(x, market_initial=NULL, mkt = market_initial, ...){

    if(is.null(mkt)) {
        print("give me market_initial!") # instead of missing(mkt)
    } else {
        print(mkt)
    }

}