问:
set_constrained_layout doesn't work on my code
The following is mycode
if use fig.set_constrained_layout(True) , legend:lga display error
if use fig.tight_layout(), legend:lga dispaly ok
could you please tell me the reason and how to use the set_constrained_layout

import numpy as np
import matplotlib.pyplot as plt

x1 = np.arange(10)
x2 = x1*10
y1 = x1*2
y2 = x1*100

fig = plt.figure()
fig.set_constrained_layout(True)

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,1,frameon=False,sharex=ax1)

ax3 = fig.add_subplot(2,2,2)
ax4 = fig.add_subplot(2,2,2,frameon=False,sharex=ax3)

lg1 = ax1.plot(x1,y1,label='ax1')
lg2 = ax2.plot(x2,y2,label='ax2',color='tab:red')
ax2.get_yaxis().set_ticks_position('right')

lg3 = ax3.plot(x1,y1,label='ax3')
lg4 = ax4.plot(x2,y2,label='ax4',color='tab:red')
ax4.get_yaxis().set_ticks_position('right')

ax1.tick_params(axis='x', labelcolor='tab:blue')
ax1.tick_params(axis='y', labelcolor='tab:red')
ax2.tick_params(axis='y', labelcolor='tab:red')

ax3.tick_params(axis='x', labelcolor='tab:blue')
ax3.tick_params(axis='y', labelcolor='tab:red')
ax4.tick_params(axis='y', labelcolor='tab:red')

loc_val = "upper right"

lga = lg1 + lg2
labs = [l.get_label() for l in lga]
ax1.legend(lga, labs, loc=loc_val ,bbox_to_anchor=(2,1))

lgb = lg3 + lg4
labs = [l.get_label() for l in lgb]
ax3.legend(lgb, labs, loc=loc_val )

fig.set_constrained_layout(True)
#fig.tight_layout()
plt.show()

```

答:
You need to organize the layout using gridspecs (or plt.subplots which does the same thing).  Future versions of matplotlib will do what you want, but its present limitation that each add_subplot command adds a new gridspec, and they don't know anything about each other, so the layout is bad.

In your example you will want to mess with your legend placement.  Not quite sure what you were after with the bbox_to-anchor value.

```<code>import numpy as np
import matplotlib.pyplot as plt

x1 = np.arange(10)
x2 = x1*10
y1 = x1*2
y2 = x1*100

fig = plt.figure()
fig.set_constrained_layout(True)
gs = fig.add_gridspec(2, 2)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 0],frameon=False,sharex=ax1)

ax3 = fig.add_subplot(gs[0, 1])
ax4 = fig.add_subplot(gs[0, 1],frameon=False,sharex=ax3)

lg1 = ax1.plot(x1,y1,label='ax1')
lg2 = ax2.plot(x2,y2,label='ax2',color='tab:red')
ax2.get_yaxis().set_ticks_position('right')

lg3 = ax3.plot(x1,y1,label='ax3')
lg4 = ax4.plot(x2,y2,label='ax4',color='tab:red')

ax4.get_yaxis().set_ticks_position('right')

ax1.tick_params(axis='x', labelcolor='tab:blue')
ax1.tick_params(axis='y', labelcolor='tab:red')
ax2.tick_params(axis='y', labelcolor='tab:red')

ax3.tick_params(axis='x', labelcolor='tab:blue')
ax3.tick_params(axis='y', labelcolor='tab:red')
ax4.tick_params(axis='y', labelcolor='tab:red')

loc_val = "upper right"

lga = lg1 + lg2
labs = [l.get_label() for l in lga]
ax1.legend(lga, labs, loc=loc_val)

lgb = lg3 + lg4
labs = [l.get_label() for l in lgb]
ax3.legend(lgb, labs, loc=loc_val )

plt.show()
</code>```

Body:
You need to organize the layout using gridspecs (or plt.subplots which does the same thing).  Future versions of matplotlib will do what you want, but its present limitation that each add_subplot command adds a new gridspec, and they don't know anything about each other, so the layout is bad.

In your example you will want to mess with your legend placement.  Not quite sure what you were after with the bbox_to-anchor value.

import numpy as np
import matplotlib.pyplot as plt

x1 = np.arange(10)
x2 = x1*10
y1 = x1*2
y2 = x1*100

fig = plt.figure()
fig.set_constrained_layout(True)
gs = fig.add_gridspec(2, 2)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 0],frameon=False,sharex=ax1)

ax3 = fig.add_subplot(gs[0, 1])
ax4 = fig.add_subplot(gs[0, 1],frameon=False,sharex=ax3)

lg1 = ax1.plot(x1,y1,label='ax1')
lg2 = ax2.plot(x2,y2,label='ax2',color='tab:red')
ax2.get_yaxis().set_ticks_position('right')

lg3 = ax3.plot(x1,y1,label='ax3')
lg4 = ax4.plot(x2,y2,label='ax4',color='tab:red')

ax4.get_yaxis().set_ticks_position('right')

ax1.tick_params(axis='x', labelcolor='tab:blue')
ax1.tick_params(axis='y', labelcolor='tab:red')
ax2.tick_params(axis='y', labelcolor='tab:red')

ax3.tick_params(axis='x', labelcolor='tab:blue')
ax3.tick_params(axis='y', labelcolor='tab:red')
ax4.tick_params(axis='y', labelcolor='tab:red')

loc_val = "upper right"

lga = lg1 + lg2
labs = [l.get_label() for l in lga]
ax1.legend(lga, labs, loc=loc_val)

lgb = lg3 + lg4
labs = [l.get_label() for l in lgb]
ax3.legend(lgb, labs, loc=loc_val )

plt.show()


来源: stackexchange

问:
Port is taken for a ssh session
```<code>bind [127.0.0.1]:5432: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 5432
Could not request local forwarding.
</code>```

I am trying to access a remote server but the port 5432 is taken.

I tried lsof -ti:5432 but nothing is working. Plz help.

答:
What seems to be happening here is that you are asked to access PostgreSQL through SSH tunnel as described here: https://www.postgresql.org/docs/10/ssh-tunnels.html

You were asked to use:

```<code>ssh -L localhost:5432:localhost:5432 -Y ambisense@scifilab.dyndns.org
</code>```

That means, port 5432 from scifilab.dyndns.org will be forwarded to your computer's local port 5432 (as long as your computer's 5432 port is not used by anything else). Once that tunnel is made, you can connect to PostgreSQL on scifilab.dyndns.org as if it was running on your machine.

Free up port 5432 on your computer

In your case, 5432 was bound by a local instance of PostgreSQL. sudo service postgresql stop or brew services stop postgresql or similar command depending on your OS will stop PostgreSQL running locally on your computer and free up port 5432. Once that port is freed up, you can run your ssh command to create a tunnel.

Once the tunnel is made, you can connect to scifilab's PostgreSQL using psql -h localhost -U youruser -d yourdatabase.

Create tunnel to another port instead

In case you can't get 5432 freed up, you can tunnel scifilab's PostgreSQL to another port on your computer by running:

```<code>ssh -L localhost:55432:localhost:5432 -Y ambisense@scifilab.dyndns.org
</code>```

Then, you can connect to scifilab's PostgreSQL using:

```<code>psql -h localhost -p 55432 -U youruser -d yourdatabase
</code>```

ContentLicense: CC BY-SA 4.0

Title: Port is taken for a ssh session

Body:
bind [127.0.0.1]:5432: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 5432
Could not request local forwarding.

I am trying to access a remote server but the port 5432 is taken.

I tried lsof -ti:5432 but nothing is working. Plz help.

Body:
What seems to be happening here is that you are asked to access PostgreSQL through SSH tunnel as described here: https://www.postgresql.org/docs/10/ssh-tunnels.html

You were asked to use:

ssh -L localhost:5432:localhost:5432 -Y ambisense@scifilab.dyndns.org

That means, port 5432 from scifilab.dyndns.org will be forwarded to your computer's local port 5432 (as long as your computer's 5432 port is not used by anything else). Once that tunnel is made, you can connect to PostgreSQL on scifilab.dyndns.org as if it was running on your machine.

Free up port 5432 on your computer

In your case, 5432 was bound by a local instance of PostgreSQL. sudo service postgresql stop or brew services stop postgresql or similar command depending on your OS will stop PostgreSQL running locally on your computer and free up port 5432. Once that port is freed up, you can run your ssh command to create a tunnel.

Once the tunnel is made, you can connect to scifilab's PostgreSQL using psql -h localhost -U youruser -d yourdatabase.

Create tunnel to another port instead

In case you can't get 5432 freed up, you can tunnel scifilab's PostgreSQL to another port on your computer by running:

ssh -L localhost:55432:localhost:5432 -Y ambisense@scifilab.dyndns.org

Then, you can connect to scifilab's PostgreSQL using:

psql -h localhost -p 55432 -U youruser -d yourdatabase


问:
How to delete the line which matches the string shared in array
I have a file which consist of text like below

```<code>compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.so
compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.dill
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/Rakefile.pg
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/mmsystem.c
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/winnt.h
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/test/test_xchar.HEX
</code>```

I want to delete the line which is having file extension .so , .dill ,.pg and .HEX. i have tried below code but didn't make out.

```<code>#! /bin/bash
array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
for a in "${array[@]}"
do
sed -i -e "/\$a\b/d" copyright
done
</code>```

答:
Instead of calling sed once for each extension, you can use something like this:

```<code>IFS=$'\n'
grep -F -v "${array[*]}" copyright
</code>```

If its output looks good, redirect it to a file and change its name to copyright (and restore IFS if necessary).

Body:
I have a file which consist of text like below

compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.so
compile_tool/opt/CSDTK/bin/chipgen/Modem2G/toolpool/plugins/Calib/libcalibplugin.dill
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/Rakefile.pg
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/mmsystem.c
compile_tool/opt/mingw32_3.4.4/usr/i586-mingw32msvc/include/winnt.h
compile_tool/opt/CSDTK/bin/lib/ruby/gems/1.8/gems/builder-2.1.2/test/test_xchar.HEX

I want to delete the line which is having file extension .so , .dill ,.pg and .HEX. i have tried below code but didn't make out.

#! /bin/bash
array=(.a .so .bin.ihex .dll .exe .gem .bin .png .HEX)
for a in "${array[@]}"
do
sed -i -e "/\$a\b/d" copyright
done

Body:
Instead of calling sed once for each extension, you can use something like this:

IFS=$'\n'
grep -F -v "${array[*]}" copyright

If its output looks good, redirect it to a file and change its name to copyright (and restore IFS if necessary).


问:
Assigning user role upon registration in laravel issue
In my laravel application i'm trying to assign user role upon the registration. Following is my RegistrationController

```<code>protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'mobile'=>$data['mobile'],
            'username'=>$data['username'],
            'password' => Hash::make($data['password']),
            'propic'=>'user-pic.png',
            'user_roles' =>'customer',
        ]);

        $lastdata = DB::table('users')->orderBy('id', 'desc')->first();
        $last_id=$lastdata->id;

        $user= User::where('id','=',$last_id)->firstOrFail();
        $user->assignRole('customer');
    }
</code>```

But when I run the code user get created, activation mail has been sent but the role is not assigning! how can i fix that and where am I doing wrong?

答:
There are a few things you might want to consider.

1) your function won't proceed further after the return statement. You are creating a user with a return statement hence your code below of that won't execute. I'll recommend storing the return object into some variable.

```<code>// let's say
$user =  User::create([
            'name' => $data['name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'mobile'=>$data['mobile'],
            'username'=>$data['username'],
            'password' => Hash::make($data['password']),
            'propic'=>'user-pic.png',
            'user_roles' =>'customer',
        ]);
// then you can simply get it's value by
$user_id = $user->id; // you won't need to query last added row's value.
</code>```

2) If the user role is not getting saved into your database then check if you have assigned that 'user_roles' field as fillable into User model.

Body:
In my laravel application i'm trying to assign user role upon the registration. Following is my RegistrationController

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'mobile'=>$data['mobile'],
            'username'=>$data['username'],
            'password' => Hash::make($data['password']),
            'propic'=>'user-pic.png',
            'user_roles' =>'customer',
        ]);

        $lastdata = DB::table('users')->orderBy('id', 'desc')->first();
        $last_id=$lastdata->id;

        $user= User::where('id','=',$last_id)->firstOrFail();
        $user->assignRole('customer');
    }

But when I run the code user get created, activation mail has been sent but the role is not assigning! how can i fix that and where am I doing wrong?

Body:
There are a few things you might want to consider.

1) your function won't proceed further after the return statement. You are creating a user with a return statement hence your code below of that won't execute. I'll recommend storing the return object into some variable.

// let's say
$user =  User::create([
            'name' => $data['name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'mobile'=>$data['mobile'],
            'username'=>$data['username'],
            'password' => Hash::make($data['password']),
            'propic'=>'user-pic.png',
            'user_roles' =>'customer',
        ]);
// then you can simply get it's value by
$user_id = $user->id; // you won't need to query last added row's value.

2) If the user role is not getting saved into your database then check if you have assigned that 'user_roles' field as fillable into User model.


问:
How do I set up Android Studio to work completely offline?
I have very slow bandwidth, so I'm trying to keep all the required files on the local machine to work with Android Studio completely offline. When I click on "New Project" it always tries to download a file named gradle-1.6-bin.zip which I downloaded and tried to install locally via the plugin manager but it gives me an error:

fail to load plugin descriptor from file gradle-1.6-bin.zip

So what other files do I need to download and how do I install them properly to work offline with Android Studio?

答:
Android Studio Version < 3.6:

For Windows:

```<code>File -> Settings ->Build, Execution,Deployment -> Build Tools -> Gradle
</code>```

For Mac OS:

```<code>Preferences ->Build, Execution,Deployment -> Build Tools -> Gradle
</code>```

Check/UnCheck Offline work checkbox as per your need.

Android Studio Version >= 3.6:

follow steps in the image:

Body:
Android Studio Version < 3.6:

For Windows:

File -> Settings ->Build, Execution,Deployment -> Build Tools -> Gradle

For Mac OS:

Preferences ->Build, Execution,Deployment -> Build Tools -> Gradle

Check/UnCheck Offline work checkbox as per your need.

Android Studio Version >= 3.6:

follow steps in the image:


问:
Getting error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'Complex') despite overloading the << operator
I am a newbie programmer and I am writing a simple program that adds two complex numbers. I have overloaded << in the following way:

```<code>ostream& operator << (ostream& output, Complex &complex_num){

        output << complex_num.realPart << " + " << "(" << complex_num.imaginaryPart << ")i" <<endl;
        return output;

    }
</code>```

My addition function is as follows:

```<code>Complex operator +(Complex &c2){
        Complex temp;
        temp.realPart=realPart+c2.realPart;
        temp.imaginaryPart=imaginaryPart + c2.imaginaryPart;
        return temp;
    }
</code>```

In my main function, when I try to print out the result by typing in :

```<code>cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num1 + num2<< endl;
</code>```

I get an error saying no match for operator <<. However, when I assign another object num3 = num1 + num2 and then write the following code, the program runs fine.

```<code>cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num3<< endl;
</code>```

What is happening here? Can anyone please help me?

答:
Your operator+ returns a Complex, which is a temporary object. It doesn't work when used with the operator<<, because you are trying to bind it to a non-const reference argument.

A variable can be bound to a non-const reference, so that works.

The fix would be to take the argument to operator<< by const reference:

```<code>ostream& operator << (ostream& output, Complex const &complex_num);
</code>```

so it now works for temporaries as well. Even better, it works for const arguments too.

Body:
I am a newbie programmer and I am writing a simple program that adds two complex numbers. I have overloaded << in the following way:

ostream& operator << (ostream& output, Complex &complex_num){

        output << complex_num.realPart << " + " << "(" << complex_num.imaginaryPart << ")i" <<endl;
        return output;

    }

My addition function is as follows:

Complex operator +(Complex &c2){
        Complex temp;
        temp.realPart=realPart+c2.realPart;
        temp.imaginaryPart=imaginaryPart + c2.imaginaryPart;
        return temp;
    }

In my main function, when I try to print out the result by typing in :

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num1 + num2<< endl;

I get an error saying no match for operator <<. However, when I assign another object num3 = num1 + num2 and then write the following code, the program runs fine.

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num3<< endl;

What is happening here? Can anyone please help me?

Body:
Your operator+ returns a Complex, which is a temporary object. It doesn't work when used with the operator<<, because you are trying to bind it to a non-const reference argument.

A variable can be bound to a non-const reference, so that works.

The fix would be to take the argument to operator<< by const reference:

ostream& operator << (ostream& output, Complex const &complex_num);

so it now works for temporaries as well. Even better, it works for const arguments too.


问:
Bokeh Uncaught Error: property wasn't declared
I have successfully deployed my Django app on PythonAnywhere.com except for my Bokeh plots. Instead of rendering, this is the error that shows up in the console. </p>

```<code>bokeh-1.1.0.min.js:31 Uncaught Error: property Title.plot wasn't declared
at e.setv (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at new e (bokeh-1.1.0.min.js:31)
at Function.t._instantiate_object (bokeh-1.1.0.min.js:31)
at Function.t._instantiate_references_json (bokeh-1.1.0.min.js:31)
at Function.t.from_json (bokeh-1.1.0.min.js:31)
</code>```

<p>It works fine on LocalHost. Now that it is deployed, it throws up this error. I tried to read through the JS file itself, but am clueless. </p>

答:
I was facing a similar issue, but it turned out that the version of bokeh I was using was different from that required by the stylesheets and scripts I imported.

You can check the version of bokeh on the server using:

```<code>pythonX.Y
>>> import bokeh
>>> bokeh.__version__
</code>```

where X.Y is the python version you selected for deployment.
After that, just install the required bokeh module using:

```<code>pythonX.Y -m install bokeh==<required version> --upgrade --user
</code>```

(Mentioning the python version is important.)

Hope that helps!

Body:
I have successfully deployed my Django app on PythonAnywhere.com except for my Bokeh plots. Instead of rendering, this is the error that shows up in the console.

bokeh-1.1.0.min.js:31 Uncaught Error: property Title.plot wasn't declared
at e.setv (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at e [as constructor] (bokeh-1.1.0.min.js:31)
at new e (bokeh-1.1.0.min.js:31)
at Function.t._instantiate_object (bokeh-1.1.0.min.js:31)
at Function.t._instantiate_references_json (bokeh-1.1.0.min.js:31)
at Function.t.from_json (bokeh-1.1.0.min.js:31)

It works fine on LocalHost. Now that it is deployed, it throws up this error. I tried to read through the JS file itself, but am clueless.

Body:
I was facing a similar issue, but it turned out that the version of bokeh I was using was different from that required by the stylesheets and scripts I imported.

You can check the version of bokeh on the server using:

pythonX.Y
>>> import bokeh
>>> bokeh.__version__

where X.Y is the python version you selected for deployment.
After that, just install the required bokeh module using:

pythonX.Y -m install bokeh==<required version> --upgrade --user

(Mentioning the python version is important.)

Hope that helps!


问:
How to undo change in svg element once you cilck outside of it
Right now, I have all svg elements with the class "intermandibularis" (there are two) change to a white fill at 50% opacity when you click either of them.

How do I go about making it so that if you click anywhere, the fill opacity goes back to 0, and then you can redo that all over again?

This is what I have:

function homHighlight(highlightClass){
 let allOfSameLabel = document.getElementsByClassName(highlightClass);

 for (let i = 0; i < allOfSameLabel.length; i++) {
  allOfSameLabel[i].style.fill = "#ffffff";
  allOfSameLabel[i].style.opacity = "0.5";
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Left column -->
 <div class='diagram' style="width:calc(50% - 49px); float:left; height: 85%; background-image: url(Images/mudpuppy_sideview.png); background-repeat: no-repeat; background-size:contain;" id="leftCol">
  <?xml version="1.0" encoding="utf-8"?>
  <!-- Generator: Adobe Illustrator 24.1.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">
  <style type="text/css">
   .tooltip{opacity:0;fill:#FFFFFF;}
  </style>

  <path id="mud_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" onclick="homHighlight('intermandibularis')" d=" M185.78,232.53c-3.77-6.28-32.12,3.11-42.47,5.87c-10.36,2.76-39.02,8.98-41.44,14.5
   c-1.78,4.07,43.88,31.14,67.86,31.42c8.58,0.1,11.4-8.12,12.78-17.61C183.19,261.95,190.96,241.16,185.78,232.53z"/>
  <path id="mud_levator_mandibulae_externus" class="tooltip" title ="Levator mandibulae externus" d="M139.76,287.52c6.37-3.09,21.24-4.4,27.19,0
   c5.96,4.4,32.63,21.76,38.07,24.35s33.93,16.32,32.37,23.05c-1.55,6.73-20.46,17.09-39.11,11.14
   c-18.65-5.96-77.96-20.65-81.06-29.75l31.86,6.18c0,0-17.61-4.14-19.94-12.17C126.81,302.28,131.22,291.66,139.76,287.52z"/>
  <path id="mud_branchiohyoideus" class="tooltip" title="Branchiohyoideus" d="M180.94,290.11c-1.61-6.62,26.68-30.82,31.34-33.93c4.66-3.11,30.82-13.73,35.48-11.4
   c4.66,2.33,15.8,35.22,17.09,45.32c1.29,10.1,6.47,23.83,9.06,28.23c2.59,4.4,12.69,15.8,1.81,17.61c-10.88,1.81-30.04,6.73-32.89,0
   c-2.85-6.73-18.91-16.83-26.94-21.5S183.27,299.69,180.94,290.11z"/>
  <path id="mud_interhyoideus" class="tooltip" title="Interhyoideus" d="M213.06,219.4c-5.67,0.65-21.76,9.58-23.05,16.32c-1.29,6.73-4.4,19.3-5.18,21.56
   c-0.78,2.26-1.81,20.14-1.04,20.39c0.78,0.26,20.46-19.68,23.83-22.01c3.37-2.33,28.61-11.4,29.85-12.43
   c1.23-1.04-9.38-6.73-10.94-10.36S222.12,218.37,213.06,219.4z"/>
  <path id="mud_procoracohumeralis" class="tooltip" title="Procoracohumeralis" d="M256.31,249.96c-2.08,1.97,4.4,10.62,27.71,15.8c23.31,5.18,69.67,2.07,82.36-3.11
   c12.69-5.18,27.59-13.61,29.98-18.2c2.39-4.59-27.13-3.29-34.13-3.81c-6.99-0.52-30.04-4.4-41.7-2.85
   c-11.65,1.55-47.91,9.06-50.5,9.06C267.45,246.86,261.23,245.3,256.31,249.96z"/>
  </svg>

 </div>

 <!-- Right column -->
 <div class="diagram" style="width:calc(50% - 49px); float:right; height: 85%; background-image: url(Images/shark_sideview.png); background-repeat: no-repeat; background-size:contain;">
  <?xml version="1.0" encoding="utf-8"?>
  <!-- Generator: Adobe Illustrator 24.1.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">
  <style type="text/css">
   .tooltip{opacity:0;fill:#FFFFFF;}
  </style>
  <path id="shark_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" onclick="homHighlight('intermandibularis')" d="M248.8,325.07c0,0-4.14,4.92-10.36,5.96c-6.22,1.04-18.39,0-18.39,0
   s8.55,13.47,22.01,15.28c13.47,1.81,49.73-2.59,50.24-6.47S251.39,325.33,248.8,325.07z"/>
  <path id="shark_adductor_mandibulae" class="tooltip" title="Adductor mandibulae" d="M238.78,286.57c0,0-6.22-13.12-16.92-13.64c-10.71-0.52-21.76,4.83-24.35,17.78
   c-2.59,12.95,6.56,26.24,9.15,30.04c2.59,3.8,9.67,8.29,13.38,8.98c3.71,0.69,23.4,2.59,29.44-6.91s2.76-24.35,0-27.8
   S241.03,287.78,238.78,286.57z"/>
  <path id="shark_x32_nd_dorsal_constrictor" class="tooltip" title="2nd dorsal constrictor" d="M247.76,288.99c0,0-5.87-3.45-6.91-5.01c-1.04-1.55-5.53-9.22-9.15-11.08
   s-16.75-1.87-16.75-1.87s9.69-9.5,10.02-12.6c0.34-3.11,11.39-23.48,19.67-27.28c8.29-3.8,29.7-7.6,41.78,1.04
   c0,0-14.68,19.51-16.06,23.65C269,259.98,258.47,283.63,247.76,288.99z"/>
  </svg>
 </div></code>```

答:
I'd probably go about ti in rather a different way than you've proposed. Where you have a bunch of event listeners on the paths themselves, I've just put a listener on each of the svgs.
When fired, it checks for the tagName of the element that was clicked. If it's not a path, then nothing valid was chosen, so remove the style from all paths. If on the other hand, the clicked element was a path, we get the class name from it, remove "tooltip " and then apply styling to all paths that match, removing it from all that dont at the same time.

Oh, and I removed the inline event handlers from the paths also - they're now attached with js to the whole image.

"use strict";
window.addEventListener('load', onLoaded, false);

function onLoaded(evt) {
  let svgsOnPage = Array.from(document.querySelectorAll('svg'));
  svgsOnPage.forEach(svg => svg.addEventListener('click', onSvgClick, false));
}

function onSvgClick(evt) {
  let clickedElement = event.target;
  if (clickedElement.tagName == 'path') {
    let classToHighlight = Array.from(clickedElement.classList).join(' ').replace('tooltip ', '');
    let pathElems = Array.from(document.querySelectorAll('path'));
    pathElems.forEach(
      path => {
        if (path.classList.contains(classToHighlight)) {
          path.style.fill = 'white';
          path.style.opacity = "0.5";
        } else {
          path.style = '';
        }
      }
    );
  } else {
    let paths = Array.from(document.querySelectorAll('path'));
    paths.forEach(path => {
      path.style = '';
    });
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  background-color: #555;
  /* used since the linked files aren't avail */
}</code>```

  <?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">

  <path id="mud_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" d="M185.78,232.53c-3.77-6.28-32.12,3.11-42.47,5.87c-10.36,2.76-39.02,8.98-41.44,14.5
   c-1.78,4.07,43.88,31.14,67.86,31.42c8.58,0.1,11.4-8.12,12.78-17.61C183.19,261.95,190.96,241.16,185.78,232.53z"/>
  <path id="mud_levator_mandibulae_externus" class="tooltip" title ="Levator mandibulae externus" d="M139.76,287.52c6.37-3.09,21.24-4.4,27.19,0
   c5.96,4.4,32.63,21.76,38.07,24.35s33.93,16.32,32.37,23.05c-1.55,6.73-20.46,17.09-39.11,11.14
   c-18.65-5.96-77.96-20.65-81.06-29.75l31.86,6.18c0,0-17.61-4.14-19.94-12.17C126.81,302.28,131.22,291.66,139.76,287.52z"/>
  <path id="mud_branchiohyoideus" class="tooltip" title="Branchiohyoideus" d="M180.94,290.11c-1.61-6.62,26.68-30.82,31.34-33.93c4.66-3.11,30.82-13.73,35.48-11.4
   c4.66,2.33,15.8,35.22,17.09,45.32c1.29,10.1,6.47,23.83,9.06,28.23c2.59,4.4,12.69,15.8,1.81,17.61c-10.88,1.81-30.04,6.73-32.89,0
   c-2.85-6.73-18.91-16.83-26.94-21.5S183.27,299.69,180.94,290.11z"/>
  <path id="mud_interhyoideus" class="tooltip" title="Interhyoideus" d="M213.06,219.4c-5.67,0.65-21.76,9.58-23.05,16.32c-1.29,6.73-4.4,19.3-5.18,21.56
   c-0.78,2.26-1.81,20.14-1.04,20.39c0.78,0.26,20.46-19.68,23.83-22.01c3.37-2.33,28.61-11.4,29.85-12.43
   c1.23-1.04-9.38-6.73-10.94-10.36S222.12,218.37,213.06,219.4z"/>
  <path id="mud_procoracohumeralis" class="tooltip" title="Procoracohumeralis" d="M256.31,249.96c-2.08,1.97,4.4,10.62,27.71,15.8c23.31,5.18,69.67,2.07,82.36-3.11
   c12.69-5.18,27.59-13.61,29.98-18.2c2.39-4.59-27.13-3.29-34.13-3.81c-6.99-0.52-30.04-4.4-41.7-2.85
   c-11.65,1.55-47.91,9.06-50.5,9.06C267.45,246.86,261.23,245.3,256.31,249.96z"/>
  </svg>

  <?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">

  <path id="shark_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" d="M248.8,325.07c0,0-4.14,4.92-10.36,5.96c-6.22,1.04-18.39,0-18.39,0
   s8.55,13.47,22.01,15.28c13.47,1.81,49.73-2.59,50.24-6.47S251.39,325.33,248.8,325.07z"/>
  <path id="shark_adductor_mandibulae" class="tooltip" title="Adductor mandibulae" d="M238.78,286.57c0,0-6.22-13.12-16.92-13.64c-10.71-0.52-21.76,4.83-24.35,17.78
   c-2.59,12.95,6.56,26.24,9.15,30.04c2.59,3.8,9.67,8.29,13.38,8.98c3.71,0.69,23.4,2.59,29.44-6.91s2.76-24.35,0-27.8
   S241.03,287.78,238.78,286.57z"/>
  <path id="shark_x32_nd_dorsal_constrictor" class="tooltip" title="2nd dorsal constrictor" d="M247.76,288.99c0,0-5.87-3.45-6.91-5.01c-1.04-1.55-5.53-9.22-9.15-11.08
   s-16.75-1.87-16.75-1.87s9.69-9.5,10.02-12.6c0.34-3.11,11.39-23.48,19.67-27.28c8.29-3.8,29.7-7.6,41.78,1.04
   c0,0-14.68,19.51-16.06,23.65C269,259.98,258.47,283.63,247.76,288.99z"/>
  </svg>

```

Body:
Right now, I have all svg elements with the class "intermandibularis" (there are two) change to a white fill at 50% opacity when you click either of them.

How do I go about making it so that if you click anywhere, the fill opacity goes back to 0, and then you can redo that all over again?

This is what I have:

function homHighlight(highlightClass){
 let allOfSameLabel = document.getElementsByClassName(highlightClass);

 for (let i = 0; i < allOfSameLabel.length; i++) {
  allOfSameLabel[i].style.fill = "#ffffff";
  allOfSameLabel[i].style.opacity = "0.5";
 }
}

  <?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">

  <path id="mud_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" onclick="homHighlight('intermandibularis')" d=" M185.78,232.53c-3.77-6.28-32.12,3.11-42.47,5.87c-10.36,2.76-39.02,8.98-41.44,14.5
   c-1.78,4.07,43.88,31.14,67.86,31.42c8.58,0.1,11.4-8.12,12.78-17.61C183.19,261.95,190.96,241.16,185.78,232.53z"/>
  <path id="mud_levator_mandibulae_externus" class="tooltip" title ="Levator mandibulae externus" d="M139.76,287.52c6.37-3.09,21.24-4.4,27.19,0
   c5.96,4.4,32.63,21.76,38.07,24.35s33.93,16.32,32.37,23.05c-1.55,6.73-20.46,17.09-39.11,11.14
   c-18.65-5.96-77.96-20.65-81.06-29.75l31.86,6.18c0,0-17.61-4.14-19.94-12.17C126.81,302.28,131.22,291.66,139.76,287.52z"/>
  <path id="mud_branchiohyoideus" class="tooltip" title="Branchiohyoideus" d="M180.94,290.11c-1.61-6.62,26.68-30.82,31.34-33.93c4.66-3.11,30.82-13.73,35.48-11.4
   c4.66,2.33,15.8,35.22,17.09,45.32c1.29,10.1,6.47,23.83,9.06,28.23c2.59,4.4,12.69,15.8,1.81,17.61c-10.88,1.81-30.04,6.73-32.89,0
   c-2.85-6.73-18.91-16.83-26.94-21.5S183.27,299.69,180.94,290.11z"/>
  <path id="mud_interhyoideus" class="tooltip" title="Interhyoideus" d="M213.06,219.4c-5.67,0.65-21.76,9.58-23.05,16.32c-1.29,6.73-4.4,19.3-5.18,21.56
   c-0.78,2.26-1.81,20.14-1.04,20.39c0.78,0.26,20.46-19.68,23.83-22.01c3.37-2.33,28.61-11.4,29.85-12.43
   c1.23-1.04-9.38-6.73-10.94-10.36S222.12,218.37,213.06,219.4z"/>
  <path id="mud_procoracohumeralis" class="tooltip" title="Procoracohumeralis" d="M256.31,249.96c-2.08,1.97,4.4,10.62,27.71,15.8c23.31,5.18,69.67,2.07,82.36-3.11
   c12.69-5.18,27.59-13.61,29.98-18.2c2.39-4.59-27.13-3.29-34.13-3.81c-6.99-0.52-30.04-4.4-41.7-2.85
   c-11.65,1.55-47.91,9.06-50.5,9.06C267.45,246.86,261.23,245.3,256.31,249.96z"/>
  </svg>

  <?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">

  <path id="shark_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" onclick="homHighlight('intermandibularis')" d="M248.8,325.07c0,0-4.14,4.92-10.36,5.96c-6.22,1.04-18.39,0-18.39,0
   s8.55,13.47,22.01,15.28c13.47,1.81,49.73-2.59,50.24-6.47S251.39,325.33,248.8,325.07z"/>
  <path id="shark_adductor_mandibulae" class="tooltip" title="Adductor mandibulae" d="M238.78,286.57c0,0-6.22-13.12-16.92-13.64c-10.71-0.52-21.76,4.83-24.35,17.78
   c-2.59,12.95,6.56,26.24,9.15,30.04c2.59,3.8,9.67,8.29,13.38,8.98c3.71,0.69,23.4,2.59,29.44-6.91s2.76-24.35,0-27.8
   S241.03,287.78,238.78,286.57z"/>
  <path id="shark_x32_nd_dorsal_constrictor" class="tooltip" title="2nd dorsal constrictor" d="M247.76,288.99c0,0-5.87-3.45-6.91-5.01c-1.04-1.55-5.53-9.22-9.15-11.08
   s-16.75-1.87-16.75-1.87s9.69-9.5,10.02-12.6c0.34-3.11,11.39-23.48,19.67-27.28c8.29-3.8,29.7-7.6,41.78,1.04
   c0,0-14.68,19.51-16.06,23.65C269,259.98,258.47,283.63,247.76,288.99z"/>
  </svg>

Body:
I'd probably go about ti in rather a different way than you've proposed. Where you have a bunch of event listeners on the paths themselves, I've just put a listener on each of the svgs.
When fired, it checks for the tagName of the element that was clicked. If it's not a path, then nothing valid was chosen, so remove the style from all paths. If on the other hand, the clicked element was a path, we get the class name from it, remove "tooltip " and then apply styling to all paths that match, removing it from all that dont at the same time.

Oh, and I removed the inline event handlers from the paths also - they're now attached with js to the whole image.

"use strict";
window.addEventListener('load', onLoaded, false);

function onLoaded(evt) {
  let svgsOnPage = Array.from(document.querySelectorAll('svg'));
  svgsOnPage.forEach(svg => svg.addEventListener('click', onSvgClick, false));
}

function onSvgClick(evt) {
  let clickedElement = event.target;
  if (clickedElement.tagName == 'path') {
    let classToHighlight = Array.from(clickedElement.classList).join(' ').replace('tooltip ', '');
    let pathElems = Array.from(document.querySelectorAll('path'));
    pathElems.forEach(
      path => {
        if (path.classList.contains(classToHighlight)) {
          path.style.fill = 'white';
          path.style.opacity = "0.5";
        } else {
          path.style = '';
        }
      }
    );
  } else {
    let paths = Array.from(document.querySelectorAll('path'));
    paths.forEach(path => {
      path.style = '';
    });
  }
}

svg {
  background-color: #555;
  /* used since the linked files aren't avail */
}

<!-- Left column -->
<div class='diagram' style="width:calc(50% - 49px); float:left; height: 85%; background-image: url(Images/mudpuppy_sideview.png); background-repeat: no-repeat; background-size:contain;" id="leftCol">
  <?xml version="1.0" encoding="utf-8"?>
  <!-- Generator: Adobe Illustrator 24.1.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">
  <style type="text/css">
   .tooltip{opacity:0;fill:#FFFFFF;}
  </style>

  <path id="mud_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" d="M185.78,232.53c-3.77-6.28-32.12,3.11-42.47,5.87c-10.36,2.76-39.02,8.98-41.44,14.5
   c-1.78,4.07,43.88,31.14,67.86,31.42c8.58,0.1,11.4-8.12,12.78-17.61C183.19,261.95,190.96,241.16,185.78,232.53z"/>
  <path id="mud_levator_mandibulae_externus" class="tooltip" title ="Levator mandibulae externus" d="M139.76,287.52c6.37-3.09,21.24-4.4,27.19,0
   c5.96,4.4,32.63,21.76,38.07,24.35s33.93,16.32,32.37,23.05c-1.55,6.73-20.46,17.09-39.11,11.14
   c-18.65-5.96-77.96-20.65-81.06-29.75l31.86,6.18c0,0-17.61-4.14-19.94-12.17C126.81,302.28,131.22,291.66,139.76,287.52z"/>
  <path id="mud_branchiohyoideus" class="tooltip" title="Branchiohyoideus" d="M180.94,290.11c-1.61-6.62,26.68-30.82,31.34-33.93c4.66-3.11,30.82-13.73,35.48-11.4
   c4.66,2.33,15.8,35.22,17.09,45.32c1.29,10.1,6.47,23.83,9.06,28.23c2.59,4.4,12.69,15.8,1.81,17.61c-10.88,1.81-30.04,6.73-32.89,0
   c-2.85-6.73-18.91-16.83-26.94-21.5S183.27,299.69,180.94,290.11z"/>
  <path id="mud_interhyoideus" class="tooltip" title="Interhyoideus" d="M213.06,219.4c-5.67,0.65-21.76,9.58-23.05,16.32c-1.29,6.73-4.4,19.3-5.18,21.56
   c-0.78,2.26-1.81,20.14-1.04,20.39c0.78,0.26,20.46-19.68,23.83-22.01c3.37-2.33,28.61-11.4,29.85-12.43
   c1.23-1.04-9.38-6.73-10.94-10.36S222.12,218.37,213.06,219.4z"/>
  <path id="mud_procoracohumeralis" class="tooltip" title="Procoracohumeralis" d="M256.31,249.96c-2.08,1.97,4.4,10.62,27.71,15.8c23.31,5.18,69.67,2.07,82.36-3.11
   c12.69-5.18,27.59-13.61,29.98-18.2c2.39-4.59-27.13-3.29-34.13-3.81c-6.99-0.52-30.04-4.4-41.7-2.85
   c-11.65,1.55-47.91,9.06-50.5,9.06C267.45,246.86,261.23,245.3,256.31,249.96z"/>
  </svg>

</div>

<!-- Right column -->
<div class="diagram" style="width:calc(50% - 49px); float:right; height: 85%; background-image: url(Images/shark_sideview.png); background-repeat: no-repeat; background-size:contain;">
  <?xml version="1.0" encoding="utf-8"?>
  <!-- Generator: Adobe Illustrator 24.1.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">
  <style type="text/css">
   .tooltip{opacity:0;fill:#FFFFFF;}
  </style>
  <path id="shark_intermandibularis" class="tooltip intermandibularis" title="Intermandibularis" d="M248.8,325.07c0,0-4.14,4.92-10.36,5.96c-6.22,1.04-18.39,0-18.39,0
   s8.55,13.47,22.01,15.28c13.47,1.81,49.73-2.59,50.24-6.47S251.39,325.33,248.8,325.07z"/>
  <path id="shark_adductor_mandibulae" class="tooltip" title="Adductor mandibulae" d="M238.78,286.57c0,0-6.22-13.12-16.92-13.64c-10.71-0.52-21.76,4.83-24.35,17.78
   c-2.59,12.95,6.56,26.24,9.15,30.04c2.59,3.8,9.67,8.29,13.38,8.98c3.71,0.69,23.4,2.59,29.44-6.91s2.76-24.35,0-27.8
   S241.03,287.78,238.78,286.57z"/>
  <path id="shark_x32_nd_dorsal_constrictor" class="tooltip" title="2nd dorsal constrictor" d="M247.76,288.99c0,0-5.87-3.45-6.91-5.01c-1.04-1.55-5.53-9.22-9.15-11.08
   s-16.75-1.87-16.75-1.87s9.69-9.5,10.02-12.6c0.34-3.11,11.39-23.48,19.67-27.28c8.29-3.8,29.7-7.6,41.78,1.04
   c0,0-14.68,19.51-16.06,23.65C269,259.98,258.47,283.63,247.76,288.99z"/>
  </svg>
</div>


问:
Adding classes using classList
probably easy but for some reason it doenst work.

I just try to add a class to some element in my code.

```<code>document.getElementById("test").classList.add("someclass")
</code>```

However, if I check the code for the added class it doesn't appear anywhere. When I alert the class list of that element "someclass" shows up, just not in the dom (and doen't do any changes as well).

Any suggestions?

Thats pretty much the code:

```<code><section id="vergleichen">
</section>

<script>
    window.onload = function() {
               document.getElementById("vergleichen").classList.add("Test");
               alert(document.getElementById("vergleichen").classList);
    }
</script>
</code>```

答:
May your div have height 0 so you did not see visualize.

I tried to set class as

#vergleichen{
 height: 100px;
}
.Test{
background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="vergleichen">
</section>

<script>
    window.onload = function() {
       document.getElementById("vergleichen").classList.add("Test");
       alert(document.getElementById("vergleichen").classList);
    }
</script></code>```

Title: Adding classes using classList

Body:
probably easy but for some reason it doenst work.

I just try to add a class to some element in my code.

document.getElementById("test").classList.add("someclass")

However, if I check the code for the added class it doesn't appear anywhere. When I alert the class list of that element "someclass" shows up, just not in the dom (and doen't do any changes as well).

Any suggestions?

Thats pretty much the code:

Body:
May your div have height 0 so you did not see visualize.

I tried to set class as

#vergleichen{
 height: 100px;
}
.Test{
background-color: blue;
}

<section id="vergleichen">
</section>

<script>
    window.onload = function() {
       document.getElementById("vergleichen").classList.add("Test");
       alert(document.getElementById("vergleichen").classList);
    }
</script>


答:
window.onload = function() {
    document.getElementById("vergleichen").classList.add("Test");
    alert(document.getElementById("vergleichen").classList);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Test{
 background-color:red;
}</code>```

This is text

```

Title: Adding classes using classList

Body:
window.onload = function() {
    document.getElementById("vergleichen").classList.add("Test");
    alert(document.getElementById("vergleichen").classList);
}

.Test{
 background-color:red;
}

<section id="vergleichen">
  <h1>This is text<h1>
</section>


问:
Is it possible to make localhost work through a Virtual Machine?
I am using a Macbook running 10.6.  I am using VMware Fusion to run an Ubuntu Server minimal virtual machine.  Ubuntu Server is running your basic LAMP stack.

I do my development in Mac OS.  I have VMware share a directory from Mac OS to the Ubuntu Server.  Ubuntu Server uses that directory for apache.

I access my server is Mac OS in firefox using the ip address of my virtual machine.  This is a pain because I have to find out what the ip address is of my virtual machine each time I boot it up.  I could set a static ip address but this causes problems if I move my Macbook from network to network.

Is there any configuration (NAT or Bridged or something) that would let me access my virtual machine from the Mac OS using localhost or something similar?

Thanks

答: I'm using Virtual Box and typing in the computer local address (for instance 192.168.1.100) instead of localhost did the trick.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Copy data in array of a nested array of an object
So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

```<code> people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]
</code>```

So, I created a new array named animalCategory to hold every category available.

```<code> // declare new array to hold category of animals
 let animalCategory = []
</code>```

This is the logic I came up with:-

```<code>// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)
</code>```

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

UPDATED: the output I want to seek is:-

```<code>animalCategory: [ 'cat', 'dog', 'iguana', 'fish']
</code>```

How should I change my logic then? And is there any other way I can do this?

答:
people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

// declare new array to hold category of animals
 let animalCategory = []

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            if(animalCategory.indexOf(animal.category) === -1) {

            animalCategory.push(animal.category);
            }
        }
    });
});

// see result
animalCategory.forEach(function(animal) {
    console.log(animal);
});```

Hope this is helpfull.

Body:
So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

 people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

So, I created a new array named animalCategory to hold every category available.

 // declare new array to hold category of animals
 let animalCategory = []

This is the logic I came up with:-

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

UPDATED: the output I want to seek is:-

animalCategory: [ 'cat', 'dog', 'iguana', 'fish']

How should I change my logic then? And is there any other way I can do this?

Body:
people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

// declare new array to hold category of animals
 let animalCategory = []

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            if(animalCategory.indexOf(animal.category) === -1) {

            animalCategory.push(animal.category);
            }
        }
    });
});

// see result
animalCategory.forEach(function(animal) {
    console.log(animal);
});

Hope this is helpfull.


问:
Trying to mock a named commonjs module in Jest
I've searched for days on how to accomplish this and nothing i've tried has worked. I have an authenticate module that I share among other modules, and I'm wanting to create a mock for it using jest, in my my unit tests. Here's what i have currently:

authenticate.js

```<code>const got = require('got');

const authenticate = async (options) => {
  let res = ...api request using got library to retrieve token...

  return { data: res.access_token };
};

exports.authenticate = authenticate;
</code>```

schedule.js

```<code>const schedule = async (options) {
  // import authenticate library
  const authenticate = require('./authenticate');

  const login = await authenticate.authenticate(options);

  const result;

  ...stuff to set result...
  result = {
    data: 'success'
  };

  return result;
};

exports.schedule = schedule;
</code>```

shedule.test.js

```<code>const scheduler = require('./schedule');

test('[schedule]', async () => {
  const options = {...};

  jest.mock('./authenticate', () => ({
    authenticate: jest.fn()
  }));

  const authenticate = require('./authenticate');

  authenticate.authenticate.mockReturnValue({
    data: mockOptions.access_token
  });

  const moduleUnderTest = await scheduler.schedule(options);

  expect(moduleUnderTest).toEqual({ data: 'success' });
});
</code>```

答:
You SHOULD NOT use jest.mock(moduleName, factory, options) in function scope, it should be used in MODULE scope. Besides, for your case, I don't see any reason to use rewire module.

E.g.

authenticate.js:

const got = require('got');

const authenticate = async (options) => {
  let res = 'got';
  return { data: res.access_token };
};

exports.authenticate = authenticate;
```

<p><em>schedule.js</em>:</p>

<pre class="lang-js prettyprint-override"><code>const schedule = async (options) => {
  const authenticate = require('./authenticate');
  const login = await authenticate.authenticate(options);
  const result;
  result = {
    data: 'success'
  };

  return result;
};

exports.schedule = schedule;
</code>```

schedule.test.js:

const scheduler = require('./schedule');

jest.mock('./authenticate', () => ({
  authenticate: jest.fn(),
}));

describe('62074254', () => {
  test('[schedule]', async () => {
    const authenticate = require('./authenticate');
    const mockOptions = { access_token: '123' };

    authenticate.authenticate.mockReturnValue({
      data: mockOptions.access_token,
    });
    const options = {};
    const moduleUnderTest = await scheduler.schedule(options);

    expect(moduleUnderTest).toEqual({ data: 'success' });
    expect(authenticate.authenticate).toBeCalledWith({});
  });
});
```

<p>Unit test results with coverage report:</p>

<pre class="lang-sh prettyprint-override"><code> PASS  stackoverflow/62074254/schedule.test.js (10.742s)
  62074254
    ✓ [schedule] (6ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |
 schedule.js |     100 |      100 |     100 |     100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.202s
</code>```

Body:
I've searched for days on how to accomplish this and nothing i've tried has worked. I have an authenticate module that I share among other modules, and I'm wanting to create a mock for it using jest, in my my unit tests. Here's what i have currently:

authenticate.js

const got = require('got');

const authenticate = async (options) => {
  let res = ...api request using got library to retrieve token...

  return { data: res.access_token };
};

exports.authenticate = authenticate;

schedule.js

const schedule = async (options) {
  // import authenticate library
  const authenticate = require('./authenticate');

  const login = await authenticate.authenticate(options);

  const result;

  ...stuff to set result...
  result = {
    data: 'success'
  };

  return result;
};

exports.schedule = schedule;

shedule.test.js

const scheduler = require('./schedule');

test('[schedule]', async () => {
  const options = {...};

  jest.mock('./authenticate', () => ({
    authenticate: jest.fn()
  }));

  const authenticate = require('./authenticate');

  authenticate.authenticate.mockReturnValue({
    data: mockOptions.access_token
  });

  const moduleUnderTest = await scheduler.schedule(options);

  expect(moduleUnderTest).toEqual({ data: 'success' });
});

Body:
You SHOULD NOT use jest.mock(moduleName, factory, options) in function scope, it should be used in MODULE scope. Besides, for your case, I don't see any reason to use rewire module.

E.g.

authenticate.js:

const got = require('got');

const authenticate = async (options) => {
  let res = 'got';
  return { data: res.access_token };
};

exports.authenticate = authenticate;

schedule.js:

const schedule = async (options) => {
  const authenticate = require('./authenticate');
  const login = await authenticate.authenticate(options);
  const result;
  result = {
    data: 'success'
  };

  return result;
};

exports.schedule = schedule;

schedule.test.js:

const scheduler = require('./schedule');

jest.mock('./authenticate', () => ({
  authenticate: jest.fn(),
}));

describe('62074254', () => {
  test('[schedule]', async () => {
    const authenticate = require('./authenticate');
    const mockOptions = { access_token: '123' };

    authenticate.authenticate.mockReturnValue({
      data: mockOptions.access_token,
    });
    const options = {};
    const moduleUnderTest = await scheduler.schedule(options);

    expect(moduleUnderTest).toEqual({ data: 'success' });
    expect(authenticate.authenticate).toBeCalledWith({});
  });
});

Unit test results with coverage report:

 PASS  stackoverflow/62074254/schedule.test.js (10.742s)
  62074254
    ✓ [schedule] (6ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |
 schedule.js |     100 |      100 |     100 |     100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.202s


问:
Uncaught ReferenceError: BookingData is not defined - where "BookingData" is Name of Collecton In Firebase
```<code><form class="modal-content" id="bookingForm">
    <div class="formContainer">
      <h1>Booking Form</h1>
      <p>Please fill in this form to Book The Trip.</p>
      <hr>
      <label for="email"><b>Email</b></label>
      <input type="text" placeholder="Enter Email" name="email" required id="email">

      <label><b>Package</b></label>

      <input type="text" id="packageFields" name="teste2">

      <label for="psw"><b>Name</b></label>
      <input type="text" placeholder="Enter Name" name="name" required id="name">

      <label for="psw-repeat"><b>Phone No.</b></label>
      <input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">

      <label for="psw-repeat"><b>Date Of Journey</b></label>
      <input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">

      <p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p>

      <div class="clearfix">
        <button type="submit" class="signupbtn">Confirm Booking</button>
        <button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>
      </div>
    </div>
  </form>
</div>
    </section>
    <!-- animation -->
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
    AOS.init();

    var modal = document.getElementById('bookingForm');
// Script To Copy Package Name To The Form Automatically
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

function setPackage(packageName) {
  document.querySelector('#packageFields').value = packageName;
}
    </script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>

    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

 <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
 <script src="/__/firebase/7.14.5/firebase-app.js"></script>

 <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
 <script src="/__/firebase/7.14.5/firebase-analytics.js"></script>

 <!-- Add Firebase products that you want to use -->
 <script src="/__/firebase/7.14.5/firebase-auth.js"></script>
 <script src="/__/firebase/7.14.5/firebase-firestore.js"></script>
 <script src="/__/firebase/init.js"></script>
 <script src="bookingSubmit.js">    </script>
</code>```

This Is The Html And The JavaSript Is Given Below:

```<code>var firebaseConfig = {
   apiKey: "AIzaSyDT80mEpNS4CpdByl2ugrSTGzgQpkbzzeI",
   authDomain: "himwhitecab.firebaseapp.com",
   databaseURL: "https://himwhitecab.firebaseio.com",
   projectId: "himwhitecab",
   storageBucket: "himwhitecab.appspot.com",
   messagingSenderId: "505950138314",
   appId: "1:505950138314:web:c37c1b2c593f30e911e933",
   measurementId: "G-ECR97G3YY0"
 };

//reference messages collection

firebase.initializeApp(firebaseConfig);
var firestore =  firebase.firestore();

const submitBtn = document.querySelector("#signupbtn");

let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');

const db = firestore.collection(BookingData);

submitBtn.addEventListner('click', function(){
  let userEmailInput = email.value;
  let userPackageInput = packageFields.value;
  let userNameInput = name.value;
  let userPhoneInput = phone.value;
  let userDateInput = date.value;

  db.doc()
  .set({
    email:userEmailInput,
    package:userPackageInput,
    name:userNameInput,
    phone:userPhoneInput,
    date:userDateInput
  })
  .then(function(){
    console.log("Data Saved");
  })
  .catch(function(error){
    console.log(error);
  });
});

</code>```

I am using this to store the data of my contact forms in my Firebase.

But It Gives The Error:

Uncaught ReferenceError: BookingData is not defined
      at bookingSubmit.js:27

Where "BookingData" is the name of the collection in my firebase.

What Is The Cause Of The Error And How To Solve It...??

Please Check If Anything Else Is Wrong.

答:
If "BookingData" is the name of your collection, then you will need to put it in quotes:

```<code>const db = firestore.collection("BookingData");
</code>```

What you have now is trying to use a variable called BookingData, which hasn't been defined.  That's what the error message is trying to tell you.

Body:
<form class="modal-content" id="bookingForm">

Booking Form

Please fill in this form to Book The Trip.

      Email
      <input type="text" placeholder="Enter Email" name="email" required id="email">

      Package

      <input type="text" id="packageFields" name="teste2">

      Name
      <input type="text" placeholder="Enter Name" name="name" required id="name">

      Phone No.
      <input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">

      Date Of Journey
      <input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">

By creating an account you agree to our Terms & Privacy.

        <button type="submit" class="signupbtn">Confirm Booking</button>
        <button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>

  </form>

This Is The Html And The JavaSript Is Given Below:

var firebaseConfig = {
   apiKey: "AIzaSyDT80mEpNS4CpdByl2ugrSTGzgQpkbzzeI",
   authDomain: "himwhitecab.firebaseapp.com",
   databaseURL: "https://himwhitecab.firebaseio.com",
   projectId: "himwhitecab",
   storageBucket: "himwhitecab.appspot.com",
   messagingSenderId: "505950138314",
   appId: "1:505950138314:web:c37c1b2c593f30e911e933",
   measurementId: "G-ECR97G3YY0"
 };

//reference messages collection

firebase.initializeApp(firebaseConfig);
var firestore =  firebase.firestore();

const submitBtn = document.querySelector("#signupbtn");

let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');

const db = firestore.collection(BookingData);

submitBtn.addEventListner('click', function(){
  let userEmailInput = email.value;
  let userPackageInput = packageFields.value;
  let userNameInput = name.value;
  let userPhoneInput = phone.value;
  let userDateInput = date.value;

  db.doc()
  .set({
    email:userEmailInput,
    package:userPackageInput,
    name:userNameInput,
    phone:userPhoneInput,
    date:userDateInput
  })
  .then(function(){
    console.log("Data Saved");
  })
  .catch(function(error){
    console.log(error);
  });
});

I am using this to store the data of my contact forms in my Firebase.

But It Gives The Error:

Uncaught ReferenceError: BookingData is not defined
      at bookingSubmit.js:27

Where "BookingData" is the name of the collection in my firebase.

What Is The Cause Of The Error And How To Solve It...??

Please Check If Anything Else Is Wrong.

Body:
If "BookingData" is the name of your collection, then you will need to put it in quotes:

const db = firestore.collection("BookingData");

What you have now is trying to use a variable called BookingData, which hasn't been defined.  That's what the error message is trying to tell you.


问:
Chart.js - Ajax response not accept
chart.js not accept ajax post - json respose.i couldn't solve it yet.please help..
https://prnt.sc/spt4p3
https://prnt.sc/spt6j0

my json file is:

```<code>[{"DAYS":"01.05.2020","VALUES":"0"},{"DAYS":"02.05.2020","VALUES":"0"},{"DAYS":"03.05.2020","VALUES":"0"},{"DAYS":"04.05.2020","VALUES":"0"},{"DAYS":"05.05.2020","VALUES":"0"},{"DAYS":"06.05.2020","VALUES":"0"},]
</code>```

javascript file is:

```<code>                var days = [];
                var values=[];
                $.ajax({
                    url: 'class/report/daily_report.php',
                    type: 'POST',
                    data: {'reload': 'renew', 'type': 'rep_1'},
                    success: function (response) {
                        var jsonARR =$.parseJSON(response);
                        var k=0;
                        for ( var key in jsonARR ) {
                            days[k]=jsonARR[key]["DAYS"];
                            values[k]=parseInt(jsonARR[key]["VALUES"]);
                            k++;
                        }

                    }
                });
                var a = {
                    labels: days,
                    datasets: [{
                        backgroundColor: KTApp.getStateColor("danger"),
                        data: values
                    }]
                };
</code>```

答:
Please remind that $.ajax() makes an asynchronous HTTP request. In you code however, you create the chart even before ans answer from that request is received.

The problem can be solved by moving the code responsible for chart creation inside the $.ajax() block as shown below.

```<code>$.ajax({
  success: function(response) {
    var jsonARR = $.parseJSON(response);
    var k = 0;
    for (var key in jsonARR) {
      days[k] = jsonARR[key]["DAYS"];
      values[k] = parseInt(jsonARR[key]["VALUES"]);
      k++;
    };
    var a = {
      labels: days,
      datasets: [{
        backgroundColor: KTApp.getStateColor("danger"),
        data: values
      }]
    };
    new Chart(...);
  });
</code>```

Title: Chart.js - Ajax response not accept

Body:
chart.js not accept ajax post - json respose.i couldn't solve it yet.please help..
https://prnt.sc/spt4p3
https://prnt.sc/spt6j0

my json file is:

[{"DAYS":"01.05.2020","VALUES":"0"},{"DAYS":"02.05.2020","VALUES":"0"},{"DAYS":"03.05.2020","VALUES":"0"},{"DAYS":"04.05.2020","VALUES":"0"},{"DAYS":"05.05.2020","VALUES":"0"},{"DAYS":"06.05.2020","VALUES":"0"},]

javascript file is:

                var days = [];
                var values=[];
                $.ajax({
                    url: 'class/report/daily_report.php',
                    type: 'POST',
                    data: {'reload': 'renew', 'type': 'rep_1'},
                    success: function (response) {
                        var jsonARR =$.parseJSON(response);
                        var k=0;
                        for ( var key in jsonARR ) {
                            days[k]=jsonARR[key]["DAYS"];
                            values[k]=parseInt(jsonARR[key]["VALUES"]);
                            k++;
                        }

                    }
                });
                var a = {
                    labels: days,
                    datasets: [{
                        backgroundColor: KTApp.getStateColor("danger"),
                        data: values
                    }]
                };

Body:
Please remind that $.ajax() makes an asynchronous HTTP request. In you code however, you create the chart even before ans answer from that request is received.

The problem can be solved by moving the code responsible for chart creation inside the $.ajax() block as shown below.

$.ajax({
  success: function(response) {
    var jsonARR = $.parseJSON(response);
    var k = 0;
    for (var key in jsonARR) {
      days[k] = jsonARR[key]["DAYS"];
      values[k] = parseInt(jsonARR[key]["VALUES"]);
      k++;
    };
    var a = {
      labels: days,
      datasets: [{
        backgroundColor: KTApp.getStateColor("danger"),
        data: values
      }]
    };
    new Chart(...);
  });


问:
How i can change the top of my stack in C++?
Whats is wrong in this code, i need to change the top of my stack.
That's is my code and i need to change the top of my stack
Also, i need to change my function imprime to print from the bottom to the top.

Something like 10 15 20, in the function pilha_imprime will print 20 15 10.

I need to understand how do that i'm learning stack in C++ and how it`s works.

```<code>#include<stdio.h>
#include<stdlib.h>

struct no {
 float info;
 struct no* prox;
};
typedef struct no No;

struct pilha {
 No* prim;
};

pilha* pilha_cria (void){
    pilha* p = (pilha*) malloc(sizeof(pilha));
    p->prim = NULL;
    return p;
}

/* função auxiliar: insere no início */
No* ins_ini (No* l, float v)
{
     No* p = (No*) malloc(sizeof(No));
     p->info = v;
     p->prox = l;
     return p;
}
/* função auxiliar: retira do início */
No* ret_ini (No* l)
{
     No* p = l->prox;
     free(l);
     return p;
}

int vazia (pilha* p)
{
    return (p->prim==NULL);
}

void pilha_push (pilha* p, float v)
{
     p->prim = ins_ini(p->prim,v);
}

float pilha_pop (pilha* p)
{
     float v;
     if (vazia(p)) {
     printf("Pilha vazia.\n");
     exit(1); /* aborta programa */
     }
     v = p->prim->info;
     p->prim = ret_ini(p->prim);
     return v;
}

void pilha_libera (pilha* p)
{
     No* q = p->prim;
     while (q!=NULL) {
     No* t = q->prox;
     free(q);
     q = t;
     }
     free(p);
}

/* imprime: versão com lista */
void pilha_imprime (pilha* p)
{
 No* q;
 for (q=p->prim; q!=NULL; q=q->prox)
 printf("%f\n",q->info);
}

/* vai imprimir da base para o topo usando as funções já definidas e uma pilha auxiliar */
void imprime (pilha* p)
{
 No* q;
 for (q=p->prim; q!=NULL; q=q->prox)
 printf("%f\n",q->info);
}

void troca_topo(pilha* p)
{
    if(vazia(p))
    {
        printf("\nPilha Vazia!\n");
        return;
    }

    No* no_aux = (No*) malloc(sizeof(No)); // nó auxiliar.
    No* tmp = tmp->prox; // ponteiro que aponta para o primeiro nó da pilha.

    while(tmp->prox != NULL)// laco que percorre a pilha ate o ponteiro apontar para o ultimo nó.
        tmp = tmp->prox;

    // troca dos valores:
    no_aux->info = tmp->info; // elemento do nó auxiliar recebe o elemento do ultimo nó.
    tmp->info = (tmp->prox)->info; // o elemento do ultimo nó recebe o elemento do primeiro nó.
    (tmp->prox)->info = no_aux->info; // o primeiro nó recebe o elemento armazenado no nó auxiliar(que era o ultimo elemento).

    free(no_aux);// liberar a memoria do nó auxiliar.
}

int main(){

        /* Implementação de pilha com lista encadeada */
    pilha *p;
    p = pilha_cria();
    pilha_push(p,10);
    pilha_push(p,15);
    pilha_push(p,20);
    pilha_push(p,25);
    float v = pilha_pop(p);
    printf("Imprime : %f \n", v);
    printf("\n");

        /* vai imprimir do topo para a base, percorrendo a lista encadeada */
    pilha_imprime(p);
    printf("\n");

        /* vai imprimir da base para o topo usando as funções já definidas e uma pilha auxiliar */
    imprime(p);
    printf("\n");

        /*vai executar a função troca_topo, que troca o valor do topo com aquele abaixo, usando somente as funções push e pop*/
        // protótipo: void troca_topo(Pilha*p) - emite mensagem de erro para
        // pilha vazia ou com menos de dois elementos.
    troca_topo(p);
    pilha_imprime(p);

    pilha_libera(p);
    system("PAUSE");
    return 0;
}
</code>```

答:
Some functions are easier to write recursive, printing the stack backwards is one of them;

```<code>void imprime(No* no) {
    if (no != NULL) {
        imprime(no->prox);
        printf("%0.2lf\n", no->info);
    }
}

/* vai imprimir da base para o topo usando uma funções já definidas*/
void imprime(pilha* p)
{
    imprime(p->prim);
}
</code>```

Switching top with bottom does not need a malloc. Memory is already allocated, all you have to do is switch the information. And you were using variable tmp before it a value was assigned, causing odd behavior.

```<code>void troca_topo(pilha* p)
{
    if(vazia(p))
    {
        printf("\nPilha Vazia!\n");
        return;
    }

    No* tmp = p->prim; // ponteiro que aponta para o primeiro nó da pilha.
    while(tmp->prox != NULL)// laco que percorre a pilha ate o ponteiro apontar para o ultimo nó.
        tmp = tmp->prox;

    // troca dos valores:
    float aux = tmp->info; // elemento auxiliar recebe o elemento do ultimo nó.
    tmp->info = p->prim->info; // o elemento do ultimo nó recebe o elemento do primeiro nó.
    p->prim->info = aux; // o primeiro nó recebe o elemento armazenado no auxiliar(que era o ultimo elemento).
}
</code>```

Body:
Whats is wrong in this code, i need to change the top of my stack.
That's is my code and i need to change the top of my stack
Also, i need to change my function imprime to print from the bottom to the top.

Something like 10 15 20, in the function pilha_imprime will print 20 15 10.

I need to understand how do that i'm learning stack in C++ and how it`s works.

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

struct no {
 float info;
 struct no* prox;
};
typedef struct no No;

struct pilha {
 No* prim;
};

pilha* pilha_cria (void){
    pilha* p = (pilha*) malloc(sizeof(pilha));
    p->prim = NULL;
    return p;
}

/* função auxiliar: insere no início */
No* ins_ini (No* l, float v)
{
     No* p = (No*) malloc(sizeof(No));
     p->info = v;
     p->prox = l;
     return p;
}
/* função auxiliar: retira do início */
No* ret_ini (No* l)
{
     No* p = l->prox;
     free(l);
     return p;
}

int vazia (pilha* p)
{
    return (p->prim==NULL);
}

void pilha_push (pilha* p, float v)
{
     p->prim = ins_ini(p->prim,v);
}

float pilha_pop (pilha* p)
{
     float v;
     if (vazia(p)) {
     printf("Pilha vazia.\n");
     exit(1); /* aborta programa */
     }
     v = p->prim->info;
     p->prim = ret_ini(p->prim);
     return v;
}

void pilha_libera (pilha* p)
{
     No* q = p->prim;
     while (q!=NULL) {
     No* t = q->prox;
     free(q);
     q = t;
     }
     free(p);
}

/* imprime: versão com lista */
void pilha_imprime (pilha* p)
{
 No* q;
 for (q=p->prim; q!=NULL; q=q->prox)
 printf("%f\n",q->info);
}

/* vai imprimir da base para o topo usando as funções já definidas e uma pilha auxiliar */
void imprime (pilha* p)
{
 No* q;
 for (q=p->prim; q!=NULL; q=q->prox)
 printf("%f\n",q->info);
}

void troca_topo(pilha* p)
{
    if(vazia(p))
    {
        printf("\nPilha Vazia!\n");
        return;
    }

    No* no_aux = (No*) malloc(sizeof(No)); // nó auxiliar.
    No* tmp = tmp->prox; // ponteiro que aponta para o primeiro nó da pilha.

    while(tmp->prox != NULL)// laco que percorre a pilha ate o ponteiro apontar para o ultimo nó.
        tmp = tmp->prox;

    // troca dos valores:
    no_aux->info = tmp->info; // elemento do nó auxiliar recebe o elemento do ultimo nó.
    tmp->info = (tmp->prox)->info; // o elemento do ultimo nó recebe o elemento do primeiro nó.
    (tmp->prox)->info = no_aux->info; // o primeiro nó recebe o elemento armazenado no nó auxiliar(que era o ultimo elemento).

    free(no_aux);// liberar a memoria do nó auxiliar.
}

int main(){

        /* Implementação de pilha com lista encadeada */
    pilha *p;
    p = pilha_cria();
    pilha_push(p,10);
    pilha_push(p,15);
    pilha_push(p,20);
    pilha_push(p,25);
    float v = pilha_pop(p);
    printf("Imprime : %f \n", v);
    printf("\n");

        /* vai imprimir do topo para a base, percorrendo a lista encadeada */
    pilha_imprime(p);
    printf("\n");

        /* vai imprimir da base para o topo usando as funções já definidas e uma pilha auxiliar */
    imprime(p);
    printf("\n");

        /*vai executar a função troca_topo, que troca o valor do topo com aquele abaixo, usando somente as funções push e pop*/
        // protótipo: void troca_topo(Pilha*p) - emite mensagem de erro para
        // pilha vazia ou com menos de dois elementos.
    troca_topo(p);
    pilha_imprime(p);

    pilha_libera(p);
    system("PAUSE");
    return 0;
}

Body:
Some functions are easier to write recursive, printing the stack backwards is one of them;

void imprime(No* no) {
    if (no != NULL) {
        imprime(no->prox);
        printf("%0.2lf\n", no->info);
    }
}

/* vai imprimir da base para o topo usando uma funções já definidas*/
void imprime(pilha* p)
{
    imprime(p->prim);
}

Switching top with bottom does not need a malloc. Memory is already allocated, all you have to do is switch the information. And you were using variable tmp before it a value was assigned, causing odd behavior.

void troca_topo(pilha* p)
{
    if(vazia(p))
    {
        printf("\nPilha Vazia!\n");
        return;
    }

    No* tmp = p->prim; // ponteiro que aponta para o primeiro nó da pilha.
    while(tmp->prox != NULL)// laco que percorre a pilha ate o ponteiro apontar para o ultimo nó.
        tmp = tmp->prox;

    // troca dos valores:
    float aux = tmp->info; // elemento auxiliar recebe o elemento do ultimo nó.
    tmp->info = p->prim->info; // o elemento do ultimo nó recebe o elemento do primeiro nó.
    p->prim->info = aux; // o primeiro nó recebe o elemento armazenado no auxiliar(que era o ultimo elemento).
}


问:
WCF Service works locally but gives 404 on server
I've seen a number of posts about this, but can't seem to actually find an answer.

[Disclaimer: I don't know a lot about WCF -- Although I have access to the code, this is an existing project that I'm trying to connect to.]

I've created a html/javascript client to access an existing WCF Service API.  Each is a separate application so when I run locally, the client and server are both running on localhost but with different port numbers.  This works.  The client app is able to call a WCF service with a call like: https://localhost:4435/sessions.svc/getsession?sessionPK=3.

When I install both apps on a server (both running on the same server as different virtual applications), the service is indeed running -- I can hit https://myserver.com/api/sessions.svc from a web-browser and I get a page back from the service telling me that its working.

However, now when the client tries to access the service the same way that it did locally (https://myserver.com/api/sessions.svc/getsession?sessionPK=3), I get a 404 Not Found error.

Client and WCF Service are both hosted on the same server with the same root domain -- so CORS shouldn't be an issue.

Here are some code snippets:

** WCF Service **

[ServiceContract]
public interface ISessions
{
    [OperationContract]
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    string GetSession(int? sessionPK);

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Sessions : BaseService, ISessions
    {
        public string GetSession(int sessionPK)
        {
          ...
        }
}
```

<p>** Web.Config for Service **</p>

<pre class="lang-xml prettyprint-override"><code><service behaviorConfiguration="BehaviorConfig" name="Sessions">
  <endpoint address="" binding="webHttpBinding" behaviorConfiguration="json"  contract="ISessions">
    <identity>
      <dns value="localhost"/>
    </identity>
  </endpoint>
  <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</code>```

** Client **

export class DataService {

   constructor(private http : HttpClient){
     this.http.configure(config => {
      config.withBaseUrl("https://myserver.com/api/");
      config.withHeader("Accept", "application/json");
      config.withHeader("Content-Type", "application/json");
      config.withCredentials(true);
    })
  }

  public async getSessionById(id : number = 0){
    try{
       let result = this.http.get(`sessions.svc/getsession?sessionPK=${id}`);
       if(!result.isSuccess)
          throw response;

       ...
    }
    catch(error : any){
       ...
    }
}
```

Update

In response to Peter, I get the same response from https://myserver.com/api/sessions.svc as I do from https://myserver.com/api/sessions.svc?wsdl.  It is a page like this:

The service doesn't seem to return a list of the operations it exposes.  Incidentally, it performs exactly the same way on localhost.

答:
If CORS is not a problem, the URI or format of your access service may be wrong.You can open the help document in the service to see how to request the interface:

```<code>        <endpointBehaviors>
            <behavior name="ESEndPointBehavior">
                <webHttp helpEnabled="true"/>
            </behavior>
        </endpointBehaviors>
</code>```

Access help documents:

This is the design of the service interface:

```<code>      [OperationContract]
    [WebGet(UriTemplate = "user/?name={name}",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result GetUserData(string name);
</code>```

I didn't set bodystyle to WebMessageBodyStyle.Wrapped Because WebMessageBodyStyle.Wrapped It is mainly used to encapsulate body, but there is no body in get method.And set "WebMessageBodyStyle.Wrapped" the help document will not generate the correct request format.It will be like this:

Normal help documents should look like this:

It contains the URI and format of the request.

Body:
I've seen a number of posts about this, but can't seem to actually find an answer.

[Disclaimer: I don't know a lot about WCF -- Although I have access to the code, this is an existing project that I'm trying to connect to.]

I've created a html/javascript client to access an existing WCF Service API.  Each is a separate application so when I run locally, the client and server are both running on localhost but with different port numbers.  This works.  The client app is able to call a WCF service with a call like: https://localhost:4435/sessions.svc/getsession?sessionPK=3.

When I install both apps on a server (both running on the same server as different virtual applications), the service is indeed running -- I can hit https://myserver.com/api/sessions.svc from a web-browser and I get a page back from the service telling me that its working.

However, now when the client tries to access the service the same way that it did locally (https://myserver.com/api/sessions.svc/getsession?sessionPK=3), I get a 404 Not Found error.

Client and WCF Service are both hosted on the same server with the same root domain -- so CORS shouldn't be an issue.

Here are some code snippets:

** WCF Service **

[ServiceContract]
public interface ISessions
{
    [OperationContract]
    [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    string GetSession(int? sessionPK);

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Sessions : BaseService, ISessions
    {
        public string GetSession(int sessionPK)
        {
          ...
        }
}

** Web.Config for Service **

<service behaviorConfiguration="BehaviorConfig" name="Sessions">
  <endpoint address="" binding="webHttpBinding" behaviorConfiguration="json"  contract="ISessions">
    <identity>
      <dns value="localhost"/>
    </identity>
  </endpoint>
  <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>

** Client **

export class DataService {

   constructor(private http : HttpClient){
     this.http.configure(config => {
      config.withBaseUrl("https://myserver.com/api/");
      config.withHeader("Accept", "application/json");
      config.withHeader("Content-Type", "application/json");
      config.withCredentials(true);
    })
  }

  public async getSessionById(id : number = 0){
    try{
       let result = this.http.get(`sessions.svc/getsession?sessionPK=${id}`);
       if(!result.isSuccess)
          throw response;

       ...
    }
    catch(error : any){
       ...
    }
}

Update

In response to Peter, I get the same response from https://myserver.com/api/sessions.svc as I do from https://myserver.com/api/sessions.svc?wsdl.  It is a page like this:

The service doesn't seem to return a list of the operations it exposes.  Incidentally, it performs exactly the same way on localhost.

Body:
If CORS is not a problem, the URI or format of your access service may be wrong.You can open the help document in the service to see how to request the interface:

        <endpointBehaviors>
            <behavior name="ESEndPointBehavior">
                <webHttp helpEnabled="true"/>
            </behavior>
        </endpointBehaviors>

Access help documents:

This is the design of the service interface:

      [OperationContract]
    [WebGet(UriTemplate = "user/?name={name}",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result GetUserData(string name);

I didn't set bodystyle to WebMessageBodyStyle.Wrapped Because WebMessageBodyStyle.Wrapped It is mainly used to encapsulate body, but there is no body in get method.And set "WebMessageBodyStyle.Wrapped" the help document will not generate the correct request format.It will be like this:

Normal help documents should look like this:

It contains the URI and format of the request.


问:
How to write array for each operation result as a new array
Trying to process Array float data and keep it as new array for later use. Got a float[] of 10 items and want to do math with each item and save result on new array. Getting "cant convert float to float" error. Thanks for the help, could not find what im searching for on Google sorry if it's dup.

```<code>public static void Main(string[] args)
{
    Console.WriteLine("Proyecto X0n-832, Codificación de la teoría musical.");
    //Variables Generales
    float[] eau = { 440, 20000 };
    float fnd = eau[0];
    float cyc = fnd * 2;
    //Se cambia sfn por sbf
    float[] sbf = { fnd, cyc, cyc * 2, cyc * 4, cyc * 8, cyc * 16, cyc * 32, cyc * 64, cyc * 128, cyc * 256 };

    //Imprimir la información hasta ahora:
    Console.WriteLine("Rango audible definido entre " + eau[0] + " y " + eau[1] + " Hz");
    Console.WriteLine("Frecuencia fundamental: " + fnd);
    Console.WriteLine("Lista de ciclos (octavas): ");
    // Console.WriteLine(string.Join("\n", sbf));
    foreach (float i in sbf)
    {
        float[] icant = Math.Sqrt(i);
        Console.WriteLine(i*2);
    }
}
</code>```

// Edit: added Linq and code shared in comments but it still has errors:

```<code>public static void Main(string[] args)
    {
        Console.WriteLine("Proyecto X0n-832, Codificación de la teoría musical.");
        //Variables Generales
        float[] eau = { 440, 20000 };
        float fnd = eau[0];
        float cyc = fnd * 2;
        //Se cambia sfn por sbf
        float[] sbf = { fnd, cyc, cyc * 2, cyc * 4, cyc * 8, cyc * 16, cyc * 32, cyc * 64, cyc * 128, cyc * 256 };

        //Imprimir la información hasta ahora:
        Console.WriteLine("Rango audible definido entre " + eau[0] + " y " + eau[1] + " Hz");
        Console.WriteLine("Frecuencia fundamental: " + fnd);
        Console.WriteLine("Lista de ciclos (octavas): ");
        // Console.WriteLine(string.Join("\n", sbf));
        var icant = sbf.Select(i => Math.Sqrt(i)).ToArray() // icant is an arry here
        sbf.ForEach(i => Console.WriteLine(i * 2));
    }
</code>```

答:
Problem is in your foreach block. Type of output of Math.Sqrt(i) is not float[] it is float.

What I assume you want is:

```<code>var icant = sbf.Select(i => Math.Sqrt(i)).ToArray(); // icant is an arry here
Array.ForEach(sbf, i => Console.WriteLine(i));
</code>```

I just used linq extension methods to do the job. If you don't feel comfortable with that :

```<code>var result = new float[sbf.Length];
for( var i = 0; i < sbf.Length; i++)
{
    result[i] = Math.Sqrt(sbf[i]);
    Console.WriteLine(i*2);
}
</code>```

Body:
Trying to process Array float data and keep it as new array for later use. Got a float[] of 10 items and want to do math with each item and save result on new array. Getting "cant convert float to float" error. Thanks for the help, could not find what im searching for on Google sorry if it's dup.

public static void Main(string[] args)
{
    Console.WriteLine("Proyecto X0n-832, Codificación de la teoría musical.");
    //Variables Generales
    float[] eau = { 440, 20000 };
    float fnd = eau[0];
    float cyc = fnd * 2;
    //Se cambia sfn por sbf
    float[] sbf = { fnd, cyc, cyc * 2, cyc * 4, cyc * 8, cyc * 16, cyc * 32, cyc * 64, cyc * 128, cyc * 256 };

    //Imprimir la información hasta ahora:
    Console.WriteLine("Rango audible definido entre " + eau[0] + " y " + eau[1] + " Hz");
    Console.WriteLine("Frecuencia fundamental: " + fnd);
    Console.WriteLine("Lista de ciclos (octavas): ");
    // Console.WriteLine(string.Join("\n", sbf));
    foreach (float i in sbf)
    {
        float[] icant = Math.Sqrt(i);
        Console.WriteLine(i*2);
    }
}

// Edit: added Linq and code shared in comments but it still has errors:

public static void Main(string[] args)
    {
        Console.WriteLine("Proyecto X0n-832, Codificación de la teoría musical.");
        //Variables Generales
        float[] eau = { 440, 20000 };
        float fnd = eau[0];
        float cyc = fnd * 2;
        //Se cambia sfn por sbf
        float[] sbf = { fnd, cyc, cyc * 2, cyc * 4, cyc * 8, cyc * 16, cyc * 32, cyc * 64, cyc * 128, cyc * 256 };

        //Imprimir la información hasta ahora:
        Console.WriteLine("Rango audible definido entre " + eau[0] + " y " + eau[1] + " Hz");
        Console.WriteLine("Frecuencia fundamental: " + fnd);
        Console.WriteLine("Lista de ciclos (octavas): ");
        // Console.WriteLine(string.Join("\n", sbf));
        var icant = sbf.Select(i => Math.Sqrt(i)).ToArray() // icant is an arry here
        sbf.ForEach(i => Console.WriteLine(i * 2));
    }

Body:
Problem is in your foreach block. Type of output of Math.Sqrt(i) is not float[] it is float.

What I assume you want is:

var icant = sbf.Select(i => Math.Sqrt(i)).ToArray(); // icant is an arry here
Array.ForEach(sbf, i => Console.WriteLine(i));

I just used linq extension methods to do the job. If you don't feel comfortable with that :

var result = new float[sbf.Length];
for( var i = 0; i < sbf.Length; i++)
{
    result[i] = Math.Sqrt(sbf[i]);
    Console.WriteLine(i*2);
}