问:
Booking system: Find room combinations based on guest count - PHP
I am preparing a booking system and solving a specific problem. I have the following data structure (room number/occupancy/ price):

```<code>$room[222][1] = 80;

$room[223][1] = 100; //Room ID 222, occupancy 1 guest, price €100
$room[223][2] = 200; //Room ID 222, occupancy 2 guest, price €200
$room[223][3] = 300; //...

$room[224][1] = 110;
$room[224][2] = 220;
$room[224][3] = 330;
...
</code>```

I need to find the best (lowest price) combination of rooms for a specified number of guests.

For example:
For the 4 guests is the best combination of room $room[222][1] and room $room[223][3]. The total price of the rooms is €380.

Can you help me?

答:
First, I would make the rooms a more descriptive object so something like this:
Second, I wouldn't store price per customer like that, rather focus on capacity and go from there

```<code>  $room = array();
  $room[222] = array(
    'capactiy' => '3',
    'price' => array(
      1 => '100', //Use a string, likely you'll have .99 or whatever
      2 => '200',
      3 => '300',
    ),
    'booked' => false,
  );
</code>```

So you have 3 customers come in:
Loop through available rooms, if the amount of people is less than capacity then cool, book it, else (say capacity is 2) then remove 2 from the amount of customers needing room, Then loop again and grab the next room

If you want to get complex, say they want to be right next to each other, take room 222 + 1, is it available? if no then 223 + 1, is it available? yes? great! book it.

Body:
I am preparing a booking system and solving a specific problem. I have the following data structure (room number/occupancy/ price):

$room[222][1] = 80;

$room[223][1] = 100; //Room ID 222, occupancy 1 guest, price €100
$room[223][2] = 200; //Room ID 222, occupancy 2 guest, price €200
$room[223][3] = 300; //...

$room[224][1] = 110;
$room[224][2] = 220;
$room[224][3] = 330;
...

I need to find the best (lowest price) combination of rooms for a specified number of guests.

For example:
For the 4 guests is the best combination of room $room[222][1] and room $room[223][3]. The total price of the rooms is €380.

Can you help me?

Body:
First, I would make the rooms a more descriptive object so something like this:
Second, I wouldn't store price per customer like that, rather focus on capacity and go from there

  $room = array();
  $room[222] = array(
    'capactiy' => '3',
    'price' => array(
      1 => '100', //Use a string, likely you'll have .99 or whatever
      2 => '200',
      3 => '300',
    ),
    'booked' => false,
  );

So you have 3 customers come in:
Loop through available rooms, if the amount of people is less than capacity then cool, book it, else (say capacity is 2) then remove 2 from the amount of customers needing room, Then loop again and grab the next room

If you want to get complex, say they want to be right next to each other, take room 222 + 1, is it available? if no then 223 + 1, is it available? yes? great! book it.


来源: stackexchange

问:
Trouble sending form data to PHP page
I currently have a form set up inside a PHP echo. Traditionally my forms have a submit button to send data to a separate PHP document to add to or alter my database, but this time I have  tags inside of a <select> tag, and I'm using javascript to automatically submit the form when one of the option tags is selected with onchange="this.form.submit()". In my PHP document, I am using if (isset($_POST['completeStatus']) {PHP CODE}; to see if one of the options was selected inside the form, but for some reason it isn't working for me. It seems that the isset function only knows when a button is clicked, not an option tag. Please correct me if I'm wrong. I'm not sure if there is a different solution to make this work correctly, or if there is something wrong in my code that I'm not seeing.

```<code>while ($row = mysqli_fetch_assoc($result)) {
        echo "<center><div class='taskWrapper'><div class='taskTitles'><p class='subjectTitle'>subject</p><p class='taskSubject'>" . $row['subject'] ."</p></div>". " " .
                     "<div class='taskTitles'><p class='messageTitle'>Message</p><p class='taskMessage'>". $row['message'] ."</p></div>". " " .
                     "<div class='taskTitles'><form action='includes/changestatus.inc.php' method='POST'>
                       <p class='statusTitle'>Status</p><select class='taskStatus' name='myselect' onchange='this.form.submit()'>
                                                             <option value=". $row['calenderid'] .">".$row['mystatus']."</option>
                                                             <option name='stuckStatus' value=". $row['calenderid'] .">Two</option>
                                                             <option name='progressStatus' value=". $row['calenderid'] .">Three</option>
                                                             <option name='completeStatus' value=". $row['calenderid'] .">Four</option>
                                                             <input name='statusDate' type='hidden' value=". $urlDate ."></input>
                                                             <input name='statusMonth' type='hidden' value=". $urlMonth ."></input>
                                                             <input name='statusTZ' type='hidden' value=". $urlTZ ."></input>
                                                         </select>
                     </form></div></center>" ." ";
}
</code>```

Here's the PHP doc the form submits to

```<code>require 'dbh.inc.php';

    if (isset($_POST['completeStatus'])) {echo "working";}
</code>```

For testing purposes I'm expecting it to navigate and stay on the PHP page when option 4 is clicked on my form  and echo out "working", but the block of code isn't being run. It's being sent to the correct PHP doc but the if statement won't run.

答:
The names of options don't become POST parameters. You should be using the name of the <select>, $_POST['myselect'].

Then you need to give all the options different values, so you can tell which option was chosen. The value of $_POST['myselect'] will be one of those values.

I'm not sure what the first <option> is for. I suspect what you really want to do is select the current value by default, I've added code for that with ($row['mystatus'] == 'stuckStatus' ? 'selected' : '').

I added another hidden input with the ID of the task. $_POST['calendarId'] will contain $row['calendarid'] for the form that the user submitted.

```<code>while ($row = mysqli_fetch_assoc($result)) {
    echo "<center><div class='taskWrapper'><div class='taskTitles'><p class='subjectTitle'>subject</p><p class='taskSubject'>" . $row['subject'] ."</p></div>". " " .
                 "<div class='taskTitles'><p class='messageTitle'>Message</p><p class='taskMessage'>". $row['message'] ."</p></div>". " " .
                 "<div class='taskTitles'><form action='includes/changestatus.inc.php' method='POST'>
                   <p class='statusTitle'>Status</p><select class='taskStatus' name='myselect' onchange='this.form.submit()'>
                                                         <option value='stuckStatus' " . ($row['mystatus'] == 'stuckStatus' ? 'selected' : '') . ">Two</option>
                                                         <option value='progressStatus' " . ($row['mystatus'] == 'progressStatus' ? 'selected' : '') . ">Three</option>
                                                         <option value='completeStatus' " . ($row['mystatus'] == 'completeStatus' ? 'selected' : '') . ">Four</option>
                                                     </select>
                   <input name="calendarId' type='hidden' value='" . $row['calenderid'] . "'>
                   <input name='statusDate' type='hidden' value=". $urlDate ."></input>
                   <input name='statusMonth' type='hidden' value=". $urlMonth ."></input>
                   <input name='statusTZ' type='hidden' value=". $urlTZ ."></input>
                 </form></div></center>";
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Trouble sending form data to PHP page

Body:
I currently have a form set up inside a PHP echo. Traditionally my forms have a submit button to send data to a separate PHP document to add to or alter my database, but this time I have  tags inside of a <select> tag, and I'm using javascript to automatically submit the form when one of the option tags is selected with onchange="this.form.submit()". In my PHP document, I am using if (isset($_POST['completeStatus']) {PHP CODE}; to see if one of the options was selected inside the form, but for some reason it isn't working for me. It seems that the isset function only knows when a button is clicked, not an option tag. Please correct me if I'm wrong. I'm not sure if there is a different solution to make this work correctly, or if there is something wrong in my code that I'm not seeing.

while ($row = mysqli_fetch_assoc($result)) {
        echo "

subject

" . $row['subject'] ."

". " " .
                     "

Message

". $row['message'] ."

". " " .
                     "
<form action='includes/changestatus.inc.php' method='POST'>

Status
<select class='taskStatus' name='myselect' onchange='this.form.submit()'>
                                                             <option value=". $row['calenderid'] .">".$row['mystatus']."</option>
                                                             <option name='stuckStatus' value=". $row['calenderid'] .">Two</option>
                                                             <option name='progressStatus' value=". $row['calenderid'] .">Three</option>
                                                             <option name='completeStatus' value=". $row['calenderid'] .">Four</option>
                                                             <input name='statusDate' type='hidden' value=". $urlDate ."></input>
                                                             <input name='statusMonth' type='hidden' value=". $urlMonth ."></input>
                                                             <input name='statusTZ' type='hidden' value=". $urlTZ ."></input>
                                                         </select>
                     </form>
" ." ";
}

Here's the PHP doc the form submits to

require 'dbh.inc.php';

    if (isset($_POST['completeStatus'])) {echo "working";}

For testing purposes I'm expecting it to navigate and stay on the PHP page when option 4 is clicked on my form  and echo out "working", but the block of code isn't being run. It's being sent to the correct PHP doc but the if statement won't run.

Body:
The names of options don't become POST parameters. You should be using the name of the <select>, $_POST['myselect'].

Then you need to give all the options different values, so you can tell which option was chosen. The value of $_POST['myselect'] will be one of those values.

I'm not sure what the first <option> is for. I suspect what you really want to do is select the current value by default, I've added code for that with ($row['mystatus'] == 'stuckStatus' ? 'selected' : '').

I added another hidden input with the ID of the task. $_POST['calendarId'] will contain $row['calendarid'] for the form that the user submitted.

while ($row = mysqli_fetch_assoc($result)) {
    echo "<center><div class='taskWrapper'><div class='taskTitles'><p class='subjectTitle'>subject</p><p class='taskSubject'>" . $row['subject'] ."</p></div>". " " .
                 "<div class='taskTitles'><p class='messageTitle'>Message</p><p class='taskMessage'>". $row['message'] ."</p></div>". " " .
                 "<div class='taskTitles'><form action='includes/changestatus.inc.php' method='POST'>
                   <p class='statusTitle'>Status</p><select class='taskStatus' name='myselect' onchange='this.form.submit()'>
                                                         <option value='stuckStatus' " . ($row['mystatus'] == 'stuckStatus' ? 'selected' : '') . ">Two</option>
                                                         <option value='progressStatus' " . ($row['mystatus'] == 'progressStatus' ? 'selected' : '') . ">Three</option>
                                                         <option value='completeStatus' " . ($row['mystatus'] == 'completeStatus' ? 'selected' : '') . ">Four</option>
                                                     </select>
                   <input name="calendarId' type='hidden' value='" . $row['calenderid'] . "'>
                   <input name='statusDate' type='hidden' value=". $urlDate ."></input>
                   <input name='statusMonth' type='hidden' value=". $urlMonth ."></input>
                   <input name='statusTZ' type='hidden' value=". $urlTZ ."></input>
                 </form></div></center>";
}


问:
Generate oauth2orize access token programmatically for test user?
How can I generate a usable (live, authenticated) access token without forcing the client through redirect/authentication?

I'm building an IFTTT channel with node/express/oauth2orize. IFTTT requires that a test user can be generated by the endpoint test/setup. I need to return an access token that can be used for the subsequent tests.

答: Try running the Authentication Tests first, then copy the access token in one of the responses. Then use that value in your test/setup response.</p>

ContentLicense: CC BY-SA 3.0


问:
How to speed up drawing plots in Matplotlib?
I'm playing with random walk, I have two points. First one is walking randomly, second one is trying to escape from his area, which is given by formula e^(-t), where t is the distance between the two points. In my opinion it is not a difficult program, but it takes about a minute to run it with hundred points to calculate, so I'm asking you to help me find some way to speed it up and explain it to me.

import numpy as np
import matplotlib.pyplot as plt

def f(x, y, zx, zy):
    return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))

x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
#random picking first location for two points
loksx = [np.random.randn(), ]
loksy = [np.random.randn(), ]
lokzx = [np.random.randn(), ]
lokzy = [np.random.randn(), ]
for i in range(100):
    lokzx.append(np.random.randn()+lokzx[-1])
    lokzy.append(np.random.randn()+lokzy[-1])
    nsx = np.random.randn()
    nsy = np.random.randn()
    #checking if the next step has smaller value than the last one
    if f(loksx[-1]+nsx, loksy[-1]+nsy, lokzx[-1], lokzy[-1]) < f(loksx[-1], loksy[-1], lokzx[-1], lokzy[-1]):
        loksx.append(nsx+loksx[-1])
        loksy.append(nsy+loksy[-1])
Z = []
for i in range(len(lokzx)):
    Z.append(f(X, Y, lokzx[i], lokzy[i]))
ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)

ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()
```

<p>@edit
Now instead of using lists I'm using nparrays:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt

def f(x, y, zx, zy):
    return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))

x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
lokzx = np.random.randn(100)
lokzy = np.random.randn(100)
loksx = np.zeros(100)
loksy = np.zeros(100)
for i in range(1,100):
    nsx = np.random.randn()
    nsy = np.random.randn()
    if f(loksx[i-1]+nsx, loksy[i-1]+nsy, lokzx[i-1], lokzy[i-1]) < f(loksx[i-1], loksy[i-1], lokzx[i-1], lokzy[i-1]):
        loksx[i] = loksx[i-1]+nsx
        loksy[i] = loksy[i-1]+nsy
    else:
        loksx[i] = loksx[i-1]
        loksy[i] = loksy[i-1]
Z = np.zeros((100,1000,1000))
for i in range(len(lokzx)):
    Z[i] = f(X, Y, lokzx[i], lokzy[i])

ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)

ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()
</code>```

But still it takes a while to run this. The only problem left is this two lines of code:

for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
```

But I don't know how to rewrite this without using a loop.

答:
You should try to avoid the loops by learning to use the appropriate numpy functions.   i.e. something like the below will be much faster:

```<code>dx = np.random.randn(100)
dy = np.random.randn(100)
x = np.cumsum(dx)
y = np.cumsum(dy)
</code>```

If you really need the for-loop, preallocate your array; don't keep appending:

```<code>x = np.zeros(100)
y = np.zeros(100)
for i in range(1, 100):
    x[i] = x[i-1] + np.random.randn()
    y[i] = y[i-1] + np.random.randn()
</code>```

Body:
I'm playing with random walk, I have two points. First one is walking randomly, second one is trying to escape from his area, which is given by formula e^(-t), where t is the distance between the two points. In my opinion it is not a difficult program, but it takes about a minute to run it with hundred points to calculate, so I'm asking you to help me find some way to speed it up and explain it to me.

import numpy as np
import matplotlib.pyplot as plt

def f(x, y, zx, zy):
    return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))

x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
#random picking first location for two points
loksx = [np.random.randn(), ]
loksy = [np.random.randn(), ]
lokzx = [np.random.randn(), ]
lokzy = [np.random.randn(), ]
for i in range(100):
    lokzx.append(np.random.randn()+lokzx[-1])
    lokzy.append(np.random.randn()+lokzy[-1])
    nsx = np.random.randn()
    nsy = np.random.randn()
    #checking if the next step has smaller value than the last one
    if f(loksx[-1]+nsx, loksy[-1]+nsy, lokzx[-1], lokzy[-1]) < f(loksx[-1], loksy[-1], lokzx[-1], lokzy[-1]):
        loksx.append(nsx+loksx[-1])
        loksy.append(nsy+loksy[-1])
Z = []
for i in range(len(lokzx)):
    Z.append(f(X, Y, lokzx[i], lokzy[i]))
ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)

ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()

@edit
Now instead of using lists I'm using nparrays:

import numpy as np
import matplotlib.pyplot as plt

def f(x, y, zx, zy):
    return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))

x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
lokzx = np.random.randn(100)
lokzy = np.random.randn(100)
loksx = np.zeros(100)
loksy = np.zeros(100)
for i in range(1,100):
    nsx = np.random.randn()
    nsy = np.random.randn()
    if f(loksx[i-1]+nsx, loksy[i-1]+nsy, lokzx[i-1], lokzy[i-1]) < f(loksx[i-1], loksy[i-1], lokzx[i-1], lokzy[i-1]):
        loksx[i] = loksx[i-1]+nsx
        loksy[i] = loksy[i-1]+nsy
    else:
        loksx[i] = loksx[i-1]
        loksy[i] = loksy[i-1]
Z = np.zeros((100,1000,1000))
for i in range(len(lokzx)):
    Z[i] = f(X, Y, lokzx[i], lokzy[i])

ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)

ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()

But still it takes a while to run this. The only problem left is this two lines of code:

for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)

But I don't know how to rewrite this without using a loop.

Body:
You should try to avoid the loops by learning to use the appropriate numpy functions.   i.e. something like the below will be much faster:

dx = np.random.randn(100)
dy = np.random.randn(100)
x = np.cumsum(dx)
y = np.cumsum(dy)

If you really need the for-loop, preallocate your array; don't keep appending:

x = np.zeros(100)
y = np.zeros(100)
for i in range(1, 100):
    x[i] = x[i-1] + np.random.randn()
    y[i] = y[i-1] + np.random.randn()


问:
Does aria-haspopup require a true/false value?
According to the spec, the value should be a boolean. However, one of the spec examples of proper implementation uses a string value other than true/false - "listbox", which is the value of another element's role attribute. Is this a flaw in the implementation example or do screen readers, in practice, gain additional information from values other than true?

Relevant code from linked example:

```<code><div role="combobox" aria-expanded="false" aria-owns="ex1-listbox" aria-haspopup="listbox" id="ex1-combobox">
    <input type="text" aria-autocomplete="list" aria-controls="ex1-listbox" id="ex1-input" aria-activedescendant="">
</div>
</code>```

答: Originally (WAI-ARIA 1.0), aria-haspopup could only be true/false.  But WAI-ARIA 1.1 added additional values.  You can still use true/false but you can also be more specific about what kind of popup the element will have (a menu, a tree, a grid, a listbox, etc).

Body:
According to the spec, the value should be a boolean. However, one of the spec examples of proper implementation uses a string value other than true/false - "listbox", which is the value of another element's role attribute. Is this a flaw in the implementation example or do screen readers, in practice, gain additional information from values other than true?

Relevant code from linked example:

    <input type="text" aria-autocomplete="list" aria-controls="ex1-listbox" id="ex1-input" aria-activedescendant="">


问:
Is there a way to load a fully functional Menu Bar without PHP?
I'm currently trying to put the menu bar of my HTML Webpage into a separate file without using php.

How do I set this up properly?

Using a php file is not an option because of the CMS I'm using (http://www.coast-cms.de, German only). Therefore I needed to do it without Include. I almost got it to work the way I want it to by using jquery.load.

The navigation bar is loaded correctly, but the dropdown menu in it won't open until I reload, or on some pages won't work at all.

I suspect this has something to do with the order the scripts are loaded in, but given my limited experience with jQuery I was neither able to find out how to sort the loading process, nor which order would have been correct.

```

<pre class="lang-html prettyprint-override"><code><div id="navbar"></div>
<script>
  $("#navbar").load( "/modules/navbar.html");
</script>
</code>```

I expected to be able to just paste another html file into my existing one before anything else happens, but my code seems to load the file at some other point.

EDIT:
I'm using jquery.dropotron for the submenu https://github.com/ajlkn/jquery.dropotron

navbar.html

Company Name

Home

                            X

A

B

C

D

E

F

Über uns

G

H

Kontakt

```

<p>EDIT 2:
The code that I think is used for the hamburger menu in main.js</p>

<pre class="lang-js prettyprint-override"><code>a('').appendTo(b);
        a('<div id="navPanel"><nav>' + a("#nav").navList() + '</nav></div>').appendTo(d).panel({
            delay: 500,
            hideOnClick: true,
            hideOnSwipe: true,
            resetScroll: true,
            resetForms: true,
            side: "right"
        });
</code>```

答:
To "summarize" our comment discussion for others who may encounter this issue - the problem was the dropdown menu script (using jquery.dropotron) was originally occasionally running before the element was loaded by AJAX and occasionally running after (in other words, sometimes the element was loaded by AJAX fast before the parser got to the JS that called dropotron in the main.js file, and sometimes it was loaded after).

When the dropotron call was called before the element was loaded by AJAX, it failed to find anything to attach to, so it didn't do anything. When it was called after the element was loaded by AJAX, it found the element and was able to generate the dropdown (hence the navbar sometimes working and sometimes not working).

To alleviate this first issue, you confirmed that using a callback to create the dropdown after loading it did, in fact, always produce a dropdown:

```<code>$('#navbar').load('/modules/navbar.html', function() {
  $('#nav ul').dropotron();
});
</code>```

However, then the issue then became that it was being called twice in certain situations - this was due to the dropotron line being called in main.js, in the same fashion as originally, where sometimes it would run before the AJAX completed and sometimes after; when it ran after, it created a second menu.

The final solution was to comment out the line in main.js to remove the second call, and just use the AJAX callback to ensure that dropotron was called after the element was loaded.

Body:
I'm currently trying to put the menu bar of my HTML Webpage into a separate file without using php.

How do I set this up properly?

Using a php file is not an option because of the CMS I'm using (http://www.coast-cms.de, German only). Therefore I needed to do it without Include. I almost got it to work the way I want it to by using jquery.load.

The navigation bar is loaded correctly, but the dropdown menu in it won't open until I reload, or on some pages won't work at all.

I suspect this has something to do with the order the scripts are loaded in, but given my limited experience with jQuery I was neither able to find out how to sort the loading process, nor which order would have been correct.

I expected to be able to just paste another html file into my existing one before anything else happens, but my code seems to load the file at some other point.

EDIT:
I'm using jquery.dropotron for the submenu https://github.com/ajlkn/jquery.dropotron

navbar.html

Company Name

Home

                            X

A

B

C

D

E

F

Über uns

G

H

Kontakt

EDIT 2:
The code that I think is used for the hamburger menu in main.js

a('').appendTo(b);
        a('
' + a("#nav").navList() + '
').appendTo(d).panel({
            delay: 500,
            hideOnClick: true,
            hideOnSwipe: true,
            resetScroll: true,
            resetForms: true,
            side: "right"
        });

Body:
To "summarize" our comment discussion for others who may encounter this issue - the problem was the dropdown menu script (using jquery.dropotron) was originally occasionally running before the element was loaded by AJAX and occasionally running after (in other words, sometimes the element was loaded by AJAX fast before the parser got to the JS that called dropotron in the main.js file, and sometimes it was loaded after).

When the dropotron call was called before the element was loaded by AJAX, it failed to find anything to attach to, so it didn't do anything. When it was called after the element was loaded by AJAX, it found the element and was able to generate the dropdown (hence the navbar sometimes working and sometimes not working).

To alleviate this first issue, you confirmed that using a callback to create the dropdown after loading it did, in fact, always produce a dropdown:

$('#navbar').load('/modules/navbar.html', function() {
  $('#nav ul').dropotron();
});

However, then the issue then became that it was being called twice in certain situations - this was due to the dropotron line being called in main.js, in the same fashion as originally, where sometimes it would run before the AJAX completed and sometimes after; when it ran after, it created a second menu.

The final solution was to comment out the line in main.js to remove the second call, and just use the AJAX callback to ensure that dropotron was called after the element was loaded.


问:
Is there any user level privilege in Informix?
As I read, there are certain access privileges given to a user or role in Informix. If I give any of the database level privilege, it will have access to all users/ schemas under that database.

My doubt was that can I restrict this privilege to specific users/ schemas in that database? Do we have any user/schema level privilege in Informix?

答:
If you grant a user CONNECT privilege to a database, then they can access tables within that database for which they have been granted access (which is typically, but not necessarily, all tables in the database).  You can also revoke PUBLIC privileges on a table, and then grant access only to named users or roles, and then only those users who have been granted access can access it.  Here, "access" means "if they try to SELECT, they need to have been granted SELECT access; if they try to INSERT, they need to have been granted INSERT access; etc.".

By default, when you create a table in an ordinary database, then all users are given select, insert, update, delete privileges on the table.  This is done via the equivalent of GRANT ALL ON the_table TO PUBLIC.  Note that every user has the permissions granted to PUBLIC, and possibly some extra privileges.  Therefore, to ensure only selected users or roles have access, it is necessary to use REVOKE ALL ON the_table FROM PUBLIC.  There is an environment variable NODEFDAC=1 and a $ONCONFIG file setting with the same name that suppresses the default 'discretionary access controls' (DAC) granted to PUBLIC.  Note that in a MODE ANSI database, no permissions are granted to anyone else by default.

The constraints on users granted RESOURCE privilege in a database are similar users granted CONNECT privilege — the difference is that RESOURCE users can create their own tables, whereas CONNECT users cannot.

If a user is granted DBA privilege, they can access any tables in the database.  Be cautious about granting DBA privilege, therefore.


问:
how to convert large column using factor
Im writing a machine learning code for my dataset having hotels column.The hotel column contains 300 hotels name.For data preprocessing,I saw we have to use factor.Is there any easy way to covert it as there are so many values for level?</p>

答:
It's simple, use the as.factor() function to convert the column form character to factor.

Here's a sample

# Sample data
data
  a b
1 A 1
2 B 2
3 C 3
4 A 4
5 B 5

class(data$a)
[1] "character"

# Converting to factor
data$a <- as.factor(data$a)

# Results
class(data$a)
[1] "factor"
summary(data$a)
A B C
2 2 1
```


问:
How to combine multiple arrays in javascript?
I want to combine some multiple arrays into one array.

I tried _.zip of lodash library, but that's not what I want.

Here is the arrays:

```<code>var arr1 = [
    'a', 'b'
];
var arr2 = [
    'c', 'd'
];
var arr3 = [
    'e'
];
</code>```

And I want this output:

```<code>var result = [
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],
    ['b', 'c', 'e'],
    ['b', 'd', 'e']
];
</code>```

答:
Multiple people have alread mentioned that your question is a duplicate of this question. So, you might want to have a look there for a recommended solution.

I just wanted to add another functional solution which can be arbitrarily combined. The listProduct function in this case has type listProduct :: [[a]] -> [a] -> [[a]] meaning it takes a (at least) 2-dimensional array as its first argument and returns one. That's why the singletonize function is required to convert the first array into a 2-dimensional array.

As shown below you can easily combine calls to this function to get a product of n (n ≥ 2) list if you want.

const singletonize = l => l.map(x => [x])
const listProduct = (ls, list) =>
  ls.reduce((r, l) => {
      combinations = list.map(x => l.concat(x))
      return r.concat(combinations)
  }, [])

// The three arrays of your example
const a_1 = ['a', 'b'];
const a_2 = ['c', 'd'];
const a_3 = ['e'];
console.log(listProduct(listProduct(singletonize(a_1), a_2), a_3))

// Another example with five arrays
const a_4 = ['f', 'g', 'h'];
const a_5 = ['i'];

console.log(listProduct(listProduct(listProduct(listProduct(singletonize(a_1), a_2), a_3), a_4), a_5))```

Body:
I want to combine some multiple arrays into one array.

I tried _.zip of lodash library, but that's not what I want.

Here is the arrays:

var arr1 = [
    'a', 'b'
];
var arr2 = [
    'c', 'd'
];
var arr3 = [
    'e'
];

And I want this output:

var result = [
    ['a', 'c', 'e'],
    ['a', 'd', 'e'],
    ['b', 'c', 'e'],
    ['b', 'd', 'e']
];


问:
What does it mean that a sub-class's constructor followed by a base class constructor after a colon?
I would like to know what the code which is followed by a base class constructor does. Here is the code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Person
{
public:
    Person() : name(""), age(0) {}

protected:
    string name;
    int age;
};

class Student : public Person
{
public:
    Student() : Person::Person() {}

private:
    int student_id;
};
```

I know what the code does in class Person:

Person() : name(""), age(0) {}

But I do not understand what this line does in class Student:

Student() : Person::Person() {}

So what it the meaning of Person::Person() after the colon?

答:
Student() : Person::Person() {} is calling the constructor of the base class Person in the member initialization list of the derived Student constructor.

Note that Person::Person() can be simplified to just Person() in that context, as there is no need to fully qualify it using its class type.

Student() : Person() {}

You don't need to specify a base class constructor in the member initialization list of a derived constructor unless the derived constructor passes input values to the base class constructor.  Which your code does not, so you can optionally omit the base class constructor call entirely.  Person() is a default constructor, which the compiler will call automatically for you.

Student() {}

In which case, you can optionally also omit the Student constructor entirely, since it doesn't initialize anything else explicitly.

Body:
I would like to know what the code which is followed by a base class constructor does. Here is the code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Person
{
public:
    Person() : name(""), age(0) {}

protected:
    string name;
    int age;
};

class Student : public Person
{
public:
    Student() : Person::Person() {}

private:
    int student_id;
};

I know what the code does in class Person:

Person() : name(""), age(0) {}

But I do not understand what this line does in class Student:

Student() : Person::Person() {}

So what it the meaning of Person::Person() after the colon?


答:
You could take a function for a cartesian product of the given arrays.

const cartesian = (...p) =>
        p.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

var a = ['a', 'b'],
    b = ['c', 'd'],
    c = ['e'];
    result = cartesian(a, b, c);

result.forEach(a => console.log(...a));```

Title: How to combine multiple arrays in javascript?


问:
Is it possible to treat | as text instead of a filter?
I have a variable which dumps some comments from my site

{{ comment_variable }}

However the comments often contain the pipe symbol, because the users commenting have responded in multiple languages and used that symbol to separate.

eg. Hello | Bonjour

When I try to return this variable in my email template, it says

Hello

because the pipe symbol assumes that Bonjour is a filter function.

Is there any way to return the entire string as text? or will I have to do a bulk replace in the db?

I tried to assign variable and return as raw

Hello, Mr. X - here are the comments that you got on your entry.

{{ comment_variable }}

答:
I think you might be wanting the escape filter.

An example would be:

```<code>{{ comment_variable | escape }}
</code>```

Although, it makes me think there is an issue a bit deeper on how you obtain this variable. I was playing around in a liquid sandbox with both capture and assign of hello | world and it kept outputting what I expected - hello | world.

Body:
I think you might be wanting the escape filter.

An example would be:

{{ comment_variable | escape }}

Although, it makes me think there is an issue a bit deeper on how you obtain this variable. I was playing around in a liquid sandbox with both capture and assign of hello | world and it kept outputting what I expected - hello | world.


问:
Error when installing swirl in RStudio 3.1.2
Hey I tried installing swirl running the following command:

```<code>install.packages("swirl")
</code>```

I got the following error:

```<code>    ------------------------- ANTICONF ERROR -------------------------      --
Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘curl’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/curl’
Warning in install.packages :
  installation of package ‘curl’ had non-zero exit status
* installing *source* package ‘RCurl’ ...
** package ‘RCurl’ successfully unpacked and MD5 sums checked
checking for curl-config... no
Cannot find curl-config
ERROR: configuration failed for package ‘RCurl’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/RCurl’
Warning in install.packages :
  installation of package ‘RCurl’ had non-zero exit status
ERROR: dependency ‘curl’ is not available for package ‘httr’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/httr’
Warning in install.packages :
  installation of package ‘httr’ had non-zero exit status
ERROR: dependencies ‘httr’, ‘RCurl’ are not available for package       ‘swirl’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/swirl’
Warning in install.packages :
  installation of package ‘swirl’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/Rtmp7G87EM/downloaded_packages’
</code>```

I tried installing "curl" and "RCurl" packages but I got the same error messages. I don't know how to change the path as directed in the ANTICONF ERROR.

I'm running Ubuntu 15.04 and R version 3.1.2 (2014-10-31)

答:
Updated as on 30-05-2019:
I am using Ubuntu 16.04

I got this while installing the packages-
Using PKG_CFLAGS=

------------------------- ANTICONF ERROR ---------------------------

Configuration failed because openssl was not found. Try installing:  *
  deb: libssl-dev (Debian, Ubuntu, etc)  * rpm: openssl-devel (Fedora,
  CentOS, RHEL)  * csw: libssl_dev (Solaris)  * brew: openssl@1.1 (Mac
  OSX) If openssl is already installed, check that 'pkg-config' is in
  your PATH and PKG_CONFIG_PATH contains a openssl.pc file. If
  pkg-config is unavailable you can set INCLUDE_DIR and LIB_DIR manually
  via: R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

I used the command in terminal >

```<code>sudo apt-get install libssl-dev
</code>```

And then it worked fine.

Body:
Hey I tried installing swirl running the following command:

install.packages("swirl")

I got the following error:

    ------------------------- ANTICONF ERROR -------------------------      --
Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘curl’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/curl’
Warning in install.packages :
  installation of package ‘curl’ had non-zero exit status
* installing *source* package ‘RCurl’ ...
** package ‘RCurl’ successfully unpacked and MD5 sums checked
checking for curl-config... no
Cannot find curl-config
ERROR: configuration failed for package ‘RCurl’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/RCurl’
Warning in install.packages :
  installation of package ‘RCurl’ had non-zero exit status
ERROR: dependency ‘curl’ is not available for package ‘httr’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/httr’
Warning in install.packages :
  installation of package ‘httr’ had non-zero exit status
ERROR: dependencies ‘httr’, ‘RCurl’ are not available for package       ‘swirl’
* removing ‘/home/franco/R/x86_64-pc-linux-gnu-library/3.1/swirl’
Warning in install.packages :
  installation of package ‘swirl’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/Rtmp7G87EM/downloaded_packages’

I tried installing "curl" and "RCurl" packages but I got the same error messages. I don't know how to change the path as directed in the ANTICONF ERROR.

I'm running Ubuntu 15.04 and R version 3.1.2 (2014-10-31)

Body:
Updated as on 30-05-2019:
I am using Ubuntu 16.04

I got this while installing the packages-
Using PKG_CFLAGS=

------------------------- ANTICONF ERROR ---------------------------

Configuration failed because openssl was not found. Try installing:  *
  deb: libssl-dev (Debian, Ubuntu, etc)  * rpm: openssl-devel (Fedora,
  CentOS, RHEL)  * csw: libssl_dev (Solaris)  * brew: openssl@1.1 (Mac
  OSX) If openssl is already installed, check that 'pkg-config' is in
  your PATH and PKG_CONFIG_PATH contains a openssl.pc file. If
  pkg-config is unavailable you can set INCLUDE_DIR and LIB_DIR manually
  via: R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

I used the command in terminal >

sudo apt-get install libssl-dev

And then it worked fine.


问:
How to manually bind static Items to SplitButton (mahapps) via XAML
How do i manually add for example 2 items (buttons) from which the first is preselected via xaml? Like:

```<code><controls:SplitButton SelectedIndex="0">
    <controls:SplitButton.Items>
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
    </controls:SplitButton.Items>
</controls:SplitButton>
</code>```

Documentation tells me to use ItemsSource Binding but there is no example of the code behind.

答:
You can use the ItemsSource and an enumerable and don't specify a DisplayMemberPath.

```<code><controls:SplitButton HorizontalContentAlignment="Left"
                        HorizontalAlignment="Center"
                        VerticalContentAlignment="Center"
                        Width="120"
                        VerticalAlignment="Top">
    <controls:SplitButton.ItemsSource>
        <x:Array Type="system:String">
            <system:String>Label 1</system:String>
            <system:String>Another one</system:String>
            <system:String>Works now</system:String>
        </x:Array>
    </controls:SplitButton.ItemsSource>
</controls:SplitButton>
</code>```

Body:
How do i manually add for example 2 items (buttons) from which the first is preselected via xaml? Like:

<controls:SplitButton SelectedIndex="0">
    <controls:SplitButton.Items>
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
    </controls:SplitButton.Items>
</controls:SplitButton>

Documentation tells me to use ItemsSource Binding but there is no example of the code behind.

Body:
You can use the ItemsSource and an enumerable and don't specify a DisplayMemberPath.

<controls:SplitButton HorizontalContentAlignment="Left"
                        HorizontalAlignment="Center"
                        VerticalContentAlignment="Center"
                        Width="120"
                        VerticalAlignment="Top">
    <controls:SplitButton.ItemsSource>
        <x:Array Type="system:String">
            <system:String>Label 1</system:String>
            <system:String>Another one</system:String>
            <system:String>Works now</system:String>
        </x:Array>
    </controls:SplitButton.ItemsSource>
</controls:SplitButton>


问:
How to get textbox to show fraction format
How to get Me.TextBox15 to show 3/4" not 0.75? Can we change the format of a textbox?</p>

```<code>If Me.ComboBox15.Text = "CARBON" And Me.ComboBox16.Text = "150" Then
            Me.TextBox15.Value = Sheets("SHEET2").Range("F56")
        End If
</code>```

答:
This should get you close.

```<code>Me.TextBox1.Value = WorksheetFunction.Text(Me.TextBox1.Value, "?/?") & Chr(34)
</code>```

However, this will likely show you whole numbers like "4" as "4/1". It is the same, but not really as aesthetically pleasing. Another thing to consider is that fractions like .33333 repeating will not show up as 1/3, rather they will show as 33333/100000. I doubt there is an easy method to get a repeating decimal into a "nice" fraction. The Chr(34) at the end will add the single quote to the end of the string.

Good Luck!

Body:
How to get Me.TextBox15 to show 3/4" not 0.75? Can we change the format of a textbox?

If Me.ComboBox15.Text = "CARBON" And Me.ComboBox16.Text = "150" Then
            Me.TextBox15.Value = Sheets("SHEET2").Range("F56")
        End If

Body:
This should get you close.

Me.TextBox1.Value = WorksheetFunction.Text(Me.TextBox1.Value, "?/?") & Chr(34)

However, this will likely show you whole numbers like "4" as "4/1". It is the same, but not really as aesthetically pleasing. Another thing to consider is that fractions like .33333 repeating will not show up as 1/3, rather they will show as 33333/100000. I doubt there is an easy method to get a repeating decimal into a "nice" fraction. The Chr(34) at the end will add the single quote to the end of the string.

Good Luck!


问:
What is the correct way to pass data to a running thread
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

```<code>C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?
</code>```

So what is the correct way to pass data to a running thread in C# and Java?

答: One way I can think of is through property files.</p>

Body:
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?

So what is the correct way to pass data to a running thread in C# and Java?


问:
Moongose array indexOf doesn't finish running
I am trying to use Mongoose Array indexOf to check if an id is in an array of reference objects of another schema.

The following is the schema. The mongoose array is dishes.

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var favoriteSchema = new Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    dishes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Dish'
        }
    ]
}, {
    timestamps: true
});

var Favorites = mongoose.model('Favorite', favoriteSchema);

module.exports = Favorites;
</code>```

The issue is on the line

```<code>if (favorites.dishes.indexOf(mongoose.Types.ObjectId(req.params.dishId)) === -1){
</code>```

The line is in the following express router

```<code>const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var authenticate = require('../authenticate');
const cors = require('./cors');

const Favorites = require('../models/favorite');
const Dishes = require('../models/dishes');

const favoriteRouter = express.Router();

favoriteRouter.use(bodyParser.json());

favoriteRouter.route('/:dishId')
.post(authenticate.verifyUser, (req, res, next) => {
    if(mongoose.Types.ObjectId.isValid(req.params.dishId)) {
        //Dishes.findById(mongoose.Types.ObjectId(req.params.dishId))
        Dishes.findById(req.params.dishId)
        .then((dish) => {
            if (dish != null) {
                //console.log("dish: ", dish);
                Favorites.findOne({user: req.user._id})
                .then((favorites) => {
                    //console.log("favorite: ", favorites);
                    if (favorites != null){
                        //favorites = favorites[0];
                        console.log("**1", favorites.dishes);
                        if (favorites.dishes.indexOf(mongoose.Types.ObjectId(req.params.dishId)) === -1){
                            console.log("**1");
                            favorites.dishes.push(req.params.dishId);
                            favorites.save()
                            .then((favorites) => {
                                res.statusCode = 200;
                                res.setHeader('Content-Type', 'application/json');
                                res.json(favorites);
                            }, (err) => next(err))
                            .catch((err) => next(err));
                        } //Error not returned if it is already in the list.
                    }else{
                        Favorites.create({user: req.user._id})
                        .then((favorites) => {
                            favorites.dishes.push(mongoose.Types.ObjectId(req.params.dishId));
                            favorites.save()
                            .then((favorites) => {
                                res.statusCode = 200;
                                res.setHeader('Content-Type', 'application/json');
                                res.json(favorites);
                            }, (err) => next(err))
                        }, (err) => next(err))
                        .catch((err) => next(err));
                    }
                }, (err) => next(err))
                .catch((err) => next(err));
            }else {
                err = new Error('Dish ' + req.params.dishId + ' is not in the database.');
                err.status = 404;
                return next(err);
            }

        }, (err) => next(err))
        .catch((err) => next(err));
    }else{
        err = new Error('Dish ' + req.params.dishId + ' is not in the database.');
        err.status = 404;
        return next(err);
    }

});

module.exports = favoriteRouter;
</code>```

How can I solve the issu?

答:
You don't need the casting for the objectId, do it like this

```<code>favorites.dishes.indexOf(req.params.dishId === -1)
</code>```

And if you want to return an error if it's already exist you should add an else block, to throw the error.

Also I suggest that you can write your code using async/await syntax it will be much cleaner than nested promises.

https://javascript.info/async-await

Body:
I am trying to use Mongoose Array indexOf to check if an id is in an array of reference objects of another schema.

The following is the schema. The mongoose array is dishes.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var favoriteSchema = new Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    dishes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Dish'
        }
    ]
}, {
    timestamps: true
});

var Favorites = mongoose.model('Favorite', favoriteSchema);

module.exports = Favorites;

The issue is on the line

if (favorites.dishes.indexOf(mongoose.Types.ObjectId(req.params.dishId)) === -1){

The line is in the following express router

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var authenticate = require('../authenticate');
const cors = require('./cors');

const Favorites = require('../models/favorite');
const Dishes = require('../models/dishes');

const favoriteRouter = express.Router();

favoriteRouter.use(bodyParser.json());

favoriteRouter.route('/:dishId')
.post(authenticate.verifyUser, (req, res, next) => {
    if(mongoose.Types.ObjectId.isValid(req.params.dishId)) {
        //Dishes.findById(mongoose.Types.ObjectId(req.params.dishId))
        Dishes.findById(req.params.dishId)
        .then((dish) => {
            if (dish != null) {
                //console.log("dish: ", dish);
                Favorites.findOne({user: req.user._id})
                .then((favorites) => {
                    //console.log("favorite: ", favorites);
                    if (favorites != null){
                        //favorites = favorites[0];
                        console.log("**1", favorites.dishes);
                        if (favorites.dishes.indexOf(mongoose.Types.ObjectId(req.params.dishId)) === -1){
                            console.log("**1");
                            favorites.dishes.push(req.params.dishId);
                            favorites.save()
                            .then((favorites) => {
                                res.statusCode = 200;
                                res.setHeader('Content-Type', 'application/json');
                                res.json(favorites);
                            }, (err) => next(err))
                            .catch((err) => next(err));
                        } //Error not returned if it is already in the list.
                    }else{
                        Favorites.create({user: req.user._id})
                        .then((favorites) => {
                            favorites.dishes.push(mongoose.Types.ObjectId(req.params.dishId));
                            favorites.save()
                            .then((favorites) => {
                                res.statusCode = 200;
                                res.setHeader('Content-Type', 'application/json');
                                res.json(favorites);
                            }, (err) => next(err))
                        }, (err) => next(err))
                        .catch((err) => next(err));
                    }
                }, (err) => next(err))
                .catch((err) => next(err));
            }else {
                err = new Error('Dish ' + req.params.dishId + ' is not in the database.');
                err.status = 404;
                return next(err);
            }

        }, (err) => next(err))
        .catch((err) => next(err));
    }else{
        err = new Error('Dish ' + req.params.dishId + ' is not in the database.');
        err.status = 404;
        return next(err);
    }

});

module.exports = favoriteRouter;

How can I solve the issu?

Body:
You don't need the casting for the objectId, do it like this

favorites.dishes.indexOf(req.params.dishId === -1)

And if you want to return an error if it's already exist you should add an else block, to throw the error.

Also I suggest that you can write your code using async/await syntax it will be much cleaner than nested promises.

https://javascript.info/async-await


问:
how to unmock a single instance method with jest
coming from rspec, i am having trouble understanding mocking with jest. the approach i am trying for, is to automock a class's constructor and all of it's functions, and then unmock them one by one to test only that one function. the only documentation i can find on it, is with using 2 classes, mocking 1 class, and then testing that those functions are called from the other unmocked class.

below is a basic, contrived idea of what i am trying to do. can someone direct me to the jest-way of doing this?

foo.js

```<code>class Foo
  constructor: ->
    this.bar()
    this.baz()
  bar: ->
    return 'bar'
  baz: ->
    return 'baz'
</code>```

foo_test.js

```<code>// require the class
Foo = require('foo')

// mock entire Foo class methods
jest.mock('foo')

// unmock just the bar method
jest.unmock(Foo::bar)

// or by
Foo::bar.mockRestore()

// and should now be able to call
foo = new Foo
foo.bar() // 'bar'
foo.baz() // undefined (still mocked)

// i even tried unmocking the instance
foo = new Foo
jest.unmock(foo.bar)
foo.bar.mockRestore()
</code>```

答:
This does not strictly apply to the OP, but answer-seekers may end up here.  You can mock a module except certain parts for all tests like so.

mocks/saladMaker.js

// Let Jest create the mock.
const saladMaker = jest.genMockFromModule('../saladMaker');

// Get the unmocked chop method.
const {chop} = jest.requireActual('../saladMaker');

// Patch it in.
saladMaker.chop = chop;

module.exports = saladMaker;

```

The key part is to use requireActual to get at the unmocked module.

bypassing module mocks

Body:
coming from rspec, i am having trouble understanding mocking with jest. the approach i am trying for, is to automock a class's constructor and all of it's functions, and then unmock them one by one to test only that one function. the only documentation i can find on it, is with using 2 classes, mocking 1 class, and then testing that those functions are called from the other unmocked class.

below is a basic, contrived idea of what i am trying to do. can someone direct me to the jest-way of doing this?

foo.js

class Foo
  constructor: ->
    this.bar()
    this.baz()
  bar: ->
    return 'bar'
  baz: ->
    return 'baz'

foo_test.js

// require the class
Foo = require('foo')

// mock entire Foo class methods
jest.mock('foo')

// unmock just the bar method
jest.unmock(Foo::bar)

// or by
Foo::bar.mockRestore()

// and should now be able to call
foo = new Foo
foo.bar() // 'bar'
foo.baz() // undefined (still mocked)

// i even tried unmocking the instance
foo = new Foo
jest.unmock(foo.bar)
foo.bar.mockRestore()

Body:
This does not strictly apply to the OP, but answer-seekers may end up here.  You can mock a module except certain parts for all tests like so.

mocks/saladMaker.js

// Let Jest create the mock.
const saladMaker = jest.genMockFromModule('../saladMaker');

// Get the unmocked chop method.
const {chop} = jest.requireActual('../saladMaker');

// Patch it in.
saladMaker.chop = chop;

module.exports = saladMaker;

The key part is to use requireActual to get at the unmocked module.

bypassing module mocks


问:
PDFsharp and VB.NET Ximage.FromStream (FromStream is not a member of XImage)
I have been struggling using PDFsharp in VB.NET in order to create some PDF reports that need to be mailed.

I am stuck with the XImage.FromStream.  I am getting the not a member of XImage error and I haven't been able to figure out what specific library I should import in order to make it work or what else should I do.

答:
Finally I got it.  In VB.net you have to use Image.FromStream in order to work because for some reason that is unknown to me the XImage.FromStream doesn't work.

Here is the example of the solution.

```<code>Dim Picture as XImage
Picture = Image.FromStream(stream)
</code>```

After this you can draw the picture inside a PDF anywhere you want.  I hope this can help anyone with my same issue.

Body:
Finally I got it.  In VB.net you have to use Image.FromStream in order to work because for some reason that is unknown to me the XImage.FromStream doesn't work.

Here is the example of the solution.

Dim Picture as XImage
Picture = Image.FromStream(stream)

After this you can draw the picture inside a PDF anywhere you want.  I hope this can help anyone with my same issue.


问:
JSP: Confirm before submit
I'm trying to show a confirm dialog before submitting form data. I want a dialog to pop up with ok and cancel where ok submits the data and cancel does nothing.  This has proven to be trickier than I ever could have imagined.

The web application is in java and jsp.  I've tried the following using "onclick=" hoping for a simple solution to no avail:

Java: ReceiveAction.java

```<code>        public Resolution receiveInventory() {
             ...
             return new ForwardResolution(ADJUSTMENT);
        }
</code>```

jsp: receive-action.jsp

```<code>        <button name="_eventName" value="receiveInventory" type="submit" class="btn btn-green disabler-ignore-readonly" onclick="javascript:return confirm('are you sure?');">Receive</button>
</code>```

The problem is I can get the confirm dialog to appear with the above code but receiveInventory is triggered whether I hit ok or cancel.  I need it to only trigger when I hit ok.  I feel like I'm very well versed in java and jsp but I'm less than a novice when it comes to javascript(I avoid it like the plague) and I think that's what I'm going to need to pull this off.  Any help or pointing in the right direction would be greatly appreciated.

答:
Your button is a "submit" type so it is most likely triggering the form's onSubmit event when it is clicked, regardless of your own click handler. Also, confirm returns a boolean which you can use to tell if they selected the "Ok" button.

```<code>function checkSubmission() {
    let confirmed = confirm("Are you sure?");

    if (confirmed) {
         // Submit your form....
         recieveInventory(); // document.getElementById('myFormId').submit();
    } else {
        // Handle cancel here if needed
    }
}

<button name="_eventName" value="receiveInventory" type="button" class="btn btn-green disabler-ignore-readonly" onclick="javascript:return checkSubmission();">Receive</button>
</code>```

Ideally you probably should just set your form's submit handler to call checkSubmission. Then you don't have to set a click handler on the button at all

Title: JSP: Confirm before submit

Body:
I'm trying to show a confirm dialog before submitting form data. I want a dialog to pop up with ok and cancel where ok submits the data and cancel does nothing.  This has proven to be trickier than I ever could have imagined.

The web application is in java and jsp.  I've tried the following using "onclick=" hoping for a simple solution to no avail:

Java: ReceiveAction.java

        public Resolution receiveInventory() {
             ...
             return new ForwardResolution(ADJUSTMENT);
        }

jsp: receive-action.jsp

        <button name="_eventName" value="receiveInventory" type="submit" class="btn btn-green disabler-ignore-readonly" onclick="javascript:return confirm('are you sure?');">Receive</button>

The problem is I can get the confirm dialog to appear with the above code but receiveInventory is triggered whether I hit ok or cancel.  I need it to only trigger when I hit ok.  I feel like I'm very well versed in java and jsp but I'm less than a novice when it comes to javascript(I avoid it like the plague) and I think that's what I'm going to need to pull this off.  Any help or pointing in the right direction would be greatly appreciated.

Body:
Your button is a "submit" type so it is most likely triggering the form's onSubmit event when it is clicked, regardless of your own click handler. Also, confirm returns a boolean which you can use to tell if they selected the "Ok" button.

function checkSubmission() {
    let confirmed = confirm("Are you sure?");

    if (confirmed) {
         // Submit your form....
         recieveInventory(); // document.getElementById('myFormId').submit();
    } else {
        // Handle cancel here if needed
    }
}

<button name="_eventName" value="receiveInventory" type="button" class="btn btn-green disabler-ignore-readonly" onclick="javascript:return checkSubmission();">Receive</button>

Ideally you probably should just set your form's submit handler to call checkSubmission. Then you don't have to set a click handler on the button at all


问:
Decklink SDK & QtQuick
I'm trying to use BlackMagic Decklink SDK to display a video from a Decklink card into a QtQuick application. I successfully managed to do the same using QWidgets, so the video stream aquisition part is working.

When using QWidgets (more specifically QOpenGLWidget), basically all we have to do is to create a subclass of QOpenGLWidget and override initializeGL & paintGL like this:

void DeckLinkOpenGLWidget::initializeGL()
{
    if (m_deckLinkScreenPreviewHelper != nullptr)
    {
        m_mutex.lock();
        m_deckLinkScreenPreviewHelper->InitializeGL();
        m_mutex.unlock();
    }
}

void DeckLinkOpenGLWidget::paintGL()
{
    m_mutex.lock();
    glLoadIdentity();

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    m_deckLinkScreenPreviewHelper->PaintGL();
    m_mutex.unlock();
}
```

<p>When doing the same in a custom renderer with QtQuick, nothing happens. I suppose I have to write my program & shaders, but I've no idea of what it needs. When using a shader coloring each pixel in a color, a square of that color is painted, so I guess I'm no to far (but could be wrong...).</p>

<p>Here's some code:</p>

<pre class="lang-cpp prettyprint-override"><code>void VideoViewRenderer::initializeGL()
{
    QOpenGLFunctions::initializeOpenGLFunctions();

    const char* vertexShaderSource = "#version 330 core\n"
                                     "layout (location = 0) in vec3 aPos;\n"
                                     "void main()\n"
                                     "{\n"
                                     "   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
                                     "}\n";

    const char* fragmentShaderSource = "#version 330 core\n"
                                       "out vec4 FragColor;\n"
                                       "void main()\n"
                                       "{\n"
                                       "   FragColor = vec4(0.6f, 0.0f, 0.0f, 1.0f);\n"
                                       "}\n";

    m_program = new QOpenGLShaderProgram();
    m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Vertex,vertexShaderSource);
    m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
    m_program->link();

    m_mutex.lock();
    m_deckLinkScreenPreviewHelper->InitializeGL();
    m_mutex.unlock();
}

void VideoViewRenderer::paintGL()
{
    m_program->bind();

    glLoadIdentity();
    glClearColor(0.0f, 0.4f, 0.0f, 0.0f);
    glViewport(0, 0, m_viewportSize.width(), m_viewportSize.height());
    glClear(GL_COLOR_BUFFER_BIT);

    m_mutex.lock();
    m_deckLinkScreenPreviewHelper->PaintGL();
    m_mutex.unlock();

    m_program->release();
}
</code>```

How am I supposed to update my shaders?

答:
The easiest way to solve this problem is to render two triangles forming a square on the screen instead of points. Set those triangles to be textured and dynamically change the texture buffer contents with data from Decklink card.

Please see this thread for more information on using video frames in opengl:
How to input video (frames) into a GLSL shader

Title: Decklink SDK & QtQuick

Body:
I'm trying to use BlackMagic Decklink SDK to display a video from a Decklink card into a QtQuick application. I successfully managed to do the same using QWidgets, so the video stream aquisition part is working.

When using QWidgets (more specifically QOpenGLWidget), basically all we have to do is to create a subclass of QOpenGLWidget and override initializeGL & paintGL like this:

void DeckLinkOpenGLWidget::initializeGL()
{
    if (m_deckLinkScreenPreviewHelper != nullptr)
    {
        m_mutex.lock();
        m_deckLinkScreenPreviewHelper->InitializeGL();
        m_mutex.unlock();
    }
}

void DeckLinkOpenGLWidget::paintGL()
{
    m_mutex.lock();
    glLoadIdentity();

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    m_deckLinkScreenPreviewHelper->PaintGL();
    m_mutex.unlock();
}

When doing the same in a custom renderer with QtQuick, nothing happens. I suppose I have to write my program & shaders, but I've no idea of what it needs. When using a shader coloring each pixel in a color, a square of that color is painted, so I guess I'm no to far (but could be wrong...).

Here's some code:

void VideoViewRenderer::initializeGL()
{
    QOpenGLFunctions::initializeOpenGLFunctions();

    const char* vertexShaderSource = "#version 330 core\n"
                                     "layout (location = 0) in vec3 aPos;\n"
                                     "void main()\n"
                                     "{\n"
                                     "   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
                                     "}\n";

    const char* fragmentShaderSource = "#version 330 core\n"
                                       "out vec4 FragColor;\n"
                                       "void main()\n"
                                       "{\n"
                                       "   FragColor = vec4(0.6f, 0.0f, 0.0f, 1.0f);\n"
                                       "}\n";

    m_program = new QOpenGLShaderProgram();
    m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Vertex,vertexShaderSource);
    m_program->addCacheableShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
    m_program->link();

    m_mutex.lock();
    m_deckLinkScreenPreviewHelper->InitializeGL();
    m_mutex.unlock();
}

void VideoViewRenderer::paintGL()
{
    m_program->bind();

    glLoadIdentity();
    glClearColor(0.0f, 0.4f, 0.0f, 0.0f);
    glViewport(0, 0, m_viewportSize.width(), m_viewportSize.height());
    glClear(GL_COLOR_BUFFER_BIT);

    m_mutex.lock();
    m_deckLinkScreenPreviewHelper->PaintGL();
    m_mutex.unlock();

    m_program->release();
}

How am I supposed to update my shaders?


问:
can't change col type to factor upon loading
For some reason, when I try to upload this large csv file it give the error below. Any ideas?

```<code>library(readr)
data2014 <- read_csv("data2014.csv", col_types = cols(
  Year = col_factor(levels, ordered = FALSE),
  Round = col_factor(levels, ordered = FALSE),
  Game = col_factor(levels, ordered = FALSE),
  Matchup = col_factor(levels, ordered = FALSE),
  Top_Seed = col_factor(levels, ordered = FALSE),
  Low_Seed = col_factor(levels, ordered = FALSE),
  Home_Court = col_factor(levels, ordered = FALSE),
  On_Road = col_factor(levels, ordered = FALSE),
  Play = col_factor(levels, ordered = FALSE),
  Quarter = col_factor(levels, ordered = FALSE),
  Time = col_skip(),
  Minutes = col_integer(),
  Seconds = col_integer(),
  Away = col_character(),
  Away_Points_Added = col_integer(),
  Score = col_character(),
  Home_Points_Added = col_integer(),
  Home = col_character()
))
</code>```

Error in read_tokens_(data, tokenizer, col_specs, col_names, locale_, : Not compatible with STRSXP: [type=closure].

答:
Try this

library(readr)
data2014 <- read_csv("data2014.csv", col_types = cols(
  .default = "f",
  Time = col_skip(),
  Minutes = col_integer(),
  Seconds = col_integer(),
  Away = col_character(),
  Away_Points_Added = col_integer(),
  Score = col_character(),
  Home_Points_Added = col_integer(),
  Home = col_character()
))
```

Body:
For some reason, when I try to upload this large csv file it give the error below. Any ideas?

library(readr)
data2014 <- read_csv("data2014.csv", col_types = cols(
  Year = col_factor(levels, ordered = FALSE),
  Round = col_factor(levels, ordered = FALSE),
  Game = col_factor(levels, ordered = FALSE),
  Matchup = col_factor(levels, ordered = FALSE),
  Top_Seed = col_factor(levels, ordered = FALSE),
  Low_Seed = col_factor(levels, ordered = FALSE),
  Home_Court = col_factor(levels, ordered = FALSE),
  On_Road = col_factor(levels, ordered = FALSE),
  Play = col_factor(levels, ordered = FALSE),
  Quarter = col_factor(levels, ordered = FALSE),
  Time = col_skip(),
  Minutes = col_integer(),
  Seconds = col_integer(),
  Away = col_character(),
  Away_Points_Added = col_integer(),
  Score = col_character(),
  Home_Points_Added = col_integer(),
  Home = col_character()
))

Error in read_tokens_(data, tokenizer, col_specs, col_names, locale_, : Not compatible with STRSXP: [type=closure].


问:
How to solve nested ODE equations
We can use the deSolve package in R for ordinary differential equations (ODE), however, I can't find a way to solve two nested ODE equations, suppose `

```<code>b'(t) = beta - k*b(t);
a'(t) = alpha -b(t)*gamma;
</code>```

where ' means differentiation. How can we solve a and b then? as a' is a function of b, we have to solve a and b simultaneously.

I got an error:

Error in lsoda(y, times, func, parms, ...) :   The used combination of solvers cannot be nested.

When I tried to add the solve for b inside the ode solution for a.

答:
I may be confused, but you seem to be describing coupled equations, which lsoda can handle perfectly well, as follows (I implemented your ODEs but made up some parameters since I didn't know what you had in mind.)

```<code>gfun <- function(t,y,parms,...) {
  ## 'with' trick lets us write gradient in terms of variable/parameter names
  with(as.list(c(y,parms)),
       list(c(b=beta-k*b,a=alpha-b*gamma),NULL))
}

library(deSolve)
L1 <- lsoda(y=c(b=1,a=1),
            times=seq(0,10,by=0.1),
            func=gfun,
            parms=c(alpha=0.1,beta=0.2,gamma=0.05,k=0.01))

matplot(L1[,1],L1[,-1],type="l",lty=1,bty="l",las=1)
</code>```

PS: this seems to be a set of coupled linear ODEs, so you should actually be able to get a full closed-form solution rather than solving them numerically. (I'm too lazy to do that right now; b(t) can be solved immediately (an "affine" equation), a(t) can be solved by integration.)

Title: How to solve nested ODE equations

Body:
We can use the deSolve package in R for ordinary differential equations (ODE), however, I can't find a way to solve two nested ODE equations, suppose `

b'(t) = beta - k*b(t);
a'(t) = alpha -b(t)*gamma;

where ' means differentiation. How can we solve a and b then? as a' is a function of b, we have to solve a and b simultaneously.

I got an error:

Error in lsoda(y, times, func, parms, ...) :   The used combination of solvers cannot be nested.

When I tried to add the solve for b inside the ode solution for a.

Body:
I may be confused, but you seem to be describing coupled equations, which lsoda can handle perfectly well, as follows (I implemented your ODEs but made up some parameters since I didn't know what you had in mind.)

gfun <- function(t,y,parms,...) {
  ## 'with' trick lets us write gradient in terms of variable/parameter names
  with(as.list(c(y,parms)),
       list(c(b=beta-k*b,a=alpha-b*gamma),NULL))
}

library(deSolve)
L1 <- lsoda(y=c(b=1,a=1),
            times=seq(0,10,by=0.1),
            func=gfun,
            parms=c(alpha=0.1,beta=0.2,gamma=0.05,k=0.01))

matplot(L1[,1],L1[,-1],type="l",lty=1,bty="l",las=1)

PS: this seems to be a set of coupled linear ODEs, so you should actually be able to get a full closed-form solution rather than solving them numerically. (I'm too lazy to do that right now; b(t) can be solved immediately (an "affine" equation), a(t) can be solved by integration.)


问:
Single column gallery with flexbox with certain divs split in two
I am making use of a gallery which represents a column containing either one or two
 elements spanning across the entire width. The columns containing multiple
 elements also contain images with different height and width properties. I would like these columns to be the same height and then fill the width as much as possible whenever there is extra space between them.

I would use a flexbox
 element with a fixed width and a flex-wrap property. The
 elements that are to span the entire width have a property max-width: 100%. A row with multiple items are inside a container
 element which spans and then each in another box
 element. I could get the two on the same lines, but since they vary in sizes I would not want each image to be 50% width, because then the empty space is above and below an item instead of between them.

I have tried tinkering with flex-grow, flex-shrink and flex-basis, however none of these seem ever to be exact. I also considered switching the
 elements with two items to flex-direction: column and then wrap these. This however did not work for me.

.column {
  width: 600px;
  display: flex;
  flex-wrap: wrap;
}

.smallContain {
  min-width: 100%;
  display: flex;
  align-content: space-between;
}

.smallBox {
  flex: 1 1 50%;
}

.largeBox {
  min-width: 100%;
}

img {
  max-width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="container">
    <div class="column">
      <div class="smallContain">
        <div class="box smallBox">
          <img src="#" class="imgS">
        </div>
        <div class="box smallBox">
          <img src="#" class="imgS">
        </div>
      </div>
        <div class="box largeBox">
          <img src="#" class="imgL">
        </div>
      <div class="smallContain">
        <div class="box smallBox">
          <img src="#" class="imgS">
        </div>
        <div class="box smallBox">
          <img src="#" class="imgS">
        </div>
      </div>
        <div class="box largeBox">
          <img src="#" class="imgL">
        </div>
      <div class="smallContain">
        <div class="box smallBox">
          <img src="#">
        </div>
        <div class="box smallBox">
          <img src="#">
        </div>
      </div>
      <div class="smallContain">
        <div class="box smallBox">
          <img src="#" class="imgS">
        </div>
        <div class="box smallBox">
          <img src="#" class="imgS">
        </div>
      </div>
        <div class="box largeBox">
          <img src="#" class="imgL">
        </div>
      </div>
  </div>
</body></code>```

(Within the example above, the .imgS class refer to small images and .imgL class refer to large images)

Here's an example of what I'm hoping to get it to look like.

答:
your question is a bit hard to understand, even so I gave it a try, maybe what your looking is something like this?

.grid {
  align-items: stretch;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
}
.grid .item {
  max-height: 400px;
  padding: 5px;
}
.grid .item.smallBox {
  flex-basis: auto;
  flex-grow: 1;
  flex-shrink: 1;
}
.grid .item.smallBox img {
  object-fit: cover;
  object-position: center;
}
.grid .item.largeBox {
  flex-basis: 100%;
  flex-grow: 1;
  flex-shrink: 1;
}
.grid .item img {
  height: 100%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/280x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/280x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1920x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/480x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/250x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1440x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/250x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/480x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1440x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/500x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/150x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1440x500" alt="">
  </div>
</div></code>```

Hope it helps, good luck.

Body:
I am making use of a gallery which represents a column containing either one or two
 elements spanning across the entire width. The columns containing multiple
 elements also contain images with different height and width properties. I would like these columns to be the same height and then fill the width as much as possible whenever there is extra space between them.

I would use a flexbox
 element with a fixed width and a flex-wrap property. The
 elements that are to span the entire width have a property max-width: 100%. A row with multiple items are inside a container
 element which spans and then each in another box
 element. I could get the two on the same lines, but since they vary in sizes I would not want each image to be 50% width, because then the empty space is above and below an item instead of between them.

I have tried tinkering with flex-grow, flex-shrink and flex-basis, however none of these seem ever to be exact. I also considered switching the
 elements with two items to flex-direction: column and then wrap these. This however did not work for me.

.column {
  width: 600px;
  display: flex;
  flex-wrap: wrap;
}

.smallContain {
  min-width: 100%;
  display: flex;
  align-content: space-between;
}

.smallBox {
  flex: 1 1 50%;
}

.largeBox {
  min-width: 100%;
}

img {
  max-width: 100%;
}

(Within the example above, the .imgS class refer to small images and .imgL class refer to large images)

Here's an example of what I'm hoping to get it to look like.

Body:
your question is a bit hard to understand, even so I gave it a try, maybe what your looking is something like this?

.grid {
  align-items: stretch;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
}
.grid .item {
  max-height: 400px;
  padding: 5px;
}
.grid .item.smallBox {
  flex-basis: auto;
  flex-grow: 1;
  flex-shrink: 1;
}
.grid .item.smallBox img {
  object-fit: cover;
  object-position: center;
}
.grid .item.largeBox {
  flex-basis: 100%;
  flex-grow: 1;
  flex-shrink: 1;
}
.grid .item img {
  height: 100%;
  width: 100%;
}

<div class="grid">
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/280x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/280x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1920x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/480x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/250x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1440x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/250x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/480x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1440x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/500x500" alt="">
  </div>
  <div class="item smallBox">
    <img src="http://placeholder.pics/svg/150x500" alt="">
  </div>
  <div class="item largeBox">
    <img src="http://placeholder.pics/svg/1440x500" alt="">
  </div>
</div>

Hope it helps, good luck.


问:
Significane of using AsEnumerable() in query to take anonomous value in to view model
i just don't understand the meaning of writing AsEnumerable() in linq query.

i am having one UserDetail table in which i am fetching all details of user and i want to take
name,email in to my model.

```<code> var data = context.UserDetails
                   .Select(temp => new FullName = temp.Fullname, Email = temp.Email })
                   .ToList()
                   .AsEnumerable()
                   .Select(d => new UserDetailsModel { Fullname = d.FullName, Email = d.Email })
                   .ToList();
</code>```

What is the meaning of AsEnumerable() as because when i am removing this there is no error but as i have seen some queries where they are using this method.

And does anybody have better approach for taking anonymous object value in to my View Model?

Does it improve performance? What is the significance of this method? Can anybody explain me this method in context to my question and details?

答:
ToList() or AsEnumerable() work similarly, you don't need both. List is a IEnumerable + some extra features such as Add(), Count, etc., and the idea of using any of these is to materialize the query (IQueryable).

Also, You don't need the temp query, you could do a direct select:

```<code>var data = context.UserDetails
                   .Select(d => new UserDetailsModel {...})
                   .ToList()); // or AsEnumerable()
</code>```

Body:
i just don't understand the meaning of writing AsEnumerable() in linq query.

i am having one UserDetail table in which i am fetching all details of user and i want to take
name,email in to my model.

 var data = context.UserDetails
                   .Select(temp => new FullName = temp.Fullname, Email = temp.Email })
                   .ToList()
                   .AsEnumerable()
                   .Select(d => new UserDetailsModel { Fullname = d.FullName, Email = d.Email })
                   .ToList();

What is the meaning of AsEnumerable() as because when i am removing this there is no error but as i have seen some queries where they are using this method.

And does anybody have better approach for taking anonymous object value in to my View Model?

Does it improve performance? What is the significance of this method? Can anybody explain me this method in context to my question and details?

Body:
ToList() or AsEnumerable() work similarly, you don't need both. List is a IEnumerable + some extra features such as Add(), Count, etc., and the idea of using any of these is to materialize the query (IQueryable).

Also, You don't need the temp query, you could do a direct select:

var data = context.UserDetails
                   .Select(d => new UserDetailsModel {...})
                   .ToList()); // or AsEnumerable()


问:
Do we need to worry about 32bit or 64bit integers or are we fine just using 'int'
I am using cocos2d-x to make a game and when using "int" in our games do we have to worry about using int32_t and int64_t for 32 and 64 systems, or does just declaring for instance say “int score = 0;” take care of all of that under the hood ?</p>

答: In Objective-C compiling older source code that declared int variables, then using them in statements, like NSLog statements will result in warnings that implicit casting of int to long is not recommended.  It's a warning, so, if you don't mind having a lot of yellow flags in your code, you'll probably be OK.  But, to get rid of the warnings, you have to explicitly cast them to long (long)score, instead of just 'score'.</p>


问:
RNDIS gadget cannot start
I build video cameras with a Linux kernel on a TI Davinci dm365 board.

This board supports RNDIS drivers so my camera can be "plug and play" in windows. This is some kind of "Ethernet over USB" network adapter.

Windows load the RNDIS driver usb8023.sys to interact with my hardware.

When I have more than one camera plugged-in, Hell breaks loose and I get a lot of problems, sometimes all my USB ports stop working but most of the time, one of the two cameras stop working.

I've tried importing old drivers, copy usb8023.sys and load a separate driver for each cam with no luck. I've checked and double checked my ip settings.

答: I downloaded new version of the drivers from Texas Instruments and recompiled everything. I think that the problem was that the gadget pc had OTG (on the go) enabled, which allows it to switch between host and device mode.</p>

ContentLicense: CC BY-SA 2.5

Title: RNDIS gadget cannot start


问:
React js - state changing onclick from array of values - "Uncaught Invariant Violation" error
Have an array of color options, want to create a dynamic list of these items then change the state to that selected color on click.

Here is my current code:

import React from 'react';
import ReactDOM from 'react-dom';

const colors=["white","green","blue", "red", "orange"];

class Grid extends React.Component{

  constructor(props){
    super(props);
    this.state={
      color: colors[0]
    };
  }

  setCurrentColor(setColor){
    this.setState({
      color: setColor
    });
  }

  setColorSelections(){
    const colorItems = colors.map((thecolor) =>

 this.setCurrentColor(thecolor)  }
      key={thecolor} >
      {thecolor}

    );
    return(

        {colorItems}

    )
  }

  render(){
    return(

Current selection: {this.state.color}

              {this.setColorSelections()}

    )
  }
}```
</div>
</div>
</p>

<p>Receiving the following error</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Uncaught Invariant Violation: Objects are not valid as a React child</code>```

I really can't output the state? How do I fix this

答:
Remove the paramater thecolor from onClick function or rename it to something, it's giving you an error because the variable was declared in the map function map((thecolor)

```<code>setColorSelections() {
  const colorItems = colors.map((thecolor) =>
    <li
      onClick={(event) => this.setCurrentColor(thecolor)}
      key={thecolor} >
      {thecolor}
    </li>
  );
  return (
    <ul>
      {colorItems}
    </ul>
  )
}
</code>```

```

Body:
Have an array of color options, want to create a dynamic list of these items then change the state to that selected color on click.

Here is my current code:

import React from 'react';
import ReactDOM from 'react-dom';

const colors=["white","green","blue", "red", "orange"];

class Grid extends React.Component{

  constructor(props){
    super(props);
    this.state={
      color: colors[0]
    };
  }

  setCurrentColor(setColor){
    this.setState({
      color: setColor
    });
  }

  setColorSelections(){
    const colorItems = colors.map((thecolor) =>

 this.setCurrentColor(thecolor)  }
      key={thecolor} >
      {thecolor}

    );
    return(

        {colorItems}

    )
  }

  render(){
    return(

Current selection: {this.state.color}

              {this.setColorSelections()}

    )
  }
}

Receiving the following error

Uncaught Invariant Violation: Objects are not valid as a React child

I really can't output the state? How do I fix this

Body:
Remove the paramater thecolor from onClick function or rename it to something, it's giving you an error because the variable was declared in the map function map((thecolor)

setColorSelections() {
  const colorItems = colors.map((thecolor) =>
    <li
      onClick={(event) => this.setCurrentColor(thecolor)}
      key={thecolor} >
      {thecolor}
    </li>
  );
  return (
    <ul>
      {colorItems}
    </ul>
  )
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">
const colors = ["white", "green", "blue", "red", "orange"];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: colors[0]
    };
  }

  setCurrentColor(setColor) {
    this.setState({
      color: setColor
    });
  }

  setColorSelections() {
    const colorItems = colors.map((thecolor) =>
      <li
        onClick={(event) => this.setCurrentColor(thecolor)}
        key={thecolor} >
        {thecolor}
      </li>
    );
    return (
      <ul>
        {colorItems}
      </ul>
    )
  }
  render() {
    return (
    <div>
        <p style={{ backgroundColor: this.state.color }}>Current selection: {this.state.color}</p>
              {this.setColorSelections()}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>